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),
234 m_inventory_updated(false),
235 m_inventory_from_server(NULL),
236 m_inventory_from_server_age(0.0),
237 m_show_highlighted(false),
241 m_highlighted_pos(0,0,0),
243 m_password(password),
244 m_chosen_auth_mech(AUTH_MECHANISM_NONE),
246 m_access_denied(false),
247 m_access_denied_reconnect(false),
248 m_itemdef_received(false),
249 m_nodedef_received(false),
250 m_media_downloader(new ClientMediaDownloader()),
251 m_time_of_day_set(false),
252 m_last_time_of_day_f(-1),
253 m_time_of_day_update_timer(0),
254 m_recommended_send_interval(0.1),
255 m_removed_sounds_check_timer(0),
260 m_env.addPlayer(new LocalPlayer(this, playername));
262 m_mapper = new Mapper(device, this);
263 m_cache_save_interval = g_settings->getU16("server_map_save_interval");
265 m_cache_smooth_lighting = g_settings->getBool("smooth_lighting");
266 m_cache_enable_shaders = g_settings->getBool("enable_shaders");
271 //request all client managed threads to stop
272 m_mesh_update_thread.Stop();
273 // Save local server map
275 infostream << "Local map saving ended." << std::endl;
276 m_localdb->endSave();
280 bool Client::isShutdown()
283 if (!m_mesh_update_thread.IsRunning()) return true;
292 m_mesh_update_thread.Stop();
293 m_mesh_update_thread.Wait();
294 while (!m_mesh_update_thread.m_queue_out.empty()) {
295 MeshUpdateResult r = m_mesh_update_thread.m_queue_out.pop_frontNoEx();
300 delete m_inventory_from_server;
302 // Delete detached inventories
303 for (std::map<std::string, Inventory*>::iterator
304 i = m_detached_inventories.begin();
305 i != m_detached_inventories.end(); ++i) {
309 // cleanup 3d model meshes on client shutdown
310 while (m_device->getSceneManager()->getMeshCache()->getMeshCount() != 0) {
311 scene::IAnimatedMesh *mesh =
312 m_device->getSceneManager()->getMeshCache()->getMeshByIndex(0);
315 m_device->getSceneManager()->getMeshCache()->removeMesh(mesh);
321 void Client::connect(Address address,
322 const std::string &address_name,
323 bool is_local_server)
325 DSTACK(__FUNCTION_NAME);
327 initLocalMapSaving(address, address_name, is_local_server);
329 m_con.SetTimeoutMs(0);
330 m_con.Connect(address);
333 void Client::step(float dtime)
335 DSTACK(__FUNCTION_NAME);
341 if(m_ignore_damage_timer > dtime)
342 m_ignore_damage_timer -= dtime;
344 m_ignore_damage_timer = 0.0;
346 m_animation_time += dtime;
347 if(m_animation_time > 60.0)
348 m_animation_time -= 60.0;
350 m_time_of_day_update_timer += dtime;
358 float &counter = m_packetcounter_timer;
364 infostream << "Client packetcounter (" << m_packetcounter_timer
366 m_packetcounter.print(infostream);
367 m_packetcounter.clear();
371 // UGLY hack to fix 2 second startup delay caused by non existent
372 // server client startup synchronization in local server or singleplayer mode
373 static bool initial_step = true;
375 initial_step = false;
377 else if(m_state == LC_Created) {
378 float &counter = m_connection_reinit_timer;
383 Player *myplayer = m_env.getLocalPlayer();
384 FATAL_ERROR_IF(myplayer == NULL, "Local player not found in environment.");
386 // Send TOSERVER_INIT_LEGACY
387 // [0] u16 TOSERVER_INIT_LEGACY
388 // [2] u8 SER_FMT_VER_HIGHEST_READ
389 // [3] u8[20] player_name
390 // [23] u8[28] password (new in some version)
391 // [51] u16 minimum supported network protocol version (added sometime)
392 // [53] u16 maximum supported network protocol version (added later than the previous one)
394 char pName[PLAYERNAME_SIZE];
395 char pPassword[PASSWORD_SIZE];
396 memset(pName, 0, PLAYERNAME_SIZE * sizeof(char));
397 memset(pPassword, 0, PASSWORD_SIZE * sizeof(char));
399 std::string hashed_password = translatePassword(myplayer->getName(), m_password);
400 snprintf(pName, PLAYERNAME_SIZE, "%s", myplayer->getName());
401 snprintf(pPassword, PASSWORD_SIZE, "%s", hashed_password.c_str());
403 sendLegacyInit(pName, pPassword);
404 if (LATEST_PROTOCOL_VERSION >= 25)
405 sendInit(myplayer->getName());
408 // Not connected, return
413 Do stuff if connected
417 Run Map's timers and unload unused data
419 const float map_timer_and_unload_dtime = 5.25;
420 if(m_map_timer_and_unload_interval.step(dtime, map_timer_and_unload_dtime)) {
421 ScopeProfiler sp(g_profiler, "Client: map timer and unload");
422 std::vector<v3s16> deleted_blocks;
423 m_env.getMap().timerUpdate(map_timer_and_unload_dtime,
424 g_settings->getFloat("client_unload_unused_data_timeout"),
429 NOTE: This loop is intentionally iterated the way it is.
432 std::vector<v3s16>::iterator i = deleted_blocks.begin();
433 std::vector<v3s16> sendlist;
435 if(sendlist.size() == 255 || i == deleted_blocks.end()) {
446 sendDeletedBlocks(sendlist);
448 if(i == deleted_blocks.end())
454 sendlist.push_back(*i);
462 // Control local player (0ms)
463 LocalPlayer *player = m_env.getLocalPlayer();
464 assert(player != NULL);
465 player->applyControl(dtime);
474 ClientEnvEvent event = m_env.getClientEvent();
475 if(event.type == CEE_NONE) {
478 else if(event.type == CEE_PLAYER_DAMAGE) {
479 if(m_ignore_damage_timer <= 0) {
480 u8 damage = event.player_damage.amount;
482 if(event.player_damage.send_to_server)
485 // Add to ClientEvent queue
487 event.type = CE_PLAYER_DAMAGE;
488 event.player_damage.amount = damage;
489 m_client_event_queue.push(event);
492 else if(event.type == CEE_PLAYER_BREATH) {
493 u16 breath = event.player_breath.amount;
501 float &counter = m_avg_rtt_timer;
505 // connectedAndInitialized() is true, peer exists.
506 float avg_rtt = getRTT();
507 infostream << "Client: avg_rtt=" << avg_rtt << std::endl;
511 Send player position to server
514 float &counter = m_playerpos_send_timer;
516 if((m_state == LC_Ready) && (counter >= m_recommended_send_interval))
524 Replace updated meshes
527 int num_processed_meshes = 0;
528 while (!m_mesh_update_thread.m_queue_out.empty())
530 num_processed_meshes++;
532 MinimapMapblock *minimap_mapblock = NULL;
533 bool do_mapper_update = true;
535 MeshUpdateResult r = m_mesh_update_thread.m_queue_out.pop_frontNoEx();
536 MapBlock *block = m_env.getMap().getBlockNoCreateNoEx(r.p);
538 // Delete the old mesh
539 if (block->mesh != NULL) {
545 minimap_mapblock = r.mesh->moveMinimapMapblock();
546 if (minimap_mapblock == NULL)
547 do_mapper_update = false;
550 if (r.mesh && r.mesh->getMesh()->getMeshBufferCount() == 0) {
553 // Replace with the new mesh
554 block->mesh = r.mesh;
560 if (do_mapper_update)
561 m_mapper->addBlock(r.p, minimap_mapblock);
563 if (r.ack_block_to_server) {
573 if (num_processed_meshes > 0)
574 g_profiler->graphAdd("num_processed_meshes", num_processed_meshes);
580 if (m_media_downloader && m_media_downloader->isStarted()) {
581 m_media_downloader->step(this);
582 if (m_media_downloader->isDone()) {
584 delete m_media_downloader;
585 m_media_downloader = NULL;
590 If the server didn't update the inventory in a while, revert
591 the local inventory (so the player notices the lag problem
592 and knows something is wrong).
594 if(m_inventory_from_server)
596 float interval = 10.0;
597 float count_before = floor(m_inventory_from_server_age / interval);
599 m_inventory_from_server_age += dtime;
601 float count_after = floor(m_inventory_from_server_age / interval);
603 if(count_after != count_before)
605 // Do this every <interval> seconds after TOCLIENT_INVENTORY
606 // Reset the locally changed inventory to the authoritative inventory
607 Player *player = m_env.getLocalPlayer();
608 player->inventory = *m_inventory_from_server;
609 m_inventory_updated = true;
614 Update positions of sounds attached to objects
617 for(std::map<int, u16>::iterator
618 i = m_sounds_to_objects.begin();
619 i != m_sounds_to_objects.end(); i++)
621 int client_id = i->first;
622 u16 object_id = i->second;
623 ClientActiveObject *cao = m_env.getActiveObject(object_id);
626 v3f pos = cao->getPosition();
627 m_sound->updateSoundPosition(client_id, pos);
632 Handle removed remotely initiated sounds
634 m_removed_sounds_check_timer += dtime;
635 if(m_removed_sounds_check_timer >= 2.32) {
636 m_removed_sounds_check_timer = 0;
637 // Find removed sounds and clear references to them
638 std::vector<s32> removed_server_ids;
639 for(std::map<s32, int>::iterator
640 i = m_sounds_server_to_client.begin();
641 i != m_sounds_server_to_client.end();) {
642 s32 server_id = i->first;
643 int client_id = i->second;
645 if(!m_sound->soundExists(client_id)) {
646 m_sounds_server_to_client.erase(server_id);
647 m_sounds_client_to_server.erase(client_id);
648 m_sounds_to_objects.erase(client_id);
649 removed_server_ids.push_back(server_id);
654 if(!removed_server_ids.empty()) {
655 sendRemovedSounds(removed_server_ids);
660 if (m_localdb && m_localdb_save_interval.step(dtime,
661 m_cache_save_interval)) {
662 m_localdb->endSave();
663 m_localdb->beginSave();
667 bool Client::loadMedia(const std::string &data, const std::string &filename)
669 // Silly irrlicht's const-incorrectness
670 Buffer<char> data_rw(data.c_str(), data.size());
674 const char *image_ext[] = {
675 ".png", ".jpg", ".bmp", ".tga",
676 ".pcx", ".ppm", ".psd", ".wal", ".rgb",
679 name = removeStringEnd(filename, image_ext);
682 verbosestream<<"Client: Attempting to load image "
683 <<"file \""<<filename<<"\""<<std::endl;
685 io::IFileSystem *irrfs = m_device->getFileSystem();
686 video::IVideoDriver *vdrv = m_device->getVideoDriver();
688 // Create an irrlicht memory file
689 io::IReadFile *rfile = irrfs->createMemoryReadFile(
690 *data_rw, data_rw.getSize(), "_tempreadfile");
692 FATAL_ERROR_IF(!rfile, "Could not create irrlicht memory file.");
695 video::IImage *img = vdrv->createImageFromFile(rfile);
697 errorstream<<"Client: Cannot create image from data of "
698 <<"file \""<<filename<<"\""<<std::endl;
703 m_tsrc->insertSourceImage(filename, img);
710 const char *sound_ext[] = {
711 ".0.ogg", ".1.ogg", ".2.ogg", ".3.ogg", ".4.ogg",
712 ".5.ogg", ".6.ogg", ".7.ogg", ".8.ogg", ".9.ogg",
715 name = removeStringEnd(filename, sound_ext);
718 verbosestream<<"Client: Attempting to load sound "
719 <<"file \""<<filename<<"\""<<std::endl;
720 m_sound->loadSoundData(name, data);
724 const char *model_ext[] = {
725 ".x", ".b3d", ".md2", ".obj",
728 name = removeStringEnd(filename, model_ext);
731 verbosestream<<"Client: Storing model into memory: "
732 <<"\""<<filename<<"\""<<std::endl;
733 if(m_mesh_data.count(filename))
734 errorstream<<"Multiple models with name \""<<filename.c_str()
735 <<"\" found; replacing previous model"<<std::endl;
736 m_mesh_data[filename] = data;
740 errorstream<<"Client: Don't know how to load file \""
741 <<filename<<"\""<<std::endl;
745 // Virtual methods from con::PeerHandler
746 void Client::peerAdded(con::Peer *peer)
748 infostream << "Client::peerAdded(): peer->id="
749 << peer->id << std::endl;
751 void Client::deletingPeer(con::Peer *peer, bool timeout)
753 infostream << "Client::deletingPeer(): "
754 "Server Peer is getting deleted "
755 << "(timeout=" << timeout << ")" << std::endl;
758 m_access_denied = true;
759 m_access_denied_reason = gettext("Connection timed out.");
765 u16 number of files requested
771 void Client::request_media(const std::vector<std::string> &file_requests)
773 std::ostringstream os(std::ios_base::binary);
774 writeU16(os, TOSERVER_REQUEST_MEDIA);
775 size_t file_requests_size = file_requests.size();
777 FATAL_ERROR_IF(file_requests_size > 0xFFFF, "Unsupported number of file requests");
779 // Packet dynamicly resized
780 NetworkPacket pkt(TOSERVER_REQUEST_MEDIA, 2 + 0);
782 pkt << (u16) (file_requests_size & 0xFFFF);
784 for(std::vector<std::string>::const_iterator i = file_requests.begin();
785 i != file_requests.end(); ++i) {
791 infostream << "Client: Sending media request list to server ("
792 << file_requests.size() << " files. packet size)" << std::endl;
795 void Client::received_media()
797 NetworkPacket pkt(TOSERVER_RECEIVED_MEDIA, 0);
799 infostream << "Client: Notifying server that we received all media"
803 void Client::initLocalMapSaving(const Address &address,
804 const std::string &hostname,
805 bool is_local_server)
807 if (!g_settings->getBool("enable_local_map_saving") || is_local_server) {
811 const std::string world_path = porting::path_user
812 + DIR_DELIM + "worlds"
813 + DIR_DELIM + "server_"
814 + hostname + "_" + to_string(address.getPort());
816 fs::CreateAllDirs(world_path);
818 m_localdb = new Database_SQLite3(world_path);
819 m_localdb->beginSave();
820 actionstream << "Local map saving started, map will be saved at '" << world_path << "'" << std::endl;
823 void Client::ReceiveAll()
825 DSTACK(__FUNCTION_NAME);
826 u32 start_ms = porting::getTimeMs();
829 // Limit time even if there would be huge amounts of data to
831 if(porting::getTimeMs() > start_ms + 100)
836 g_profiler->graphAdd("client_received_packets", 1);
838 catch(con::NoIncomingDataException &e) {
841 catch(con::InvalidIncomingDataException &e) {
842 infostream<<"Client::ReceiveAll(): "
843 "InvalidIncomingDataException: what()="
844 <<e.what()<<std::endl;
849 void Client::Receive()
851 DSTACK(__FUNCTION_NAME);
857 inline void Client::handleCommand(NetworkPacket* pkt)
859 const ToClientCommandHandler& opHandle = toClientCommandTable[pkt->getCommand()];
860 (this->*opHandle.handler)(pkt);
864 sender_peer_id given to this shall be quaranteed to be a valid peer
866 void Client::ProcessData(NetworkPacket *pkt)
868 DSTACK(__FUNCTION_NAME);
870 ToClientCommand command = (ToClientCommand) pkt->getCommand();
871 u32 sender_peer_id = pkt->getPeerId();
873 //infostream<<"Client: received command="<<command<<std::endl;
874 m_packetcounter.add((u16)command);
877 If this check is removed, be sure to change the queue
878 system to know the ids
880 if(sender_peer_id != PEER_ID_SERVER) {
881 infostream << "Client::ProcessData(): Discarding data not "
882 "coming from server: peer_id=" << sender_peer_id
887 // Command must be handled into ToClientCommandHandler
888 if (command >= TOCLIENT_NUM_MSG_TYPES) {
889 infostream << "Client: Ignoring unknown command "
890 << command << std::endl;
895 * Those packets are handled before m_server_ser_ver is set, it's normal
896 * But we must use the new ToClientConnectionState in the future,
899 if(toClientCommandTable[command].state == TOCLIENT_STATE_NOT_CONNECTED) {
904 if(m_server_ser_ver == SER_FMT_VER_INVALID) {
905 infostream << "Client: Server serialization"
906 " format invalid or not initialized."
907 " Skipping incoming command=" << command << std::endl;
912 Handle runtime commands
918 void Client::Send(NetworkPacket* pkt)
920 m_con.Send(PEER_ID_SERVER,
921 serverCommandFactoryTable[pkt->getCommand()].channel,
923 serverCommandFactoryTable[pkt->getCommand()].reliable);
926 void Client::interact(u8 action, const PointedThing& pointed)
928 if(m_state != LC_Ready) {
929 errorstream << "Client::interact() "
930 "Canceled (not connected)"
939 [5] u32 length of the next item
940 [9] serialized PointedThing
942 0: start digging (from undersurface) or use
943 1: stop digging (all parameters ignored)
945 3: place block or item (to abovesurface)
949 NetworkPacket pkt(TOSERVER_INTERACT, 1 + 2 + 0);
952 pkt << (u16)getPlayerItem();
954 std::ostringstream tmp_os(std::ios::binary);
955 pointed.serialize(tmp_os);
957 pkt.putLongString(tmp_os.str());
962 void Client::deleteAuthData()
967 switch (m_chosen_auth_mech) {
968 case AUTH_MECHANISM_FIRST_SRP:
970 case AUTH_MECHANISM_SRP:
971 case AUTH_MECHANISM_LEGACY_PASSWORD:
972 srp_user_delete((SRPUser *) m_auth_data);
975 case AUTH_MECHANISM_NONE:
978 m_chosen_auth_mech = AUTH_MECHANISM_NONE;
982 AuthMechanism Client::choseAuthMech(const u32 mechs)
984 if (mechs & AUTH_MECHANISM_SRP)
985 return AUTH_MECHANISM_SRP;
987 if (mechs & AUTH_MECHANISM_FIRST_SRP)
988 return AUTH_MECHANISM_FIRST_SRP;
990 if (mechs & AUTH_MECHANISM_LEGACY_PASSWORD)
991 return AUTH_MECHANISM_LEGACY_PASSWORD;
993 return AUTH_MECHANISM_NONE;
996 void Client::sendLegacyInit(const char* playerName, const char* playerPassword)
998 NetworkPacket pkt(TOSERVER_INIT_LEGACY,
999 1 + PLAYERNAME_SIZE + PASSWORD_SIZE + 2 + 2);
1001 pkt << (u8) SER_FMT_VER_HIGHEST_READ;
1002 pkt.putRawString(playerName,PLAYERNAME_SIZE);
1003 pkt.putRawString(playerPassword, PASSWORD_SIZE);
1004 pkt << (u16) CLIENT_PROTOCOL_VERSION_MIN << (u16) CLIENT_PROTOCOL_VERSION_MAX;
1009 void Client::sendInit(const std::string &playerName)
1011 NetworkPacket pkt(TOSERVER_INIT, 1 + 2 + 2 + (1 + playerName.size()));
1013 // we don't support network compression yet
1014 u16 supp_comp_modes = NETPROTO_COMPRESSION_NONE;
1015 pkt << (u8) SER_FMT_VER_HIGHEST_READ << (u16) supp_comp_modes;
1016 pkt << (u16) CLIENT_PROTOCOL_VERSION_MIN << (u16) CLIENT_PROTOCOL_VERSION_MAX;
1022 void Client::startAuth(AuthMechanism chosen_auth_mechanism)
1024 m_chosen_auth_mech = chosen_auth_mechanism;
1026 switch (chosen_auth_mechanism) {
1027 case AUTH_MECHANISM_FIRST_SRP: {
1028 // send srp verifier to server
1029 NetworkPacket resp_pkt(TOSERVER_FIRST_SRP, 0);
1030 char *salt, *bytes_v;
1031 std::size_t len_salt, len_v;
1033 getSRPVerifier(getPlayerName(), m_password,
1034 &salt, &len_salt, &bytes_v, &len_v);
1036 << std::string((char*)salt, len_salt)
1037 << std::string((char*)bytes_v, len_v)
1038 << (u8)((m_password == "") ? 1 : 0);
1044 case AUTH_MECHANISM_SRP:
1045 case AUTH_MECHANISM_LEGACY_PASSWORD: {
1048 if (chosen_auth_mechanism == AUTH_MECHANISM_LEGACY_PASSWORD) {
1049 m_password = translatePassword(getPlayerName(), m_password);
1053 std::string playername_u = lowercase(getPlayerName());
1054 m_auth_data = srp_user_new(SRP_SHA256, SRP_NG_2048,
1055 getPlayerName().c_str(), playername_u.c_str(),
1056 (const unsigned char *) m_password.c_str(),
1057 m_password.length(), NULL, NULL);
1060 srp_user_start_authentication((struct SRPUser *) m_auth_data,
1061 NULL, NULL, 0, (unsigned char **) &bytes_A, &len_A);
1063 NetworkPacket resp_pkt(TOSERVER_SRP_BYTES_A, 0);
1064 resp_pkt << std::string(bytes_A, len_A) << based_on;
1068 case AUTH_MECHANISM_NONE:
1069 break; // not handled in this method
1073 void Client::sendDeletedBlocks(std::vector<v3s16> &blocks)
1075 NetworkPacket pkt(TOSERVER_DELETEDBLOCKS, 1 + sizeof(v3s16) * blocks.size());
1077 pkt << (u8) blocks.size();
1080 for(std::vector<v3s16>::iterator
1082 j != blocks.end(); ++j) {
1090 void Client::sendGotBlocks(v3s16 block)
1092 NetworkPacket pkt(TOSERVER_GOTBLOCKS, 1 + 6);
1093 pkt << (u8) 1 << block;
1097 void Client::sendRemovedSounds(std::vector<s32> &soundList)
1099 size_t server_ids = soundList.size();
1100 assert(server_ids <= 0xFFFF);
1102 NetworkPacket pkt(TOSERVER_REMOVED_SOUNDS, 2 + server_ids * 4);
1104 pkt << (u16) (server_ids & 0xFFFF);
1106 for(std::vector<s32>::iterator i = soundList.begin();
1107 i != soundList.end(); i++)
1113 void Client::sendNodemetaFields(v3s16 p, const std::string &formname,
1114 const StringMap &fields)
1116 size_t fields_size = fields.size();
1118 FATAL_ERROR_IF(fields_size > 0xFFFF, "Unsupported number of nodemeta fields");
1120 NetworkPacket pkt(TOSERVER_NODEMETA_FIELDS, 0);
1122 pkt << p << formname << (u16) (fields_size & 0xFFFF);
1124 StringMap::const_iterator it;
1125 for (it = fields.begin(); it != fields.end(); ++it) {
1126 const std::string &name = it->first;
1127 const std::string &value = it->second;
1129 pkt.putLongString(value);
1135 void Client::sendInventoryFields(const std::string &formname,
1136 const StringMap &fields)
1138 size_t fields_size = fields.size();
1139 FATAL_ERROR_IF(fields_size > 0xFFFF, "Unsupported number of inventory fields");
1141 NetworkPacket pkt(TOSERVER_INVENTORY_FIELDS, 0);
1142 pkt << formname << (u16) (fields_size & 0xFFFF);
1144 StringMap::const_iterator it;
1145 for (it = fields.begin(); it != fields.end(); ++it) {
1146 const std::string &name = it->first;
1147 const std::string &value = it->second;
1149 pkt.putLongString(value);
1155 void Client::sendInventoryAction(InventoryAction *a)
1157 std::ostringstream os(std::ios_base::binary);
1162 std::string s = os.str();
1164 NetworkPacket pkt(TOSERVER_INVENTORY_ACTION, s.size());
1165 pkt.putRawString(s.c_str(),s.size());
1170 void Client::sendChatMessage(const std::wstring &message)
1172 NetworkPacket pkt(TOSERVER_CHAT_MESSAGE, 2 + message.size() * sizeof(u16));
1179 void Client::sendChangePassword(const std::string &oldpassword,
1180 const std::string &newpassword)
1182 Player *player = m_env.getLocalPlayer();
1186 std::string playername = player->getName();
1187 if (m_proto_ver >= 25) {
1188 // get into sudo mode and then send new password to server
1189 m_password = oldpassword;
1190 m_new_password = newpassword;
1191 startAuth(choseAuthMech(m_sudo_auth_methods));
1193 std::string oldpwd = translatePassword(playername, oldpassword);
1194 std::string newpwd = translatePassword(playername, newpassword);
1196 NetworkPacket pkt(TOSERVER_PASSWORD_LEGACY, 2 * PASSWORD_SIZE);
1198 for (u8 i = 0; i < PASSWORD_SIZE; i++) {
1199 pkt << (u8) (i < oldpwd.length() ? oldpwd[i] : 0);
1202 for (u8 i = 0; i < PASSWORD_SIZE; i++) {
1203 pkt << (u8) (i < newpwd.length() ? newpwd[i] : 0);
1210 void Client::sendDamage(u8 damage)
1212 DSTACK(__FUNCTION_NAME);
1214 NetworkPacket pkt(TOSERVER_DAMAGE, sizeof(u8));
1219 void Client::sendBreath(u16 breath)
1221 DSTACK(__FUNCTION_NAME);
1223 NetworkPacket pkt(TOSERVER_BREATH, sizeof(u16));
1228 void Client::sendRespawn()
1230 DSTACK(__FUNCTION_NAME);
1232 NetworkPacket pkt(TOSERVER_RESPAWN, 0);
1236 void Client::sendReady()
1238 DSTACK(__FUNCTION_NAME);
1240 NetworkPacket pkt(TOSERVER_CLIENT_READY,
1241 1 + 1 + 1 + 1 + 2 + sizeof(char) * strlen(g_version_hash));
1243 pkt << (u8) VERSION_MAJOR << (u8) VERSION_MINOR << (u8) VERSION_PATCH
1244 << (u8) 0 << (u16) strlen(g_version_hash);
1246 pkt.putRawString(g_version_hash, (u16) strlen(g_version_hash));
1250 void Client::sendPlayerPos()
1252 LocalPlayer *myplayer = m_env.getLocalPlayer();
1253 if(myplayer == NULL)
1256 // Save bandwidth by only updating position when something changed
1257 if(myplayer->last_position == myplayer->getPosition() &&
1258 myplayer->last_speed == myplayer->getSpeed() &&
1259 myplayer->last_pitch == myplayer->getPitch() &&
1260 myplayer->last_yaw == myplayer->getYaw() &&
1261 myplayer->last_keyPressed == myplayer->keyPressed)
1264 myplayer->last_position = myplayer->getPosition();
1265 myplayer->last_speed = myplayer->getSpeed();
1266 myplayer->last_pitch = myplayer->getPitch();
1267 myplayer->last_yaw = myplayer->getYaw();
1268 myplayer->last_keyPressed = myplayer->keyPressed;
1272 //JMutexAutoLock lock(m_con_mutex); //bulk comment-out
1273 our_peer_id = m_con.GetPeerID();
1276 // Set peer id if not set already
1277 if(myplayer->peer_id == PEER_ID_INEXISTENT)
1278 myplayer->peer_id = our_peer_id;
1280 assert(myplayer->peer_id == our_peer_id);
1282 v3f pf = myplayer->getPosition();
1283 v3f sf = myplayer->getSpeed();
1284 s32 pitch = myplayer->getPitch() * 100;
1285 s32 yaw = myplayer->getYaw() * 100;
1286 u32 keyPressed = myplayer->keyPressed;
1288 v3s32 position(pf.X*100, pf.Y*100, pf.Z*100);
1289 v3s32 speed(sf.X*100, sf.Y*100, sf.Z*100);
1292 [0] v3s32 position*100
1293 [12] v3s32 speed*100
1294 [12+12] s32 pitch*100
1295 [12+12+4] s32 yaw*100
1296 [12+12+4+4] u32 keyPressed
1299 NetworkPacket pkt(TOSERVER_PLAYERPOS, 12 + 12 + 4 + 4 + 4);
1301 pkt << position << speed << pitch << yaw << keyPressed;
1306 void Client::sendPlayerItem(u16 item)
1308 Player *myplayer = m_env.getLocalPlayer();
1309 if(myplayer == NULL)
1312 u16 our_peer_id = m_con.GetPeerID();
1314 // Set peer id if not set already
1315 if(myplayer->peer_id == PEER_ID_INEXISTENT)
1316 myplayer->peer_id = our_peer_id;
1317 assert(myplayer->peer_id == our_peer_id);
1319 NetworkPacket pkt(TOSERVER_PLAYERITEM, 2);
1326 void Client::removeNode(v3s16 p)
1328 std::map<v3s16, MapBlock*> modified_blocks;
1331 m_env.getMap().removeNodeAndUpdate(p, modified_blocks);
1333 catch(InvalidPositionException &e) {
1336 for(std::map<v3s16, MapBlock *>::iterator
1337 i = modified_blocks.begin();
1338 i != modified_blocks.end(); ++i) {
1339 addUpdateMeshTaskWithEdge(i->first, false, true);
1343 void Client::addNode(v3s16 p, MapNode n, bool remove_metadata)
1345 //TimeTaker timer1("Client::addNode()");
1347 std::map<v3s16, MapBlock*> modified_blocks;
1350 //TimeTaker timer3("Client::addNode(): addNodeAndUpdate");
1351 m_env.getMap().addNodeAndUpdate(p, n, modified_blocks, remove_metadata);
1353 catch(InvalidPositionException &e) {
1356 for(std::map<v3s16, MapBlock *>::iterator
1357 i = modified_blocks.begin();
1358 i != modified_blocks.end(); ++i) {
1359 addUpdateMeshTaskWithEdge(i->first, false, true);
1363 void Client::setPlayerControl(PlayerControl &control)
1365 LocalPlayer *player = m_env.getLocalPlayer();
1366 assert(player != NULL);
1367 player->control = control;
1370 void Client::selectPlayerItem(u16 item)
1372 m_playeritem = item;
1373 m_inventory_updated = true;
1374 sendPlayerItem(item);
1377 // Returns true if the inventory of the local player has been
1378 // updated from the server. If it is true, it is set to false.
1379 bool Client::getLocalInventoryUpdated()
1381 bool updated = m_inventory_updated;
1382 m_inventory_updated = false;
1386 // Copies the inventory of the local player to parameter
1387 void Client::getLocalInventory(Inventory &dst)
1389 Player *player = m_env.getLocalPlayer();
1390 assert(player != NULL);
1391 dst = player->inventory;
1394 Inventory* Client::getInventory(const InventoryLocation &loc)
1397 case InventoryLocation::UNDEFINED:
1400 case InventoryLocation::CURRENT_PLAYER:
1402 Player *player = m_env.getLocalPlayer();
1403 assert(player != NULL);
1404 return &player->inventory;
1407 case InventoryLocation::PLAYER:
1409 Player *player = m_env.getPlayer(loc.name.c_str());
1412 return &player->inventory;
1415 case InventoryLocation::NODEMETA:
1417 NodeMetadata *meta = m_env.getMap().getNodeMetadata(loc.p);
1420 return meta->getInventory();
1423 case InventoryLocation::DETACHED:
1425 if(m_detached_inventories.count(loc.name) == 0)
1427 return m_detached_inventories[loc.name];
1431 FATAL_ERROR("Invalid inventory location type.");
1437 void Client::inventoryAction(InventoryAction *a)
1440 Send it to the server
1442 sendInventoryAction(a);
1445 Predict some local inventory changes
1447 a->clientApply(this, this);
1453 ClientActiveObject * Client::getSelectedActiveObject(
1455 v3f from_pos_f_on_map,
1456 core::line3d<f32> shootline_on_map
1459 std::vector<DistanceSortedActiveObject> objects;
1461 m_env.getActiveObjects(from_pos_f_on_map, max_d, objects);
1464 // After this, the closest object is the first in the array.
1465 std::sort(objects.begin(), objects.end());
1467 for(unsigned int i=0; i<objects.size(); i++)
1469 ClientActiveObject *obj = objects[i].obj;
1471 core::aabbox3d<f32> *selection_box = obj->getSelectionBox();
1472 if(selection_box == NULL)
1475 v3f pos = obj->getPosition();
1477 core::aabbox3d<f32> offsetted_box(
1478 selection_box->MinEdge + pos,
1479 selection_box->MaxEdge + pos
1482 if(offsetted_box.intersectsWithLine(shootline_on_map))
1491 std::list<std::string> Client::getConnectedPlayerNames()
1493 return m_env.getPlayerNames();
1496 float Client::getAnimationTime()
1498 return m_animation_time;
1501 int Client::getCrackLevel()
1503 return m_crack_level;
1506 void Client::setHighlighted(v3s16 pos, bool show_highlighted)
1508 m_show_highlighted = show_highlighted;
1509 v3s16 old_highlighted_pos = m_highlighted_pos;
1510 m_highlighted_pos = pos;
1511 addUpdateMeshTaskForNode(old_highlighted_pos, false, true);
1512 addUpdateMeshTaskForNode(m_highlighted_pos, false, true);
1515 void Client::setCrack(int level, v3s16 pos)
1517 int old_crack_level = m_crack_level;
1518 v3s16 old_crack_pos = m_crack_pos;
1520 m_crack_level = level;
1523 if(old_crack_level >= 0 && (level < 0 || pos != old_crack_pos))
1526 addUpdateMeshTaskForNode(old_crack_pos, false, true);
1528 if(level >= 0 && (old_crack_level < 0 || pos != old_crack_pos))
1531 addUpdateMeshTaskForNode(pos, false, true);
1537 Player *player = m_env.getLocalPlayer();
1538 assert(player != NULL);
1542 u16 Client::getBreath()
1544 Player *player = m_env.getLocalPlayer();
1545 assert(player != NULL);
1546 return player->getBreath();
1549 bool Client::getChatMessage(std::wstring &message)
1551 if(m_chat_queue.size() == 0)
1553 message = m_chat_queue.front();
1558 void Client::typeChatMessage(const std::wstring &message)
1560 // Discard empty line
1565 sendChatMessage(message);
1568 if (message[0] == L'/')
1570 m_chat_queue.push((std::wstring)L"issued command: " + message);
1574 LocalPlayer *player = m_env.getLocalPlayer();
1575 assert(player != NULL);
1576 std::wstring name = narrow_to_wide(player->getName());
1577 m_chat_queue.push((std::wstring)L"<" + name + L"> " + message);
1581 void Client::addUpdateMeshTask(v3s16 p, bool ack_to_server, bool urgent)
1583 MapBlock *b = m_env.getMap().getBlockNoCreateNoEx(p);
1588 Create a task to update the mesh of the block
1591 MeshMakeData *data = new MeshMakeData(this, m_cache_enable_shaders);
1594 //TimeTaker timer("data fill");
1596 // Debug: 1-6ms, avg=2ms
1598 data->setCrack(m_crack_level, m_crack_pos);
1599 data->setHighlighted(m_highlighted_pos, m_show_highlighted);
1600 data->setSmoothLighting(m_cache_smooth_lighting);
1603 // Add task to queue
1604 m_mesh_update_thread.enqueueUpdate(p, data, ack_to_server, urgent);
1607 void Client::addUpdateMeshTaskWithEdge(v3s16 blockpos, bool ack_to_server, bool urgent)
1610 addUpdateMeshTask(blockpos, ack_to_server, urgent);
1612 catch(InvalidPositionException &e){}
1615 for (int i=0;i<6;i++)
1618 v3s16 p = blockpos + g_6dirs[i];
1619 addUpdateMeshTask(p, false, urgent);
1621 catch(InvalidPositionException &e){}
1625 void Client::addUpdateMeshTaskForNode(v3s16 nodepos, bool ack_to_server, bool urgent)
1629 infostream<<"Client::addUpdateMeshTaskForNode(): "
1630 <<"("<<p.X<<","<<p.Y<<","<<p.Z<<")"
1634 v3s16 blockpos = getNodeBlockPos(nodepos);
1635 v3s16 blockpos_relative = blockpos * MAP_BLOCKSIZE;
1638 addUpdateMeshTask(blockpos, ack_to_server, urgent);
1640 catch(InvalidPositionException &e) {}
1643 if(nodepos.X == blockpos_relative.X){
1645 v3s16 p = blockpos + v3s16(-1,0,0);
1646 addUpdateMeshTask(p, false, urgent);
1648 catch(InvalidPositionException &e){}
1651 if(nodepos.Y == blockpos_relative.Y){
1653 v3s16 p = blockpos + v3s16(0,-1,0);
1654 addUpdateMeshTask(p, false, urgent);
1656 catch(InvalidPositionException &e){}
1659 if(nodepos.Z == blockpos_relative.Z){
1661 v3s16 p = blockpos + v3s16(0,0,-1);
1662 addUpdateMeshTask(p, false, urgent);
1664 catch(InvalidPositionException &e){}
1668 ClientEvent Client::getClientEvent()
1671 if(m_client_event_queue.size() == 0) {
1672 event.type = CE_NONE;
1675 event = m_client_event_queue.front();
1676 m_client_event_queue.pop();
1681 float Client::mediaReceiveProgress()
1683 if (m_media_downloader)
1684 return m_media_downloader->getProgress();
1686 return 1.0; // downloader only exists when not yet done
1689 typedef struct TextureUpdateArgs {
1690 IrrlichtDevice *device;
1691 gui::IGUIEnvironment *guienv;
1694 const wchar_t* text_base;
1695 } TextureUpdateArgs;
1697 void texture_update_progress(void *args, u32 progress, u32 max_progress)
1699 TextureUpdateArgs* targs = (TextureUpdateArgs*) args;
1700 u16 cur_percent = ceil(progress / (double) max_progress * 100.);
1702 // update the loading menu -- if neccessary
1703 bool do_draw = false;
1704 u32 time_ms = targs->last_time_ms;
1705 if (cur_percent != targs->last_percent) {
1706 targs->last_percent = cur_percent;
1707 time_ms = getTimeMs();
1708 // only draw when the user will notice something:
1709 do_draw = (time_ms - targs->last_time_ms > 100);
1713 targs->last_time_ms = time_ms;
1714 std::basic_stringstream<wchar_t> strm;
1715 strm << targs->text_base << " " << targs->last_percent << "%...";
1716 draw_load_screen(strm.str(), targs->device, targs->guienv, 0,
1717 72 + (u16) ((18. / 100.) * (double) targs->last_percent));
1721 void Client::afterContentReceived(IrrlichtDevice *device)
1723 infostream<<"Client::afterContentReceived() started"<<std::endl;
1724 assert(m_itemdef_received); // pre-condition
1725 assert(m_nodedef_received); // pre-condition
1726 assert(mediaReceived()); // pre-condition
1728 const wchar_t* text = wgettext("Loading textures...");
1730 // Clear cached pre-scaled 2D GUI images, as this cache
1731 // might have images with the same name but different
1732 // content from previous sessions.
1733 guiScalingCacheClear(device->getVideoDriver());
1735 // Rebuild inherited images and recreate textures
1736 infostream<<"- Rebuilding images and textures"<<std::endl;
1737 draw_load_screen(text,device, guienv, 0, 70);
1738 m_tsrc->rebuildImagesAndTextures();
1742 infostream<<"- Rebuilding shaders"<<std::endl;
1743 text = wgettext("Rebuilding shaders...");
1744 draw_load_screen(text, device, guienv, 0, 71);
1745 m_shsrc->rebuildShaders();
1748 // Update node aliases
1749 infostream<<"- Updating node aliases"<<std::endl;
1750 text = wgettext("Initializing nodes...");
1751 draw_load_screen(text, device, guienv, 0, 72);
1752 m_nodedef->updateAliases(m_itemdef);
1753 std::string texture_path = g_settings->get("texture_path");
1754 if (texture_path != "" && fs::IsDir(texture_path))
1755 m_nodedef->applyTextureOverrides(texture_path + DIR_DELIM + "override.txt");
1756 m_nodedef->setNodeRegistrationStatus(true);
1757 m_nodedef->runNodeResolveCallbacks();
1760 // Update node textures and assign shaders to each tile
1761 infostream<<"- Updating node textures"<<std::endl;
1762 TextureUpdateArgs tu_args;
1763 tu_args.device = device;
1764 tu_args.guienv = guienv;
1765 tu_args.last_time_ms = getTimeMs();
1766 tu_args.last_percent = 0;
1767 tu_args.text_base = wgettext("Initializing nodes");
1768 m_nodedef->updateTextures(this, texture_update_progress, &tu_args);
1769 delete[] tu_args.text_base;
1771 // Preload item textures and meshes if configured to
1772 if(g_settings->getBool("preload_item_visuals"))
1774 verbosestream<<"Updating item textures and meshes"<<std::endl;
1775 text = wgettext("Item textures...");
1776 draw_load_screen(text, device, guienv, 0, 0);
1777 std::set<std::string> names = m_itemdef->getAll();
1778 size_t size = names.size();
1781 for(std::set<std::string>::const_iterator
1782 i = names.begin(); i != names.end(); ++i)
1784 // Asking for these caches the result
1785 m_itemdef->getInventoryTexture(*i, this);
1786 m_itemdef->getWieldMesh(*i, this);
1788 percent = (count * 100 / size * 0.2) + 80;
1789 draw_load_screen(text, device, guienv, 0, percent);
1794 // Start mesh update thread after setting up content definitions
1795 infostream<<"- Starting mesh update thread"<<std::endl;
1796 m_mesh_update_thread.Start();
1800 text = wgettext("Done!");
1801 draw_load_screen(text, device, guienv, 0, 100);
1802 infostream<<"Client::afterContentReceived() done"<<std::endl;
1806 float Client::getRTT(void)
1808 return m_con.getPeerStat(PEER_ID_SERVER,con::AVG_RTT);
1811 float Client::getCurRate(void)
1813 return ( m_con.getLocalStat(con::CUR_INC_RATE) +
1814 m_con.getLocalStat(con::CUR_DL_RATE));
1817 float Client::getAvgRate(void)
1819 return ( m_con.getLocalStat(con::AVG_INC_RATE) +
1820 m_con.getLocalStat(con::AVG_DL_RATE));
1823 void Client::makeScreenshot(IrrlichtDevice *device)
1825 irr::video::IVideoDriver *driver = device->getVideoDriver();
1826 irr::video::IImage* const raw_image = driver->createScreenShot();
1831 time_t t = time(NULL);
1832 struct tm *tm = localtime(&t);
1834 char timetstamp_c[64];
1835 strftime(timetstamp_c, sizeof(timetstamp_c), "%Y%m%d_%H%M%S", tm);
1837 std::string filename_base = g_settings->get("screenshot_path")
1839 + std::string("screenshot_")
1840 + std::string(timetstamp_c);
1841 std::string filename_ext = ".png";
1842 std::string filename;
1844 // Try to find a unique filename
1845 unsigned serial = 0;
1847 while (serial < SCREENSHOT_MAX_SERIAL_TRIES) {
1848 filename = filename_base + (serial > 0 ? ("_" + itos(serial)) : "") + filename_ext;
1849 std::ifstream tmp(filename.c_str());
1851 break; // File did not apparently exist, we'll go with it
1855 if (serial == SCREENSHOT_MAX_SERIAL_TRIES) {
1856 infostream << "Could not find suitable filename for screenshot" << std::endl;
1858 irr::video::IImage* const image =
1859 driver->createImage(video::ECF_R8G8B8, raw_image->getDimension());
1862 raw_image->copyTo(image);
1864 std::ostringstream sstr;
1865 if (driver->writeImageToFile(image, filename.c_str())) {
1866 sstr << "Saved screenshot to '" << filename << "'";
1868 sstr << "Failed to save screenshot '" << filename << "'";
1870 m_chat_queue.push(narrow_to_wide(sstr.str()));
1871 infostream << sstr.str() << std::endl;
1879 // IGameDef interface
1881 IItemDefManager* Client::getItemDefManager()
1885 INodeDefManager* Client::getNodeDefManager()
1889 ICraftDefManager* Client::getCraftDefManager()
1892 //return m_craftdef;
1894 ITextureSource* Client::getTextureSource()
1898 IShaderSource* Client::getShaderSource()
1902 scene::ISceneManager* Client::getSceneManager()
1904 return m_device->getSceneManager();
1906 u16 Client::allocateUnknownNodeId(const std::string &name)
1908 errorstream << "Client::allocateUnknownNodeId(): "
1909 << "Client cannot allocate node IDs" << std::endl;
1910 FATAL_ERROR("Client allocated unknown node");
1912 return CONTENT_IGNORE;
1914 ISoundManager* Client::getSoundManager()
1918 MtEventManager* Client::getEventManager()
1923 ParticleManager* Client::getParticleManager()
1925 return &m_particle_manager;
1928 scene::IAnimatedMesh* Client::getMesh(const std::string &filename)
1930 StringMap::const_iterator it = m_mesh_data.find(filename);
1931 if (it == m_mesh_data.end()) {
1932 errorstream << "Client::getMesh(): Mesh not found: \"" << filename
1933 << "\"" << std::endl;
1936 const std::string &data = it->second;
1937 scene::ISceneManager *smgr = m_device->getSceneManager();
1939 // Create the mesh, remove it from cache and return it
1940 // This allows unique vertex colors and other properties for each instance
1941 Buffer<char> data_rw(data.c_str(), data.size()); // Const-incorrect Irrlicht
1942 io::IFileSystem *irrfs = m_device->getFileSystem();
1943 io::IReadFile *rfile = irrfs->createMemoryReadFile(
1944 *data_rw, data_rw.getSize(), filename.c_str());
1945 FATAL_ERROR_IF(!rfile, "Could not create/open RAM file");
1947 scene::IAnimatedMesh *mesh = smgr->getMesh(rfile);
1949 // NOTE: By playing with Irrlicht refcounts, maybe we could cache a bunch
1950 // of uniquely named instances and re-use them
1952 smgr->getMeshCache()->removeMesh(mesh);