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"
42 #include "nodemetadata.h"
45 #include "clientmap.h"
46 #include "clientmedia.h"
48 #include "IMeshCache.h"
51 #include "drawscene.h"
52 #include "database-sqlite3.h"
53 #include "serialization.h"
54 #include "guiscalingfilter.h"
56 extern gui::IGUIEnvironment* guienv;
62 QueuedMeshUpdate::QueuedMeshUpdate():
65 ack_block_to_server(false)
69 QueuedMeshUpdate::~QueuedMeshUpdate()
79 MeshUpdateQueue::MeshUpdateQueue()
83 MeshUpdateQueue::~MeshUpdateQueue()
85 JMutexAutoLock lock(m_mutex);
87 for(std::vector<QueuedMeshUpdate*>::iterator
89 i != m_queue.end(); i++)
91 QueuedMeshUpdate *q = *i;
97 peer_id=0 adds with nobody to send to
99 void MeshUpdateQueue::addBlock(v3s16 p, MeshMakeData *data, bool ack_block_to_server, bool urgent)
101 DSTACK(__FUNCTION_NAME);
103 assert(data); // pre-condition
105 JMutexAutoLock lock(m_mutex);
111 Find if block is already in queue.
112 If it is, update the data and quit.
114 for(std::vector<QueuedMeshUpdate*>::iterator
116 i != m_queue.end(); i++)
118 QueuedMeshUpdate *q = *i;
124 if(ack_block_to_server)
125 q->ack_block_to_server = true;
133 QueuedMeshUpdate *q = new QueuedMeshUpdate;
136 q->ack_block_to_server = ack_block_to_server;
137 m_queue.push_back(q);
140 // Returned pointer must be deleted
141 // Returns NULL if queue is empty
142 QueuedMeshUpdate *MeshUpdateQueue::pop()
144 JMutexAutoLock lock(m_mutex);
146 bool must_be_urgent = !m_urgents.empty();
147 for(std::vector<QueuedMeshUpdate*>::iterator
149 i != m_queue.end(); i++)
151 QueuedMeshUpdate *q = *i;
152 if(must_be_urgent && m_urgents.count(q->p) == 0)
155 m_urgents.erase(q->p);
165 void MeshUpdateThread::enqueueUpdate(v3s16 p, MeshMakeData *data,
166 bool ack_block_to_server, bool urgent)
168 m_queue_in.addBlock(p, data, ack_block_to_server, urgent);
172 void MeshUpdateThread::doUpdate()
175 while ((q = m_queue_in.pop())) {
177 ScopeProfiler sp(g_profiler, "Client: Mesh making");
179 MapBlockMesh *mesh_new = new MapBlockMesh(q->data, m_camera_offset);
184 r.ack_block_to_server = q->ack_block_to_server;
186 m_queue_out.push_back(r);
197 IrrlichtDevice *device,
198 const char *playername,
199 std::string password,
200 MapDrawControl &control,
201 IWritableTextureSource *tsrc,
202 IWritableShaderSource *shsrc,
203 IWritableItemDefManager *itemdef,
204 IWritableNodeDefManager *nodedef,
205 ISoundManager *sound,
206 MtEventManager *event,
209 m_packetcounter_timer(0.0),
210 m_connection_reinit_timer(0.1),
211 m_avg_rtt_timer(0.0),
212 m_playerpos_send_timer(0.0),
213 m_ignore_damage_timer(0.0),
220 m_mesh_update_thread(),
222 new ClientMap(this, this, control,
223 device->getSceneManager()->getRootSceneNode(),
224 device->getSceneManager(), 666),
225 device->getSceneManager(),
228 m_particle_manager(&m_env),
229 m_con(PROTOCOL_ID, 512, CONNECTION_TIMEOUT, ipv6, this),
231 m_server_ser_ver(SER_FMT_VER_INVALID),
233 m_inventory_updated(false),
234 m_inventory_from_server(NULL),
235 m_inventory_from_server_age(0.0),
236 m_show_highlighted(false),
240 m_highlighted_pos(0,0,0),
242 m_password(password),
243 m_chosen_auth_mech(AUTH_MECHANISM_NONE),
245 m_access_denied(false),
246 m_itemdef_received(false),
247 m_nodedef_received(false),
248 m_media_downloader(new ClientMediaDownloader()),
249 m_time_of_day_set(false),
250 m_last_time_of_day_f(-1),
251 m_time_of_day_update_timer(0),
252 m_recommended_send_interval(0.1),
253 m_removed_sounds_check_timer(0),
258 m_env.addPlayer(new LocalPlayer(this, playername));
260 m_mapper = new Mapper(device, this);
261 m_cache_save_interval = g_settings->getU16("server_map_save_interval");
263 m_cache_smooth_lighting = g_settings->getBool("smooth_lighting");
264 m_cache_enable_shaders = g_settings->getBool("enable_shaders");
269 //request all client managed threads to stop
270 m_mesh_update_thread.Stop();
271 // Save local server map
273 infostream << "Local map saving ended." << std::endl;
274 m_localdb->endSave();
278 bool Client::isShutdown()
281 if (!m_mesh_update_thread.IsRunning()) return true;
290 m_mesh_update_thread.Stop();
291 m_mesh_update_thread.Wait();
292 while(!m_mesh_update_thread.m_queue_out.empty()) {
293 MeshUpdateResult r = m_mesh_update_thread.m_queue_out.pop_frontNoEx();
298 delete m_inventory_from_server;
300 // Delete detached inventories
301 for(std::map<std::string, Inventory*>::iterator
302 i = m_detached_inventories.begin();
303 i != m_detached_inventories.end(); i++){
307 // cleanup 3d model meshes on client shutdown
308 while (m_device->getSceneManager()->getMeshCache()->getMeshCount() != 0) {
309 scene::IAnimatedMesh * mesh =
310 m_device->getSceneManager()->getMeshCache()->getMeshByIndex(0);
313 m_device->getSceneManager()->getMeshCache()->removeMesh(mesh);
317 void Client::connect(Address address,
318 const std::string &address_name,
319 bool is_local_server)
321 DSTACK(__FUNCTION_NAME);
323 initLocalMapSaving(address, address_name, is_local_server);
325 m_con.SetTimeoutMs(0);
326 m_con.Connect(address);
329 void Client::step(float dtime)
331 DSTACK(__FUNCTION_NAME);
337 if(m_ignore_damage_timer > dtime)
338 m_ignore_damage_timer -= dtime;
340 m_ignore_damage_timer = 0.0;
342 m_animation_time += dtime;
343 if(m_animation_time > 60.0)
344 m_animation_time -= 60.0;
346 m_time_of_day_update_timer += dtime;
354 float &counter = m_packetcounter_timer;
360 infostream << "Client packetcounter (" << m_packetcounter_timer
362 m_packetcounter.print(infostream);
363 m_packetcounter.clear();
367 // UGLY hack to fix 2 second startup delay caused by non existent
368 // server client startup synchronization in local server or singleplayer mode
369 static bool initial_step = true;
371 initial_step = false;
373 else if(m_state == LC_Created) {
374 float &counter = m_connection_reinit_timer;
379 Player *myplayer = m_env.getLocalPlayer();
380 FATAL_ERROR_IF(myplayer == NULL, "Local player not found in environment.");
382 // Send TOSERVER_INIT_LEGACY
383 // [0] u16 TOSERVER_INIT_LEGACY
384 // [2] u8 SER_FMT_VER_HIGHEST_READ
385 // [3] u8[20] player_name
386 // [23] u8[28] password (new in some version)
387 // [51] u16 minimum supported network protocol version (added sometime)
388 // [53] u16 maximum supported network protocol version (added later than the previous one)
390 char pName[PLAYERNAME_SIZE];
391 char pPassword[PASSWORD_SIZE];
392 memset(pName, 0, PLAYERNAME_SIZE * sizeof(char));
393 memset(pPassword, 0, PASSWORD_SIZE * sizeof(char));
395 std::string hashed_password = translatePassword(myplayer->getName(), m_password);
396 snprintf(pName, PLAYERNAME_SIZE, "%s", myplayer->getName());
397 snprintf(pPassword, PASSWORD_SIZE, "%s", hashed_password.c_str());
399 sendLegacyInit(pName, pPassword);
400 if (LATEST_PROTOCOL_VERSION >= 25)
401 sendInit(myplayer->getName());
404 // Not connected, return
409 Do stuff if connected
413 Run Map's timers and unload unused data
415 const float map_timer_and_unload_dtime = 5.25;
416 if(m_map_timer_and_unload_interval.step(dtime, map_timer_and_unload_dtime)) {
417 ScopeProfiler sp(g_profiler, "Client: map timer and unload");
418 std::vector<v3s16> deleted_blocks;
419 m_env.getMap().timerUpdate(map_timer_and_unload_dtime,
420 g_settings->getFloat("client_unload_unused_data_timeout"),
425 NOTE: This loop is intentionally iterated the way it is.
428 std::vector<v3s16>::iterator i = deleted_blocks.begin();
429 std::vector<v3s16> sendlist;
431 if(sendlist.size() == 255 || i == deleted_blocks.end()) {
442 sendDeletedBlocks(sendlist);
444 if(i == deleted_blocks.end())
450 sendlist.push_back(*i);
458 // Control local player (0ms)
459 LocalPlayer *player = m_env.getLocalPlayer();
460 assert(player != NULL);
461 player->applyControl(dtime);
470 ClientEnvEvent event = m_env.getClientEvent();
471 if(event.type == CEE_NONE) {
474 else if(event.type == CEE_PLAYER_DAMAGE) {
475 if(m_ignore_damage_timer <= 0) {
476 u8 damage = event.player_damage.amount;
478 if(event.player_damage.send_to_server)
481 // Add to ClientEvent queue
483 event.type = CE_PLAYER_DAMAGE;
484 event.player_damage.amount = damage;
485 m_client_event_queue.push(event);
488 else if(event.type == CEE_PLAYER_BREATH) {
489 u16 breath = event.player_breath.amount;
497 float &counter = m_avg_rtt_timer;
501 // connectedAndInitialized() is true, peer exists.
502 float avg_rtt = getRTT();
503 infostream << "Client: avg_rtt=" << avg_rtt << std::endl;
507 Send player position to server
510 float &counter = m_playerpos_send_timer;
512 if((m_state == LC_Ready) && (counter >= m_recommended_send_interval))
520 Replace updated meshes
523 int num_processed_meshes = 0;
524 while (!m_mesh_update_thread.m_queue_out.empty())
526 num_processed_meshes++;
527 MeshUpdateResult r = m_mesh_update_thread.m_queue_out.pop_frontNoEx();
528 MapBlock *block = m_env.getMap().getBlockNoCreateNoEx(r.p);
529 MinimapMapblock *minimap_mapblock = NULL;
531 // Delete the old mesh
532 if (block->mesh != NULL) {
538 minimap_mapblock = r.mesh->getMinimapMapblock();
540 if (r.mesh && r.mesh->getMesh()->getMeshBufferCount() == 0) {
544 // Replace with the new mesh
545 block->mesh = r.mesh;
549 minimap_mapblock = NULL;
552 m_mapper->addBlock(r.p, minimap_mapblock);
554 if (r.ack_block_to_server) {
564 if (num_processed_meshes > 0)
565 g_profiler->graphAdd("num_processed_meshes", num_processed_meshes);
571 if (m_media_downloader && m_media_downloader->isStarted()) {
572 m_media_downloader->step(this);
573 if (m_media_downloader->isDone()) {
575 delete m_media_downloader;
576 m_media_downloader = NULL;
581 If the server didn't update the inventory in a while, revert
582 the local inventory (so the player notices the lag problem
583 and knows something is wrong).
585 if(m_inventory_from_server)
587 float interval = 10.0;
588 float count_before = floor(m_inventory_from_server_age / interval);
590 m_inventory_from_server_age += dtime;
592 float count_after = floor(m_inventory_from_server_age / interval);
594 if(count_after != count_before)
596 // Do this every <interval> seconds after TOCLIENT_INVENTORY
597 // Reset the locally changed inventory to the authoritative inventory
598 Player *player = m_env.getLocalPlayer();
599 player->inventory = *m_inventory_from_server;
600 m_inventory_updated = true;
605 Update positions of sounds attached to objects
608 for(std::map<int, u16>::iterator
609 i = m_sounds_to_objects.begin();
610 i != m_sounds_to_objects.end(); i++)
612 int client_id = i->first;
613 u16 object_id = i->second;
614 ClientActiveObject *cao = m_env.getActiveObject(object_id);
617 v3f pos = cao->getPosition();
618 m_sound->updateSoundPosition(client_id, pos);
623 Handle removed remotely initiated sounds
625 m_removed_sounds_check_timer += dtime;
626 if(m_removed_sounds_check_timer >= 2.32) {
627 m_removed_sounds_check_timer = 0;
628 // Find removed sounds and clear references to them
629 std::vector<s32> removed_server_ids;
630 for(std::map<s32, int>::iterator
631 i = m_sounds_server_to_client.begin();
632 i != m_sounds_server_to_client.end();) {
633 s32 server_id = i->first;
634 int client_id = i->second;
636 if(!m_sound->soundExists(client_id)) {
637 m_sounds_server_to_client.erase(server_id);
638 m_sounds_client_to_server.erase(client_id);
639 m_sounds_to_objects.erase(client_id);
640 removed_server_ids.push_back(server_id);
645 if(!removed_server_ids.empty()) {
646 sendRemovedSounds(removed_server_ids);
651 if (m_localdb && m_localdb_save_interval.step(dtime,
652 m_cache_save_interval)) {
653 m_localdb->endSave();
654 m_localdb->beginSave();
658 bool Client::loadMedia(const std::string &data, const std::string &filename)
660 // Silly irrlicht's const-incorrectness
661 Buffer<char> data_rw(data.c_str(), data.size());
665 const char *image_ext[] = {
666 ".png", ".jpg", ".bmp", ".tga",
667 ".pcx", ".ppm", ".psd", ".wal", ".rgb",
670 name = removeStringEnd(filename, image_ext);
673 verbosestream<<"Client: Attempting to load image "
674 <<"file \""<<filename<<"\""<<std::endl;
676 io::IFileSystem *irrfs = m_device->getFileSystem();
677 video::IVideoDriver *vdrv = m_device->getVideoDriver();
679 // Create an irrlicht memory file
680 io::IReadFile *rfile = irrfs->createMemoryReadFile(
681 *data_rw, data_rw.getSize(), "_tempreadfile");
683 FATAL_ERROR_IF(!rfile, "Could not create irrlicht memory file.");
686 video::IImage *img = vdrv->createImageFromFile(rfile);
688 errorstream<<"Client: Cannot create image from data of "
689 <<"file \""<<filename<<"\""<<std::endl;
694 m_tsrc->insertSourceImage(filename, img);
701 const char *sound_ext[] = {
702 ".0.ogg", ".1.ogg", ".2.ogg", ".3.ogg", ".4.ogg",
703 ".5.ogg", ".6.ogg", ".7.ogg", ".8.ogg", ".9.ogg",
706 name = removeStringEnd(filename, sound_ext);
709 verbosestream<<"Client: Attempting to load sound "
710 <<"file \""<<filename<<"\""<<std::endl;
711 m_sound->loadSoundData(name, data);
715 const char *model_ext[] = {
716 ".x", ".b3d", ".md2", ".obj",
719 name = removeStringEnd(filename, model_ext);
722 verbosestream<<"Client: Storing model into memory: "
723 <<"\""<<filename<<"\""<<std::endl;
724 if(m_mesh_data.count(filename))
725 errorstream<<"Multiple models with name \""<<filename.c_str()
726 <<"\" found; replacing previous model"<<std::endl;
727 m_mesh_data[filename] = data;
731 errorstream<<"Client: Don't know how to load file \""
732 <<filename<<"\""<<std::endl;
736 // Virtual methods from con::PeerHandler
737 void Client::peerAdded(con::Peer *peer)
739 infostream<<"Client::peerAdded(): peer->id="
740 <<peer->id<<std::endl;
742 void Client::deletingPeer(con::Peer *peer, bool timeout)
744 infostream<<"Client::deletingPeer(): "
745 "Server Peer is getting deleted "
746 <<"(timeout="<<timeout<<")"<<std::endl;
751 u16 number of files requested
757 void Client::request_media(const std::vector<std::string> &file_requests)
759 std::ostringstream os(std::ios_base::binary);
760 writeU16(os, TOSERVER_REQUEST_MEDIA);
761 size_t file_requests_size = file_requests.size();
763 FATAL_ERROR_IF(file_requests_size > 0xFFFF, "Unsupported number of file requests");
765 // Packet dynamicly resized
766 NetworkPacket pkt(TOSERVER_REQUEST_MEDIA, 2 + 0);
768 pkt << (u16) (file_requests_size & 0xFFFF);
770 for(std::vector<std::string>::const_iterator i = file_requests.begin();
771 i != file_requests.end(); ++i) {
777 infostream << "Client: Sending media request list to server ("
778 << file_requests.size() << " files. packet size)" << std::endl;
781 void Client::received_media()
783 NetworkPacket pkt(TOSERVER_RECEIVED_MEDIA, 0);
785 infostream << "Client: Notifying server that we received all media"
789 void Client::initLocalMapSaving(const Address &address,
790 const std::string &hostname,
791 bool is_local_server)
793 if (!g_settings->getBool("enable_local_map_saving") || is_local_server) {
797 const std::string world_path = porting::path_user
798 + DIR_DELIM + "worlds"
799 + DIR_DELIM + "server_"
800 + hostname + "_" + to_string(address.getPort());
802 fs::CreateAllDirs(world_path);
804 m_localdb = new Database_SQLite3(world_path);
805 m_localdb->beginSave();
806 actionstream << "Local map saving started, map will be saved at '" << world_path << "'" << std::endl;
809 void Client::ReceiveAll()
811 DSTACK(__FUNCTION_NAME);
812 u32 start_ms = porting::getTimeMs();
815 // Limit time even if there would be huge amounts of data to
817 if(porting::getTimeMs() > start_ms + 100)
822 g_profiler->graphAdd("client_received_packets", 1);
824 catch(con::NoIncomingDataException &e) {
827 catch(con::InvalidIncomingDataException &e) {
828 infostream<<"Client::ReceiveAll(): "
829 "InvalidIncomingDataException: what()="
830 <<e.what()<<std::endl;
835 void Client::Receive()
837 DSTACK(__FUNCTION_NAME);
843 inline void Client::handleCommand(NetworkPacket* pkt)
845 const ToClientCommandHandler& opHandle = toClientCommandTable[pkt->getCommand()];
846 (this->*opHandle.handler)(pkt);
850 sender_peer_id given to this shall be quaranteed to be a valid peer
852 void Client::ProcessData(NetworkPacket *pkt)
854 DSTACK(__FUNCTION_NAME);
856 ToClientCommand command = (ToClientCommand) pkt->getCommand();
857 u32 sender_peer_id = pkt->getPeerId();
859 //infostream<<"Client: received command="<<command<<std::endl;
860 m_packetcounter.add((u16)command);
863 If this check is removed, be sure to change the queue
864 system to know the ids
866 if(sender_peer_id != PEER_ID_SERVER) {
867 infostream << "Client::ProcessData(): Discarding data not "
868 "coming from server: peer_id=" << sender_peer_id
873 // Command must be handled into ToClientCommandHandler
874 if (command >= TOCLIENT_NUM_MSG_TYPES) {
875 infostream << "Client: Ignoring unknown command "
876 << command << std::endl;
881 * Those packets are handled before m_server_ser_ver is set, it's normal
882 * But we must use the new ToClientConnectionState in the future,
885 if(toClientCommandTable[command].state == TOCLIENT_STATE_NOT_CONNECTED) {
890 if(m_server_ser_ver == SER_FMT_VER_INVALID) {
891 infostream << "Client: Server serialization"
892 " format invalid or not initialized."
893 " Skipping incoming command=" << command << std::endl;
898 Handle runtime commands
904 void Client::Send(NetworkPacket* pkt)
906 m_con.Send(PEER_ID_SERVER,
907 serverCommandFactoryTable[pkt->getCommand()].channel,
909 serverCommandFactoryTable[pkt->getCommand()].reliable);
912 void Client::interact(u8 action, const PointedThing& pointed)
914 if(m_state != LC_Ready) {
915 errorstream << "Client::interact() "
916 "Canceled (not connected)"
925 [5] u32 length of the next item
926 [9] serialized PointedThing
928 0: start digging (from undersurface) or use
929 1: stop digging (all parameters ignored)
931 3: place block or item (to abovesurface)
935 NetworkPacket pkt(TOSERVER_INTERACT, 1 + 2 + 0);
938 pkt << (u16)getPlayerItem();
940 std::ostringstream tmp_os(std::ios::binary);
941 pointed.serialize(tmp_os);
943 pkt.putLongString(tmp_os.str());
948 void Client::deleteAuthData()
953 switch (m_chosen_auth_mech) {
954 case AUTH_MECHANISM_FIRST_SRP:
956 case AUTH_MECHANISM_SRP:
957 case AUTH_MECHANISM_LEGACY_PASSWORD:
958 srp_user_delete((SRPUser *) m_auth_data);
961 case AUTH_MECHANISM_NONE:
967 AuthMechanism Client::choseAuthMech(const u32 mechs)
969 if (mechs & AUTH_MECHANISM_SRP)
970 return AUTH_MECHANISM_SRP;
972 if (mechs & AUTH_MECHANISM_FIRST_SRP)
973 return AUTH_MECHANISM_FIRST_SRP;
975 if (mechs & AUTH_MECHANISM_LEGACY_PASSWORD)
976 return AUTH_MECHANISM_LEGACY_PASSWORD;
978 return AUTH_MECHANISM_NONE;
981 void Client::sendLegacyInit(const char* playerName, const char* playerPassword)
983 NetworkPacket pkt(TOSERVER_INIT_LEGACY,
984 1 + PLAYERNAME_SIZE + PASSWORD_SIZE + 2 + 2);
986 pkt << (u8) SER_FMT_VER_HIGHEST_READ;
987 pkt.putRawString(playerName,PLAYERNAME_SIZE);
988 pkt.putRawString(playerPassword, PASSWORD_SIZE);
989 pkt << (u16) CLIENT_PROTOCOL_VERSION_MIN << (u16) CLIENT_PROTOCOL_VERSION_MAX;
994 void Client::sendInit(const std::string &playerName)
996 NetworkPacket pkt(TOSERVER_INIT, 1 + 2 + 2 + (1 + playerName.size()));
998 // we don't support network compression yet
999 u16 supp_comp_modes = NETPROTO_COMPRESSION_NONE;
1000 pkt << (u8) SER_FMT_VER_HIGHEST_READ << (u16) supp_comp_modes;
1001 pkt << (u16) CLIENT_PROTOCOL_VERSION_MIN << (u16) CLIENT_PROTOCOL_VERSION_MAX;
1007 void Client::startAuth(AuthMechanism chosen_auth_mechanism)
1009 m_chosen_auth_mech = chosen_auth_mechanism;
1011 switch (chosen_auth_mechanism) {
1012 case AUTH_MECHANISM_FIRST_SRP: {
1013 // send srp verifier to server
1014 NetworkPacket resp_pkt(TOSERVER_FIRST_SRP, 0);
1015 char *salt, *bytes_v;
1016 std::size_t len_salt, len_v;
1018 getSRPVerifier(getPlayerName(), m_password,
1019 &salt, &len_salt, &bytes_v, &len_v);
1021 << std::string((char*)salt, len_salt)
1022 << std::string((char*)bytes_v, len_v)
1023 << (u8)((m_password == "") ? 1 : 0);
1029 case AUTH_MECHANISM_SRP:
1030 case AUTH_MECHANISM_LEGACY_PASSWORD: {
1033 if (chosen_auth_mechanism == AUTH_MECHANISM_LEGACY_PASSWORD) {
1034 m_password = translatePassword(getPlayerName(), m_password);
1038 std::string playername_u = lowercase(getPlayerName());
1039 m_auth_data = srp_user_new(SRP_SHA256, SRP_NG_2048,
1040 getPlayerName().c_str(), playername_u.c_str(),
1041 (const unsigned char *) m_password.c_str(),
1042 m_password.length(), NULL, NULL);
1045 srp_user_start_authentication((struct SRPUser *) m_auth_data,
1046 NULL, NULL, 0, (unsigned char **) &bytes_A, &len_A);
1048 NetworkPacket resp_pkt(TOSERVER_SRP_BYTES_A, 0);
1049 resp_pkt << std::string(bytes_A, len_A) << based_on;
1054 case AUTH_MECHANISM_NONE:
1055 break; // not handled in this method
1059 void Client::sendDeletedBlocks(std::vector<v3s16> &blocks)
1061 NetworkPacket pkt(TOSERVER_DELETEDBLOCKS, 1 + sizeof(v3s16) * blocks.size());
1063 pkt << (u8) blocks.size();
1066 for(std::vector<v3s16>::iterator
1068 j != blocks.end(); ++j) {
1076 void Client::sendGotBlocks(v3s16 block)
1078 NetworkPacket pkt(TOSERVER_GOTBLOCKS, 1 + 6);
1079 pkt << (u8) 1 << block;
1083 void Client::sendRemovedSounds(std::vector<s32> &soundList)
1085 size_t server_ids = soundList.size();
1086 assert(server_ids <= 0xFFFF);
1088 NetworkPacket pkt(TOSERVER_REMOVED_SOUNDS, 2 + server_ids * 4);
1090 pkt << (u16) (server_ids & 0xFFFF);
1092 for(std::vector<s32>::iterator i = soundList.begin();
1093 i != soundList.end(); i++)
1099 void Client::sendNodemetaFields(v3s16 p, const std::string &formname,
1100 const StringMap &fields)
1102 size_t fields_size = fields.size();
1104 FATAL_ERROR_IF(fields_size > 0xFFFF, "Unsupported number of nodemeta fields");
1106 NetworkPacket pkt(TOSERVER_NODEMETA_FIELDS, 0);
1108 pkt << p << formname << (u16) (fields_size & 0xFFFF);
1110 StringMap::const_iterator it;
1111 for (it = fields.begin(); it != fields.end(); ++it) {
1112 const std::string &name = it->first;
1113 const std::string &value = it->second;
1115 pkt.putLongString(value);
1121 void Client::sendInventoryFields(const std::string &formname,
1122 const StringMap &fields)
1124 size_t fields_size = fields.size();
1125 FATAL_ERROR_IF(fields_size > 0xFFFF, "Unsupported number of inventory fields");
1127 NetworkPacket pkt(TOSERVER_INVENTORY_FIELDS, 0);
1128 pkt << formname << (u16) (fields_size & 0xFFFF);
1130 StringMap::const_iterator it;
1131 for (it = fields.begin(); it != fields.end(); ++it) {
1132 const std::string &name = it->first;
1133 const std::string &value = it->second;
1135 pkt.putLongString(value);
1141 void Client::sendInventoryAction(InventoryAction *a)
1143 std::ostringstream os(std::ios_base::binary);
1148 std::string s = os.str();
1150 NetworkPacket pkt(TOSERVER_INVENTORY_ACTION, s.size());
1151 pkt.putRawString(s.c_str(),s.size());
1156 void Client::sendChatMessage(const std::wstring &message)
1158 NetworkPacket pkt(TOSERVER_CHAT_MESSAGE, 2 + message.size() * sizeof(u16));
1165 void Client::sendChangePassword(const std::string &oldpassword,
1166 const std::string &newpassword)
1168 Player *player = m_env.getLocalPlayer();
1172 std::string playername = player->getName();
1173 if (m_proto_ver >= 25) {
1174 // get into sudo mode and then send new password to server
1175 m_password = oldpassword;
1176 m_new_password = newpassword;
1177 startAuth(choseAuthMech(m_sudo_auth_methods));
1179 std::string oldpwd = translatePassword(playername, oldpassword);
1180 std::string newpwd = translatePassword(playername, newpassword);
1182 NetworkPacket pkt(TOSERVER_PASSWORD_LEGACY, 2 * PASSWORD_SIZE);
1184 for (u8 i = 0; i < PASSWORD_SIZE; i++) {
1185 pkt << (u8) (i < oldpwd.length() ? oldpwd[i] : 0);
1188 for (u8 i = 0; i < PASSWORD_SIZE; i++) {
1189 pkt << (u8) (i < newpwd.length() ? newpwd[i] : 0);
1196 void Client::sendDamage(u8 damage)
1198 DSTACK(__FUNCTION_NAME);
1200 NetworkPacket pkt(TOSERVER_DAMAGE, sizeof(u8));
1205 void Client::sendBreath(u16 breath)
1207 DSTACK(__FUNCTION_NAME);
1209 NetworkPacket pkt(TOSERVER_BREATH, sizeof(u16));
1214 void Client::sendRespawn()
1216 DSTACK(__FUNCTION_NAME);
1218 NetworkPacket pkt(TOSERVER_RESPAWN, 0);
1222 void Client::sendReady()
1224 DSTACK(__FUNCTION_NAME);
1226 NetworkPacket pkt(TOSERVER_CLIENT_READY,
1227 1 + 1 + 1 + 1 + 2 + sizeof(char) * strlen(g_version_hash));
1229 pkt << (u8) VERSION_MAJOR << (u8) VERSION_MINOR << (u8) VERSION_PATCH
1230 << (u8) 0 << (u16) strlen(g_version_hash);
1232 pkt.putRawString(g_version_hash, (u16) strlen(g_version_hash));
1236 void Client::sendPlayerPos()
1238 LocalPlayer *myplayer = m_env.getLocalPlayer();
1239 if(myplayer == NULL)
1242 // Save bandwidth by only updating position when something changed
1243 if(myplayer->last_position == myplayer->getPosition() &&
1244 myplayer->last_speed == myplayer->getSpeed() &&
1245 myplayer->last_pitch == myplayer->getPitch() &&
1246 myplayer->last_yaw == myplayer->getYaw() &&
1247 myplayer->last_keyPressed == myplayer->keyPressed)
1250 myplayer->last_position = myplayer->getPosition();
1251 myplayer->last_speed = myplayer->getSpeed();
1252 myplayer->last_pitch = myplayer->getPitch();
1253 myplayer->last_yaw = myplayer->getYaw();
1254 myplayer->last_keyPressed = myplayer->keyPressed;
1258 //JMutexAutoLock lock(m_con_mutex); //bulk comment-out
1259 our_peer_id = m_con.GetPeerID();
1262 // Set peer id if not set already
1263 if(myplayer->peer_id == PEER_ID_INEXISTENT)
1264 myplayer->peer_id = our_peer_id;
1266 assert(myplayer->peer_id == our_peer_id);
1268 v3f pf = myplayer->getPosition();
1269 v3f sf = myplayer->getSpeed();
1270 s32 pitch = myplayer->getPitch() * 100;
1271 s32 yaw = myplayer->getYaw() * 100;
1272 u32 keyPressed = myplayer->keyPressed;
1274 v3s32 position(pf.X*100, pf.Y*100, pf.Z*100);
1275 v3s32 speed(sf.X*100, sf.Y*100, sf.Z*100);
1278 [0] v3s32 position*100
1279 [12] v3s32 speed*100
1280 [12+12] s32 pitch*100
1281 [12+12+4] s32 yaw*100
1282 [12+12+4+4] u32 keyPressed
1285 NetworkPacket pkt(TOSERVER_PLAYERPOS, 12 + 12 + 4 + 4 + 4);
1287 pkt << position << speed << pitch << yaw << keyPressed;
1292 void Client::sendPlayerItem(u16 item)
1294 Player *myplayer = m_env.getLocalPlayer();
1295 if(myplayer == NULL)
1298 u16 our_peer_id = m_con.GetPeerID();
1300 // Set peer id if not set already
1301 if(myplayer->peer_id == PEER_ID_INEXISTENT)
1302 myplayer->peer_id = our_peer_id;
1303 assert(myplayer->peer_id == our_peer_id);
1305 NetworkPacket pkt(TOSERVER_PLAYERITEM, 2);
1312 void Client::removeNode(v3s16 p)
1314 std::map<v3s16, MapBlock*> modified_blocks;
1317 m_env.getMap().removeNodeAndUpdate(p, modified_blocks);
1319 catch(InvalidPositionException &e) {
1322 for(std::map<v3s16, MapBlock *>::iterator
1323 i = modified_blocks.begin();
1324 i != modified_blocks.end(); ++i) {
1325 addUpdateMeshTaskWithEdge(i->first, false, true);
1329 void Client::addNode(v3s16 p, MapNode n, bool remove_metadata)
1331 //TimeTaker timer1("Client::addNode()");
1333 std::map<v3s16, MapBlock*> modified_blocks;
1336 //TimeTaker timer3("Client::addNode(): addNodeAndUpdate");
1337 m_env.getMap().addNodeAndUpdate(p, n, modified_blocks, remove_metadata);
1339 catch(InvalidPositionException &e) {
1342 for(std::map<v3s16, MapBlock *>::iterator
1343 i = modified_blocks.begin();
1344 i != modified_blocks.end(); ++i) {
1345 addUpdateMeshTaskWithEdge(i->first, false, true);
1349 void Client::setPlayerControl(PlayerControl &control)
1351 LocalPlayer *player = m_env.getLocalPlayer();
1352 assert(player != NULL);
1353 player->control = control;
1356 void Client::selectPlayerItem(u16 item)
1358 m_playeritem = item;
1359 m_inventory_updated = true;
1360 sendPlayerItem(item);
1363 // Returns true if the inventory of the local player has been
1364 // updated from the server. If it is true, it is set to false.
1365 bool Client::getLocalInventoryUpdated()
1367 bool updated = m_inventory_updated;
1368 m_inventory_updated = false;
1372 // Copies the inventory of the local player to parameter
1373 void Client::getLocalInventory(Inventory &dst)
1375 Player *player = m_env.getLocalPlayer();
1376 assert(player != NULL);
1377 dst = player->inventory;
1380 Inventory* Client::getInventory(const InventoryLocation &loc)
1383 case InventoryLocation::UNDEFINED:
1386 case InventoryLocation::CURRENT_PLAYER:
1388 Player *player = m_env.getLocalPlayer();
1389 assert(player != NULL);
1390 return &player->inventory;
1393 case InventoryLocation::PLAYER:
1395 Player *player = m_env.getPlayer(loc.name.c_str());
1398 return &player->inventory;
1401 case InventoryLocation::NODEMETA:
1403 NodeMetadata *meta = m_env.getMap().getNodeMetadata(loc.p);
1406 return meta->getInventory();
1409 case InventoryLocation::DETACHED:
1411 if(m_detached_inventories.count(loc.name) == 0)
1413 return m_detached_inventories[loc.name];
1417 FATAL_ERROR("Invalid inventory location type.");
1423 void Client::inventoryAction(InventoryAction *a)
1426 Send it to the server
1428 sendInventoryAction(a);
1431 Predict some local inventory changes
1433 a->clientApply(this, this);
1439 ClientActiveObject * Client::getSelectedActiveObject(
1441 v3f from_pos_f_on_map,
1442 core::line3d<f32> shootline_on_map
1445 std::vector<DistanceSortedActiveObject> objects;
1447 m_env.getActiveObjects(from_pos_f_on_map, max_d, objects);
1450 // After this, the closest object is the first in the array.
1451 std::sort(objects.begin(), objects.end());
1453 for(unsigned int i=0; i<objects.size(); i++)
1455 ClientActiveObject *obj = objects[i].obj;
1457 core::aabbox3d<f32> *selection_box = obj->getSelectionBox();
1458 if(selection_box == NULL)
1461 v3f pos = obj->getPosition();
1463 core::aabbox3d<f32> offsetted_box(
1464 selection_box->MinEdge + pos,
1465 selection_box->MaxEdge + pos
1468 if(offsetted_box.intersectsWithLine(shootline_on_map))
1477 std::list<std::string> Client::getConnectedPlayerNames()
1479 return m_env.getPlayerNames();
1482 float Client::getAnimationTime()
1484 return m_animation_time;
1487 int Client::getCrackLevel()
1489 return m_crack_level;
1492 void Client::setHighlighted(v3s16 pos, bool show_highlighted)
1494 m_show_highlighted = show_highlighted;
1495 v3s16 old_highlighted_pos = m_highlighted_pos;
1496 m_highlighted_pos = pos;
1497 addUpdateMeshTaskForNode(old_highlighted_pos, false, true);
1498 addUpdateMeshTaskForNode(m_highlighted_pos, false, true);
1501 void Client::setCrack(int level, v3s16 pos)
1503 int old_crack_level = m_crack_level;
1504 v3s16 old_crack_pos = m_crack_pos;
1506 m_crack_level = level;
1509 if(old_crack_level >= 0 && (level < 0 || pos != old_crack_pos))
1512 addUpdateMeshTaskForNode(old_crack_pos, false, true);
1514 if(level >= 0 && (old_crack_level < 0 || pos != old_crack_pos))
1517 addUpdateMeshTaskForNode(pos, false, true);
1523 Player *player = m_env.getLocalPlayer();
1524 assert(player != NULL);
1528 u16 Client::getBreath()
1530 Player *player = m_env.getLocalPlayer();
1531 assert(player != NULL);
1532 return player->getBreath();
1535 bool Client::getChatMessage(std::wstring &message)
1537 if(m_chat_queue.size() == 0)
1539 message = m_chat_queue.front();
1544 void Client::typeChatMessage(const std::wstring &message)
1546 // Discard empty line
1551 sendChatMessage(message);
1554 if (message[0] == L'/')
1556 m_chat_queue.push((std::wstring)L"issued command: " + message);
1560 LocalPlayer *player = m_env.getLocalPlayer();
1561 assert(player != NULL);
1562 std::wstring name = narrow_to_wide(player->getName());
1563 m_chat_queue.push((std::wstring)L"<" + name + L"> " + message);
1567 void Client::addUpdateMeshTask(v3s16 p, bool ack_to_server, bool urgent)
1569 MapBlock *b = m_env.getMap().getBlockNoCreateNoEx(p);
1574 Create a task to update the mesh of the block
1577 MeshMakeData *data = new MeshMakeData(this, m_cache_enable_shaders);
1580 //TimeTaker timer("data fill");
1582 // Debug: 1-6ms, avg=2ms
1584 data->setCrack(m_crack_level, m_crack_pos);
1585 data->setHighlighted(m_highlighted_pos, m_show_highlighted);
1586 data->setSmoothLighting(m_cache_smooth_lighting);
1589 // Add task to queue
1590 m_mesh_update_thread.enqueueUpdate(p, data, ack_to_server, urgent);
1593 void Client::addUpdateMeshTaskWithEdge(v3s16 blockpos, bool ack_to_server, bool urgent)
1596 addUpdateMeshTask(blockpos, ack_to_server, urgent);
1598 catch(InvalidPositionException &e){}
1601 for (int i=0;i<6;i++)
1604 v3s16 p = blockpos + g_6dirs[i];
1605 addUpdateMeshTask(p, false, urgent);
1607 catch(InvalidPositionException &e){}
1611 void Client::addUpdateMeshTaskForNode(v3s16 nodepos, bool ack_to_server, bool urgent)
1615 infostream<<"Client::addUpdateMeshTaskForNode(): "
1616 <<"("<<p.X<<","<<p.Y<<","<<p.Z<<")"
1620 v3s16 blockpos = getNodeBlockPos(nodepos);
1621 v3s16 blockpos_relative = blockpos * MAP_BLOCKSIZE;
1624 addUpdateMeshTask(blockpos, ack_to_server, urgent);
1626 catch(InvalidPositionException &e) {}
1629 if(nodepos.X == blockpos_relative.X){
1631 v3s16 p = blockpos + v3s16(-1,0,0);
1632 addUpdateMeshTask(p, false, urgent);
1634 catch(InvalidPositionException &e){}
1637 if(nodepos.Y == blockpos_relative.Y){
1639 v3s16 p = blockpos + v3s16(0,-1,0);
1640 addUpdateMeshTask(p, false, urgent);
1642 catch(InvalidPositionException &e){}
1645 if(nodepos.Z == blockpos_relative.Z){
1647 v3s16 p = blockpos + v3s16(0,0,-1);
1648 addUpdateMeshTask(p, false, urgent);
1650 catch(InvalidPositionException &e){}
1654 ClientEvent Client::getClientEvent()
1657 if(m_client_event_queue.size() == 0) {
1658 event.type = CE_NONE;
1661 event = m_client_event_queue.front();
1662 m_client_event_queue.pop();
1667 float Client::mediaReceiveProgress()
1669 if (m_media_downloader)
1670 return m_media_downloader->getProgress();
1672 return 1.0; // downloader only exists when not yet done
1675 typedef struct TextureUpdateArgs {
1676 IrrlichtDevice *device;
1677 gui::IGUIEnvironment *guienv;
1680 const wchar_t* text_base;
1681 } TextureUpdateArgs;
1683 void texture_update_progress(void *args, u32 progress, u32 max_progress)
1685 TextureUpdateArgs* targs = (TextureUpdateArgs*) args;
1686 u16 cur_percent = ceil(progress / (double) max_progress * 100.);
1688 // update the loading menu -- if neccessary
1689 bool do_draw = false;
1690 u32 time_ms = targs->last_time_ms;
1691 if (cur_percent != targs->last_percent) {
1692 targs->last_percent = cur_percent;
1693 time_ms = getTimeMs();
1694 // only draw when the user will notice something:
1695 do_draw = (time_ms - targs->last_time_ms > 100);
1699 targs->last_time_ms = time_ms;
1700 std::basic_stringstream<wchar_t> strm;
1701 strm << targs->text_base << " " << targs->last_percent << "%...";
1702 draw_load_screen(strm.str(), targs->device, targs->guienv, 0,
1703 72 + (u16) ((18. / 100.) * (double) targs->last_percent));
1707 void Client::afterContentReceived(IrrlichtDevice *device)
1709 infostream<<"Client::afterContentReceived() started"<<std::endl;
1710 assert(m_itemdef_received); // pre-condition
1711 assert(m_nodedef_received); // pre-condition
1712 assert(mediaReceived()); // pre-condition
1714 const wchar_t* text = wgettext("Loading textures...");
1716 // Clear cached pre-scaled 2D GUI images, as this cache
1717 // might have images with the same name but different
1718 // content from previous sessions.
1719 guiScalingCacheClear(device->getVideoDriver());
1721 // Rebuild inherited images and recreate textures
1722 infostream<<"- Rebuilding images and textures"<<std::endl;
1723 draw_load_screen(text,device, guienv, 0, 70);
1724 m_tsrc->rebuildImagesAndTextures();
1728 infostream<<"- Rebuilding shaders"<<std::endl;
1729 text = wgettext("Rebuilding shaders...");
1730 draw_load_screen(text, device, guienv, 0, 71);
1731 m_shsrc->rebuildShaders();
1734 // Update node aliases
1735 infostream<<"- Updating node aliases"<<std::endl;
1736 text = wgettext("Initializing nodes...");
1737 draw_load_screen(text, device, guienv, 0, 72);
1738 m_nodedef->updateAliases(m_itemdef);
1739 std::string texture_path = g_settings->get("texture_path");
1740 if (texture_path != "" && fs::IsDir(texture_path))
1741 m_nodedef->applyTextureOverrides(texture_path + DIR_DELIM + "override.txt");
1742 m_nodedef->setNodeRegistrationStatus(true);
1743 m_nodedef->runNodeResolveCallbacks();
1746 // Update node textures and assign shaders to each tile
1747 infostream<<"- Updating node textures"<<std::endl;
1748 TextureUpdateArgs tu_args;
1749 tu_args.device = device;
1750 tu_args.guienv = guienv;
1751 tu_args.last_time_ms = getTimeMs();
1752 tu_args.last_percent = 0;
1753 tu_args.text_base = wgettext("Initializing nodes");
1754 m_nodedef->updateTextures(this, texture_update_progress, &tu_args);
1755 delete[] tu_args.text_base;
1757 // Preload item textures and meshes if configured to
1758 if(g_settings->getBool("preload_item_visuals"))
1760 verbosestream<<"Updating item textures and meshes"<<std::endl;
1761 text = wgettext("Item textures...");
1762 draw_load_screen(text, device, guienv, 0, 0);
1763 std::set<std::string> names = m_itemdef->getAll();
1764 size_t size = names.size();
1767 for(std::set<std::string>::const_iterator
1768 i = names.begin(); i != names.end(); ++i)
1770 // Asking for these caches the result
1771 m_itemdef->getInventoryTexture(*i, this);
1772 m_itemdef->getWieldMesh(*i, this);
1774 percent = (count * 100 / size * 0.2) + 80;
1775 draw_load_screen(text, device, guienv, 0, percent);
1780 // Start mesh update thread after setting up content definitions
1781 infostream<<"- Starting mesh update thread"<<std::endl;
1782 m_mesh_update_thread.Start();
1786 text = wgettext("Done!");
1787 draw_load_screen(text, device, guienv, 0, 100);
1788 infostream<<"Client::afterContentReceived() done"<<std::endl;
1792 float Client::getRTT(void)
1794 return m_con.getPeerStat(PEER_ID_SERVER,con::AVG_RTT);
1797 float Client::getCurRate(void)
1799 return ( m_con.getLocalStat(con::CUR_INC_RATE) +
1800 m_con.getLocalStat(con::CUR_DL_RATE));
1803 float Client::getAvgRate(void)
1805 return ( m_con.getLocalStat(con::AVG_INC_RATE) +
1806 m_con.getLocalStat(con::AVG_DL_RATE));
1809 void Client::makeScreenshot(IrrlichtDevice *device)
1811 irr::video::IVideoDriver *driver = device->getVideoDriver();
1812 irr::video::IImage* const raw_image = driver->createScreenShot();
1817 time_t t = time(NULL);
1818 struct tm *tm = localtime(&t);
1820 char timetstamp_c[64];
1821 strftime(timetstamp_c, sizeof(timetstamp_c), "%Y%m%d_%H%M%S", tm);
1823 std::string filename_base = g_settings->get("screenshot_path")
1825 + std::string("screenshot_")
1826 + std::string(timetstamp_c);
1827 std::string filename_ext = ".png";
1828 std::string filename;
1830 // Try to find a unique filename
1831 unsigned serial = 0;
1833 while (serial < SCREENSHOT_MAX_SERIAL_TRIES) {
1834 filename = filename_base + (serial > 0 ? ("_" + itos(serial)) : "") + filename_ext;
1835 std::ifstream tmp(filename.c_str());
1837 break; // File did not apparently exist, we'll go with it
1841 if (serial == SCREENSHOT_MAX_SERIAL_TRIES) {
1842 infostream << "Could not find suitable filename for screenshot" << std::endl;
1844 irr::video::IImage* const image =
1845 driver->createImage(video::ECF_R8G8B8, raw_image->getDimension());
1848 raw_image->copyTo(image);
1850 std::ostringstream sstr;
1851 if (driver->writeImageToFile(image, filename.c_str())) {
1852 sstr << "Saved screenshot to '" << filename << "'";
1854 sstr << "Failed to save screenshot '" << filename << "'";
1856 m_chat_queue.push(narrow_to_wide(sstr.str()));
1857 infostream << sstr.str() << std::endl;
1865 // IGameDef interface
1867 IItemDefManager* Client::getItemDefManager()
1871 INodeDefManager* Client::getNodeDefManager()
1875 ICraftDefManager* Client::getCraftDefManager()
1878 //return m_craftdef;
1880 ITextureSource* Client::getTextureSource()
1884 IShaderSource* Client::getShaderSource()
1888 scene::ISceneManager* Client::getSceneManager()
1890 return m_device->getSceneManager();
1892 u16 Client::allocateUnknownNodeId(const std::string &name)
1894 errorstream << "Client::allocateUnknownNodeId(): "
1895 << "Client cannot allocate node IDs" << std::endl;
1896 FATAL_ERROR("Client allocated unknown node");
1898 return CONTENT_IGNORE;
1900 ISoundManager* Client::getSoundManager()
1904 MtEventManager* Client::getEventManager()
1909 ParticleManager* Client::getParticleManager()
1911 return &m_particle_manager;
1914 scene::IAnimatedMesh* Client::getMesh(const std::string &filename)
1916 StringMap::const_iterator it = m_mesh_data.find(filename);
1917 if (it == m_mesh_data.end()) {
1918 errorstream << "Client::getMesh(): Mesh not found: \"" << filename
1919 << "\"" << std::endl;
1922 const std::string &data = it->second;
1923 scene::ISceneManager *smgr = m_device->getSceneManager();
1925 // Create the mesh, remove it from cache and return it
1926 // This allows unique vertex colors and other properties for each instance
1927 Buffer<char> data_rw(data.c_str(), data.size()); // Const-incorrect Irrlicht
1928 io::IFileSystem *irrfs = m_device->getFileSystem();
1929 io::IReadFile *rfile = irrfs->createMemoryReadFile(
1930 *data_rw, data_rw.getSize(), filename.c_str());
1931 FATAL_ERROR_IF(!rfile, "Could not create/open RAM file");
1933 scene::IAnimatedMesh *mesh = smgr->getMesh(rfile);
1935 // NOTE: By playing with Irrlicht refcounts, maybe we could cache a bunch
1936 // of uniquely named instances and re-use them
1938 smgr->getMeshCache()->removeMesh(mesh);