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);
319 void Client::connect(Address address,
320 const std::string &address_name,
321 bool is_local_server)
323 DSTACK(__FUNCTION_NAME);
325 initLocalMapSaving(address, address_name, is_local_server);
327 m_con.SetTimeoutMs(0);
328 m_con.Connect(address);
331 void Client::step(float dtime)
333 DSTACK(__FUNCTION_NAME);
339 if(m_ignore_damage_timer > dtime)
340 m_ignore_damage_timer -= dtime;
342 m_ignore_damage_timer = 0.0;
344 m_animation_time += dtime;
345 if(m_animation_time > 60.0)
346 m_animation_time -= 60.0;
348 m_time_of_day_update_timer += dtime;
356 float &counter = m_packetcounter_timer;
362 infostream << "Client packetcounter (" << m_packetcounter_timer
364 m_packetcounter.print(infostream);
365 m_packetcounter.clear();
369 // UGLY hack to fix 2 second startup delay caused by non existent
370 // server client startup synchronization in local server or singleplayer mode
371 static bool initial_step = true;
373 initial_step = false;
375 else if(m_state == LC_Created) {
376 float &counter = m_connection_reinit_timer;
381 Player *myplayer = m_env.getLocalPlayer();
382 FATAL_ERROR_IF(myplayer == NULL, "Local player not found in environment.");
384 // Send TOSERVER_INIT_LEGACY
385 // [0] u16 TOSERVER_INIT_LEGACY
386 // [2] u8 SER_FMT_VER_HIGHEST_READ
387 // [3] u8[20] player_name
388 // [23] u8[28] password (new in some version)
389 // [51] u16 minimum supported network protocol version (added sometime)
390 // [53] u16 maximum supported network protocol version (added later than the previous one)
392 char pName[PLAYERNAME_SIZE];
393 char pPassword[PASSWORD_SIZE];
394 memset(pName, 0, PLAYERNAME_SIZE * sizeof(char));
395 memset(pPassword, 0, PASSWORD_SIZE * sizeof(char));
397 std::string hashed_password = translatePassword(myplayer->getName(), m_password);
398 snprintf(pName, PLAYERNAME_SIZE, "%s", myplayer->getName());
399 snprintf(pPassword, PASSWORD_SIZE, "%s", hashed_password.c_str());
401 sendLegacyInit(pName, pPassword);
402 if (LATEST_PROTOCOL_VERSION >= 25)
403 sendInit(myplayer->getName());
406 // Not connected, return
411 Do stuff if connected
415 Run Map's timers and unload unused data
417 const float map_timer_and_unload_dtime = 5.25;
418 if(m_map_timer_and_unload_interval.step(dtime, map_timer_and_unload_dtime)) {
419 ScopeProfiler sp(g_profiler, "Client: map timer and unload");
420 std::vector<v3s16> deleted_blocks;
421 m_env.getMap().timerUpdate(map_timer_and_unload_dtime,
422 g_settings->getFloat("client_unload_unused_data_timeout"),
427 NOTE: This loop is intentionally iterated the way it is.
430 std::vector<v3s16>::iterator i = deleted_blocks.begin();
431 std::vector<v3s16> sendlist;
433 if(sendlist.size() == 255 || i == deleted_blocks.end()) {
444 sendDeletedBlocks(sendlist);
446 if(i == deleted_blocks.end())
452 sendlist.push_back(*i);
460 // Control local player (0ms)
461 LocalPlayer *player = m_env.getLocalPlayer();
462 assert(player != NULL);
463 player->applyControl(dtime);
472 ClientEnvEvent event = m_env.getClientEvent();
473 if(event.type == CEE_NONE) {
476 else if(event.type == CEE_PLAYER_DAMAGE) {
477 if(m_ignore_damage_timer <= 0) {
478 u8 damage = event.player_damage.amount;
480 if(event.player_damage.send_to_server)
483 // Add to ClientEvent queue
485 event.type = CE_PLAYER_DAMAGE;
486 event.player_damage.amount = damage;
487 m_client_event_queue.push(event);
490 else if(event.type == CEE_PLAYER_BREATH) {
491 u16 breath = event.player_breath.amount;
499 float &counter = m_avg_rtt_timer;
503 // connectedAndInitialized() is true, peer exists.
504 float avg_rtt = getRTT();
505 infostream << "Client: avg_rtt=" << avg_rtt << std::endl;
509 Send player position to server
512 float &counter = m_playerpos_send_timer;
514 if((m_state == LC_Ready) && (counter >= m_recommended_send_interval))
522 Replace updated meshes
525 int num_processed_meshes = 0;
526 while (!m_mesh_update_thread.m_queue_out.empty())
528 num_processed_meshes++;
530 MinimapMapblock *minimap_mapblock = NULL;
531 bool do_mapper_update = true;
533 MeshUpdateResult r = m_mesh_update_thread.m_queue_out.pop_frontNoEx();
534 MapBlock *block = m_env.getMap().getBlockNoCreateNoEx(r.p);
536 // Delete the old mesh
537 if (block->mesh != NULL) {
543 minimap_mapblock = r.mesh->moveMinimapMapblock();
544 if (minimap_mapblock == NULL)
545 do_mapper_update = false;
548 if (r.mesh && r.mesh->getMesh()->getMeshBufferCount() == 0) {
551 // Replace with the new mesh
552 block->mesh = r.mesh;
558 if (do_mapper_update)
559 m_mapper->addBlock(r.p, minimap_mapblock);
561 if (r.ack_block_to_server) {
571 if (num_processed_meshes > 0)
572 g_profiler->graphAdd("num_processed_meshes", num_processed_meshes);
578 if (m_media_downloader && m_media_downloader->isStarted()) {
579 m_media_downloader->step(this);
580 if (m_media_downloader->isDone()) {
582 delete m_media_downloader;
583 m_media_downloader = NULL;
588 If the server didn't update the inventory in a while, revert
589 the local inventory (so the player notices the lag problem
590 and knows something is wrong).
592 if(m_inventory_from_server)
594 float interval = 10.0;
595 float count_before = floor(m_inventory_from_server_age / interval);
597 m_inventory_from_server_age += dtime;
599 float count_after = floor(m_inventory_from_server_age / interval);
601 if(count_after != count_before)
603 // Do this every <interval> seconds after TOCLIENT_INVENTORY
604 // Reset the locally changed inventory to the authoritative inventory
605 Player *player = m_env.getLocalPlayer();
606 player->inventory = *m_inventory_from_server;
607 m_inventory_updated = true;
612 Update positions of sounds attached to objects
615 for(std::map<int, u16>::iterator
616 i = m_sounds_to_objects.begin();
617 i != m_sounds_to_objects.end(); i++)
619 int client_id = i->first;
620 u16 object_id = i->second;
621 ClientActiveObject *cao = m_env.getActiveObject(object_id);
624 v3f pos = cao->getPosition();
625 m_sound->updateSoundPosition(client_id, pos);
630 Handle removed remotely initiated sounds
632 m_removed_sounds_check_timer += dtime;
633 if(m_removed_sounds_check_timer >= 2.32) {
634 m_removed_sounds_check_timer = 0;
635 // Find removed sounds and clear references to them
636 std::vector<s32> removed_server_ids;
637 for(std::map<s32, int>::iterator
638 i = m_sounds_server_to_client.begin();
639 i != m_sounds_server_to_client.end();) {
640 s32 server_id = i->first;
641 int client_id = i->second;
643 if(!m_sound->soundExists(client_id)) {
644 m_sounds_server_to_client.erase(server_id);
645 m_sounds_client_to_server.erase(client_id);
646 m_sounds_to_objects.erase(client_id);
647 removed_server_ids.push_back(server_id);
652 if(!removed_server_ids.empty()) {
653 sendRemovedSounds(removed_server_ids);
658 if (m_localdb && m_localdb_save_interval.step(dtime,
659 m_cache_save_interval)) {
660 m_localdb->endSave();
661 m_localdb->beginSave();
665 bool Client::loadMedia(const std::string &data, const std::string &filename)
667 // Silly irrlicht's const-incorrectness
668 Buffer<char> data_rw(data.c_str(), data.size());
672 const char *image_ext[] = {
673 ".png", ".jpg", ".bmp", ".tga",
674 ".pcx", ".ppm", ".psd", ".wal", ".rgb",
677 name = removeStringEnd(filename, image_ext);
680 verbosestream<<"Client: Attempting to load image "
681 <<"file \""<<filename<<"\""<<std::endl;
683 io::IFileSystem *irrfs = m_device->getFileSystem();
684 video::IVideoDriver *vdrv = m_device->getVideoDriver();
686 // Create an irrlicht memory file
687 io::IReadFile *rfile = irrfs->createMemoryReadFile(
688 *data_rw, data_rw.getSize(), "_tempreadfile");
690 FATAL_ERROR_IF(!rfile, "Could not create irrlicht memory file.");
693 video::IImage *img = vdrv->createImageFromFile(rfile);
695 errorstream<<"Client: Cannot create image from data of "
696 <<"file \""<<filename<<"\""<<std::endl;
701 m_tsrc->insertSourceImage(filename, img);
708 const char *sound_ext[] = {
709 ".0.ogg", ".1.ogg", ".2.ogg", ".3.ogg", ".4.ogg",
710 ".5.ogg", ".6.ogg", ".7.ogg", ".8.ogg", ".9.ogg",
713 name = removeStringEnd(filename, sound_ext);
716 verbosestream<<"Client: Attempting to load sound "
717 <<"file \""<<filename<<"\""<<std::endl;
718 m_sound->loadSoundData(name, data);
722 const char *model_ext[] = {
723 ".x", ".b3d", ".md2", ".obj",
726 name = removeStringEnd(filename, model_ext);
729 verbosestream<<"Client: Storing model into memory: "
730 <<"\""<<filename<<"\""<<std::endl;
731 if(m_mesh_data.count(filename))
732 errorstream<<"Multiple models with name \""<<filename.c_str()
733 <<"\" found; replacing previous model"<<std::endl;
734 m_mesh_data[filename] = data;
738 errorstream<<"Client: Don't know how to load file \""
739 <<filename<<"\""<<std::endl;
743 // Virtual methods from con::PeerHandler
744 void Client::peerAdded(con::Peer *peer)
746 infostream << "Client::peerAdded(): peer->id="
747 << peer->id << std::endl;
749 void Client::deletingPeer(con::Peer *peer, bool timeout)
751 infostream << "Client::deletingPeer(): "
752 "Server Peer is getting deleted "
753 << "(timeout=" << timeout << ")" << std::endl;
756 m_access_denied = true;
757 m_access_denied_reason = gettext("Connection timed out.");
763 u16 number of files requested
769 void Client::request_media(const std::vector<std::string> &file_requests)
771 std::ostringstream os(std::ios_base::binary);
772 writeU16(os, TOSERVER_REQUEST_MEDIA);
773 size_t file_requests_size = file_requests.size();
775 FATAL_ERROR_IF(file_requests_size > 0xFFFF, "Unsupported number of file requests");
777 // Packet dynamicly resized
778 NetworkPacket pkt(TOSERVER_REQUEST_MEDIA, 2 + 0);
780 pkt << (u16) (file_requests_size & 0xFFFF);
782 for(std::vector<std::string>::const_iterator i = file_requests.begin();
783 i != file_requests.end(); ++i) {
789 infostream << "Client: Sending media request list to server ("
790 << file_requests.size() << " files. packet size)" << std::endl;
793 void Client::received_media()
795 NetworkPacket pkt(TOSERVER_RECEIVED_MEDIA, 0);
797 infostream << "Client: Notifying server that we received all media"
801 void Client::initLocalMapSaving(const Address &address,
802 const std::string &hostname,
803 bool is_local_server)
805 if (!g_settings->getBool("enable_local_map_saving") || is_local_server) {
809 const std::string world_path = porting::path_user
810 + DIR_DELIM + "worlds"
811 + DIR_DELIM + "server_"
812 + hostname + "_" + to_string(address.getPort());
814 fs::CreateAllDirs(world_path);
816 m_localdb = new Database_SQLite3(world_path);
817 m_localdb->beginSave();
818 actionstream << "Local map saving started, map will be saved at '" << world_path << "'" << std::endl;
821 void Client::ReceiveAll()
823 DSTACK(__FUNCTION_NAME);
824 u32 start_ms = porting::getTimeMs();
827 // Limit time even if there would be huge amounts of data to
829 if(porting::getTimeMs() > start_ms + 100)
834 g_profiler->graphAdd("client_received_packets", 1);
836 catch(con::NoIncomingDataException &e) {
839 catch(con::InvalidIncomingDataException &e) {
840 infostream<<"Client::ReceiveAll(): "
841 "InvalidIncomingDataException: what()="
842 <<e.what()<<std::endl;
847 void Client::Receive()
849 DSTACK(__FUNCTION_NAME);
855 inline void Client::handleCommand(NetworkPacket* pkt)
857 const ToClientCommandHandler& opHandle = toClientCommandTable[pkt->getCommand()];
858 (this->*opHandle.handler)(pkt);
862 sender_peer_id given to this shall be quaranteed to be a valid peer
864 void Client::ProcessData(NetworkPacket *pkt)
866 DSTACK(__FUNCTION_NAME);
868 ToClientCommand command = (ToClientCommand) pkt->getCommand();
869 u32 sender_peer_id = pkt->getPeerId();
871 //infostream<<"Client: received command="<<command<<std::endl;
872 m_packetcounter.add((u16)command);
875 If this check is removed, be sure to change the queue
876 system to know the ids
878 if(sender_peer_id != PEER_ID_SERVER) {
879 infostream << "Client::ProcessData(): Discarding data not "
880 "coming from server: peer_id=" << sender_peer_id
885 // Command must be handled into ToClientCommandHandler
886 if (command >= TOCLIENT_NUM_MSG_TYPES) {
887 infostream << "Client: Ignoring unknown command "
888 << command << std::endl;
893 * Those packets are handled before m_server_ser_ver is set, it's normal
894 * But we must use the new ToClientConnectionState in the future,
897 if(toClientCommandTable[command].state == TOCLIENT_STATE_NOT_CONNECTED) {
902 if(m_server_ser_ver == SER_FMT_VER_INVALID) {
903 infostream << "Client: Server serialization"
904 " format invalid or not initialized."
905 " Skipping incoming command=" << command << std::endl;
910 Handle runtime commands
916 void Client::Send(NetworkPacket* pkt)
918 m_con.Send(PEER_ID_SERVER,
919 serverCommandFactoryTable[pkt->getCommand()].channel,
921 serverCommandFactoryTable[pkt->getCommand()].reliable);
924 void Client::interact(u8 action, const PointedThing& pointed)
926 if(m_state != LC_Ready) {
927 errorstream << "Client::interact() "
928 "Canceled (not connected)"
937 [5] u32 length of the next item
938 [9] serialized PointedThing
940 0: start digging (from undersurface) or use
941 1: stop digging (all parameters ignored)
943 3: place block or item (to abovesurface)
947 NetworkPacket pkt(TOSERVER_INTERACT, 1 + 2 + 0);
950 pkt << (u16)getPlayerItem();
952 std::ostringstream tmp_os(std::ios::binary);
953 pointed.serialize(tmp_os);
955 pkt.putLongString(tmp_os.str());
960 void Client::deleteAuthData()
965 switch (m_chosen_auth_mech) {
966 case AUTH_MECHANISM_FIRST_SRP:
968 case AUTH_MECHANISM_SRP:
969 case AUTH_MECHANISM_LEGACY_PASSWORD:
970 srp_user_delete((SRPUser *) m_auth_data);
973 case AUTH_MECHANISM_NONE:
976 m_chosen_auth_mech = AUTH_MECHANISM_NONE;
980 AuthMechanism Client::choseAuthMech(const u32 mechs)
982 if (mechs & AUTH_MECHANISM_SRP)
983 return AUTH_MECHANISM_SRP;
985 if (mechs & AUTH_MECHANISM_FIRST_SRP)
986 return AUTH_MECHANISM_FIRST_SRP;
988 if (mechs & AUTH_MECHANISM_LEGACY_PASSWORD)
989 return AUTH_MECHANISM_LEGACY_PASSWORD;
991 return AUTH_MECHANISM_NONE;
994 void Client::sendLegacyInit(const char* playerName, const char* playerPassword)
996 NetworkPacket pkt(TOSERVER_INIT_LEGACY,
997 1 + PLAYERNAME_SIZE + PASSWORD_SIZE + 2 + 2);
999 pkt << (u8) SER_FMT_VER_HIGHEST_READ;
1000 pkt.putRawString(playerName,PLAYERNAME_SIZE);
1001 pkt.putRawString(playerPassword, PASSWORD_SIZE);
1002 pkt << (u16) CLIENT_PROTOCOL_VERSION_MIN << (u16) CLIENT_PROTOCOL_VERSION_MAX;
1007 void Client::sendInit(const std::string &playerName)
1009 NetworkPacket pkt(TOSERVER_INIT, 1 + 2 + 2 + (1 + playerName.size()));
1011 // we don't support network compression yet
1012 u16 supp_comp_modes = NETPROTO_COMPRESSION_NONE;
1013 pkt << (u8) SER_FMT_VER_HIGHEST_READ << (u16) supp_comp_modes;
1014 pkt << (u16) CLIENT_PROTOCOL_VERSION_MIN << (u16) CLIENT_PROTOCOL_VERSION_MAX;
1020 void Client::startAuth(AuthMechanism chosen_auth_mechanism)
1022 m_chosen_auth_mech = chosen_auth_mechanism;
1024 switch (chosen_auth_mechanism) {
1025 case AUTH_MECHANISM_FIRST_SRP: {
1026 // send srp verifier to server
1027 NetworkPacket resp_pkt(TOSERVER_FIRST_SRP, 0);
1028 char *salt, *bytes_v;
1029 std::size_t len_salt, len_v;
1031 getSRPVerifier(getPlayerName(), m_password,
1032 &salt, &len_salt, &bytes_v, &len_v);
1034 << std::string((char*)salt, len_salt)
1035 << std::string((char*)bytes_v, len_v)
1036 << (u8)((m_password == "") ? 1 : 0);
1042 case AUTH_MECHANISM_SRP:
1043 case AUTH_MECHANISM_LEGACY_PASSWORD: {
1046 if (chosen_auth_mechanism == AUTH_MECHANISM_LEGACY_PASSWORD) {
1047 m_password = translatePassword(getPlayerName(), m_password);
1051 std::string playername_u = lowercase(getPlayerName());
1052 m_auth_data = srp_user_new(SRP_SHA256, SRP_NG_2048,
1053 getPlayerName().c_str(), playername_u.c_str(),
1054 (const unsigned char *) m_password.c_str(),
1055 m_password.length(), NULL, NULL);
1058 srp_user_start_authentication((struct SRPUser *) m_auth_data,
1059 NULL, NULL, 0, (unsigned char **) &bytes_A, &len_A);
1061 NetworkPacket resp_pkt(TOSERVER_SRP_BYTES_A, 0);
1062 resp_pkt << std::string(bytes_A, len_A) << based_on;
1066 case AUTH_MECHANISM_NONE:
1067 break; // not handled in this method
1071 void Client::sendDeletedBlocks(std::vector<v3s16> &blocks)
1073 NetworkPacket pkt(TOSERVER_DELETEDBLOCKS, 1 + sizeof(v3s16) * blocks.size());
1075 pkt << (u8) blocks.size();
1078 for(std::vector<v3s16>::iterator
1080 j != blocks.end(); ++j) {
1088 void Client::sendGotBlocks(v3s16 block)
1090 NetworkPacket pkt(TOSERVER_GOTBLOCKS, 1 + 6);
1091 pkt << (u8) 1 << block;
1095 void Client::sendRemovedSounds(std::vector<s32> &soundList)
1097 size_t server_ids = soundList.size();
1098 assert(server_ids <= 0xFFFF);
1100 NetworkPacket pkt(TOSERVER_REMOVED_SOUNDS, 2 + server_ids * 4);
1102 pkt << (u16) (server_ids & 0xFFFF);
1104 for(std::vector<s32>::iterator i = soundList.begin();
1105 i != soundList.end(); i++)
1111 void Client::sendNodemetaFields(v3s16 p, const std::string &formname,
1112 const StringMap &fields)
1114 size_t fields_size = fields.size();
1116 FATAL_ERROR_IF(fields_size > 0xFFFF, "Unsupported number of nodemeta fields");
1118 NetworkPacket pkt(TOSERVER_NODEMETA_FIELDS, 0);
1120 pkt << p << formname << (u16) (fields_size & 0xFFFF);
1122 StringMap::const_iterator it;
1123 for (it = fields.begin(); it != fields.end(); ++it) {
1124 const std::string &name = it->first;
1125 const std::string &value = it->second;
1127 pkt.putLongString(value);
1133 void Client::sendInventoryFields(const std::string &formname,
1134 const StringMap &fields)
1136 size_t fields_size = fields.size();
1137 FATAL_ERROR_IF(fields_size > 0xFFFF, "Unsupported number of inventory fields");
1139 NetworkPacket pkt(TOSERVER_INVENTORY_FIELDS, 0);
1140 pkt << formname << (u16) (fields_size & 0xFFFF);
1142 StringMap::const_iterator it;
1143 for (it = fields.begin(); it != fields.end(); ++it) {
1144 const std::string &name = it->first;
1145 const std::string &value = it->second;
1147 pkt.putLongString(value);
1153 void Client::sendInventoryAction(InventoryAction *a)
1155 std::ostringstream os(std::ios_base::binary);
1160 std::string s = os.str();
1162 NetworkPacket pkt(TOSERVER_INVENTORY_ACTION, s.size());
1163 pkt.putRawString(s.c_str(),s.size());
1168 void Client::sendChatMessage(const std::wstring &message)
1170 NetworkPacket pkt(TOSERVER_CHAT_MESSAGE, 2 + message.size() * sizeof(u16));
1177 void Client::sendChangePassword(const std::string &oldpassword,
1178 const std::string &newpassword)
1180 Player *player = m_env.getLocalPlayer();
1184 std::string playername = player->getName();
1185 if (m_proto_ver >= 25) {
1186 // get into sudo mode and then send new password to server
1187 m_password = oldpassword;
1188 m_new_password = newpassword;
1189 startAuth(choseAuthMech(m_sudo_auth_methods));
1191 std::string oldpwd = translatePassword(playername, oldpassword);
1192 std::string newpwd = translatePassword(playername, newpassword);
1194 NetworkPacket pkt(TOSERVER_PASSWORD_LEGACY, 2 * PASSWORD_SIZE);
1196 for (u8 i = 0; i < PASSWORD_SIZE; i++) {
1197 pkt << (u8) (i < oldpwd.length() ? oldpwd[i] : 0);
1200 for (u8 i = 0; i < PASSWORD_SIZE; i++) {
1201 pkt << (u8) (i < newpwd.length() ? newpwd[i] : 0);
1208 void Client::sendDamage(u8 damage)
1210 DSTACK(__FUNCTION_NAME);
1212 NetworkPacket pkt(TOSERVER_DAMAGE, sizeof(u8));
1217 void Client::sendBreath(u16 breath)
1219 DSTACK(__FUNCTION_NAME);
1221 NetworkPacket pkt(TOSERVER_BREATH, sizeof(u16));
1226 void Client::sendRespawn()
1228 DSTACK(__FUNCTION_NAME);
1230 NetworkPacket pkt(TOSERVER_RESPAWN, 0);
1234 void Client::sendReady()
1236 DSTACK(__FUNCTION_NAME);
1238 NetworkPacket pkt(TOSERVER_CLIENT_READY,
1239 1 + 1 + 1 + 1 + 2 + sizeof(char) * strlen(g_version_hash));
1241 pkt << (u8) VERSION_MAJOR << (u8) VERSION_MINOR << (u8) VERSION_PATCH
1242 << (u8) 0 << (u16) strlen(g_version_hash);
1244 pkt.putRawString(g_version_hash, (u16) strlen(g_version_hash));
1248 void Client::sendPlayerPos()
1250 LocalPlayer *myplayer = m_env.getLocalPlayer();
1251 if(myplayer == NULL)
1254 // Save bandwidth by only updating position when something changed
1255 if(myplayer->last_position == myplayer->getPosition() &&
1256 myplayer->last_speed == myplayer->getSpeed() &&
1257 myplayer->last_pitch == myplayer->getPitch() &&
1258 myplayer->last_yaw == myplayer->getYaw() &&
1259 myplayer->last_keyPressed == myplayer->keyPressed)
1262 myplayer->last_position = myplayer->getPosition();
1263 myplayer->last_speed = myplayer->getSpeed();
1264 myplayer->last_pitch = myplayer->getPitch();
1265 myplayer->last_yaw = myplayer->getYaw();
1266 myplayer->last_keyPressed = myplayer->keyPressed;
1270 //JMutexAutoLock lock(m_con_mutex); //bulk comment-out
1271 our_peer_id = m_con.GetPeerID();
1274 // Set peer id if not set already
1275 if(myplayer->peer_id == PEER_ID_INEXISTENT)
1276 myplayer->peer_id = our_peer_id;
1278 assert(myplayer->peer_id == our_peer_id);
1280 v3f pf = myplayer->getPosition();
1281 v3f sf = myplayer->getSpeed();
1282 s32 pitch = myplayer->getPitch() * 100;
1283 s32 yaw = myplayer->getYaw() * 100;
1284 u32 keyPressed = myplayer->keyPressed;
1286 v3s32 position(pf.X*100, pf.Y*100, pf.Z*100);
1287 v3s32 speed(sf.X*100, sf.Y*100, sf.Z*100);
1290 [0] v3s32 position*100
1291 [12] v3s32 speed*100
1292 [12+12] s32 pitch*100
1293 [12+12+4] s32 yaw*100
1294 [12+12+4+4] u32 keyPressed
1297 NetworkPacket pkt(TOSERVER_PLAYERPOS, 12 + 12 + 4 + 4 + 4);
1299 pkt << position << speed << pitch << yaw << keyPressed;
1304 void Client::sendPlayerItem(u16 item)
1306 Player *myplayer = m_env.getLocalPlayer();
1307 if(myplayer == NULL)
1310 u16 our_peer_id = m_con.GetPeerID();
1312 // Set peer id if not set already
1313 if(myplayer->peer_id == PEER_ID_INEXISTENT)
1314 myplayer->peer_id = our_peer_id;
1315 assert(myplayer->peer_id == our_peer_id);
1317 NetworkPacket pkt(TOSERVER_PLAYERITEM, 2);
1324 void Client::removeNode(v3s16 p)
1326 std::map<v3s16, MapBlock*> modified_blocks;
1329 m_env.getMap().removeNodeAndUpdate(p, modified_blocks);
1331 catch(InvalidPositionException &e) {
1334 for(std::map<v3s16, MapBlock *>::iterator
1335 i = modified_blocks.begin();
1336 i != modified_blocks.end(); ++i) {
1337 addUpdateMeshTaskWithEdge(i->first, false, true);
1341 void Client::addNode(v3s16 p, MapNode n, bool remove_metadata)
1343 //TimeTaker timer1("Client::addNode()");
1345 std::map<v3s16, MapBlock*> modified_blocks;
1348 //TimeTaker timer3("Client::addNode(): addNodeAndUpdate");
1349 m_env.getMap().addNodeAndUpdate(p, n, modified_blocks, remove_metadata);
1351 catch(InvalidPositionException &e) {
1354 for(std::map<v3s16, MapBlock *>::iterator
1355 i = modified_blocks.begin();
1356 i != modified_blocks.end(); ++i) {
1357 addUpdateMeshTaskWithEdge(i->first, false, true);
1361 void Client::setPlayerControl(PlayerControl &control)
1363 LocalPlayer *player = m_env.getLocalPlayer();
1364 assert(player != NULL);
1365 player->control = control;
1368 void Client::selectPlayerItem(u16 item)
1370 m_playeritem = item;
1371 m_inventory_updated = true;
1372 sendPlayerItem(item);
1375 // Returns true if the inventory of the local player has been
1376 // updated from the server. If it is true, it is set to false.
1377 bool Client::getLocalInventoryUpdated()
1379 bool updated = m_inventory_updated;
1380 m_inventory_updated = false;
1384 // Copies the inventory of the local player to parameter
1385 void Client::getLocalInventory(Inventory &dst)
1387 Player *player = m_env.getLocalPlayer();
1388 assert(player != NULL);
1389 dst = player->inventory;
1392 Inventory* Client::getInventory(const InventoryLocation &loc)
1395 case InventoryLocation::UNDEFINED:
1398 case InventoryLocation::CURRENT_PLAYER:
1400 Player *player = m_env.getLocalPlayer();
1401 assert(player != NULL);
1402 return &player->inventory;
1405 case InventoryLocation::PLAYER:
1407 Player *player = m_env.getPlayer(loc.name.c_str());
1410 return &player->inventory;
1413 case InventoryLocation::NODEMETA:
1415 NodeMetadata *meta = m_env.getMap().getNodeMetadata(loc.p);
1418 return meta->getInventory();
1421 case InventoryLocation::DETACHED:
1423 if(m_detached_inventories.count(loc.name) == 0)
1425 return m_detached_inventories[loc.name];
1429 FATAL_ERROR("Invalid inventory location type.");
1435 void Client::inventoryAction(InventoryAction *a)
1438 Send it to the server
1440 sendInventoryAction(a);
1443 Predict some local inventory changes
1445 a->clientApply(this, this);
1451 ClientActiveObject * Client::getSelectedActiveObject(
1453 v3f from_pos_f_on_map,
1454 core::line3d<f32> shootline_on_map
1457 std::vector<DistanceSortedActiveObject> objects;
1459 m_env.getActiveObjects(from_pos_f_on_map, max_d, objects);
1462 // After this, the closest object is the first in the array.
1463 std::sort(objects.begin(), objects.end());
1465 for(unsigned int i=0; i<objects.size(); i++)
1467 ClientActiveObject *obj = objects[i].obj;
1469 core::aabbox3d<f32> *selection_box = obj->getSelectionBox();
1470 if(selection_box == NULL)
1473 v3f pos = obj->getPosition();
1475 core::aabbox3d<f32> offsetted_box(
1476 selection_box->MinEdge + pos,
1477 selection_box->MaxEdge + pos
1480 if(offsetted_box.intersectsWithLine(shootline_on_map))
1489 std::list<std::string> Client::getConnectedPlayerNames()
1491 return m_env.getPlayerNames();
1494 float Client::getAnimationTime()
1496 return m_animation_time;
1499 int Client::getCrackLevel()
1501 return m_crack_level;
1504 void Client::setHighlighted(v3s16 pos, bool show_highlighted)
1506 m_show_highlighted = show_highlighted;
1507 v3s16 old_highlighted_pos = m_highlighted_pos;
1508 m_highlighted_pos = pos;
1509 addUpdateMeshTaskForNode(old_highlighted_pos, false, true);
1510 addUpdateMeshTaskForNode(m_highlighted_pos, false, true);
1513 void Client::setCrack(int level, v3s16 pos)
1515 int old_crack_level = m_crack_level;
1516 v3s16 old_crack_pos = m_crack_pos;
1518 m_crack_level = level;
1521 if(old_crack_level >= 0 && (level < 0 || pos != old_crack_pos))
1524 addUpdateMeshTaskForNode(old_crack_pos, false, true);
1526 if(level >= 0 && (old_crack_level < 0 || pos != old_crack_pos))
1529 addUpdateMeshTaskForNode(pos, false, true);
1535 Player *player = m_env.getLocalPlayer();
1536 assert(player != NULL);
1540 u16 Client::getBreath()
1542 Player *player = m_env.getLocalPlayer();
1543 assert(player != NULL);
1544 return player->getBreath();
1547 bool Client::getChatMessage(std::wstring &message)
1549 if(m_chat_queue.size() == 0)
1551 message = m_chat_queue.front();
1556 void Client::typeChatMessage(const std::wstring &message)
1558 // Discard empty line
1563 sendChatMessage(message);
1566 if (message[0] == L'/')
1568 m_chat_queue.push((std::wstring)L"issued command: " + message);
1572 LocalPlayer *player = m_env.getLocalPlayer();
1573 assert(player != NULL);
1574 std::wstring name = narrow_to_wide(player->getName());
1575 m_chat_queue.push((std::wstring)L"<" + name + L"> " + message);
1579 void Client::addUpdateMeshTask(v3s16 p, bool ack_to_server, bool urgent)
1581 MapBlock *b = m_env.getMap().getBlockNoCreateNoEx(p);
1586 Create a task to update the mesh of the block
1589 MeshMakeData *data = new MeshMakeData(this, m_cache_enable_shaders);
1592 //TimeTaker timer("data fill");
1594 // Debug: 1-6ms, avg=2ms
1596 data->setCrack(m_crack_level, m_crack_pos);
1597 data->setHighlighted(m_highlighted_pos, m_show_highlighted);
1598 data->setSmoothLighting(m_cache_smooth_lighting);
1601 // Add task to queue
1602 m_mesh_update_thread.enqueueUpdate(p, data, ack_to_server, urgent);
1605 void Client::addUpdateMeshTaskWithEdge(v3s16 blockpos, bool ack_to_server, bool urgent)
1608 addUpdateMeshTask(blockpos, ack_to_server, urgent);
1610 catch(InvalidPositionException &e){}
1613 for (int i=0;i<6;i++)
1616 v3s16 p = blockpos + g_6dirs[i];
1617 addUpdateMeshTask(p, false, urgent);
1619 catch(InvalidPositionException &e){}
1623 void Client::addUpdateMeshTaskForNode(v3s16 nodepos, bool ack_to_server, bool urgent)
1627 infostream<<"Client::addUpdateMeshTaskForNode(): "
1628 <<"("<<p.X<<","<<p.Y<<","<<p.Z<<")"
1632 v3s16 blockpos = getNodeBlockPos(nodepos);
1633 v3s16 blockpos_relative = blockpos * MAP_BLOCKSIZE;
1636 addUpdateMeshTask(blockpos, ack_to_server, urgent);
1638 catch(InvalidPositionException &e) {}
1641 if(nodepos.X == blockpos_relative.X){
1643 v3s16 p = blockpos + v3s16(-1,0,0);
1644 addUpdateMeshTask(p, false, urgent);
1646 catch(InvalidPositionException &e){}
1649 if(nodepos.Y == blockpos_relative.Y){
1651 v3s16 p = blockpos + v3s16(0,-1,0);
1652 addUpdateMeshTask(p, false, urgent);
1654 catch(InvalidPositionException &e){}
1657 if(nodepos.Z == blockpos_relative.Z){
1659 v3s16 p = blockpos + v3s16(0,0,-1);
1660 addUpdateMeshTask(p, false, urgent);
1662 catch(InvalidPositionException &e){}
1666 ClientEvent Client::getClientEvent()
1669 if(m_client_event_queue.size() == 0) {
1670 event.type = CE_NONE;
1673 event = m_client_event_queue.front();
1674 m_client_event_queue.pop();
1679 float Client::mediaReceiveProgress()
1681 if (m_media_downloader)
1682 return m_media_downloader->getProgress();
1684 return 1.0; // downloader only exists when not yet done
1687 typedef struct TextureUpdateArgs {
1688 IrrlichtDevice *device;
1689 gui::IGUIEnvironment *guienv;
1692 const wchar_t* text_base;
1693 } TextureUpdateArgs;
1695 void texture_update_progress(void *args, u32 progress, u32 max_progress)
1697 TextureUpdateArgs* targs = (TextureUpdateArgs*) args;
1698 u16 cur_percent = ceil(progress / (double) max_progress * 100.);
1700 // update the loading menu -- if neccessary
1701 bool do_draw = false;
1702 u32 time_ms = targs->last_time_ms;
1703 if (cur_percent != targs->last_percent) {
1704 targs->last_percent = cur_percent;
1705 time_ms = getTimeMs();
1706 // only draw when the user will notice something:
1707 do_draw = (time_ms - targs->last_time_ms > 100);
1711 targs->last_time_ms = time_ms;
1712 std::basic_stringstream<wchar_t> strm;
1713 strm << targs->text_base << " " << targs->last_percent << "%...";
1714 draw_load_screen(strm.str(), targs->device, targs->guienv, 0,
1715 72 + (u16) ((18. / 100.) * (double) targs->last_percent));
1719 void Client::afterContentReceived(IrrlichtDevice *device)
1721 infostream<<"Client::afterContentReceived() started"<<std::endl;
1722 assert(m_itemdef_received); // pre-condition
1723 assert(m_nodedef_received); // pre-condition
1724 assert(mediaReceived()); // pre-condition
1726 const wchar_t* text = wgettext("Loading textures...");
1728 // Clear cached pre-scaled 2D GUI images, as this cache
1729 // might have images with the same name but different
1730 // content from previous sessions.
1731 guiScalingCacheClear(device->getVideoDriver());
1733 // Rebuild inherited images and recreate textures
1734 infostream<<"- Rebuilding images and textures"<<std::endl;
1735 draw_load_screen(text,device, guienv, 0, 70);
1736 m_tsrc->rebuildImagesAndTextures();
1740 infostream<<"- Rebuilding shaders"<<std::endl;
1741 text = wgettext("Rebuilding shaders...");
1742 draw_load_screen(text, device, guienv, 0, 71);
1743 m_shsrc->rebuildShaders();
1746 // Update node aliases
1747 infostream<<"- Updating node aliases"<<std::endl;
1748 text = wgettext("Initializing nodes...");
1749 draw_load_screen(text, device, guienv, 0, 72);
1750 m_nodedef->updateAliases(m_itemdef);
1751 std::string texture_path = g_settings->get("texture_path");
1752 if (texture_path != "" && fs::IsDir(texture_path))
1753 m_nodedef->applyTextureOverrides(texture_path + DIR_DELIM + "override.txt");
1754 m_nodedef->setNodeRegistrationStatus(true);
1755 m_nodedef->runNodeResolveCallbacks();
1758 // Update node textures and assign shaders to each tile
1759 infostream<<"- Updating node textures"<<std::endl;
1760 TextureUpdateArgs tu_args;
1761 tu_args.device = device;
1762 tu_args.guienv = guienv;
1763 tu_args.last_time_ms = getTimeMs();
1764 tu_args.last_percent = 0;
1765 tu_args.text_base = wgettext("Initializing nodes");
1766 m_nodedef->updateTextures(this, texture_update_progress, &tu_args);
1767 delete[] tu_args.text_base;
1769 // Preload item textures and meshes if configured to
1770 if(g_settings->getBool("preload_item_visuals"))
1772 verbosestream<<"Updating item textures and meshes"<<std::endl;
1773 text = wgettext("Item textures...");
1774 draw_load_screen(text, device, guienv, 0, 0);
1775 std::set<std::string> names = m_itemdef->getAll();
1776 size_t size = names.size();
1779 for(std::set<std::string>::const_iterator
1780 i = names.begin(); i != names.end(); ++i)
1782 // Asking for these caches the result
1783 m_itemdef->getInventoryTexture(*i, this);
1784 m_itemdef->getWieldMesh(*i, this);
1786 percent = (count * 100 / size * 0.2) + 80;
1787 draw_load_screen(text, device, guienv, 0, percent);
1792 // Start mesh update thread after setting up content definitions
1793 infostream<<"- Starting mesh update thread"<<std::endl;
1794 m_mesh_update_thread.Start();
1798 text = wgettext("Done!");
1799 draw_load_screen(text, device, guienv, 0, 100);
1800 infostream<<"Client::afterContentReceived() done"<<std::endl;
1804 float Client::getRTT(void)
1806 return m_con.getPeerStat(PEER_ID_SERVER,con::AVG_RTT);
1809 float Client::getCurRate(void)
1811 return ( m_con.getLocalStat(con::CUR_INC_RATE) +
1812 m_con.getLocalStat(con::CUR_DL_RATE));
1815 float Client::getAvgRate(void)
1817 return ( m_con.getLocalStat(con::AVG_INC_RATE) +
1818 m_con.getLocalStat(con::AVG_DL_RATE));
1821 void Client::makeScreenshot(IrrlichtDevice *device)
1823 irr::video::IVideoDriver *driver = device->getVideoDriver();
1824 irr::video::IImage* const raw_image = driver->createScreenShot();
1829 time_t t = time(NULL);
1830 struct tm *tm = localtime(&t);
1832 char timetstamp_c[64];
1833 strftime(timetstamp_c, sizeof(timetstamp_c), "%Y%m%d_%H%M%S", tm);
1835 std::string filename_base = g_settings->get("screenshot_path")
1837 + std::string("screenshot_")
1838 + std::string(timetstamp_c);
1839 std::string filename_ext = ".png";
1840 std::string filename;
1842 // Try to find a unique filename
1843 unsigned serial = 0;
1845 while (serial < SCREENSHOT_MAX_SERIAL_TRIES) {
1846 filename = filename_base + (serial > 0 ? ("_" + itos(serial)) : "") + filename_ext;
1847 std::ifstream tmp(filename.c_str());
1849 break; // File did not apparently exist, we'll go with it
1853 if (serial == SCREENSHOT_MAX_SERIAL_TRIES) {
1854 infostream << "Could not find suitable filename for screenshot" << std::endl;
1856 irr::video::IImage* const image =
1857 driver->createImage(video::ECF_R8G8B8, raw_image->getDimension());
1860 raw_image->copyTo(image);
1862 std::ostringstream sstr;
1863 if (driver->writeImageToFile(image, filename.c_str())) {
1864 sstr << "Saved screenshot to '" << filename << "'";
1866 sstr << "Failed to save screenshot '" << filename << "'";
1868 m_chat_queue.push(narrow_to_wide(sstr.str()));
1869 infostream << sstr.str() << std::endl;
1877 // IGameDef interface
1879 IItemDefManager* Client::getItemDefManager()
1883 INodeDefManager* Client::getNodeDefManager()
1887 ICraftDefManager* Client::getCraftDefManager()
1890 //return m_craftdef;
1892 ITextureSource* Client::getTextureSource()
1896 IShaderSource* Client::getShaderSource()
1900 scene::ISceneManager* Client::getSceneManager()
1902 return m_device->getSceneManager();
1904 u16 Client::allocateUnknownNodeId(const std::string &name)
1906 errorstream << "Client::allocateUnknownNodeId(): "
1907 << "Client cannot allocate node IDs" << std::endl;
1908 FATAL_ERROR("Client allocated unknown node");
1910 return CONTENT_IGNORE;
1912 ISoundManager* Client::getSoundManager()
1916 MtEventManager* Client::getEventManager()
1921 ParticleManager* Client::getParticleManager()
1923 return &m_particle_manager;
1926 scene::IAnimatedMesh* Client::getMesh(const std::string &filename)
1928 StringMap::const_iterator it = m_mesh_data.find(filename);
1929 if (it == m_mesh_data.end()) {
1930 errorstream << "Client::getMesh(): Mesh not found: \"" << filename
1931 << "\"" << std::endl;
1934 const std::string &data = it->second;
1935 scene::ISceneManager *smgr = m_device->getSceneManager();
1937 // Create the mesh, remove it from cache and return it
1938 // This allows unique vertex colors and other properties for each instance
1939 Buffer<char> data_rw(data.c_str(), data.size()); // Const-incorrect Irrlicht
1940 io::IFileSystem *irrfs = m_device->getFileSystem();
1941 io::IReadFile *rfile = irrfs->createMemoryReadFile(
1942 *data_rw, data_rw.getSize(), filename.c_str());
1943 FATAL_ERROR_IF(!rfile, "Could not create/open RAM file");
1945 scene::IAnimatedMesh *mesh = smgr->getMesh(rfile);
1947 // NOTE: By playing with Irrlicht refcounts, maybe we could cache a bunch
1948 // of uniquely named instances and re-use them
1950 smgr->getMeshCache()->removeMesh(mesh);