3 Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com>
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU Lesser General Public License as published by
7 the Free Software Foundation; either version 2.1 of the License, or
8 (at your option) any later version.
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU Lesser General Public License for more details.
15 You should have received a copy of the GNU Lesser General Public License along
16 with this program; if not, write to the Free Software Foundation, Inc.,
17 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
23 #include <IFileSystem.h>
24 #include "jthread/jmutexautolock.h"
25 #include "util/auth.h"
26 #include "util/directiontables.h"
27 #include "util/pointedthing.h"
28 #include "util/serialize.h"
29 #include "util/string.h"
32 #include "network/clientopcodes.h"
35 #include "mapblock_mesh.h"
41 #include "nodemetadata.h"
44 #include "clientmap.h"
45 #include "clientmedia.h"
47 #include "IMeshCache.h"
50 #include "drawscene.h"
51 #include "database-sqlite3.h"
52 #include "serialization.h"
53 #include "guiscalingfilter.h"
55 extern gui::IGUIEnvironment* guienv;
61 QueuedMeshUpdate::QueuedMeshUpdate():
64 ack_block_to_server(false)
68 QueuedMeshUpdate::~QueuedMeshUpdate()
78 MeshUpdateQueue::MeshUpdateQueue()
82 MeshUpdateQueue::~MeshUpdateQueue()
84 JMutexAutoLock lock(m_mutex);
86 for(std::vector<QueuedMeshUpdate*>::iterator
88 i != m_queue.end(); i++)
90 QueuedMeshUpdate *q = *i;
96 peer_id=0 adds with nobody to send to
98 void MeshUpdateQueue::addBlock(v3s16 p, MeshMakeData *data, bool ack_block_to_server, bool urgent)
100 DSTACK(__FUNCTION_NAME);
102 assert(data); // pre-condition
104 JMutexAutoLock lock(m_mutex);
110 Find if block is already in queue.
111 If it is, update the data and quit.
113 for(std::vector<QueuedMeshUpdate*>::iterator
115 i != m_queue.end(); i++)
117 QueuedMeshUpdate *q = *i;
123 if(ack_block_to_server)
124 q->ack_block_to_server = true;
132 QueuedMeshUpdate *q = new QueuedMeshUpdate;
135 q->ack_block_to_server = ack_block_to_server;
136 m_queue.push_back(q);
139 // Returned pointer must be deleted
140 // Returns NULL if queue is empty
141 QueuedMeshUpdate * MeshUpdateQueue::pop()
143 JMutexAutoLock lock(m_mutex);
145 bool must_be_urgent = !m_urgents.empty();
146 for(std::vector<QueuedMeshUpdate*>::iterator
148 i != m_queue.end(); i++)
150 QueuedMeshUpdate *q = *i;
151 if(must_be_urgent && m_urgents.count(q->p) == 0)
154 m_urgents.erase(q->p);
164 void * MeshUpdateThread::Thread()
168 log_register_thread("MeshUpdateThread");
170 DSTACK(__FUNCTION_NAME);
172 BEGIN_DEBUG_EXCEPTION_HANDLER
174 porting::setThreadName("MeshUpdateThread");
176 while(!StopRequested())
178 QueuedMeshUpdate *q = m_queue_in.pop();
185 ScopeProfiler sp(g_profiler, "Client: Mesh making");
187 MapBlockMesh *mesh_new = new MapBlockMesh(q->data, m_camera_offset);
188 if(mesh_new->getMesh()->getMeshBufferCount() == 0)
197 r.ack_block_to_server = q->ack_block_to_server;
199 m_queue_out.push_back(r);
204 END_DEBUG_EXCEPTION_HANDLER(errorstream)
214 IrrlichtDevice *device,
215 const char *playername,
216 std::string password,
217 MapDrawControl &control,
218 IWritableTextureSource *tsrc,
219 IWritableShaderSource *shsrc,
220 IWritableItemDefManager *itemdef,
221 IWritableNodeDefManager *nodedef,
222 ISoundManager *sound,
223 MtEventManager *event,
226 m_packetcounter_timer(0.0),
227 m_connection_reinit_timer(0.1),
228 m_avg_rtt_timer(0.0),
229 m_playerpos_send_timer(0.0),
230 m_ignore_damage_timer(0.0),
237 m_mesh_update_thread(this),
239 new ClientMap(this, this, control,
240 device->getSceneManager()->getRootSceneNode(),
241 device->getSceneManager(), 666),
242 device->getSceneManager(),
245 m_particle_manager(&m_env),
246 m_con(PROTOCOL_ID, 512, CONNECTION_TIMEOUT, ipv6, this),
248 m_server_ser_ver(SER_FMT_VER_INVALID),
250 m_inventory_updated(false),
251 m_inventory_from_server(NULL),
252 m_inventory_from_server_age(0.0),
253 m_show_highlighted(false),
257 m_highlighted_pos(0,0,0),
259 m_password(password),
260 m_chosen_auth_mech(AUTH_MECHANISM_NONE),
262 m_access_denied(false),
263 m_itemdef_received(false),
264 m_nodedef_received(false),
265 m_media_downloader(new ClientMediaDownloader()),
266 m_time_of_day_set(false),
267 m_last_time_of_day_f(-1),
268 m_time_of_day_update_timer(0),
269 m_recommended_send_interval(0.1),
270 m_removed_sounds_check_timer(0),
275 m_env.addPlayer(new LocalPlayer(this, playername));
277 m_cache_save_interval = g_settings->getU16("server_map_save_interval");
279 m_cache_smooth_lighting = g_settings->getBool("smooth_lighting");
280 m_cache_enable_shaders = g_settings->getBool("enable_shaders");
285 //request all client managed threads to stop
286 m_mesh_update_thread.Stop();
287 // Save local server map
289 infostream << "Local map saving ended." << std::endl;
290 m_localdb->endSave();
294 bool Client::isShutdown()
297 if (!m_mesh_update_thread.IsRunning()) return true;
306 m_mesh_update_thread.Stop();
307 m_mesh_update_thread.Wait();
308 while(!m_mesh_update_thread.m_queue_out.empty()) {
309 MeshUpdateResult r = m_mesh_update_thread.m_queue_out.pop_frontNoEx();
314 delete m_inventory_from_server;
316 // Delete detached inventories
317 for(std::map<std::string, Inventory*>::iterator
318 i = m_detached_inventories.begin();
319 i != m_detached_inventories.end(); i++){
323 // cleanup 3d model meshes on client shutdown
324 while (m_device->getSceneManager()->getMeshCache()->getMeshCount() != 0) {
325 scene::IAnimatedMesh * mesh =
326 m_device->getSceneManager()->getMeshCache()->getMeshByIndex(0);
329 m_device->getSceneManager()->getMeshCache()->removeMesh(mesh);
333 void Client::connect(Address address,
334 const std::string &address_name,
335 bool is_local_server)
337 DSTACK(__FUNCTION_NAME);
339 initLocalMapSaving(address, address_name, is_local_server);
341 m_con.SetTimeoutMs(0);
342 m_con.Connect(address);
345 void Client::step(float dtime)
347 DSTACK(__FUNCTION_NAME);
353 if(m_ignore_damage_timer > dtime)
354 m_ignore_damage_timer -= dtime;
356 m_ignore_damage_timer = 0.0;
358 m_animation_time += dtime;
359 if(m_animation_time > 60.0)
360 m_animation_time -= 60.0;
362 m_time_of_day_update_timer += dtime;
370 float &counter = m_packetcounter_timer;
376 infostream << "Client packetcounter (" << m_packetcounter_timer
378 m_packetcounter.print(infostream);
379 m_packetcounter.clear();
383 // UGLY hack to fix 2 second startup delay caused by non existent
384 // server client startup synchronization in local server or singleplayer mode
385 static bool initial_step = true;
387 initial_step = false;
389 else if(m_state == LC_Created) {
390 float &counter = m_connection_reinit_timer;
395 Player *myplayer = m_env.getLocalPlayer();
396 FATAL_ERROR_IF(myplayer == NULL, "Local player not found in environment.");
398 // Send TOSERVER_INIT_LEGACY
399 // [0] u16 TOSERVER_INIT_LEGACY
400 // [2] u8 SER_FMT_VER_HIGHEST_READ
401 // [3] u8[20] player_name
402 // [23] u8[28] password (new in some version)
403 // [51] u16 minimum supported network protocol version (added sometime)
404 // [53] u16 maximum supported network protocol version (added later than the previous one)
406 char pName[PLAYERNAME_SIZE];
407 char pPassword[PASSWORD_SIZE];
408 memset(pName, 0, PLAYERNAME_SIZE * sizeof(char));
409 memset(pPassword, 0, PASSWORD_SIZE * sizeof(char));
411 std::string hashed_password = translatePassword(myplayer->getName(), m_password);
412 snprintf(pName, PLAYERNAME_SIZE, "%s", myplayer->getName());
413 snprintf(pPassword, PASSWORD_SIZE, "%s", hashed_password.c_str());
415 sendLegacyInit(pName, pPassword);
416 if (LATEST_PROTOCOL_VERSION >= 25)
417 sendInit(myplayer->getName());
420 // Not connected, return
425 Do stuff if connected
429 Run Map's timers and unload unused data
431 const float map_timer_and_unload_dtime = 5.25;
432 if(m_map_timer_and_unload_interval.step(dtime, map_timer_and_unload_dtime)) {
433 ScopeProfiler sp(g_profiler, "Client: map timer and unload");
434 std::vector<v3s16> deleted_blocks;
435 m_env.getMap().timerUpdate(map_timer_and_unload_dtime,
436 g_settings->getFloat("client_unload_unused_data_timeout"),
441 NOTE: This loop is intentionally iterated the way it is.
444 std::vector<v3s16>::iterator i = deleted_blocks.begin();
445 std::vector<v3s16> sendlist;
447 if(sendlist.size() == 255 || i == deleted_blocks.end()) {
458 sendDeletedBlocks(sendlist);
460 if(i == deleted_blocks.end())
466 sendlist.push_back(*i);
474 // Control local player (0ms)
475 LocalPlayer *player = m_env.getLocalPlayer();
476 assert(player != NULL);
477 player->applyControl(dtime);
486 ClientEnvEvent event = m_env.getClientEvent();
487 if(event.type == CEE_NONE) {
490 else if(event.type == CEE_PLAYER_DAMAGE) {
491 if(m_ignore_damage_timer <= 0) {
492 u8 damage = event.player_damage.amount;
494 if(event.player_damage.send_to_server)
497 // Add to ClientEvent queue
499 event.type = CE_PLAYER_DAMAGE;
500 event.player_damage.amount = damage;
501 m_client_event_queue.push(event);
504 else if(event.type == CEE_PLAYER_BREATH) {
505 u16 breath = event.player_breath.amount;
513 float &counter = m_avg_rtt_timer;
517 // connectedAndInitialized() is true, peer exists.
518 float avg_rtt = getRTT();
519 infostream << "Client: avg_rtt=" << avg_rtt << std::endl;
523 Send player position to server
526 float &counter = m_playerpos_send_timer;
528 if((m_state == LC_Ready) && (counter >= m_recommended_send_interval))
536 Replace updated meshes
539 int num_processed_meshes = 0;
540 while(!m_mesh_update_thread.m_queue_out.empty())
542 num_processed_meshes++;
543 MeshUpdateResult r = m_mesh_update_thread.m_queue_out.pop_frontNoEx();
544 MapBlock *block = m_env.getMap().getBlockNoCreateNoEx(r.p);
546 // Delete the old mesh
547 if(block->mesh != NULL)
549 // TODO: Remove hardware buffers of meshbuffers of block->mesh
554 // Replace with the new mesh
555 block->mesh = r.mesh;
560 if(r.ack_block_to_server) {
570 if(num_processed_meshes > 0)
571 g_profiler->graphAdd("num_processed_meshes", num_processed_meshes);
577 if (m_media_downloader && m_media_downloader->isStarted()) {
578 m_media_downloader->step(this);
579 if (m_media_downloader->isDone()) {
581 delete m_media_downloader;
582 m_media_downloader = NULL;
587 If the server didn't update the inventory in a while, revert
588 the local inventory (so the player notices the lag problem
589 and knows something is wrong).
591 if(m_inventory_from_server)
593 float interval = 10.0;
594 float count_before = floor(m_inventory_from_server_age / interval);
596 m_inventory_from_server_age += dtime;
598 float count_after = floor(m_inventory_from_server_age / interval);
600 if(count_after != count_before)
602 // Do this every <interval> seconds after TOCLIENT_INVENTORY
603 // Reset the locally changed inventory to the authoritative inventory
604 Player *player = m_env.getLocalPlayer();
605 player->inventory = *m_inventory_from_server;
606 m_inventory_updated = true;
611 Update positions of sounds attached to objects
614 for(std::map<int, u16>::iterator
615 i = m_sounds_to_objects.begin();
616 i != m_sounds_to_objects.end(); i++)
618 int client_id = i->first;
619 u16 object_id = i->second;
620 ClientActiveObject *cao = m_env.getActiveObject(object_id);
623 v3f pos = cao->getPosition();
624 m_sound->updateSoundPosition(client_id, pos);
629 Handle removed remotely initiated sounds
631 m_removed_sounds_check_timer += dtime;
632 if(m_removed_sounds_check_timer >= 2.32) {
633 m_removed_sounds_check_timer = 0;
634 // Find removed sounds and clear references to them
635 std::vector<s32> removed_server_ids;
636 for(std::map<s32, int>::iterator
637 i = m_sounds_server_to_client.begin();
638 i != m_sounds_server_to_client.end();) {
639 s32 server_id = i->first;
640 int client_id = i->second;
642 if(!m_sound->soundExists(client_id)) {
643 m_sounds_server_to_client.erase(server_id);
644 m_sounds_client_to_server.erase(client_id);
645 m_sounds_to_objects.erase(client_id);
646 removed_server_ids.push_back(server_id);
651 if(!removed_server_ids.empty()) {
652 sendRemovedSounds(removed_server_ids);
657 if (m_localdb && m_localdb_save_interval.step(dtime,
658 m_cache_save_interval)) {
659 m_localdb->endSave();
660 m_localdb->beginSave();
664 bool Client::loadMedia(const std::string &data, const std::string &filename)
666 // Silly irrlicht's const-incorrectness
667 Buffer<char> data_rw(data.c_str(), data.size());
671 const char *image_ext[] = {
672 ".png", ".jpg", ".bmp", ".tga",
673 ".pcx", ".ppm", ".psd", ".wal", ".rgb",
676 name = removeStringEnd(filename, image_ext);
679 verbosestream<<"Client: Attempting to load image "
680 <<"file \""<<filename<<"\""<<std::endl;
682 io::IFileSystem *irrfs = m_device->getFileSystem();
683 video::IVideoDriver *vdrv = m_device->getVideoDriver();
685 // Create an irrlicht memory file
686 io::IReadFile *rfile = irrfs->createMemoryReadFile(
687 *data_rw, data_rw.getSize(), "_tempreadfile");
689 FATAL_ERROR_IF(!rfile, "Could not create irrlicht memory file.");
692 video::IImage *img = vdrv->createImageFromFile(rfile);
694 errorstream<<"Client: Cannot create image from data of "
695 <<"file \""<<filename<<"\""<<std::endl;
700 m_tsrc->insertSourceImage(filename, img);
707 const char *sound_ext[] = {
708 ".0.ogg", ".1.ogg", ".2.ogg", ".3.ogg", ".4.ogg",
709 ".5.ogg", ".6.ogg", ".7.ogg", ".8.ogg", ".9.ogg",
712 name = removeStringEnd(filename, sound_ext);
715 verbosestream<<"Client: Attempting to load sound "
716 <<"file \""<<filename<<"\""<<std::endl;
717 m_sound->loadSoundData(name, data);
721 const char *model_ext[] = {
722 ".x", ".b3d", ".md2", ".obj",
725 name = removeStringEnd(filename, model_ext);
728 verbosestream<<"Client: Storing model into memory: "
729 <<"\""<<filename<<"\""<<std::endl;
730 if(m_mesh_data.count(filename))
731 errorstream<<"Multiple models with name \""<<filename.c_str()
732 <<"\" found; replacing previous model"<<std::endl;
733 m_mesh_data[filename] = data;
737 errorstream<<"Client: Don't know how to load file \""
738 <<filename<<"\""<<std::endl;
742 // Virtual methods from con::PeerHandler
743 void Client::peerAdded(con::Peer *peer)
745 infostream<<"Client::peerAdded(): peer->id="
746 <<peer->id<<std::endl;
748 void Client::deletingPeer(con::Peer *peer, bool timeout)
750 infostream<<"Client::deletingPeer(): "
751 "Server Peer is getting deleted "
752 <<"(timeout="<<timeout<<")"<<std::endl;
757 u16 number of files requested
763 void Client::request_media(const std::vector<std::string> &file_requests)
765 std::ostringstream os(std::ios_base::binary);
766 writeU16(os, TOSERVER_REQUEST_MEDIA);
767 size_t file_requests_size = file_requests.size();
769 FATAL_ERROR_IF(file_requests_size > 0xFFFF, "Unsupported number of file requests");
771 // Packet dynamicly resized
772 NetworkPacket pkt(TOSERVER_REQUEST_MEDIA, 2 + 0);
774 pkt << (u16) (file_requests_size & 0xFFFF);
776 for(std::vector<std::string>::const_iterator i = file_requests.begin();
777 i != file_requests.end(); ++i) {
783 infostream << "Client: Sending media request list to server ("
784 << file_requests.size() << " files. packet size)" << std::endl;
787 void Client::received_media()
789 NetworkPacket pkt(TOSERVER_RECEIVED_MEDIA, 0);
791 infostream << "Client: Notifying server that we received all media"
795 void Client::initLocalMapSaving(const Address &address,
796 const std::string &hostname,
797 bool is_local_server)
799 if (!g_settings->getBool("enable_local_map_saving") || is_local_server) {
803 const std::string world_path = porting::path_user
804 + DIR_DELIM + "worlds"
805 + DIR_DELIM + "server_"
806 + hostname + "_" + to_string(address.getPort());
808 fs::CreateAllDirs(world_path);
810 m_localdb = new Database_SQLite3(world_path);
811 m_localdb->beginSave();
812 actionstream << "Local map saving started, map will be saved at '" << world_path << "'" << std::endl;
815 void Client::ReceiveAll()
817 DSTACK(__FUNCTION_NAME);
818 u32 start_ms = porting::getTimeMs();
821 // Limit time even if there would be huge amounts of data to
823 if(porting::getTimeMs() > start_ms + 100)
828 g_profiler->graphAdd("client_received_packets", 1);
830 catch(con::NoIncomingDataException &e) {
833 catch(con::InvalidIncomingDataException &e) {
834 infostream<<"Client::ReceiveAll(): "
835 "InvalidIncomingDataException: what()="
836 <<e.what()<<std::endl;
841 void Client::Receive()
843 DSTACK(__FUNCTION_NAME);
849 inline void Client::handleCommand(NetworkPacket* pkt)
851 const ToClientCommandHandler& opHandle = toClientCommandTable[pkt->getCommand()];
852 (this->*opHandle.handler)(pkt);
856 sender_peer_id given to this shall be quaranteed to be a valid peer
858 void Client::ProcessData(NetworkPacket *pkt)
860 DSTACK(__FUNCTION_NAME);
862 ToClientCommand command = (ToClientCommand) pkt->getCommand();
863 u32 sender_peer_id = pkt->getPeerId();
865 //infostream<<"Client: received command="<<command<<std::endl;
866 m_packetcounter.add((u16)command);
869 If this check is removed, be sure to change the queue
870 system to know the ids
872 if(sender_peer_id != PEER_ID_SERVER) {
873 infostream << "Client::ProcessData(): Discarding data not "
874 "coming from server: peer_id=" << sender_peer_id
879 // Command must be handled into ToClientCommandHandler
880 if (command >= TOCLIENT_NUM_MSG_TYPES) {
881 infostream << "Client: Ignoring unknown command "
882 << command << std::endl;
887 * Those packets are handled before m_server_ser_ver is set, it's normal
888 * But we must use the new ToClientConnectionState in the future,
891 if(toClientCommandTable[command].state == TOCLIENT_STATE_NOT_CONNECTED) {
896 if(m_server_ser_ver == SER_FMT_VER_INVALID) {
897 infostream << "Client: Server serialization"
898 " format invalid or not initialized."
899 " Skipping incoming command=" << command << std::endl;
904 Handle runtime commands
910 void Client::Send(NetworkPacket* pkt)
912 m_con.Send(PEER_ID_SERVER,
913 serverCommandFactoryTable[pkt->getCommand()].channel,
915 serverCommandFactoryTable[pkt->getCommand()].reliable);
918 void Client::interact(u8 action, const PointedThing& pointed)
920 if(m_state != LC_Ready) {
921 errorstream << "Client::interact() "
922 "Canceled (not connected)"
931 [5] u32 length of the next item
932 [9] serialized PointedThing
934 0: start digging (from undersurface) or use
935 1: stop digging (all parameters ignored)
937 3: place block or item (to abovesurface)
941 NetworkPacket pkt(TOSERVER_INTERACT, 1 + 2 + 0);
944 pkt << (u16)getPlayerItem();
946 std::ostringstream tmp_os(std::ios::binary);
947 pointed.serialize(tmp_os);
949 pkt.putLongString(tmp_os.str());
954 void Client::deleteAuthData()
959 switch (m_chosen_auth_mech) {
960 case AUTH_MECHANISM_FIRST_SRP:
962 case AUTH_MECHANISM_SRP:
963 case AUTH_MECHANISM_LEGACY_PASSWORD:
964 srp_user_delete((SRPUser *) m_auth_data);
967 case AUTH_MECHANISM_NONE:
973 AuthMechanism Client::choseAuthMech(const u32 mechs)
975 if (mechs & AUTH_MECHANISM_SRP)
976 return AUTH_MECHANISM_SRP;
978 if (mechs & AUTH_MECHANISM_FIRST_SRP)
979 return AUTH_MECHANISM_FIRST_SRP;
981 if (mechs & AUTH_MECHANISM_LEGACY_PASSWORD)
982 return AUTH_MECHANISM_LEGACY_PASSWORD;
984 return AUTH_MECHANISM_NONE;
987 void Client::sendLegacyInit(const char* playerName, const char* playerPassword)
989 NetworkPacket pkt(TOSERVER_INIT_LEGACY,
990 1 + PLAYERNAME_SIZE + PASSWORD_SIZE + 2 + 2);
992 pkt << (u8) SER_FMT_VER_HIGHEST_READ;
993 pkt.putRawString(playerName,PLAYERNAME_SIZE);
994 pkt.putRawString(playerPassword, PASSWORD_SIZE);
995 pkt << (u16) CLIENT_PROTOCOL_VERSION_MIN << (u16) CLIENT_PROTOCOL_VERSION_MAX;
1000 void Client::sendInit(const std::string &playerName)
1002 NetworkPacket pkt(TOSERVER_INIT, 1 + 2 + 2 + (1 + playerName.size()));
1004 // we don't support network compression yet
1005 u16 supp_comp_modes = NETPROTO_COMPRESSION_NONE;
1006 pkt << (u8) SER_FMT_VER_HIGHEST_READ << (u16) supp_comp_modes;
1007 pkt << (u16) CLIENT_PROTOCOL_VERSION_MIN << (u16) CLIENT_PROTOCOL_VERSION_MAX;
1013 void Client::startAuth(AuthMechanism chosen_auth_mechanism)
1015 m_chosen_auth_mech = chosen_auth_mechanism;
1017 switch (chosen_auth_mechanism) {
1018 case AUTH_MECHANISM_FIRST_SRP: {
1019 // send srp verifier to server
1020 NetworkPacket resp_pkt(TOSERVER_FIRST_SRP, 0);
1021 char *salt, *bytes_v;
1022 std::size_t len_salt, len_v;
1024 getSRPVerifier(getPlayerName(), m_password,
1025 &salt, &len_salt, &bytes_v, &len_v);
1027 << std::string((char*)salt, len_salt)
1028 << std::string((char*)bytes_v, len_v)
1029 << (u8)((m_password == "") ? 1 : 0);
1035 case AUTH_MECHANISM_SRP:
1036 case AUTH_MECHANISM_LEGACY_PASSWORD: {
1039 if (chosen_auth_mechanism == AUTH_MECHANISM_LEGACY_PASSWORD) {
1040 m_password = translatePassword(getPlayerName(), m_password);
1044 std::string playername_u = lowercase(getPlayerName());
1045 m_auth_data = srp_user_new(SRP_SHA256, SRP_NG_2048,
1046 getPlayerName().c_str(), playername_u.c_str(),
1047 (const unsigned char *) m_password.c_str(),
1048 m_password.length(), NULL, NULL);
1051 srp_user_start_authentication((struct SRPUser *) m_auth_data,
1052 NULL, NULL, 0, (unsigned char **) &bytes_A, &len_A);
1054 NetworkPacket resp_pkt(TOSERVER_SRP_BYTES_A, 0);
1055 resp_pkt << std::string(bytes_A, len_A) << based_on;
1060 case AUTH_MECHANISM_NONE:
1061 break; // not handled in this method
1065 void Client::sendDeletedBlocks(std::vector<v3s16> &blocks)
1067 NetworkPacket pkt(TOSERVER_DELETEDBLOCKS, 1 + sizeof(v3s16) * blocks.size());
1069 pkt << (u8) blocks.size();
1072 for(std::vector<v3s16>::iterator
1074 j != blocks.end(); ++j) {
1082 void Client::sendGotBlocks(v3s16 block)
1084 NetworkPacket pkt(TOSERVER_GOTBLOCKS, 1 + 6);
1085 pkt << (u8) 1 << block;
1089 void Client::sendRemovedSounds(std::vector<s32> &soundList)
1091 size_t server_ids = soundList.size();
1092 assert(server_ids <= 0xFFFF);
1094 NetworkPacket pkt(TOSERVER_REMOVED_SOUNDS, 2 + server_ids * 4);
1096 pkt << (u16) (server_ids & 0xFFFF);
1098 for(std::vector<s32>::iterator i = soundList.begin();
1099 i != soundList.end(); i++)
1105 void Client::sendNodemetaFields(v3s16 p, const std::string &formname,
1106 const StringMap &fields)
1108 size_t fields_size = fields.size();
1110 FATAL_ERROR_IF(fields_size > 0xFFFF, "Unsupported number of nodemeta fields");
1112 NetworkPacket pkt(TOSERVER_NODEMETA_FIELDS, 0);
1114 pkt << p << formname << (u16) (fields_size & 0xFFFF);
1116 StringMap::const_iterator it;
1117 for (it = fields.begin(); it != fields.end(); ++it) {
1118 const std::string &name = it->first;
1119 const std::string &value = it->second;
1121 pkt.putLongString(value);
1127 void Client::sendInventoryFields(const std::string &formname,
1128 const StringMap &fields)
1130 size_t fields_size = fields.size();
1131 FATAL_ERROR_IF(fields_size > 0xFFFF, "Unsupported number of inventory fields");
1133 NetworkPacket pkt(TOSERVER_INVENTORY_FIELDS, 0);
1134 pkt << formname << (u16) (fields_size & 0xFFFF);
1136 StringMap::const_iterator it;
1137 for (it = fields.begin(); it != fields.end(); ++it) {
1138 const std::string &name = it->first;
1139 const std::string &value = it->second;
1141 pkt.putLongString(value);
1147 void Client::sendInventoryAction(InventoryAction *a)
1149 std::ostringstream os(std::ios_base::binary);
1154 std::string s = os.str();
1156 NetworkPacket pkt(TOSERVER_INVENTORY_ACTION, s.size());
1157 pkt.putRawString(s.c_str(),s.size());
1162 void Client::sendChatMessage(const std::wstring &message)
1164 NetworkPacket pkt(TOSERVER_CHAT_MESSAGE, 2 + message.size() * sizeof(u16));
1171 void Client::sendChangePassword(const std::string &oldpassword,
1172 const std::string &newpassword)
1174 Player *player = m_env.getLocalPlayer();
1178 std::string playername = player->getName();
1179 if (m_proto_ver >= 25) {
1180 // get into sudo mode and then send new password to server
1181 m_password = oldpassword;
1182 m_new_password = newpassword;
1183 startAuth(choseAuthMech(m_sudo_auth_methods));
1185 std::string oldpwd = translatePassword(playername, oldpassword);
1186 std::string newpwd = translatePassword(playername, newpassword);
1188 NetworkPacket pkt(TOSERVER_PASSWORD_LEGACY, 2 * PASSWORD_SIZE);
1190 for (u8 i = 0; i < PASSWORD_SIZE; i++) {
1191 pkt << (u8) (i < oldpwd.length() ? oldpwd[i] : 0);
1194 for (u8 i = 0; i < PASSWORD_SIZE; i++) {
1195 pkt << (u8) (i < newpwd.length() ? newpwd[i] : 0);
1202 void Client::sendDamage(u8 damage)
1204 DSTACK(__FUNCTION_NAME);
1206 NetworkPacket pkt(TOSERVER_DAMAGE, sizeof(u8));
1211 void Client::sendBreath(u16 breath)
1213 DSTACK(__FUNCTION_NAME);
1215 NetworkPacket pkt(TOSERVER_BREATH, sizeof(u16));
1220 void Client::sendRespawn()
1222 DSTACK(__FUNCTION_NAME);
1224 NetworkPacket pkt(TOSERVER_RESPAWN, 0);
1228 void Client::sendReady()
1230 DSTACK(__FUNCTION_NAME);
1232 NetworkPacket pkt(TOSERVER_CLIENT_READY,
1233 1 + 1 + 1 + 1 + 2 + sizeof(char) * strlen(g_version_hash));
1235 pkt << (u8) VERSION_MAJOR << (u8) VERSION_MINOR << (u8) VERSION_PATCH
1236 << (u8) 0 << (u16) strlen(g_version_hash);
1238 pkt.putRawString(g_version_hash, (u16) strlen(g_version_hash));
1242 void Client::sendPlayerPos()
1244 LocalPlayer *myplayer = m_env.getLocalPlayer();
1245 if(myplayer == NULL)
1248 // Save bandwidth by only updating position when something changed
1249 if(myplayer->last_position == myplayer->getPosition() &&
1250 myplayer->last_speed == myplayer->getSpeed() &&
1251 myplayer->last_pitch == myplayer->getPitch() &&
1252 myplayer->last_yaw == myplayer->getYaw() &&
1253 myplayer->last_keyPressed == myplayer->keyPressed)
1256 myplayer->last_position = myplayer->getPosition();
1257 myplayer->last_speed = myplayer->getSpeed();
1258 myplayer->last_pitch = myplayer->getPitch();
1259 myplayer->last_yaw = myplayer->getYaw();
1260 myplayer->last_keyPressed = myplayer->keyPressed;
1264 //JMutexAutoLock lock(m_con_mutex); //bulk comment-out
1265 our_peer_id = m_con.GetPeerID();
1268 // Set peer id if not set already
1269 if(myplayer->peer_id == PEER_ID_INEXISTENT)
1270 myplayer->peer_id = our_peer_id;
1272 assert(myplayer->peer_id == our_peer_id);
1274 v3f pf = myplayer->getPosition();
1275 v3f sf = myplayer->getSpeed();
1276 s32 pitch = myplayer->getPitch() * 100;
1277 s32 yaw = myplayer->getYaw() * 100;
1278 u32 keyPressed = myplayer->keyPressed;
1280 v3s32 position(pf.X*100, pf.Y*100, pf.Z*100);
1281 v3s32 speed(sf.X*100, sf.Y*100, sf.Z*100);
1284 [0] v3s32 position*100
1285 [12] v3s32 speed*100
1286 [12+12] s32 pitch*100
1287 [12+12+4] s32 yaw*100
1288 [12+12+4+4] u32 keyPressed
1291 NetworkPacket pkt(TOSERVER_PLAYERPOS, 12 + 12 + 4 + 4 + 4);
1293 pkt << position << speed << pitch << yaw << keyPressed;
1298 void Client::sendPlayerItem(u16 item)
1300 Player *myplayer = m_env.getLocalPlayer();
1301 if(myplayer == NULL)
1304 u16 our_peer_id = m_con.GetPeerID();
1306 // Set peer id if not set already
1307 if(myplayer->peer_id == PEER_ID_INEXISTENT)
1308 myplayer->peer_id = our_peer_id;
1309 assert(myplayer->peer_id == our_peer_id);
1311 NetworkPacket pkt(TOSERVER_PLAYERITEM, 2);
1318 void Client::removeNode(v3s16 p)
1320 std::map<v3s16, MapBlock*> modified_blocks;
1323 m_env.getMap().removeNodeAndUpdate(p, modified_blocks);
1325 catch(InvalidPositionException &e) {
1328 for(std::map<v3s16, MapBlock *>::iterator
1329 i = modified_blocks.begin();
1330 i != modified_blocks.end(); ++i) {
1331 addUpdateMeshTaskWithEdge(i->first, false, true);
1335 void Client::addNode(v3s16 p, MapNode n, bool remove_metadata)
1337 //TimeTaker timer1("Client::addNode()");
1339 std::map<v3s16, MapBlock*> modified_blocks;
1342 //TimeTaker timer3("Client::addNode(): addNodeAndUpdate");
1343 m_env.getMap().addNodeAndUpdate(p, n, modified_blocks, remove_metadata);
1345 catch(InvalidPositionException &e) {
1348 for(std::map<v3s16, MapBlock *>::iterator
1349 i = modified_blocks.begin();
1350 i != modified_blocks.end(); ++i) {
1351 addUpdateMeshTaskWithEdge(i->first, false, true);
1355 void Client::setPlayerControl(PlayerControl &control)
1357 LocalPlayer *player = m_env.getLocalPlayer();
1358 assert(player != NULL);
1359 player->control = control;
1362 void Client::selectPlayerItem(u16 item)
1364 m_playeritem = item;
1365 m_inventory_updated = true;
1366 sendPlayerItem(item);
1369 // Returns true if the inventory of the local player has been
1370 // updated from the server. If it is true, it is set to false.
1371 bool Client::getLocalInventoryUpdated()
1373 bool updated = m_inventory_updated;
1374 m_inventory_updated = false;
1378 // Copies the inventory of the local player to parameter
1379 void Client::getLocalInventory(Inventory &dst)
1381 Player *player = m_env.getLocalPlayer();
1382 assert(player != NULL);
1383 dst = player->inventory;
1386 Inventory* Client::getInventory(const InventoryLocation &loc)
1389 case InventoryLocation::UNDEFINED:
1392 case InventoryLocation::CURRENT_PLAYER:
1394 Player *player = m_env.getLocalPlayer();
1395 assert(player != NULL);
1396 return &player->inventory;
1399 case InventoryLocation::PLAYER:
1401 Player *player = m_env.getPlayer(loc.name.c_str());
1404 return &player->inventory;
1407 case InventoryLocation::NODEMETA:
1409 NodeMetadata *meta = m_env.getMap().getNodeMetadata(loc.p);
1412 return meta->getInventory();
1415 case InventoryLocation::DETACHED:
1417 if(m_detached_inventories.count(loc.name) == 0)
1419 return m_detached_inventories[loc.name];
1423 FATAL_ERROR("Invalid inventory location type.");
1429 void Client::inventoryAction(InventoryAction *a)
1432 Send it to the server
1434 sendInventoryAction(a);
1437 Predict some local inventory changes
1439 a->clientApply(this, this);
1445 ClientActiveObject * Client::getSelectedActiveObject(
1447 v3f from_pos_f_on_map,
1448 core::line3d<f32> shootline_on_map
1451 std::vector<DistanceSortedActiveObject> objects;
1453 m_env.getActiveObjects(from_pos_f_on_map, max_d, objects);
1456 // After this, the closest object is the first in the array.
1457 std::sort(objects.begin(), objects.end());
1459 for(unsigned int i=0; i<objects.size(); i++)
1461 ClientActiveObject *obj = objects[i].obj;
1463 core::aabbox3d<f32> *selection_box = obj->getSelectionBox();
1464 if(selection_box == NULL)
1467 v3f pos = obj->getPosition();
1469 core::aabbox3d<f32> offsetted_box(
1470 selection_box->MinEdge + pos,
1471 selection_box->MaxEdge + pos
1474 if(offsetted_box.intersectsWithLine(shootline_on_map))
1483 std::list<std::string> Client::getConnectedPlayerNames()
1485 return m_env.getPlayerNames();
1488 float Client::getAnimationTime()
1490 return m_animation_time;
1493 int Client::getCrackLevel()
1495 return m_crack_level;
1498 void Client::setHighlighted(v3s16 pos, bool show_highlighted)
1500 m_show_highlighted = show_highlighted;
1501 v3s16 old_highlighted_pos = m_highlighted_pos;
1502 m_highlighted_pos = pos;
1503 addUpdateMeshTaskForNode(old_highlighted_pos, false, true);
1504 addUpdateMeshTaskForNode(m_highlighted_pos, false, true);
1507 void Client::setCrack(int level, v3s16 pos)
1509 int old_crack_level = m_crack_level;
1510 v3s16 old_crack_pos = m_crack_pos;
1512 m_crack_level = level;
1515 if(old_crack_level >= 0 && (level < 0 || pos != old_crack_pos))
1518 addUpdateMeshTaskForNode(old_crack_pos, false, true);
1520 if(level >= 0 && (old_crack_level < 0 || pos != old_crack_pos))
1523 addUpdateMeshTaskForNode(pos, false, true);
1529 Player *player = m_env.getLocalPlayer();
1530 assert(player != NULL);
1534 u16 Client::getBreath()
1536 Player *player = m_env.getLocalPlayer();
1537 assert(player != NULL);
1538 return player->getBreath();
1541 bool Client::getChatMessage(std::wstring &message)
1543 if(m_chat_queue.size() == 0)
1545 message = m_chat_queue.front();
1550 void Client::typeChatMessage(const std::wstring &message)
1552 // Discard empty line
1557 sendChatMessage(message);
1560 if (message[0] == L'/')
1562 m_chat_queue.push((std::wstring)L"issued command: " + message);
1566 LocalPlayer *player = m_env.getLocalPlayer();
1567 assert(player != NULL);
1568 std::wstring name = narrow_to_wide(player->getName());
1569 m_chat_queue.push((std::wstring)L"<" + name + L"> " + message);
1573 void Client::addUpdateMeshTask(v3s16 p, bool ack_to_server, bool urgent)
1575 MapBlock *b = m_env.getMap().getBlockNoCreateNoEx(p);
1580 Create a task to update the mesh of the block
1583 MeshMakeData *data = new MeshMakeData(this, m_cache_enable_shaders);
1586 //TimeTaker timer("data fill");
1588 // Debug: 1-6ms, avg=2ms
1590 data->setCrack(m_crack_level, m_crack_pos);
1591 data->setHighlighted(m_highlighted_pos, m_show_highlighted);
1592 data->setSmoothLighting(m_cache_smooth_lighting);
1595 // Add task to queue
1596 m_mesh_update_thread.m_queue_in.addBlock(p, data, ack_to_server, urgent);
1599 void Client::addUpdateMeshTaskWithEdge(v3s16 blockpos, bool ack_to_server, bool urgent)
1602 addUpdateMeshTask(blockpos, ack_to_server, urgent);
1604 catch(InvalidPositionException &e){}
1607 for (int i=0;i<6;i++)
1610 v3s16 p = blockpos + g_6dirs[i];
1611 addUpdateMeshTask(p, false, urgent);
1613 catch(InvalidPositionException &e){}
1617 void Client::addUpdateMeshTaskForNode(v3s16 nodepos, bool ack_to_server, bool urgent)
1621 infostream<<"Client::addUpdateMeshTaskForNode(): "
1622 <<"("<<p.X<<","<<p.Y<<","<<p.Z<<")"
1626 v3s16 blockpos = getNodeBlockPos(nodepos);
1627 v3s16 blockpos_relative = blockpos * MAP_BLOCKSIZE;
1630 addUpdateMeshTask(blockpos, ack_to_server, urgent);
1632 catch(InvalidPositionException &e) {}
1635 if(nodepos.X == blockpos_relative.X){
1637 v3s16 p = blockpos + v3s16(-1,0,0);
1638 addUpdateMeshTask(p, false, urgent);
1640 catch(InvalidPositionException &e){}
1643 if(nodepos.Y == blockpos_relative.Y){
1645 v3s16 p = blockpos + v3s16(0,-1,0);
1646 addUpdateMeshTask(p, false, urgent);
1648 catch(InvalidPositionException &e){}
1651 if(nodepos.Z == blockpos_relative.Z){
1653 v3s16 p = blockpos + v3s16(0,0,-1);
1654 addUpdateMeshTask(p, false, urgent);
1656 catch(InvalidPositionException &e){}
1660 ClientEvent Client::getClientEvent()
1663 if(m_client_event_queue.size() == 0) {
1664 event.type = CE_NONE;
1667 event = m_client_event_queue.front();
1668 m_client_event_queue.pop();
1673 float Client::mediaReceiveProgress()
1675 if (m_media_downloader)
1676 return m_media_downloader->getProgress();
1678 return 1.0; // downloader only exists when not yet done
1681 typedef struct TextureUpdateArgs {
1682 IrrlichtDevice *device;
1683 gui::IGUIEnvironment *guienv;
1686 const wchar_t* text_base;
1687 } TextureUpdateArgs;
1689 void texture_update_progress(void *args, u32 progress, u32 max_progress)
1691 TextureUpdateArgs* targs = (TextureUpdateArgs*) args;
1692 u16 cur_percent = ceil(progress / (double) max_progress * 100.);
1694 // update the loading menu -- if neccessary
1695 bool do_draw = false;
1696 u32 time_ms = targs->last_time_ms;
1697 if (cur_percent != targs->last_percent) {
1698 targs->last_percent = cur_percent;
1699 time_ms = getTimeMs();
1700 // only draw when the user will notice something:
1701 do_draw = (time_ms - targs->last_time_ms > 100);
1705 targs->last_time_ms = time_ms;
1706 std::basic_stringstream<wchar_t> strm;
1707 strm << targs->text_base << " " << targs->last_percent << "%...";
1708 draw_load_screen(strm.str(), targs->device, targs->guienv, 0,
1709 72 + (u16) ((18. / 100.) * (double) targs->last_percent));
1713 void Client::afterContentReceived(IrrlichtDevice *device)
1715 infostream<<"Client::afterContentReceived() started"<<std::endl;
1716 assert(m_itemdef_received); // pre-condition
1717 assert(m_nodedef_received); // pre-condition
1718 assert(mediaReceived()); // pre-condition
1720 const wchar_t* text = wgettext("Loading textures...");
1722 // Clear cached pre-scaled 2D GUI images, as this cache
1723 // might have images with the same name but different
1724 // content from previous sessions.
1725 guiScalingCacheClear(device->getVideoDriver());
1727 // Rebuild inherited images and recreate textures
1728 infostream<<"- Rebuilding images and textures"<<std::endl;
1729 draw_load_screen(text,device, guienv, 0, 70);
1730 m_tsrc->rebuildImagesAndTextures();
1734 infostream<<"- Rebuilding shaders"<<std::endl;
1735 text = wgettext("Rebuilding shaders...");
1736 draw_load_screen(text, device, guienv, 0, 71);
1737 m_shsrc->rebuildShaders();
1740 // Update node aliases
1741 infostream<<"- Updating node aliases"<<std::endl;
1742 text = wgettext("Initializing nodes...");
1743 draw_load_screen(text, device, guienv, 0, 72);
1744 m_nodedef->updateAliases(m_itemdef);
1745 std::string texture_path = g_settings->get("texture_path");
1746 if (texture_path != "" && fs::IsDir(texture_path))
1747 m_nodedef->applyTextureOverrides(texture_path + DIR_DELIM + "override.txt");
1748 m_nodedef->setNodeRegistrationStatus(true);
1749 m_nodedef->runNodeResolveCallbacks();
1752 // Update node textures and assign shaders to each tile
1753 infostream<<"- Updating node textures"<<std::endl;
1754 TextureUpdateArgs tu_args;
1755 tu_args.device = device;
1756 tu_args.guienv = guienv;
1757 tu_args.last_time_ms = getTimeMs();
1758 tu_args.last_percent = 0;
1759 tu_args.text_base = wgettext("Initializing nodes");
1760 m_nodedef->updateTextures(this, texture_update_progress, &tu_args);
1761 delete[] tu_args.text_base;
1763 // Preload item textures and meshes if configured to
1764 if(g_settings->getBool("preload_item_visuals"))
1766 verbosestream<<"Updating item textures and meshes"<<std::endl;
1767 text = wgettext("Item textures...");
1768 draw_load_screen(text, device, guienv, 0, 0);
1769 std::set<std::string> names = m_itemdef->getAll();
1770 size_t size = names.size();
1773 for(std::set<std::string>::const_iterator
1774 i = names.begin(); i != names.end(); ++i)
1776 // Asking for these caches the result
1777 m_itemdef->getInventoryTexture(*i, this);
1778 m_itemdef->getWieldMesh(*i, this);
1780 percent = (count * 100 / size * 0.2) + 80;
1781 draw_load_screen(text, device, guienv, 0, percent);
1786 // Start mesh update thread after setting up content definitions
1787 infostream<<"- Starting mesh update thread"<<std::endl;
1788 m_mesh_update_thread.Start();
1792 text = wgettext("Done!");
1793 draw_load_screen(text, device, guienv, 0, 100);
1794 infostream<<"Client::afterContentReceived() done"<<std::endl;
1798 float Client::getRTT(void)
1800 return m_con.getPeerStat(PEER_ID_SERVER,con::AVG_RTT);
1803 float Client::getCurRate(void)
1805 return ( m_con.getLocalStat(con::CUR_INC_RATE) +
1806 m_con.getLocalStat(con::CUR_DL_RATE));
1809 float Client::getAvgRate(void)
1811 return ( m_con.getLocalStat(con::AVG_INC_RATE) +
1812 m_con.getLocalStat(con::AVG_DL_RATE));
1815 void Client::makeScreenshot(IrrlichtDevice *device)
1817 irr::video::IVideoDriver *driver = device->getVideoDriver();
1818 irr::video::IImage* const raw_image = driver->createScreenShot();
1823 time_t t = time(NULL);
1824 struct tm *tm = localtime(&t);
1826 char timetstamp_c[64];
1827 strftime(timetstamp_c, sizeof(timetstamp_c), "%Y%m%d_%H%M%S", tm);
1829 std::string filename_base = g_settings->get("screenshot_path")
1831 + std::string("screenshot_")
1832 + std::string(timetstamp_c);
1833 std::string filename_ext = ".png";
1834 std::string filename;
1836 // Try to find a unique filename
1837 unsigned serial = 0;
1839 while (serial < SCREENSHOT_MAX_SERIAL_TRIES) {
1840 filename = filename_base + (serial > 0 ? ("_" + itos(serial)) : "") + filename_ext;
1841 std::ifstream tmp(filename.c_str());
1843 break; // File did not apparently exist, we'll go with it
1847 if (serial == SCREENSHOT_MAX_SERIAL_TRIES) {
1848 infostream << "Could not find suitable filename for screenshot" << std::endl;
1850 irr::video::IImage* const image =
1851 driver->createImage(video::ECF_R8G8B8, raw_image->getDimension());
1854 raw_image->copyTo(image);
1856 std::ostringstream sstr;
1857 if (driver->writeImageToFile(image, filename.c_str())) {
1858 sstr << "Saved screenshot to '" << filename << "'";
1860 sstr << "Failed to save screenshot '" << filename << "'";
1862 m_chat_queue.push(narrow_to_wide(sstr.str()));
1863 infostream << sstr.str() << std::endl;
1871 // IGameDef interface
1873 IItemDefManager* Client::getItemDefManager()
1877 INodeDefManager* Client::getNodeDefManager()
1881 ICraftDefManager* Client::getCraftDefManager()
1884 //return m_craftdef;
1886 ITextureSource* Client::getTextureSource()
1890 IShaderSource* Client::getShaderSource()
1894 scene::ISceneManager* Client::getSceneManager()
1896 return m_device->getSceneManager();
1898 u16 Client::allocateUnknownNodeId(const std::string &name)
1900 errorstream << "Client::allocateUnknownNodeId(): "
1901 << "Client cannot allocate node IDs" << std::endl;
1902 FATAL_ERROR("Client allocated unknown node");
1904 return CONTENT_IGNORE;
1906 ISoundManager* Client::getSoundManager()
1910 MtEventManager* Client::getEventManager()
1915 ParticleManager* Client::getParticleManager()
1917 return &m_particle_manager;
1920 scene::IAnimatedMesh* Client::getMesh(const std::string &filename)
1922 StringMap::const_iterator it = m_mesh_data.find(filename);
1923 if (it == m_mesh_data.end()) {
1924 errorstream << "Client::getMesh(): Mesh not found: \"" << filename
1925 << "\"" << std::endl;
1928 const std::string &data = it->second;
1929 scene::ISceneManager *smgr = m_device->getSceneManager();
1931 // Create the mesh, remove it from cache and return it
1932 // This allows unique vertex colors and other properties for each instance
1933 Buffer<char> data_rw(data.c_str(), data.size()); // Const-incorrect Irrlicht
1934 io::IFileSystem *irrfs = m_device->getFileSystem();
1935 io::IReadFile *rfile = irrfs->createMemoryReadFile(
1936 *data_rw, data_rw.getSize(), filename.c_str());
1937 FATAL_ERROR_IF(!rfile, "Could not create/open RAM file");
1939 scene::IAnimatedMesh *mesh = smgr->getMesh(rfile);
1941 // NOTE: By playing with Irrlicht refcounts, maybe we could cache a bunch
1942 // of uniquely named instances and re-use them
1944 smgr->getMeshCache()->removeMesh(mesh);