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.
24 #include <IFileSystem.h>
25 #include "threading/mutex_auto_lock.h"
26 #include "util/auth.h"
27 #include "util/directiontables.h"
28 #include "util/pointedthing.h"
29 #include "util/serialize.h"
30 #include "util/string.h"
33 #include "network/clientopcodes.h"
35 #include "mapblock_mesh.h"
41 #include "clientmap.h"
42 #include "clientmedia.h"
44 #include "drawscene.h"
45 #include "database-sqlite3.h"
46 #include "serialization.h"
47 #include "guiscalingfilter.h"
48 #include "script/clientscripting.h"
50 extern gui::IGUIEnvironment* guienv;
56 QueuedMeshUpdate::QueuedMeshUpdate():
59 ack_block_to_server(false)
63 QueuedMeshUpdate::~QueuedMeshUpdate()
73 MeshUpdateQueue::MeshUpdateQueue()
77 MeshUpdateQueue::~MeshUpdateQueue()
79 MutexAutoLock lock(m_mutex);
81 for(std::vector<QueuedMeshUpdate*>::iterator
83 i != m_queue.end(); ++i)
85 QueuedMeshUpdate *q = *i;
91 peer_id=0 adds with nobody to send to
93 void MeshUpdateQueue::addBlock(v3s16 p, MeshMakeData *data, bool ack_block_to_server, bool urgent)
95 DSTACK(FUNCTION_NAME);
97 assert(data); // pre-condition
99 MutexAutoLock lock(m_mutex);
105 Find if block is already in queue.
106 If it is, update the data and quit.
108 for(std::vector<QueuedMeshUpdate*>::iterator
110 i != m_queue.end(); ++i)
112 QueuedMeshUpdate *q = *i;
118 if(ack_block_to_server)
119 q->ack_block_to_server = true;
127 QueuedMeshUpdate *q = new QueuedMeshUpdate;
130 q->ack_block_to_server = ack_block_to_server;
131 m_queue.push_back(q);
134 // Returned pointer must be deleted
135 // Returns NULL if queue is empty
136 QueuedMeshUpdate *MeshUpdateQueue::pop()
138 MutexAutoLock lock(m_mutex);
140 bool must_be_urgent = !m_urgents.empty();
141 for(std::vector<QueuedMeshUpdate*>::iterator
143 i != m_queue.end(); ++i)
145 QueuedMeshUpdate *q = *i;
146 if(must_be_urgent && m_urgents.count(q->p) == 0)
149 m_urgents.erase(q->p);
159 void MeshUpdateThread::enqueueUpdate(v3s16 p, MeshMakeData *data,
160 bool ack_block_to_server, bool urgent)
162 m_queue_in.addBlock(p, data, ack_block_to_server, urgent);
166 void MeshUpdateThread::doUpdate()
169 while ((q = m_queue_in.pop())) {
171 ScopeProfiler sp(g_profiler, "Client: Mesh making");
173 MapBlockMesh *mesh_new = new MapBlockMesh(q->data, m_camera_offset);
178 r.ack_block_to_server = q->ack_block_to_server;
180 m_queue_out.push_back(r);
191 IrrlichtDevice *device,
192 const char *playername,
193 std::string password,
194 MapDrawControl &control,
195 IWritableTextureSource *tsrc,
196 IWritableShaderSource *shsrc,
197 IWritableItemDefManager *itemdef,
198 IWritableNodeDefManager *nodedef,
199 ISoundManager *sound,
200 MtEventManager *event,
203 m_packetcounter_timer(0.0),
204 m_connection_reinit_timer(0.1),
205 m_avg_rtt_timer(0.0),
206 m_playerpos_send_timer(0.0),
207 m_ignore_damage_timer(0.0),
214 m_mesh_update_thread(),
216 new ClientMap(this, control,
217 device->getSceneManager()->getRootSceneNode(),
218 device->getSceneManager(), 666),
219 device->getSceneManager(),
222 m_particle_manager(&m_env),
223 m_con(PROTOCOL_ID, 512, CONNECTION_TIMEOUT, ipv6, this),
226 m_minimap_disabled_by_server(false),
227 m_server_ser_ver(SER_FMT_VER_INVALID),
230 m_inventory_updated(false),
231 m_inventory_from_server(NULL),
232 m_inventory_from_server_age(0.0),
237 m_password(password),
238 m_chosen_auth_mech(AUTH_MECHANISM_NONE),
240 m_access_denied(false),
241 m_access_denied_reconnect(false),
242 m_itemdef_received(false),
243 m_nodedef_received(false),
244 m_media_downloader(new ClientMediaDownloader()),
245 m_time_of_day_set(false),
246 m_last_time_of_day_f(-1),
247 m_time_of_day_update_timer(0),
248 m_recommended_send_interval(0.1),
249 m_removed_sounds_check_timer(0),
254 m_env.setLocalPlayer(new LocalPlayer(this, playername));
256 m_mapper = new Mapper(device, this);
257 m_cache_save_interval = g_settings->getU16("server_map_save_interval");
259 m_cache_smooth_lighting = g_settings->getBool("smooth_lighting");
260 m_cache_enable_shaders = g_settings->getBool("enable_shaders");
261 m_cache_use_tangent_vertices = m_cache_enable_shaders && (
262 g_settings->getBool("enable_bumpmapping") ||
263 g_settings->getBool("enable_parallax_occlusion"));
265 m_script = new ClientScripting(this);
268 void Client::initMods()
270 std::string script_path = getBuiltinLuaPath() + DIR_DELIM "init.lua";
272 m_script->loadMod(script_path, BUILTIN_MOD_NAME);
275 const std::string Client::getBuiltinLuaPath()
277 return porting::path_share + DIR_DELIM + "builtin";
280 const std::vector<ModSpec>& Client::getMods() const
282 static std::vector<ModSpec> client_modspec_temp;
283 return client_modspec_temp;
286 const ModSpec* Client::getModSpec(const std::string &modname) const
293 m_script->on_shutdown();
294 //request all client managed threads to stop
295 m_mesh_update_thread.stop();
296 // Save local server map
298 infostream << "Local map saving ended." << std::endl;
299 m_localdb->endSave();
305 bool Client::isShutdown()
308 if (!m_mesh_update_thread.isRunning()) return true;
317 m_mesh_update_thread.stop();
318 m_mesh_update_thread.wait();
319 while (!m_mesh_update_thread.m_queue_out.empty()) {
320 MeshUpdateResult r = m_mesh_update_thread.m_queue_out.pop_frontNoEx();
325 delete m_inventory_from_server;
327 // Delete detached inventories
328 for (UNORDERED_MAP<std::string, Inventory*>::iterator
329 i = m_detached_inventories.begin();
330 i != m_detached_inventories.end(); ++i) {
334 // cleanup 3d model meshes on client shutdown
335 while (m_device->getSceneManager()->getMeshCache()->getMeshCount() != 0) {
336 scene::IAnimatedMesh *mesh =
337 m_device->getSceneManager()->getMeshCache()->getMeshByIndex(0);
340 m_device->getSceneManager()->getMeshCache()->removeMesh(mesh);
346 void Client::connect(Address address,
347 const std::string &address_name,
348 bool is_local_server)
350 DSTACK(FUNCTION_NAME);
352 initLocalMapSaving(address, address_name, is_local_server);
354 m_con.SetTimeoutMs(0);
355 m_con.Connect(address);
358 void Client::step(float dtime)
360 DSTACK(FUNCTION_NAME);
366 if(m_ignore_damage_timer > dtime)
367 m_ignore_damage_timer -= dtime;
369 m_ignore_damage_timer = 0.0;
371 m_animation_time += dtime;
372 if(m_animation_time > 60.0)
373 m_animation_time -= 60.0;
375 m_time_of_day_update_timer += dtime;
383 float &counter = m_packetcounter_timer;
389 infostream << "Client packetcounter (" << m_packetcounter_timer
391 m_packetcounter.print(infostream);
392 m_packetcounter.clear();
396 // UGLY hack to fix 2 second startup delay caused by non existent
397 // server client startup synchronization in local server or singleplayer mode
398 static bool initial_step = true;
400 initial_step = false;
402 else if(m_state == LC_Created) {
403 float &counter = m_connection_reinit_timer;
408 LocalPlayer *myplayer = m_env.getLocalPlayer();
409 FATAL_ERROR_IF(myplayer == NULL, "Local player not found in environment.");
411 u16 proto_version_min = g_settings->getFlag("send_pre_v25_init") ?
412 CLIENT_PROTOCOL_VERSION_MIN_LEGACY : CLIENT_PROTOCOL_VERSION_MIN;
414 if (proto_version_min < 25) {
415 // Send TOSERVER_INIT_LEGACY
416 // [0] u16 TOSERVER_INIT_LEGACY
417 // [2] u8 SER_FMT_VER_HIGHEST_READ
418 // [3] u8[20] player_name
419 // [23] u8[28] password (new in some version)
420 // [51] u16 minimum supported network protocol version (added sometime)
421 // [53] u16 maximum supported network protocol version (added later than the previous one)
423 char pName[PLAYERNAME_SIZE];
424 char pPassword[PASSWORD_SIZE];
425 memset(pName, 0, PLAYERNAME_SIZE * sizeof(char));
426 memset(pPassword, 0, PASSWORD_SIZE * sizeof(char));
428 std::string hashed_password = translate_password(myplayer->getName(), m_password);
429 snprintf(pName, PLAYERNAME_SIZE, "%s", myplayer->getName());
430 snprintf(pPassword, PASSWORD_SIZE, "%s", hashed_password.c_str());
432 sendLegacyInit(pName, pPassword);
434 if (CLIENT_PROTOCOL_VERSION_MAX >= 25)
435 sendInit(myplayer->getName());
438 // Not connected, return
443 Do stuff if connected
447 Run Map's timers and unload unused data
449 const float map_timer_and_unload_dtime = 5.25;
450 if(m_map_timer_and_unload_interval.step(dtime, map_timer_and_unload_dtime)) {
451 ScopeProfiler sp(g_profiler, "Client: map timer and unload");
452 std::vector<v3s16> deleted_blocks;
453 m_env.getMap().timerUpdate(map_timer_and_unload_dtime,
454 g_settings->getFloat("client_unload_unused_data_timeout"),
455 g_settings->getS32("client_mapblock_limit"),
460 NOTE: This loop is intentionally iterated the way it is.
463 std::vector<v3s16>::iterator i = deleted_blocks.begin();
464 std::vector<v3s16> sendlist;
466 if(sendlist.size() == 255 || i == deleted_blocks.end()) {
477 sendDeletedBlocks(sendlist);
479 if(i == deleted_blocks.end())
485 sendlist.push_back(*i);
493 // Control local player (0ms)
494 LocalPlayer *player = m_env.getLocalPlayer();
495 assert(player != NULL);
496 player->applyControl(dtime);
505 ClientEnvEvent event = m_env.getClientEvent();
506 if(event.type == CEE_NONE) {
509 else if(event.type == CEE_PLAYER_DAMAGE) {
510 if(m_ignore_damage_timer <= 0) {
511 u8 damage = event.player_damage.amount;
513 if(event.player_damage.send_to_server)
516 // Add to ClientEvent queue
518 event.type = CE_PLAYER_DAMAGE;
519 event.player_damage.amount = damage;
520 m_client_event_queue.push(event);
523 // Protocol v29 or greater obsoleted this event
524 else if (event.type == CEE_PLAYER_BREATH && m_proto_ver < 29) {
525 u16 breath = event.player_breath.amount;
533 float &counter = m_avg_rtt_timer;
537 // connectedAndInitialized() is true, peer exists.
538 float avg_rtt = getRTT();
539 infostream << "Client: avg_rtt=" << avg_rtt << std::endl;
543 Send player position to server
546 float &counter = m_playerpos_send_timer;
548 if((m_state == LC_Ready) && (counter >= m_recommended_send_interval))
556 Replace updated meshes
559 int num_processed_meshes = 0;
560 while (!m_mesh_update_thread.m_queue_out.empty())
562 num_processed_meshes++;
564 MinimapMapblock *minimap_mapblock = NULL;
565 bool do_mapper_update = true;
567 MeshUpdateResult r = m_mesh_update_thread.m_queue_out.pop_frontNoEx();
568 MapBlock *block = m_env.getMap().getBlockNoCreateNoEx(r.p);
570 // Delete the old mesh
571 if (block->mesh != NULL) {
577 minimap_mapblock = r.mesh->moveMinimapMapblock();
578 if (minimap_mapblock == NULL)
579 do_mapper_update = false;
582 if (r.mesh && r.mesh->getMesh()->getMeshBufferCount() == 0) {
585 // Replace with the new mesh
586 block->mesh = r.mesh;
592 if (do_mapper_update)
593 m_mapper->addBlock(r.p, minimap_mapblock);
595 if (r.ack_block_to_server) {
605 if (num_processed_meshes > 0)
606 g_profiler->graphAdd("num_processed_meshes", num_processed_meshes);
612 if (m_media_downloader && m_media_downloader->isStarted()) {
613 m_media_downloader->step(this);
614 if (m_media_downloader->isDone()) {
616 delete m_media_downloader;
617 m_media_downloader = NULL;
622 If the server didn't update the inventory in a while, revert
623 the local inventory (so the player notices the lag problem
624 and knows something is wrong).
626 if(m_inventory_from_server)
628 float interval = 10.0;
629 float count_before = floor(m_inventory_from_server_age / interval);
631 m_inventory_from_server_age += dtime;
633 float count_after = floor(m_inventory_from_server_age / interval);
635 if(count_after != count_before)
637 // Do this every <interval> seconds after TOCLIENT_INVENTORY
638 // Reset the locally changed inventory to the authoritative inventory
639 LocalPlayer *player = m_env.getLocalPlayer();
640 player->inventory = *m_inventory_from_server;
641 m_inventory_updated = true;
646 Update positions of sounds attached to objects
649 for(UNORDERED_MAP<int, u16>::iterator i = m_sounds_to_objects.begin();
650 i != m_sounds_to_objects.end(); ++i) {
651 int client_id = i->first;
652 u16 object_id = i->second;
653 ClientActiveObject *cao = m_env.getActiveObject(object_id);
656 v3f pos = cao->getPosition();
657 m_sound->updateSoundPosition(client_id, pos);
662 Handle removed remotely initiated sounds
664 m_removed_sounds_check_timer += dtime;
665 if(m_removed_sounds_check_timer >= 2.32) {
666 m_removed_sounds_check_timer = 0;
667 // Find removed sounds and clear references to them
668 std::vector<s32> removed_server_ids;
669 for(UNORDERED_MAP<s32, int>::iterator i = m_sounds_server_to_client.begin();
670 i != m_sounds_server_to_client.end();) {
671 s32 server_id = i->first;
672 int client_id = i->second;
674 if(!m_sound->soundExists(client_id)) {
675 m_sounds_server_to_client.erase(server_id);
676 m_sounds_client_to_server.erase(client_id);
677 m_sounds_to_objects.erase(client_id);
678 removed_server_ids.push_back(server_id);
683 if(!removed_server_ids.empty()) {
684 sendRemovedSounds(removed_server_ids);
689 if (m_localdb && m_localdb_save_interval.step(dtime,
690 m_cache_save_interval)) {
691 m_localdb->endSave();
692 m_localdb->beginSave();
696 bool Client::loadMedia(const std::string &data, const std::string &filename)
698 // Silly irrlicht's const-incorrectness
699 Buffer<char> data_rw(data.c_str(), data.size());
703 const char *image_ext[] = {
704 ".png", ".jpg", ".bmp", ".tga",
705 ".pcx", ".ppm", ".psd", ".wal", ".rgb",
708 name = removeStringEnd(filename, image_ext);
711 verbosestream<<"Client: Attempting to load image "
712 <<"file \""<<filename<<"\""<<std::endl;
714 io::IFileSystem *irrfs = m_device->getFileSystem();
715 video::IVideoDriver *vdrv = m_device->getVideoDriver();
717 // Create an irrlicht memory file
718 io::IReadFile *rfile = irrfs->createMemoryReadFile(
719 *data_rw, data_rw.getSize(), "_tempreadfile");
721 FATAL_ERROR_IF(!rfile, "Could not create irrlicht memory file.");
724 video::IImage *img = vdrv->createImageFromFile(rfile);
726 errorstream<<"Client: Cannot create image from data of "
727 <<"file \""<<filename<<"\""<<std::endl;
732 m_tsrc->insertSourceImage(filename, img);
739 const char *sound_ext[] = {
740 ".0.ogg", ".1.ogg", ".2.ogg", ".3.ogg", ".4.ogg",
741 ".5.ogg", ".6.ogg", ".7.ogg", ".8.ogg", ".9.ogg",
744 name = removeStringEnd(filename, sound_ext);
747 verbosestream<<"Client: Attempting to load sound "
748 <<"file \""<<filename<<"\""<<std::endl;
749 m_sound->loadSoundData(name, data);
753 const char *model_ext[] = {
754 ".x", ".b3d", ".md2", ".obj",
757 name = removeStringEnd(filename, model_ext);
760 verbosestream<<"Client: Storing model into memory: "
761 <<"\""<<filename<<"\""<<std::endl;
762 if(m_mesh_data.count(filename))
763 errorstream<<"Multiple models with name \""<<filename.c_str()
764 <<"\" found; replacing previous model"<<std::endl;
765 m_mesh_data[filename] = data;
769 errorstream<<"Client: Don't know how to load file \""
770 <<filename<<"\""<<std::endl;
774 // Virtual methods from con::PeerHandler
775 void Client::peerAdded(con::Peer *peer)
777 infostream << "Client::peerAdded(): peer->id="
778 << peer->id << std::endl;
780 void Client::deletingPeer(con::Peer *peer, bool timeout)
782 infostream << "Client::deletingPeer(): "
783 "Server Peer is getting deleted "
784 << "(timeout=" << timeout << ")" << std::endl;
787 m_access_denied = true;
788 m_access_denied_reason = gettext("Connection timed out.");
794 u16 number of files requested
800 void Client::request_media(const std::vector<std::string> &file_requests)
802 std::ostringstream os(std::ios_base::binary);
803 writeU16(os, TOSERVER_REQUEST_MEDIA);
804 size_t file_requests_size = file_requests.size();
806 FATAL_ERROR_IF(file_requests_size > 0xFFFF, "Unsupported number of file requests");
808 // Packet dynamicly resized
809 NetworkPacket pkt(TOSERVER_REQUEST_MEDIA, 2 + 0);
811 pkt << (u16) (file_requests_size & 0xFFFF);
813 for(std::vector<std::string>::const_iterator i = file_requests.begin();
814 i != file_requests.end(); ++i) {
820 infostream << "Client: Sending media request list to server ("
821 << file_requests.size() << " files. packet size)" << std::endl;
824 void Client::received_media()
826 NetworkPacket pkt(TOSERVER_RECEIVED_MEDIA, 0);
828 infostream << "Client: Notifying server that we received all media"
832 void Client::initLocalMapSaving(const Address &address,
833 const std::string &hostname,
834 bool is_local_server)
836 if (!g_settings->getBool("enable_local_map_saving") || is_local_server) {
840 const std::string world_path = porting::path_user
841 + DIR_DELIM + "worlds"
842 + DIR_DELIM + "server_"
843 + hostname + "_" + std::to_string(address.getPort());
845 fs::CreateAllDirs(world_path);
847 m_localdb = new Database_SQLite3(world_path);
848 m_localdb->beginSave();
849 actionstream << "Local map saving started, map will be saved at '" << world_path << "'" << std::endl;
852 void Client::ReceiveAll()
854 DSTACK(FUNCTION_NAME);
855 u32 start_ms = porting::getTimeMs();
858 // Limit time even if there would be huge amounts of data to
860 if(porting::getTimeMs() > start_ms + 100)
865 g_profiler->graphAdd("client_received_packets", 1);
867 catch(con::NoIncomingDataException &e) {
870 catch(con::InvalidIncomingDataException &e) {
871 infostream<<"Client::ReceiveAll(): "
872 "InvalidIncomingDataException: what()="
873 <<e.what()<<std::endl;
878 void Client::Receive()
880 DSTACK(FUNCTION_NAME);
886 inline void Client::handleCommand(NetworkPacket* pkt)
888 const ToClientCommandHandler& opHandle = toClientCommandTable[pkt->getCommand()];
889 (this->*opHandle.handler)(pkt);
893 sender_peer_id given to this shall be quaranteed to be a valid peer
895 void Client::ProcessData(NetworkPacket *pkt)
897 DSTACK(FUNCTION_NAME);
899 ToClientCommand command = (ToClientCommand) pkt->getCommand();
900 u32 sender_peer_id = pkt->getPeerId();
902 //infostream<<"Client: received command="<<command<<std::endl;
903 m_packetcounter.add((u16)command);
906 If this check is removed, be sure to change the queue
907 system to know the ids
909 if(sender_peer_id != PEER_ID_SERVER) {
910 infostream << "Client::ProcessData(): Discarding data not "
911 "coming from server: peer_id=" << sender_peer_id
916 // Command must be handled into ToClientCommandHandler
917 if (command >= TOCLIENT_NUM_MSG_TYPES) {
918 infostream << "Client: Ignoring unknown command "
919 << command << std::endl;
924 * Those packets are handled before m_server_ser_ver is set, it's normal
925 * But we must use the new ToClientConnectionState in the future,
928 if(toClientCommandTable[command].state == TOCLIENT_STATE_NOT_CONNECTED) {
933 if(m_server_ser_ver == SER_FMT_VER_INVALID) {
934 infostream << "Client: Server serialization"
935 " format invalid or not initialized."
936 " Skipping incoming command=" << command << std::endl;
941 Handle runtime commands
947 void Client::Send(NetworkPacket* pkt)
949 m_con.Send(PEER_ID_SERVER,
950 serverCommandFactoryTable[pkt->getCommand()].channel,
952 serverCommandFactoryTable[pkt->getCommand()].reliable);
955 // Will fill up 12 + 12 + 4 + 4 + 4 bytes
956 void writePlayerPos(LocalPlayer *myplayer, ClientMap *clientMap, NetworkPacket *pkt)
958 v3f pf = myplayer->getPosition() * 100;
959 v3f sf = myplayer->getSpeed() * 100;
960 s32 pitch = myplayer->getPitch() * 100;
961 s32 yaw = myplayer->getYaw() * 100;
962 u32 keyPressed = myplayer->keyPressed;
963 // scaled by 80, so that pi can fit into a u8
964 u8 fov = clientMap->getCameraFov() * 80;
965 u8 wanted_range = MYMIN(255,
966 std::ceil(clientMap->getControl().wanted_range / MAP_BLOCKSIZE));
968 v3s32 position(pf.X, pf.Y, pf.Z);
969 v3s32 speed(sf.X, sf.Y, sf.Z);
973 [0] v3s32 position*100
975 [12+12] s32 pitch*100
976 [12+12+4] s32 yaw*100
977 [12+12+4+4] u32 keyPressed
978 [12+12+4+4+4] u8 fov*80
979 [12+12+4+4+4+1] u8 ceil(wanted_range / MAP_BLOCKSIZE)
981 *pkt << position << speed << pitch << yaw << keyPressed;
982 *pkt << fov << wanted_range;
985 void Client::interact(u8 action, const PointedThing& pointed)
987 if(m_state != LC_Ready) {
988 errorstream << "Client::interact() "
989 "Canceled (not connected)"
994 LocalPlayer *myplayer = m_env.getLocalPlayer();
995 if (myplayer == NULL)
1002 [5] u32 length of the next item (plen)
1003 [9] serialized PointedThing
1004 [9 + plen] player position information
1006 0: start digging (from undersurface) or use
1007 1: stop digging (all parameters ignored)
1008 2: digging completed
1009 3: place block or item (to abovesurface)
1011 5: perform secondary action of item
1014 NetworkPacket pkt(TOSERVER_INTERACT, 1 + 2 + 0);
1017 pkt << (u16)getPlayerItem();
1019 std::ostringstream tmp_os(std::ios::binary);
1020 pointed.serialize(tmp_os);
1022 pkt.putLongString(tmp_os.str());
1024 writePlayerPos(myplayer, &m_env.getClientMap(), &pkt);
1029 void Client::deleteAuthData()
1034 switch (m_chosen_auth_mech) {
1035 case AUTH_MECHANISM_FIRST_SRP:
1037 case AUTH_MECHANISM_SRP:
1038 case AUTH_MECHANISM_LEGACY_PASSWORD:
1039 srp_user_delete((SRPUser *) m_auth_data);
1042 case AUTH_MECHANISM_NONE:
1045 m_chosen_auth_mech = AUTH_MECHANISM_NONE;
1049 AuthMechanism Client::choseAuthMech(const u32 mechs)
1051 if (mechs & AUTH_MECHANISM_SRP)
1052 return AUTH_MECHANISM_SRP;
1054 if (mechs & AUTH_MECHANISM_FIRST_SRP)
1055 return AUTH_MECHANISM_FIRST_SRP;
1057 if (mechs & AUTH_MECHANISM_LEGACY_PASSWORD)
1058 return AUTH_MECHANISM_LEGACY_PASSWORD;
1060 return AUTH_MECHANISM_NONE;
1063 void Client::sendLegacyInit(const char* playerName, const char* playerPassword)
1065 NetworkPacket pkt(TOSERVER_INIT_LEGACY,
1066 1 + PLAYERNAME_SIZE + PASSWORD_SIZE + 2 + 2);
1068 u16 proto_version_min = g_settings->getFlag("send_pre_v25_init") ?
1069 CLIENT_PROTOCOL_VERSION_MIN_LEGACY : CLIENT_PROTOCOL_VERSION_MIN;
1071 pkt << (u8) SER_FMT_VER_HIGHEST_READ;
1072 pkt.putRawString(playerName,PLAYERNAME_SIZE);
1073 pkt.putRawString(playerPassword, PASSWORD_SIZE);
1074 pkt << (u16) proto_version_min << (u16) CLIENT_PROTOCOL_VERSION_MAX;
1079 void Client::sendInit(const std::string &playerName)
1081 NetworkPacket pkt(TOSERVER_INIT, 1 + 2 + 2 + (1 + playerName.size()));
1083 // we don't support network compression yet
1084 u16 supp_comp_modes = NETPROTO_COMPRESSION_NONE;
1086 u16 proto_version_min = g_settings->getFlag("send_pre_v25_init") ?
1087 CLIENT_PROTOCOL_VERSION_MIN_LEGACY : CLIENT_PROTOCOL_VERSION_MIN;
1089 pkt << (u8) SER_FMT_VER_HIGHEST_READ << (u16) supp_comp_modes;
1090 pkt << (u16) proto_version_min << (u16) CLIENT_PROTOCOL_VERSION_MAX;
1096 void Client::startAuth(AuthMechanism chosen_auth_mechanism)
1098 m_chosen_auth_mech = chosen_auth_mechanism;
1100 switch (chosen_auth_mechanism) {
1101 case AUTH_MECHANISM_FIRST_SRP: {
1102 // send srp verifier to server
1103 std::string verifier;
1105 generate_srp_verifier_and_salt(getPlayerName(), m_password,
1108 NetworkPacket resp_pkt(TOSERVER_FIRST_SRP, 0);
1109 resp_pkt << salt << verifier << (u8)((m_password == "") ? 1 : 0);
1114 case AUTH_MECHANISM_SRP:
1115 case AUTH_MECHANISM_LEGACY_PASSWORD: {
1118 if (chosen_auth_mechanism == AUTH_MECHANISM_LEGACY_PASSWORD) {
1119 m_password = translate_password(getPlayerName(), m_password);
1123 std::string playername_u = lowercase(getPlayerName());
1124 m_auth_data = srp_user_new(SRP_SHA256, SRP_NG_2048,
1125 getPlayerName().c_str(), playername_u.c_str(),
1126 (const unsigned char *) m_password.c_str(),
1127 m_password.length(), NULL, NULL);
1130 SRP_Result res = srp_user_start_authentication(
1131 (struct SRPUser *) m_auth_data, NULL, NULL, 0,
1132 (unsigned char **) &bytes_A, &len_A);
1133 FATAL_ERROR_IF(res != SRP_OK, "Creating local SRP user failed.");
1135 NetworkPacket resp_pkt(TOSERVER_SRP_BYTES_A, 0);
1136 resp_pkt << std::string(bytes_A, len_A) << based_on;
1140 case AUTH_MECHANISM_NONE:
1141 break; // not handled in this method
1145 void Client::sendDeletedBlocks(std::vector<v3s16> &blocks)
1147 NetworkPacket pkt(TOSERVER_DELETEDBLOCKS, 1 + sizeof(v3s16) * blocks.size());
1149 pkt << (u8) blocks.size();
1152 for(std::vector<v3s16>::iterator
1154 j != blocks.end(); ++j) {
1162 void Client::sendGotBlocks(v3s16 block)
1164 NetworkPacket pkt(TOSERVER_GOTBLOCKS, 1 + 6);
1165 pkt << (u8) 1 << block;
1169 void Client::sendRemovedSounds(std::vector<s32> &soundList)
1171 size_t server_ids = soundList.size();
1172 assert(server_ids <= 0xFFFF);
1174 NetworkPacket pkt(TOSERVER_REMOVED_SOUNDS, 2 + server_ids * 4);
1176 pkt << (u16) (server_ids & 0xFFFF);
1178 for(std::vector<s32>::iterator i = soundList.begin();
1179 i != soundList.end(); ++i)
1185 void Client::sendNodemetaFields(v3s16 p, const std::string &formname,
1186 const StringMap &fields)
1188 size_t fields_size = fields.size();
1190 FATAL_ERROR_IF(fields_size > 0xFFFF, "Unsupported number of nodemeta fields");
1192 NetworkPacket pkt(TOSERVER_NODEMETA_FIELDS, 0);
1194 pkt << p << formname << (u16) (fields_size & 0xFFFF);
1196 StringMap::const_iterator it;
1197 for (it = fields.begin(); it != fields.end(); ++it) {
1198 const std::string &name = it->first;
1199 const std::string &value = it->second;
1201 pkt.putLongString(value);
1207 void Client::sendInventoryFields(const std::string &formname,
1208 const StringMap &fields)
1210 size_t fields_size = fields.size();
1211 FATAL_ERROR_IF(fields_size > 0xFFFF, "Unsupported number of inventory fields");
1213 NetworkPacket pkt(TOSERVER_INVENTORY_FIELDS, 0);
1214 pkt << formname << (u16) (fields_size & 0xFFFF);
1216 StringMap::const_iterator it;
1217 for (it = fields.begin(); it != fields.end(); ++it) {
1218 const std::string &name = it->first;
1219 const std::string &value = it->second;
1221 pkt.putLongString(value);
1227 void Client::sendInventoryAction(InventoryAction *a)
1229 std::ostringstream os(std::ios_base::binary);
1234 std::string s = os.str();
1236 NetworkPacket pkt(TOSERVER_INVENTORY_ACTION, s.size());
1237 pkt.putRawString(s.c_str(),s.size());
1242 void Client::sendChatMessage(const std::wstring &message)
1244 NetworkPacket pkt(TOSERVER_CHAT_MESSAGE, 2 + message.size() * sizeof(u16));
1251 void Client::sendChangePassword(const std::string &oldpassword,
1252 const std::string &newpassword)
1254 LocalPlayer *player = m_env.getLocalPlayer();
1258 std::string playername = player->getName();
1259 if (m_proto_ver >= 25) {
1260 // get into sudo mode and then send new password to server
1261 m_password = oldpassword;
1262 m_new_password = newpassword;
1263 startAuth(choseAuthMech(m_sudo_auth_methods));
1265 std::string oldpwd = translate_password(playername, oldpassword);
1266 std::string newpwd = translate_password(playername, newpassword);
1268 NetworkPacket pkt(TOSERVER_PASSWORD_LEGACY, 2 * PASSWORD_SIZE);
1270 for (u8 i = 0; i < PASSWORD_SIZE; i++) {
1271 pkt << (u8) (i < oldpwd.length() ? oldpwd[i] : 0);
1274 for (u8 i = 0; i < PASSWORD_SIZE; i++) {
1275 pkt << (u8) (i < newpwd.length() ? newpwd[i] : 0);
1282 void Client::sendDamage(u8 damage)
1284 DSTACK(FUNCTION_NAME);
1286 NetworkPacket pkt(TOSERVER_DAMAGE, sizeof(u8));
1291 void Client::sendBreath(u16 breath)
1293 DSTACK(FUNCTION_NAME);
1295 // Protocol v29 make this obsolete
1296 if (m_proto_ver >= 29)
1299 NetworkPacket pkt(TOSERVER_BREATH, sizeof(u16));
1304 void Client::sendRespawn()
1306 DSTACK(FUNCTION_NAME);
1308 NetworkPacket pkt(TOSERVER_RESPAWN, 0);
1312 void Client::sendReady()
1314 DSTACK(FUNCTION_NAME);
1316 NetworkPacket pkt(TOSERVER_CLIENT_READY,
1317 1 + 1 + 1 + 1 + 2 + sizeof(char) * strlen(g_version_hash));
1319 pkt << (u8) VERSION_MAJOR << (u8) VERSION_MINOR << (u8) VERSION_PATCH
1320 << (u8) 0 << (u16) strlen(g_version_hash);
1322 pkt.putRawString(g_version_hash, (u16) strlen(g_version_hash));
1326 void Client::sendPlayerPos()
1328 LocalPlayer *myplayer = m_env.getLocalPlayer();
1329 if(myplayer == NULL)
1332 ClientMap &map = m_env.getClientMap();
1334 u8 camera_fov = map.getCameraFov();
1335 u8 wanted_range = map.getControl().wanted_range;
1337 // Save bandwidth by only updating position when something changed
1338 if(myplayer->last_position == myplayer->getPosition() &&
1339 myplayer->last_speed == myplayer->getSpeed() &&
1340 myplayer->last_pitch == myplayer->getPitch() &&
1341 myplayer->last_yaw == myplayer->getYaw() &&
1342 myplayer->last_keyPressed == myplayer->keyPressed &&
1343 myplayer->last_camera_fov == camera_fov &&
1344 myplayer->last_wanted_range == wanted_range)
1347 myplayer->last_position = myplayer->getPosition();
1348 myplayer->last_speed = myplayer->getSpeed();
1349 myplayer->last_pitch = myplayer->getPitch();
1350 myplayer->last_yaw = myplayer->getYaw();
1351 myplayer->last_keyPressed = myplayer->keyPressed;
1352 myplayer->last_camera_fov = camera_fov;
1353 myplayer->last_wanted_range = wanted_range;
1355 //infostream << "Sending Player Position information" << std::endl;
1359 //MutexAutoLock lock(m_con_mutex); //bulk comment-out
1360 our_peer_id = m_con.GetPeerID();
1363 // Set peer id if not set already
1364 if(myplayer->peer_id == PEER_ID_INEXISTENT)
1365 myplayer->peer_id = our_peer_id;
1367 assert(myplayer->peer_id == our_peer_id);
1369 NetworkPacket pkt(TOSERVER_PLAYERPOS, 12 + 12 + 4 + 4 + 4 + 1 + 1);
1371 writePlayerPos(myplayer, &map, &pkt);
1376 void Client::sendPlayerItem(u16 item)
1378 LocalPlayer *myplayer = m_env.getLocalPlayer();
1379 if(myplayer == NULL)
1382 u16 our_peer_id = m_con.GetPeerID();
1384 // Set peer id if not set already
1385 if(myplayer->peer_id == PEER_ID_INEXISTENT)
1386 myplayer->peer_id = our_peer_id;
1387 assert(myplayer->peer_id == our_peer_id);
1389 NetworkPacket pkt(TOSERVER_PLAYERITEM, 2);
1396 void Client::removeNode(v3s16 p)
1398 std::map<v3s16, MapBlock*> modified_blocks;
1401 m_env.getMap().removeNodeAndUpdate(p, modified_blocks);
1403 catch(InvalidPositionException &e) {
1406 for(std::map<v3s16, MapBlock *>::iterator
1407 i = modified_blocks.begin();
1408 i != modified_blocks.end(); ++i) {
1409 addUpdateMeshTaskWithEdge(i->first, false, true);
1413 void Client::addNode(v3s16 p, MapNode n, bool remove_metadata)
1415 //TimeTaker timer1("Client::addNode()");
1417 std::map<v3s16, MapBlock*> modified_blocks;
1420 //TimeTaker timer3("Client::addNode(): addNodeAndUpdate");
1421 m_env.getMap().addNodeAndUpdate(p, n, modified_blocks, remove_metadata);
1423 catch(InvalidPositionException &e) {
1426 for(std::map<v3s16, MapBlock *>::iterator
1427 i = modified_blocks.begin();
1428 i != modified_blocks.end(); ++i) {
1429 addUpdateMeshTaskWithEdge(i->first, false, true);
1433 void Client::setPlayerControl(PlayerControl &control)
1435 LocalPlayer *player = m_env.getLocalPlayer();
1436 assert(player != NULL);
1437 player->control = control;
1440 void Client::selectPlayerItem(u16 item)
1442 m_playeritem = item;
1443 m_inventory_updated = true;
1444 sendPlayerItem(item);
1447 // Returns true if the inventory of the local player has been
1448 // updated from the server. If it is true, it is set to false.
1449 bool Client::getLocalInventoryUpdated()
1451 bool updated = m_inventory_updated;
1452 m_inventory_updated = false;
1456 // Copies the inventory of the local player to parameter
1457 void Client::getLocalInventory(Inventory &dst)
1459 LocalPlayer *player = m_env.getLocalPlayer();
1460 assert(player != NULL);
1461 dst = player->inventory;
1464 Inventory* Client::getInventory(const InventoryLocation &loc)
1467 case InventoryLocation::UNDEFINED:
1470 case InventoryLocation::CURRENT_PLAYER:
1472 LocalPlayer *player = m_env.getLocalPlayer();
1473 assert(player != NULL);
1474 return &player->inventory;
1477 case InventoryLocation::PLAYER:
1479 // Check if we are working with local player inventory
1480 LocalPlayer *player = m_env.getLocalPlayer();
1481 if (!player || strcmp(player->getName(), loc.name.c_str()) != 0)
1483 return &player->inventory;
1486 case InventoryLocation::NODEMETA:
1488 NodeMetadata *meta = m_env.getMap().getNodeMetadata(loc.p);
1491 return meta->getInventory();
1494 case InventoryLocation::DETACHED:
1496 if (m_detached_inventories.count(loc.name) == 0)
1498 return m_detached_inventories[loc.name];
1502 FATAL_ERROR("Invalid inventory location type.");
1508 void Client::inventoryAction(InventoryAction *a)
1511 Send it to the server
1513 sendInventoryAction(a);
1516 Predict some local inventory changes
1518 a->clientApply(this, this);
1524 float Client::getAnimationTime()
1526 return m_animation_time;
1529 int Client::getCrackLevel()
1531 return m_crack_level;
1534 void Client::setCrack(int level, v3s16 pos)
1536 int old_crack_level = m_crack_level;
1537 v3s16 old_crack_pos = m_crack_pos;
1539 m_crack_level = level;
1542 if(old_crack_level >= 0 && (level < 0 || pos != old_crack_pos))
1545 addUpdateMeshTaskForNode(old_crack_pos, false, true);
1547 if(level >= 0 && (old_crack_level < 0 || pos != old_crack_pos))
1550 addUpdateMeshTaskForNode(pos, false, true);
1556 LocalPlayer *player = m_env.getLocalPlayer();
1557 assert(player != NULL);
1561 bool Client::getChatMessage(std::wstring &message)
1563 if(m_chat_queue.size() == 0)
1565 message = m_chat_queue.front();
1570 void Client::typeChatMessage(const std::wstring &message)
1572 // Discard empty line
1576 // If message was ate by script API, don't send it to server
1577 if (m_script->on_sending_message(wide_to_utf8(message))) {
1582 sendChatMessage(message);
1585 if (message[0] == L'/')
1587 pushToChatQueue((std::wstring)L"issued command: " + message);
1591 // compatibility code
1592 if (m_proto_ver < 29) {
1593 LocalPlayer *player = m_env.getLocalPlayer();
1594 assert(player != NULL);
1595 std::wstring name = narrow_to_wide(player->getName());
1596 pushToChatQueue((std::wstring)L"<" + name + L"> " + message);
1601 void Client::addUpdateMeshTask(v3s16 p, bool ack_to_server, bool urgent)
1603 MapBlock *b = m_env.getMap().getBlockNoCreateNoEx(p);
1608 Create a task to update the mesh of the block
1611 MeshMakeData *data = new MeshMakeData(this, m_cache_enable_shaders,
1612 m_cache_use_tangent_vertices);
1615 //TimeTaker timer("data fill");
1617 // Debug: 1-6ms, avg=2ms
1619 data->setCrack(m_crack_level, m_crack_pos);
1620 data->setSmoothLighting(m_cache_smooth_lighting);
1623 // Add task to queue
1624 m_mesh_update_thread.enqueueUpdate(p, data, ack_to_server, urgent);
1627 void Client::addUpdateMeshTaskWithEdge(v3s16 blockpos, bool ack_to_server, bool urgent)
1630 addUpdateMeshTask(blockpos, ack_to_server, urgent);
1632 catch(InvalidPositionException &e){}
1635 for (int i=0;i<6;i++)
1638 v3s16 p = blockpos + g_6dirs[i];
1639 addUpdateMeshTask(p, false, urgent);
1641 catch(InvalidPositionException &e){}
1645 void Client::addUpdateMeshTaskForNode(v3s16 nodepos, bool ack_to_server, bool urgent)
1649 infostream<<"Client::addUpdateMeshTaskForNode(): "
1650 <<"("<<p.X<<","<<p.Y<<","<<p.Z<<")"
1654 v3s16 blockpos = getNodeBlockPos(nodepos);
1655 v3s16 blockpos_relative = blockpos * MAP_BLOCKSIZE;
1658 addUpdateMeshTask(blockpos, ack_to_server, urgent);
1660 catch(InvalidPositionException &e) {}
1663 if(nodepos.X == blockpos_relative.X){
1665 v3s16 p = blockpos + v3s16(-1,0,0);
1666 addUpdateMeshTask(p, false, urgent);
1668 catch(InvalidPositionException &e){}
1671 if(nodepos.Y == blockpos_relative.Y){
1673 v3s16 p = blockpos + v3s16(0,-1,0);
1674 addUpdateMeshTask(p, false, urgent);
1676 catch(InvalidPositionException &e){}
1679 if(nodepos.Z == blockpos_relative.Z){
1681 v3s16 p = blockpos + v3s16(0,0,-1);
1682 addUpdateMeshTask(p, false, urgent);
1684 catch(InvalidPositionException &e){}
1688 ClientEvent Client::getClientEvent()
1691 if (m_client_event_queue.empty()) {
1692 event.type = CE_NONE;
1695 event = m_client_event_queue.front();
1696 m_client_event_queue.pop();
1701 float Client::mediaReceiveProgress()
1703 if (m_media_downloader)
1704 return m_media_downloader->getProgress();
1706 return 1.0; // downloader only exists when not yet done
1709 typedef struct TextureUpdateArgs {
1710 IrrlichtDevice *device;
1711 gui::IGUIEnvironment *guienv;
1714 const wchar_t* text_base;
1715 } TextureUpdateArgs;
1717 void texture_update_progress(void *args, u32 progress, u32 max_progress)
1719 TextureUpdateArgs* targs = (TextureUpdateArgs*) args;
1720 u16 cur_percent = ceil(progress / (double) max_progress * 100.);
1722 // update the loading menu -- if neccessary
1723 bool do_draw = false;
1724 u32 time_ms = targs->last_time_ms;
1725 if (cur_percent != targs->last_percent) {
1726 targs->last_percent = cur_percent;
1727 time_ms = getTimeMs();
1728 // only draw when the user will notice something:
1729 do_draw = (time_ms - targs->last_time_ms > 100);
1733 targs->last_time_ms = time_ms;
1734 std::basic_stringstream<wchar_t> strm;
1735 strm << targs->text_base << " " << targs->last_percent << "%...";
1736 draw_load_screen(strm.str(), targs->device, targs->guienv, 0,
1737 72 + (u16) ((18. / 100.) * (double) targs->last_percent));
1741 void Client::afterContentReceived(IrrlichtDevice *device)
1743 infostream<<"Client::afterContentReceived() started"<<std::endl;
1744 assert(m_itemdef_received); // pre-condition
1745 assert(m_nodedef_received); // pre-condition
1746 assert(mediaReceived()); // pre-condition
1748 const wchar_t* text = wgettext("Loading textures...");
1750 // Clear cached pre-scaled 2D GUI images, as this cache
1751 // might have images with the same name but different
1752 // content from previous sessions.
1753 guiScalingCacheClear(device->getVideoDriver());
1755 // Rebuild inherited images and recreate textures
1756 infostream<<"- Rebuilding images and textures"<<std::endl;
1757 draw_load_screen(text,device, guienv, 0, 70);
1758 m_tsrc->rebuildImagesAndTextures();
1762 infostream<<"- Rebuilding shaders"<<std::endl;
1763 text = wgettext("Rebuilding shaders...");
1764 draw_load_screen(text, device, guienv, 0, 71);
1765 m_shsrc->rebuildShaders();
1768 // Update node aliases
1769 infostream<<"- Updating node aliases"<<std::endl;
1770 text = wgettext("Initializing nodes...");
1771 draw_load_screen(text, device, guienv, 0, 72);
1772 m_nodedef->updateAliases(m_itemdef);
1773 std::string texture_path = g_settings->get("texture_path");
1774 if (texture_path != "" && fs::IsDir(texture_path))
1775 m_nodedef->applyTextureOverrides(texture_path + DIR_DELIM + "override.txt");
1776 m_nodedef->setNodeRegistrationStatus(true);
1777 m_nodedef->runNodeResolveCallbacks();
1780 // Update node textures and assign shaders to each tile
1781 infostream<<"- Updating node textures"<<std::endl;
1782 TextureUpdateArgs tu_args;
1783 tu_args.device = device;
1784 tu_args.guienv = guienv;
1785 tu_args.last_time_ms = getTimeMs();
1786 tu_args.last_percent = 0;
1787 tu_args.text_base = wgettext("Initializing nodes");
1788 m_nodedef->updateTextures(this, texture_update_progress, &tu_args);
1789 delete[] tu_args.text_base;
1791 // Start mesh update thread after setting up content definitions
1792 infostream<<"- Starting mesh update thread"<<std::endl;
1793 m_mesh_update_thread.start();
1797 text = wgettext("Done!");
1798 draw_load_screen(text, device, guienv, 0, 100);
1799 infostream<<"Client::afterContentReceived() done"<<std::endl;
1803 float Client::getRTT(void)
1805 return m_con.getPeerStat(PEER_ID_SERVER,con::AVG_RTT);
1808 float Client::getCurRate(void)
1810 return ( m_con.getLocalStat(con::CUR_INC_RATE) +
1811 m_con.getLocalStat(con::CUR_DL_RATE));
1814 float Client::getAvgRate(void)
1816 return ( m_con.getLocalStat(con::AVG_INC_RATE) +
1817 m_con.getLocalStat(con::AVG_DL_RATE));
1820 void Client::makeScreenshot(IrrlichtDevice *device)
1822 irr::video::IVideoDriver *driver = device->getVideoDriver();
1823 irr::video::IImage* const raw_image = driver->createScreenShot();
1828 time_t t = time(NULL);
1829 struct tm *tm = localtime(&t);
1831 char timetstamp_c[64];
1832 strftime(timetstamp_c, sizeof(timetstamp_c), "%Y%m%d_%H%M%S", tm);
1834 std::string filename_base = g_settings->get("screenshot_path")
1836 + std::string("screenshot_")
1837 + std::string(timetstamp_c);
1838 std::string filename_ext = "." + g_settings->get("screenshot_format");
1839 std::string filename;
1841 u32 quality = (u32)g_settings->getS32("screenshot_quality");
1842 quality = MYMIN(MYMAX(quality, 0), 100) / 100.0 * 255;
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(), quality)) {
1866 sstr << "Saved screenshot to '" << filename << "'";
1868 sstr << "Failed to save screenshot '" << filename << "'";
1870 pushToChatQueue(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);