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 "threading/mutex_auto_lock.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 MutexAutoLock 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 MutexAutoLock 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 MutexAutoLock 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),
232 m_minimap_disabled_by_server(false),
233 m_server_ser_ver(SER_FMT_VER_INVALID),
236 m_inventory_updated(false),
237 m_inventory_from_server(NULL),
238 m_inventory_from_server_age(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.setLocalPlayer(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");
267 m_cache_use_tangent_vertices = m_cache_enable_shaders && (
268 g_settings->getBool("enable_bumpmapping") ||
269 g_settings->getBool("enable_parallax_occlusion"));
274 //request all client managed threads to stop
275 m_mesh_update_thread.stop();
276 // Save local server map
278 infostream << "Local map saving ended." << std::endl;
279 m_localdb->endSave();
283 bool Client::isShutdown()
286 if (!m_mesh_update_thread.isRunning()) return true;
295 m_mesh_update_thread.stop();
296 m_mesh_update_thread.wait();
297 while (!m_mesh_update_thread.m_queue_out.empty()) {
298 MeshUpdateResult r = m_mesh_update_thread.m_queue_out.pop_frontNoEx();
303 delete m_inventory_from_server;
305 // Delete detached inventories
306 for (UNORDERED_MAP<std::string, Inventory*>::iterator
307 i = m_detached_inventories.begin();
308 i != m_detached_inventories.end(); ++i) {
312 // cleanup 3d model meshes on client shutdown
313 while (m_device->getSceneManager()->getMeshCache()->getMeshCount() != 0) {
314 scene::IAnimatedMesh *mesh =
315 m_device->getSceneManager()->getMeshCache()->getMeshByIndex(0);
318 m_device->getSceneManager()->getMeshCache()->removeMesh(mesh);
324 void Client::connect(Address address,
325 const std::string &address_name,
326 bool is_local_server)
328 DSTACK(FUNCTION_NAME);
330 initLocalMapSaving(address, address_name, is_local_server);
332 m_con.SetTimeoutMs(0);
333 m_con.Connect(address);
336 void Client::step(float dtime)
338 DSTACK(FUNCTION_NAME);
344 if(m_ignore_damage_timer > dtime)
345 m_ignore_damage_timer -= dtime;
347 m_ignore_damage_timer = 0.0;
349 m_animation_time += dtime;
350 if(m_animation_time > 60.0)
351 m_animation_time -= 60.0;
353 m_time_of_day_update_timer += dtime;
361 float &counter = m_packetcounter_timer;
367 infostream << "Client packetcounter (" << m_packetcounter_timer
369 m_packetcounter.print(infostream);
370 m_packetcounter.clear();
374 // UGLY hack to fix 2 second startup delay caused by non existent
375 // server client startup synchronization in local server or singleplayer mode
376 static bool initial_step = true;
378 initial_step = false;
380 else if(m_state == LC_Created) {
381 float &counter = m_connection_reinit_timer;
386 LocalPlayer *myplayer = m_env.getLocalPlayer();
387 FATAL_ERROR_IF(myplayer == NULL, "Local player not found in environment.");
389 u16 proto_version_min = g_settings->getFlag("send_pre_v25_init") ?
390 CLIENT_PROTOCOL_VERSION_MIN_LEGACY : CLIENT_PROTOCOL_VERSION_MIN;
392 if (proto_version_min < 25) {
393 // Send TOSERVER_INIT_LEGACY
394 // [0] u16 TOSERVER_INIT_LEGACY
395 // [2] u8 SER_FMT_VER_HIGHEST_READ
396 // [3] u8[20] player_name
397 // [23] u8[28] password (new in some version)
398 // [51] u16 minimum supported network protocol version (added sometime)
399 // [53] u16 maximum supported network protocol version (added later than the previous one)
401 char pName[PLAYERNAME_SIZE];
402 char pPassword[PASSWORD_SIZE];
403 memset(pName, 0, PLAYERNAME_SIZE * sizeof(char));
404 memset(pPassword, 0, PASSWORD_SIZE * sizeof(char));
406 std::string hashed_password = translate_password(myplayer->getName(), m_password);
407 snprintf(pName, PLAYERNAME_SIZE, "%s", myplayer->getName());
408 snprintf(pPassword, PASSWORD_SIZE, "%s", hashed_password.c_str());
410 sendLegacyInit(pName, pPassword);
412 if (CLIENT_PROTOCOL_VERSION_MAX >= 25)
413 sendInit(myplayer->getName());
416 // Not connected, return
421 Do stuff if connected
425 Run Map's timers and unload unused data
427 const float map_timer_and_unload_dtime = 5.25;
428 if(m_map_timer_and_unload_interval.step(dtime, map_timer_and_unload_dtime)) {
429 ScopeProfiler sp(g_profiler, "Client: map timer and unload");
430 std::vector<v3s16> deleted_blocks;
431 m_env.getMap().timerUpdate(map_timer_and_unload_dtime,
432 g_settings->getFloat("client_unload_unused_data_timeout"),
433 g_settings->getS32("client_mapblock_limit"),
438 NOTE: This loop is intentionally iterated the way it is.
441 std::vector<v3s16>::iterator i = deleted_blocks.begin();
442 std::vector<v3s16> sendlist;
444 if(sendlist.size() == 255 || i == deleted_blocks.end()) {
455 sendDeletedBlocks(sendlist);
457 if(i == deleted_blocks.end())
463 sendlist.push_back(*i);
471 // Control local player (0ms)
472 LocalPlayer *player = m_env.getLocalPlayer();
473 assert(player != NULL);
474 player->applyControl(dtime);
483 ClientEnvEvent event = m_env.getClientEvent();
484 if(event.type == CEE_NONE) {
487 else if(event.type == CEE_PLAYER_DAMAGE) {
488 if(m_ignore_damage_timer <= 0) {
489 u8 damage = event.player_damage.amount;
491 if(event.player_damage.send_to_server)
494 // Add to ClientEvent queue
496 event.type = CE_PLAYER_DAMAGE;
497 event.player_damage.amount = damage;
498 m_client_event_queue.push(event);
501 else if(event.type == CEE_PLAYER_BREATH) {
502 u16 breath = event.player_breath.amount;
510 float &counter = m_avg_rtt_timer;
514 // connectedAndInitialized() is true, peer exists.
515 float avg_rtt = getRTT();
516 infostream << "Client: avg_rtt=" << avg_rtt << std::endl;
520 Send player position to server
523 float &counter = m_playerpos_send_timer;
525 if((m_state == LC_Ready) && (counter >= m_recommended_send_interval))
533 Replace updated meshes
536 int num_processed_meshes = 0;
537 while (!m_mesh_update_thread.m_queue_out.empty())
539 num_processed_meshes++;
541 MinimapMapblock *minimap_mapblock = NULL;
542 bool do_mapper_update = true;
544 MeshUpdateResult r = m_mesh_update_thread.m_queue_out.pop_frontNoEx();
545 MapBlock *block = m_env.getMap().getBlockNoCreateNoEx(r.p);
547 // Delete the old mesh
548 if (block->mesh != NULL) {
554 minimap_mapblock = r.mesh->moveMinimapMapblock();
555 if (minimap_mapblock == NULL)
556 do_mapper_update = false;
559 if (r.mesh && r.mesh->getMesh()->getMeshBufferCount() == 0) {
562 // Replace with the new mesh
563 block->mesh = r.mesh;
569 if (do_mapper_update)
570 m_mapper->addBlock(r.p, minimap_mapblock);
572 if (r.ack_block_to_server) {
582 if (num_processed_meshes > 0)
583 g_profiler->graphAdd("num_processed_meshes", num_processed_meshes);
589 if (m_media_downloader && m_media_downloader->isStarted()) {
590 m_media_downloader->step(this);
591 if (m_media_downloader->isDone()) {
593 delete m_media_downloader;
594 m_media_downloader = NULL;
599 If the server didn't update the inventory in a while, revert
600 the local inventory (so the player notices the lag problem
601 and knows something is wrong).
603 if(m_inventory_from_server)
605 float interval = 10.0;
606 float count_before = floor(m_inventory_from_server_age / interval);
608 m_inventory_from_server_age += dtime;
610 float count_after = floor(m_inventory_from_server_age / interval);
612 if(count_after != count_before)
614 // Do this every <interval> seconds after TOCLIENT_INVENTORY
615 // Reset the locally changed inventory to the authoritative inventory
616 LocalPlayer *player = m_env.getLocalPlayer();
617 player->inventory = *m_inventory_from_server;
618 m_inventory_updated = true;
623 Update positions of sounds attached to objects
626 for(UNORDERED_MAP<int, u16>::iterator i = m_sounds_to_objects.begin();
627 i != m_sounds_to_objects.end(); ++i) {
628 int client_id = i->first;
629 u16 object_id = i->second;
630 ClientActiveObject *cao = m_env.getActiveObject(object_id);
633 v3f pos = cao->getPosition();
634 m_sound->updateSoundPosition(client_id, pos);
639 Handle removed remotely initiated sounds
641 m_removed_sounds_check_timer += dtime;
642 if(m_removed_sounds_check_timer >= 2.32) {
643 m_removed_sounds_check_timer = 0;
644 // Find removed sounds and clear references to them
645 std::vector<s32> removed_server_ids;
646 for(UNORDERED_MAP<s32, int>::iterator i = m_sounds_server_to_client.begin();
647 i != m_sounds_server_to_client.end();) {
648 s32 server_id = i->first;
649 int client_id = i->second;
651 if(!m_sound->soundExists(client_id)) {
652 m_sounds_server_to_client.erase(server_id);
653 m_sounds_client_to_server.erase(client_id);
654 m_sounds_to_objects.erase(client_id);
655 removed_server_ids.push_back(server_id);
660 if(!removed_server_ids.empty()) {
661 sendRemovedSounds(removed_server_ids);
666 if (m_localdb && m_localdb_save_interval.step(dtime,
667 m_cache_save_interval)) {
668 m_localdb->endSave();
669 m_localdb->beginSave();
673 bool Client::loadMedia(const std::string &data, const std::string &filename)
675 // Silly irrlicht's const-incorrectness
676 Buffer<char> data_rw(data.c_str(), data.size());
680 const char *image_ext[] = {
681 ".png", ".jpg", ".bmp", ".tga",
682 ".pcx", ".ppm", ".psd", ".wal", ".rgb",
685 name = removeStringEnd(filename, image_ext);
688 verbosestream<<"Client: Attempting to load image "
689 <<"file \""<<filename<<"\""<<std::endl;
691 io::IFileSystem *irrfs = m_device->getFileSystem();
692 video::IVideoDriver *vdrv = m_device->getVideoDriver();
694 // Create an irrlicht memory file
695 io::IReadFile *rfile = irrfs->createMemoryReadFile(
696 *data_rw, data_rw.getSize(), "_tempreadfile");
698 FATAL_ERROR_IF(!rfile, "Could not create irrlicht memory file.");
701 video::IImage *img = vdrv->createImageFromFile(rfile);
703 errorstream<<"Client: Cannot create image from data of "
704 <<"file \""<<filename<<"\""<<std::endl;
709 m_tsrc->insertSourceImage(filename, img);
716 const char *sound_ext[] = {
717 ".0.ogg", ".1.ogg", ".2.ogg", ".3.ogg", ".4.ogg",
718 ".5.ogg", ".6.ogg", ".7.ogg", ".8.ogg", ".9.ogg",
721 name = removeStringEnd(filename, sound_ext);
724 verbosestream<<"Client: Attempting to load sound "
725 <<"file \""<<filename<<"\""<<std::endl;
726 m_sound->loadSoundData(name, data);
730 const char *model_ext[] = {
731 ".x", ".b3d", ".md2", ".obj",
734 name = removeStringEnd(filename, model_ext);
737 verbosestream<<"Client: Storing model into memory: "
738 <<"\""<<filename<<"\""<<std::endl;
739 if(m_mesh_data.count(filename))
740 errorstream<<"Multiple models with name \""<<filename.c_str()
741 <<"\" found; replacing previous model"<<std::endl;
742 m_mesh_data[filename] = data;
746 errorstream<<"Client: Don't know how to load file \""
747 <<filename<<"\""<<std::endl;
751 // Virtual methods from con::PeerHandler
752 void Client::peerAdded(con::Peer *peer)
754 infostream << "Client::peerAdded(): peer->id="
755 << peer->id << std::endl;
757 void Client::deletingPeer(con::Peer *peer, bool timeout)
759 infostream << "Client::deletingPeer(): "
760 "Server Peer is getting deleted "
761 << "(timeout=" << timeout << ")" << std::endl;
764 m_access_denied = true;
765 m_access_denied_reason = gettext("Connection timed out.");
771 u16 number of files requested
777 void Client::request_media(const std::vector<std::string> &file_requests)
779 std::ostringstream os(std::ios_base::binary);
780 writeU16(os, TOSERVER_REQUEST_MEDIA);
781 size_t file_requests_size = file_requests.size();
783 FATAL_ERROR_IF(file_requests_size > 0xFFFF, "Unsupported number of file requests");
785 // Packet dynamicly resized
786 NetworkPacket pkt(TOSERVER_REQUEST_MEDIA, 2 + 0);
788 pkt << (u16) (file_requests_size & 0xFFFF);
790 for(std::vector<std::string>::const_iterator i = file_requests.begin();
791 i != file_requests.end(); ++i) {
797 infostream << "Client: Sending media request list to server ("
798 << file_requests.size() << " files. packet size)" << std::endl;
801 void Client::received_media()
803 NetworkPacket pkt(TOSERVER_RECEIVED_MEDIA, 0);
805 infostream << "Client: Notifying server that we received all media"
809 void Client::initLocalMapSaving(const Address &address,
810 const std::string &hostname,
811 bool is_local_server)
813 if (!g_settings->getBool("enable_local_map_saving") || is_local_server) {
817 const std::string world_path = porting::path_user
818 + DIR_DELIM + "worlds"
819 + DIR_DELIM + "server_"
820 + hostname + "_" + std::to_string(address.getPort());
822 fs::CreateAllDirs(world_path);
824 m_localdb = new Database_SQLite3(world_path);
825 m_localdb->beginSave();
826 actionstream << "Local map saving started, map will be saved at '" << world_path << "'" << std::endl;
829 void Client::ReceiveAll()
831 DSTACK(FUNCTION_NAME);
832 u32 start_ms = porting::getTimeMs();
835 // Limit time even if there would be huge amounts of data to
837 if(porting::getTimeMs() > start_ms + 100)
842 g_profiler->graphAdd("client_received_packets", 1);
844 catch(con::NoIncomingDataException &e) {
847 catch(con::InvalidIncomingDataException &e) {
848 infostream<<"Client::ReceiveAll(): "
849 "InvalidIncomingDataException: what()="
850 <<e.what()<<std::endl;
855 void Client::Receive()
857 DSTACK(FUNCTION_NAME);
863 inline void Client::handleCommand(NetworkPacket* pkt)
865 const ToClientCommandHandler& opHandle = toClientCommandTable[pkt->getCommand()];
866 (this->*opHandle.handler)(pkt);
870 sender_peer_id given to this shall be quaranteed to be a valid peer
872 void Client::ProcessData(NetworkPacket *pkt)
874 DSTACK(FUNCTION_NAME);
876 ToClientCommand command = (ToClientCommand) pkt->getCommand();
877 u32 sender_peer_id = pkt->getPeerId();
879 //infostream<<"Client: received command="<<command<<std::endl;
880 m_packetcounter.add((u16)command);
883 If this check is removed, be sure to change the queue
884 system to know the ids
886 if(sender_peer_id != PEER_ID_SERVER) {
887 infostream << "Client::ProcessData(): Discarding data not "
888 "coming from server: peer_id=" << sender_peer_id
893 // Command must be handled into ToClientCommandHandler
894 if (command >= TOCLIENT_NUM_MSG_TYPES) {
895 infostream << "Client: Ignoring unknown command "
896 << command << std::endl;
901 * Those packets are handled before m_server_ser_ver is set, it's normal
902 * But we must use the new ToClientConnectionState in the future,
905 if(toClientCommandTable[command].state == TOCLIENT_STATE_NOT_CONNECTED) {
910 if(m_server_ser_ver == SER_FMT_VER_INVALID) {
911 infostream << "Client: Server serialization"
912 " format invalid or not initialized."
913 " Skipping incoming command=" << command << std::endl;
918 Handle runtime commands
924 void Client::Send(NetworkPacket* pkt)
926 m_con.Send(PEER_ID_SERVER,
927 serverCommandFactoryTable[pkt->getCommand()].channel,
929 serverCommandFactoryTable[pkt->getCommand()].reliable);
932 // Will fill up 12 + 12 + 4 + 4 + 4 bytes
933 void writePlayerPos(LocalPlayer *myplayer, NetworkPacket *pkt)
935 v3f pf = myplayer->getPosition() * 100;
936 v3f sf = myplayer->getSpeed() * 100;
937 s32 pitch = myplayer->getPitch() * 100;
938 s32 yaw = myplayer->getYaw() * 100;
939 u32 keyPressed = myplayer->keyPressed;
941 v3s32 position(pf.X, pf.Y, pf.Z);
942 v3s32 speed(sf.X, sf.Y, sf.Z);
946 [0] v3s32 position*100
948 [12+12] s32 pitch*100
949 [12+12+4] s32 yaw*100
950 [12+12+4+4] u32 keyPressed
953 *pkt << position << speed << pitch << yaw << keyPressed;
956 void Client::interact(u8 action, const PointedThing& pointed)
958 if(m_state != LC_Ready) {
959 errorstream << "Client::interact() "
960 "Canceled (not connected)"
965 LocalPlayer *myplayer = m_env.getLocalPlayer();
966 if (myplayer == NULL)
973 [5] u32 length of the next item (plen)
974 [9] serialized PointedThing
975 [9 + plen] player position information
977 0: start digging (from undersurface) or use
978 1: stop digging (all parameters ignored)
980 3: place block or item (to abovesurface)
982 5: perform secondary action of item
985 NetworkPacket pkt(TOSERVER_INTERACT, 1 + 2 + 0);
988 pkt << (u16)getPlayerItem();
990 std::ostringstream tmp_os(std::ios::binary);
991 pointed.serialize(tmp_os);
993 pkt.putLongString(tmp_os.str());
995 writePlayerPos(myplayer, &pkt);
1000 void Client::deleteAuthData()
1005 switch (m_chosen_auth_mech) {
1006 case AUTH_MECHANISM_FIRST_SRP:
1008 case AUTH_MECHANISM_SRP:
1009 case AUTH_MECHANISM_LEGACY_PASSWORD:
1010 srp_user_delete((SRPUser *) m_auth_data);
1013 case AUTH_MECHANISM_NONE:
1016 m_chosen_auth_mech = AUTH_MECHANISM_NONE;
1020 AuthMechanism Client::choseAuthMech(const u32 mechs)
1022 if (mechs & AUTH_MECHANISM_SRP)
1023 return AUTH_MECHANISM_SRP;
1025 if (mechs & AUTH_MECHANISM_FIRST_SRP)
1026 return AUTH_MECHANISM_FIRST_SRP;
1028 if (mechs & AUTH_MECHANISM_LEGACY_PASSWORD)
1029 return AUTH_MECHANISM_LEGACY_PASSWORD;
1031 return AUTH_MECHANISM_NONE;
1034 void Client::sendLegacyInit(const char* playerName, const char* playerPassword)
1036 NetworkPacket pkt(TOSERVER_INIT_LEGACY,
1037 1 + PLAYERNAME_SIZE + PASSWORD_SIZE + 2 + 2);
1039 u16 proto_version_min = g_settings->getFlag("send_pre_v25_init") ?
1040 CLIENT_PROTOCOL_VERSION_MIN_LEGACY : CLIENT_PROTOCOL_VERSION_MIN;
1042 pkt << (u8) SER_FMT_VER_HIGHEST_READ;
1043 pkt.putRawString(playerName,PLAYERNAME_SIZE);
1044 pkt.putRawString(playerPassword, PASSWORD_SIZE);
1045 pkt << (u16) proto_version_min << (u16) CLIENT_PROTOCOL_VERSION_MAX;
1050 void Client::sendInit(const std::string &playerName)
1052 NetworkPacket pkt(TOSERVER_INIT, 1 + 2 + 2 + (1 + playerName.size()));
1054 // we don't support network compression yet
1055 u16 supp_comp_modes = NETPROTO_COMPRESSION_NONE;
1057 u16 proto_version_min = g_settings->getFlag("send_pre_v25_init") ?
1058 CLIENT_PROTOCOL_VERSION_MIN_LEGACY : CLIENT_PROTOCOL_VERSION_MIN;
1060 pkt << (u8) SER_FMT_VER_HIGHEST_READ << (u16) supp_comp_modes;
1061 pkt << (u16) proto_version_min << (u16) CLIENT_PROTOCOL_VERSION_MAX;
1067 void Client::startAuth(AuthMechanism chosen_auth_mechanism)
1069 m_chosen_auth_mech = chosen_auth_mechanism;
1071 switch (chosen_auth_mechanism) {
1072 case AUTH_MECHANISM_FIRST_SRP: {
1073 // send srp verifier to server
1074 std::string verifier;
1076 generate_srp_verifier_and_salt(getPlayerName(), m_password,
1079 NetworkPacket resp_pkt(TOSERVER_FIRST_SRP, 0);
1080 resp_pkt << salt << verifier << (u8)((m_password == "") ? 1 : 0);
1085 case AUTH_MECHANISM_SRP:
1086 case AUTH_MECHANISM_LEGACY_PASSWORD: {
1089 if (chosen_auth_mechanism == AUTH_MECHANISM_LEGACY_PASSWORD) {
1090 m_password = translate_password(getPlayerName(), m_password);
1094 std::string playername_u = lowercase(getPlayerName());
1095 m_auth_data = srp_user_new(SRP_SHA256, SRP_NG_2048,
1096 getPlayerName().c_str(), playername_u.c_str(),
1097 (const unsigned char *) m_password.c_str(),
1098 m_password.length(), NULL, NULL);
1101 SRP_Result res = srp_user_start_authentication(
1102 (struct SRPUser *) m_auth_data, NULL, NULL, 0,
1103 (unsigned char **) &bytes_A, &len_A);
1104 FATAL_ERROR_IF(res != SRP_OK, "Creating local SRP user failed.");
1106 NetworkPacket resp_pkt(TOSERVER_SRP_BYTES_A, 0);
1107 resp_pkt << std::string(bytes_A, len_A) << based_on;
1111 case AUTH_MECHANISM_NONE:
1112 break; // not handled in this method
1116 void Client::sendDeletedBlocks(std::vector<v3s16> &blocks)
1118 NetworkPacket pkt(TOSERVER_DELETEDBLOCKS, 1 + sizeof(v3s16) * blocks.size());
1120 pkt << (u8) blocks.size();
1123 for(std::vector<v3s16>::iterator
1125 j != blocks.end(); ++j) {
1133 void Client::sendGotBlocks(v3s16 block)
1135 NetworkPacket pkt(TOSERVER_GOTBLOCKS, 1 + 6);
1136 pkt << (u8) 1 << block;
1140 void Client::sendRemovedSounds(std::vector<s32> &soundList)
1142 size_t server_ids = soundList.size();
1143 assert(server_ids <= 0xFFFF);
1145 NetworkPacket pkt(TOSERVER_REMOVED_SOUNDS, 2 + server_ids * 4);
1147 pkt << (u16) (server_ids & 0xFFFF);
1149 for(std::vector<s32>::iterator i = soundList.begin();
1150 i != soundList.end(); ++i)
1156 void Client::sendNodemetaFields(v3s16 p, const std::string &formname,
1157 const StringMap &fields)
1159 size_t fields_size = fields.size();
1161 FATAL_ERROR_IF(fields_size > 0xFFFF, "Unsupported number of nodemeta fields");
1163 NetworkPacket pkt(TOSERVER_NODEMETA_FIELDS, 0);
1165 pkt << p << formname << (u16) (fields_size & 0xFFFF);
1167 StringMap::const_iterator it;
1168 for (it = fields.begin(); it != fields.end(); ++it) {
1169 const std::string &name = it->first;
1170 const std::string &value = it->second;
1172 pkt.putLongString(value);
1178 void Client::sendInventoryFields(const std::string &formname,
1179 const StringMap &fields)
1181 size_t fields_size = fields.size();
1182 FATAL_ERROR_IF(fields_size > 0xFFFF, "Unsupported number of inventory fields");
1184 NetworkPacket pkt(TOSERVER_INVENTORY_FIELDS, 0);
1185 pkt << formname << (u16) (fields_size & 0xFFFF);
1187 StringMap::const_iterator it;
1188 for (it = fields.begin(); it != fields.end(); ++it) {
1189 const std::string &name = it->first;
1190 const std::string &value = it->second;
1192 pkt.putLongString(value);
1198 void Client::sendInventoryAction(InventoryAction *a)
1200 std::ostringstream os(std::ios_base::binary);
1205 std::string s = os.str();
1207 NetworkPacket pkt(TOSERVER_INVENTORY_ACTION, s.size());
1208 pkt.putRawString(s.c_str(),s.size());
1213 void Client::sendChatMessage(const std::wstring &message)
1215 NetworkPacket pkt(TOSERVER_CHAT_MESSAGE, 2 + message.size() * sizeof(u16));
1222 void Client::sendChangePassword(const std::string &oldpassword,
1223 const std::string &newpassword)
1225 LocalPlayer *player = m_env.getLocalPlayer();
1229 std::string playername = player->getName();
1230 if (m_proto_ver >= 25) {
1231 // get into sudo mode and then send new password to server
1232 m_password = oldpassword;
1233 m_new_password = newpassword;
1234 startAuth(choseAuthMech(m_sudo_auth_methods));
1236 std::string oldpwd = translate_password(playername, oldpassword);
1237 std::string newpwd = translate_password(playername, newpassword);
1239 NetworkPacket pkt(TOSERVER_PASSWORD_LEGACY, 2 * PASSWORD_SIZE);
1241 for (u8 i = 0; i < PASSWORD_SIZE; i++) {
1242 pkt << (u8) (i < oldpwd.length() ? oldpwd[i] : 0);
1245 for (u8 i = 0; i < PASSWORD_SIZE; i++) {
1246 pkt << (u8) (i < newpwd.length() ? newpwd[i] : 0);
1253 void Client::sendDamage(u8 damage)
1255 DSTACK(FUNCTION_NAME);
1257 NetworkPacket pkt(TOSERVER_DAMAGE, sizeof(u8));
1262 void Client::sendBreath(u16 breath)
1264 DSTACK(FUNCTION_NAME);
1266 NetworkPacket pkt(TOSERVER_BREATH, sizeof(u16));
1271 void Client::sendRespawn()
1273 DSTACK(FUNCTION_NAME);
1275 NetworkPacket pkt(TOSERVER_RESPAWN, 0);
1279 void Client::sendReady()
1281 DSTACK(FUNCTION_NAME);
1283 NetworkPacket pkt(TOSERVER_CLIENT_READY,
1284 1 + 1 + 1 + 1 + 2 + sizeof(char) * strlen(g_version_hash));
1286 pkt << (u8) VERSION_MAJOR << (u8) VERSION_MINOR << (u8) VERSION_PATCH
1287 << (u8) 0 << (u16) strlen(g_version_hash);
1289 pkt.putRawString(g_version_hash, (u16) strlen(g_version_hash));
1293 void Client::sendPlayerPos()
1295 LocalPlayer *myplayer = m_env.getLocalPlayer();
1296 if(myplayer == NULL)
1299 // Save bandwidth by only updating position when something changed
1300 if(myplayer->last_position == myplayer->getPosition() &&
1301 myplayer->last_speed == myplayer->getSpeed() &&
1302 myplayer->last_pitch == myplayer->getPitch() &&
1303 myplayer->last_yaw == myplayer->getYaw() &&
1304 myplayer->last_keyPressed == myplayer->keyPressed)
1307 myplayer->last_position = myplayer->getPosition();
1308 myplayer->last_speed = myplayer->getSpeed();
1309 myplayer->last_pitch = myplayer->getPitch();
1310 myplayer->last_yaw = myplayer->getYaw();
1311 myplayer->last_keyPressed = myplayer->keyPressed;
1315 //MutexAutoLock lock(m_con_mutex); //bulk comment-out
1316 our_peer_id = m_con.GetPeerID();
1319 // Set peer id if not set already
1320 if(myplayer->peer_id == PEER_ID_INEXISTENT)
1321 myplayer->peer_id = our_peer_id;
1323 assert(myplayer->peer_id == our_peer_id);
1325 NetworkPacket pkt(TOSERVER_PLAYERPOS, 12 + 12 + 4 + 4 + 4);
1327 writePlayerPos(myplayer, &pkt);
1332 void Client::sendPlayerItem(u16 item)
1334 LocalPlayer *myplayer = m_env.getLocalPlayer();
1335 if(myplayer == NULL)
1338 u16 our_peer_id = m_con.GetPeerID();
1340 // Set peer id if not set already
1341 if(myplayer->peer_id == PEER_ID_INEXISTENT)
1342 myplayer->peer_id = our_peer_id;
1343 assert(myplayer->peer_id == our_peer_id);
1345 NetworkPacket pkt(TOSERVER_PLAYERITEM, 2);
1352 void Client::removeNode(v3s16 p)
1354 std::map<v3s16, MapBlock*> modified_blocks;
1357 m_env.getMap().removeNodeAndUpdate(p, modified_blocks);
1359 catch(InvalidPositionException &e) {
1362 for(std::map<v3s16, MapBlock *>::iterator
1363 i = modified_blocks.begin();
1364 i != modified_blocks.end(); ++i) {
1365 addUpdateMeshTaskWithEdge(i->first, false, true);
1369 void Client::addNode(v3s16 p, MapNode n, bool remove_metadata)
1371 //TimeTaker timer1("Client::addNode()");
1373 std::map<v3s16, MapBlock*> modified_blocks;
1376 //TimeTaker timer3("Client::addNode(): addNodeAndUpdate");
1377 m_env.getMap().addNodeAndUpdate(p, n, modified_blocks, remove_metadata);
1379 catch(InvalidPositionException &e) {
1382 for(std::map<v3s16, MapBlock *>::iterator
1383 i = modified_blocks.begin();
1384 i != modified_blocks.end(); ++i) {
1385 addUpdateMeshTaskWithEdge(i->first, false, true);
1389 void Client::setPlayerControl(PlayerControl &control)
1391 LocalPlayer *player = m_env.getLocalPlayer();
1392 assert(player != NULL);
1393 player->control = control;
1396 void Client::selectPlayerItem(u16 item)
1398 m_playeritem = item;
1399 m_inventory_updated = true;
1400 sendPlayerItem(item);
1403 // Returns true if the inventory of the local player has been
1404 // updated from the server. If it is true, it is set to false.
1405 bool Client::getLocalInventoryUpdated()
1407 bool updated = m_inventory_updated;
1408 m_inventory_updated = false;
1412 // Copies the inventory of the local player to parameter
1413 void Client::getLocalInventory(Inventory &dst)
1415 LocalPlayer *player = m_env.getLocalPlayer();
1416 assert(player != NULL);
1417 dst = player->inventory;
1420 Inventory* Client::getInventory(const InventoryLocation &loc)
1423 case InventoryLocation::UNDEFINED:
1426 case InventoryLocation::CURRENT_PLAYER:
1428 LocalPlayer *player = m_env.getLocalPlayer();
1429 assert(player != NULL);
1430 return &player->inventory;
1433 case InventoryLocation::PLAYER:
1435 // Check if we are working with local player inventory
1436 LocalPlayer *player = m_env.getLocalPlayer();
1437 if (!player || strcmp(player->getName(), loc.name.c_str()) != 0)
1439 return &player->inventory;
1442 case InventoryLocation::NODEMETA:
1444 NodeMetadata *meta = m_env.getMap().getNodeMetadata(loc.p);
1447 return meta->getInventory();
1450 case InventoryLocation::DETACHED:
1452 if (m_detached_inventories.count(loc.name) == 0)
1454 return m_detached_inventories[loc.name];
1458 FATAL_ERROR("Invalid inventory location type.");
1464 void Client::inventoryAction(InventoryAction *a)
1467 Send it to the server
1469 sendInventoryAction(a);
1472 Predict some local inventory changes
1474 a->clientApply(this, this);
1480 ClientActiveObject * Client::getSelectedActiveObject(
1482 v3f from_pos_f_on_map,
1483 core::line3d<f32> shootline_on_map
1486 std::vector<DistanceSortedActiveObject> objects;
1488 m_env.getActiveObjects(from_pos_f_on_map, max_d, objects);
1491 // After this, the closest object is the first in the array.
1492 std::sort(objects.begin(), objects.end());
1494 for(unsigned int i=0; i<objects.size(); i++)
1496 ClientActiveObject *obj = objects[i].obj;
1498 aabb3f *selection_box = obj->getSelectionBox();
1499 if(selection_box == NULL)
1502 v3f pos = obj->getPosition();
1504 aabb3f offsetted_box(
1505 selection_box->MinEdge + pos,
1506 selection_box->MaxEdge + pos
1509 if(offsetted_box.intersectsWithLine(shootline_on_map))
1518 float Client::getAnimationTime()
1520 return m_animation_time;
1523 int Client::getCrackLevel()
1525 return m_crack_level;
1528 void Client::setCrack(int level, v3s16 pos)
1530 int old_crack_level = m_crack_level;
1531 v3s16 old_crack_pos = m_crack_pos;
1533 m_crack_level = level;
1536 if(old_crack_level >= 0 && (level < 0 || pos != old_crack_pos))
1539 addUpdateMeshTaskForNode(old_crack_pos, false, true);
1541 if(level >= 0 && (old_crack_level < 0 || pos != old_crack_pos))
1544 addUpdateMeshTaskForNode(pos, false, true);
1550 LocalPlayer *player = m_env.getLocalPlayer();
1551 assert(player != NULL);
1555 bool Client::getChatMessage(std::wstring &message)
1557 if(m_chat_queue.size() == 0)
1559 message = m_chat_queue.front();
1564 void Client::typeChatMessage(const std::wstring &message)
1566 // Discard empty line
1571 sendChatMessage(message);
1574 if (message[0] == L'/')
1576 m_chat_queue.push((std::wstring)L"issued command: " + message);
1580 LocalPlayer *player = m_env.getLocalPlayer();
1581 assert(player != NULL);
1582 std::wstring name = narrow_to_wide(player->getName());
1583 m_chat_queue.push((std::wstring)L"<" + name + L"> " + message);
1587 void Client::addUpdateMeshTask(v3s16 p, bool ack_to_server, bool urgent)
1589 MapBlock *b = m_env.getMap().getBlockNoCreateNoEx(p);
1594 Create a task to update the mesh of the block
1597 MeshMakeData *data = new MeshMakeData(this, m_cache_enable_shaders,
1598 m_cache_use_tangent_vertices);
1601 //TimeTaker timer("data fill");
1603 // Debug: 1-6ms, avg=2ms
1605 data->setCrack(m_crack_level, m_crack_pos);
1606 data->setSmoothLighting(m_cache_smooth_lighting);
1609 // Add task to queue
1610 m_mesh_update_thread.enqueueUpdate(p, data, ack_to_server, urgent);
1613 void Client::addUpdateMeshTaskWithEdge(v3s16 blockpos, bool ack_to_server, bool urgent)
1616 addUpdateMeshTask(blockpos, ack_to_server, urgent);
1618 catch(InvalidPositionException &e){}
1621 for (int i=0;i<6;i++)
1624 v3s16 p = blockpos + g_6dirs[i];
1625 addUpdateMeshTask(p, false, urgent);
1627 catch(InvalidPositionException &e){}
1631 void Client::addUpdateMeshTaskForNode(v3s16 nodepos, bool ack_to_server, bool urgent)
1635 infostream<<"Client::addUpdateMeshTaskForNode(): "
1636 <<"("<<p.X<<","<<p.Y<<","<<p.Z<<")"
1640 v3s16 blockpos = getNodeBlockPos(nodepos);
1641 v3s16 blockpos_relative = blockpos * MAP_BLOCKSIZE;
1644 addUpdateMeshTask(blockpos, ack_to_server, urgent);
1646 catch(InvalidPositionException &e) {}
1649 if(nodepos.X == blockpos_relative.X){
1651 v3s16 p = blockpos + v3s16(-1,0,0);
1652 addUpdateMeshTask(p, false, urgent);
1654 catch(InvalidPositionException &e){}
1657 if(nodepos.Y == blockpos_relative.Y){
1659 v3s16 p = blockpos + v3s16(0,-1,0);
1660 addUpdateMeshTask(p, false, urgent);
1662 catch(InvalidPositionException &e){}
1665 if(nodepos.Z == blockpos_relative.Z){
1667 v3s16 p = blockpos + v3s16(0,0,-1);
1668 addUpdateMeshTask(p, false, urgent);
1670 catch(InvalidPositionException &e){}
1674 ClientEvent Client::getClientEvent()
1677 if (m_client_event_queue.empty()) {
1678 event.type = CE_NONE;
1681 event = m_client_event_queue.front();
1682 m_client_event_queue.pop();
1687 float Client::mediaReceiveProgress()
1689 if (m_media_downloader)
1690 return m_media_downloader->getProgress();
1692 return 1.0; // downloader only exists when not yet done
1695 typedef struct TextureUpdateArgs {
1696 IrrlichtDevice *device;
1697 gui::IGUIEnvironment *guienv;
1700 const wchar_t* text_base;
1701 } TextureUpdateArgs;
1703 void texture_update_progress(void *args, u32 progress, u32 max_progress)
1705 TextureUpdateArgs* targs = (TextureUpdateArgs*) args;
1706 u16 cur_percent = ceil(progress / (double) max_progress * 100.);
1708 // update the loading menu -- if neccessary
1709 bool do_draw = false;
1710 u32 time_ms = targs->last_time_ms;
1711 if (cur_percent != targs->last_percent) {
1712 targs->last_percent = cur_percent;
1713 time_ms = getTimeMs();
1714 // only draw when the user will notice something:
1715 do_draw = (time_ms - targs->last_time_ms > 100);
1719 targs->last_time_ms = time_ms;
1720 std::basic_stringstream<wchar_t> strm;
1721 strm << targs->text_base << " " << targs->last_percent << "%...";
1722 draw_load_screen(strm.str(), targs->device, targs->guienv, 0,
1723 72 + (u16) ((18. / 100.) * (double) targs->last_percent));
1727 void Client::afterContentReceived(IrrlichtDevice *device)
1729 infostream<<"Client::afterContentReceived() started"<<std::endl;
1730 assert(m_itemdef_received); // pre-condition
1731 assert(m_nodedef_received); // pre-condition
1732 assert(mediaReceived()); // pre-condition
1734 const wchar_t* text = wgettext("Loading textures...");
1736 // Clear cached pre-scaled 2D GUI images, as this cache
1737 // might have images with the same name but different
1738 // content from previous sessions.
1739 guiScalingCacheClear(device->getVideoDriver());
1741 // Rebuild inherited images and recreate textures
1742 infostream<<"- Rebuilding images and textures"<<std::endl;
1743 draw_load_screen(text,device, guienv, 0, 70);
1744 m_tsrc->rebuildImagesAndTextures();
1748 infostream<<"- Rebuilding shaders"<<std::endl;
1749 text = wgettext("Rebuilding shaders...");
1750 draw_load_screen(text, device, guienv, 0, 71);
1751 m_shsrc->rebuildShaders();
1754 // Update node aliases
1755 infostream<<"- Updating node aliases"<<std::endl;
1756 text = wgettext("Initializing nodes...");
1757 draw_load_screen(text, device, guienv, 0, 72);
1758 m_nodedef->updateAliases(m_itemdef);
1759 std::string texture_path = g_settings->get("texture_path");
1760 if (texture_path != "" && fs::IsDir(texture_path))
1761 m_nodedef->applyTextureOverrides(texture_path + DIR_DELIM + "override.txt");
1762 m_nodedef->setNodeRegistrationStatus(true);
1763 m_nodedef->runNodeResolveCallbacks();
1766 // Update node textures and assign shaders to each tile
1767 infostream<<"- Updating node textures"<<std::endl;
1768 TextureUpdateArgs tu_args;
1769 tu_args.device = device;
1770 tu_args.guienv = guienv;
1771 tu_args.last_time_ms = getTimeMs();
1772 tu_args.last_percent = 0;
1773 tu_args.text_base = wgettext("Initializing nodes");
1774 m_nodedef->updateTextures(this, texture_update_progress, &tu_args);
1775 delete[] tu_args.text_base;
1777 // Start mesh update thread after setting up content definitions
1778 infostream<<"- Starting mesh update thread"<<std::endl;
1779 m_mesh_update_thread.start();
1783 text = wgettext("Done!");
1784 draw_load_screen(text, device, guienv, 0, 100);
1785 infostream<<"Client::afterContentReceived() done"<<std::endl;
1789 float Client::getRTT(void)
1791 return m_con.getPeerStat(PEER_ID_SERVER,con::AVG_RTT);
1794 float Client::getCurRate(void)
1796 return ( m_con.getLocalStat(con::CUR_INC_RATE) +
1797 m_con.getLocalStat(con::CUR_DL_RATE));
1800 float Client::getAvgRate(void)
1802 return ( m_con.getLocalStat(con::AVG_INC_RATE) +
1803 m_con.getLocalStat(con::AVG_DL_RATE));
1806 void Client::makeScreenshot(IrrlichtDevice *device)
1808 irr::video::IVideoDriver *driver = device->getVideoDriver();
1809 irr::video::IImage* const raw_image = driver->createScreenShot();
1814 time_t t = time(NULL);
1815 struct tm *tm = localtime(&t);
1817 char timetstamp_c[64];
1818 strftime(timetstamp_c, sizeof(timetstamp_c), "%Y%m%d_%H%M%S", tm);
1820 std::string filename_base = g_settings->get("screenshot_path")
1822 + std::string("screenshot_")
1823 + std::string(timetstamp_c);
1824 std::string filename_ext = "." + g_settings->get("screenshot_format");
1825 std::string filename;
1827 u32 quality = (u32)g_settings->getS32("screenshot_quality");
1828 quality = MYMIN(MYMAX(quality, 0), 100) / 100.0 * 255;
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(), quality)) {
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);