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/scripting_client.h"
51 extern gui::IGUIEnvironment* guienv;
58 IrrlichtDevice *device,
59 const char *playername,
60 const std::string &password,
61 const std::string &address_name,
62 MapDrawControl &control,
63 IWritableTextureSource *tsrc,
64 IWritableShaderSource *shsrc,
65 IWritableItemDefManager *itemdef,
66 IWritableNodeDefManager *nodedef,
68 MtEventManager *event,
70 GameUIFlags *game_ui_flags
72 m_packetcounter_timer(0.0),
73 m_connection_reinit_timer(0.1),
75 m_playerpos_send_timer(0.0),
76 m_ignore_damage_timer(0.0),
83 m_mesh_update_thread(this),
85 new ClientMap(this, control,
86 device->getSceneManager()->getRootSceneNode(),
87 device->getSceneManager(), 666),
88 device->getSceneManager(),
91 m_particle_manager(&m_env),
92 m_con(PROTOCOL_ID, 512, CONNECTION_TIMEOUT, ipv6, this),
93 m_address_name(address_name),
97 m_minimap_disabled_by_server(false),
98 m_server_ser_ver(SER_FMT_VER_INVALID),
101 m_inventory_updated(false),
102 m_inventory_from_server(NULL),
103 m_inventory_from_server_age(0.0),
108 m_password(password),
109 m_chosen_auth_mech(AUTH_MECHANISM_NONE),
111 m_access_denied(false),
112 m_access_denied_reconnect(false),
113 m_itemdef_received(false),
114 m_nodedef_received(false),
115 m_media_downloader(new ClientMediaDownloader()),
116 m_time_of_day_set(false),
117 m_last_time_of_day_f(-1),
118 m_time_of_day_update_timer(0),
119 m_recommended_send_interval(0.1),
120 m_removed_sounds_check_timer(0),
124 m_mod_storage_save_timer(10.0f),
125 m_game_ui_flags(game_ui_flags),
129 m_env.setLocalPlayer(new LocalPlayer(this, playername));
131 if (g_settings->getBool("enable_minimap")) {
132 m_minimap = new Minimap(device, this);
134 m_cache_save_interval = g_settings->getU16("server_map_save_interval");
136 m_modding_enabled = g_settings->getBool("enable_client_modding");
137 m_script = new ClientScripting(this);
138 m_env.setScript(m_script);
139 m_script->setEnv(&m_env);
142 void Client::initMods()
144 m_script->loadMod(getBuiltinLuaPath() + DIR_DELIM "init.lua", BUILTIN_MOD_NAME);
146 // If modding is not enabled, don't load mods, just builtin
147 if (!m_modding_enabled) {
151 ClientModConfiguration modconf(getClientModsLuaPath());
152 std::vector<ModSpec> mods = modconf.getMods();
153 std::vector<ModSpec> unsatisfied_mods = modconf.getUnsatisfiedMods();
154 // complain about mods with unsatisfied dependencies
155 if (!modconf.isConsistent()) {
156 modconf.printUnsatisfiedModsError();
160 infostream << "Client Loading mods: ";
161 for (std::vector<ModSpec>::const_iterator i = mods.begin();
162 i != mods.end(); ++i) {
163 infostream << (*i).name << " ";
166 infostream << std::endl;
167 // Load and run "mod" scripts
168 for (std::vector<ModSpec>::const_iterator it = mods.begin();
169 it != mods.end(); ++it) {
170 const ModSpec &mod = *it;
171 if (!string_allowed(mod.name, MODNAME_ALLOWED_CHARS)) {
172 throw ModError("Error loading mod \"" + mod.name +
173 "\": Mod name does not follow naming conventions: "
174 "Only characters [a-z0-9_] are allowed.");
176 std::string script_path = mod.path + DIR_DELIM + "init.lua";
177 infostream << " [" << padStringRight(mod.name, 12) << "] [\""
178 << script_path << "\"]" << std::endl;
179 m_script->loadMod(script_path, mod.name);
183 const std::string &Client::getBuiltinLuaPath()
185 static const std::string builtin_dir = porting::path_share + DIR_DELIM + "builtin";
189 const std::string &Client::getClientModsLuaPath()
191 static const std::string clientmods_dir = porting::path_share + DIR_DELIM + "clientmods";
192 return clientmods_dir;
195 const std::vector<ModSpec>& Client::getMods() const
197 static std::vector<ModSpec> client_modspec_temp;
198 return client_modspec_temp;
201 const ModSpec* Client::getModSpec(const std::string &modname) const
209 // Don't disable this part when modding is disabled, it's used in builtin
210 m_script->on_shutdown();
211 //request all client managed threads to stop
212 m_mesh_update_thread.stop();
213 // Save local server map
215 infostream << "Local map saving ended." << std::endl;
216 m_localdb->endSave();
222 bool Client::isShutdown()
224 return m_shutdown || !m_mesh_update_thread.isRunning();
232 m_mesh_update_thread.stop();
233 m_mesh_update_thread.wait();
234 while (!m_mesh_update_thread.m_queue_out.empty()) {
235 MeshUpdateResult r = m_mesh_update_thread.m_queue_out.pop_frontNoEx();
240 delete m_inventory_from_server;
242 // Delete detached inventories
243 for (UNORDERED_MAP<std::string, Inventory*>::iterator
244 i = m_detached_inventories.begin();
245 i != m_detached_inventories.end(); ++i) {
249 // cleanup 3d model meshes on client shutdown
250 while (m_device->getSceneManager()->getMeshCache()->getMeshCount() != 0) {
251 scene::IAnimatedMesh *mesh =
252 m_device->getSceneManager()->getMeshCache()->getMeshByIndex(0);
255 m_device->getSceneManager()->getMeshCache()->removeMesh(mesh);
261 void Client::connect(Address address, bool is_local_server)
263 DSTACK(FUNCTION_NAME);
265 initLocalMapSaving(address, m_address_name, is_local_server);
267 m_con.SetTimeoutMs(0);
268 m_con.Connect(address);
271 void Client::step(float dtime)
273 DSTACK(FUNCTION_NAME);
279 if(m_ignore_damage_timer > dtime)
280 m_ignore_damage_timer -= dtime;
282 m_ignore_damage_timer = 0.0;
284 m_animation_time += dtime;
285 if(m_animation_time > 60.0)
286 m_animation_time -= 60.0;
288 m_time_of_day_update_timer += dtime;
296 float &counter = m_packetcounter_timer;
302 infostream << "Client packetcounter (" << m_packetcounter_timer
304 m_packetcounter.print(infostream);
305 m_packetcounter.clear();
309 // UGLY hack to fix 2 second startup delay caused by non existent
310 // server client startup synchronization in local server or singleplayer mode
311 static bool initial_step = true;
313 initial_step = false;
315 else if(m_state == LC_Created) {
316 float &counter = m_connection_reinit_timer;
321 LocalPlayer *myplayer = m_env.getLocalPlayer();
322 FATAL_ERROR_IF(myplayer == NULL, "Local player not found in environment.");
324 u16 proto_version_min = g_settings->getFlag("send_pre_v25_init") ?
325 CLIENT_PROTOCOL_VERSION_MIN_LEGACY : CLIENT_PROTOCOL_VERSION_MIN;
327 if (proto_version_min < 25) {
328 // Send TOSERVER_INIT_LEGACY
329 // [0] u16 TOSERVER_INIT_LEGACY
330 // [2] u8 SER_FMT_VER_HIGHEST_READ
331 // [3] u8[20] player_name
332 // [23] u8[28] password (new in some version)
333 // [51] u16 minimum supported network protocol version (added sometime)
334 // [53] u16 maximum supported network protocol version (added later than the previous one)
336 char pName[PLAYERNAME_SIZE];
337 char pPassword[PASSWORD_SIZE];
338 memset(pName, 0, PLAYERNAME_SIZE * sizeof(char));
339 memset(pPassword, 0, PASSWORD_SIZE * sizeof(char));
341 std::string hashed_password = translate_password(myplayer->getName(), m_password);
342 snprintf(pName, PLAYERNAME_SIZE, "%s", myplayer->getName());
343 snprintf(pPassword, PASSWORD_SIZE, "%s", hashed_password.c_str());
345 sendLegacyInit(pName, pPassword);
347 if (CLIENT_PROTOCOL_VERSION_MAX >= 25)
348 sendInit(myplayer->getName());
351 // Not connected, return
356 Do stuff if connected
360 Run Map's timers and unload unused data
362 const float map_timer_and_unload_dtime = 5.25;
363 if(m_map_timer_and_unload_interval.step(dtime, map_timer_and_unload_dtime)) {
364 ScopeProfiler sp(g_profiler, "Client: map timer and unload");
365 std::vector<v3s16> deleted_blocks;
366 m_env.getMap().timerUpdate(map_timer_and_unload_dtime,
367 g_settings->getFloat("client_unload_unused_data_timeout"),
368 g_settings->getS32("client_mapblock_limit"),
373 NOTE: This loop is intentionally iterated the way it is.
376 std::vector<v3s16>::iterator i = deleted_blocks.begin();
377 std::vector<v3s16> sendlist;
379 if(sendlist.size() == 255 || i == deleted_blocks.end()) {
390 sendDeletedBlocks(sendlist);
392 if(i == deleted_blocks.end())
398 sendlist.push_back(*i);
406 // Control local player (0ms)
407 LocalPlayer *player = m_env.getLocalPlayer();
408 assert(player != NULL);
409 player->applyControl(dtime);
413 m_sound->step(dtime);
418 while (m_env.hasClientEnvEvents()) {
419 ClientEnvEvent envEvent = m_env.getClientEnvEvent();
421 if (envEvent.type == CEE_PLAYER_DAMAGE) {
422 if (m_ignore_damage_timer <= 0) {
423 u8 damage = envEvent.player_damage.amount;
425 if (envEvent.player_damage.send_to_server)
428 // Add to ClientEvent queue
430 event.type = CE_PLAYER_DAMAGE;
431 event.player_damage.amount = damage;
432 m_client_event_queue.push(event);
435 // Protocol v29 or greater obsoleted this event
436 else if (envEvent.type == CEE_PLAYER_BREATH && m_proto_ver < 29) {
437 u16 breath = envEvent.player_breath.amount;
445 float &counter = m_avg_rtt_timer;
449 // connectedAndInitialized() is true, peer exists.
450 float avg_rtt = getRTT();
451 infostream << "Client: avg_rtt=" << avg_rtt << std::endl;
455 Send player position to server
458 float &counter = m_playerpos_send_timer;
460 if((m_state == LC_Ready) && (counter >= m_recommended_send_interval))
468 Replace updated meshes
471 int num_processed_meshes = 0;
472 while (!m_mesh_update_thread.m_queue_out.empty())
474 num_processed_meshes++;
476 MinimapMapblock *minimap_mapblock = NULL;
477 bool do_mapper_update = true;
479 MeshUpdateResult r = m_mesh_update_thread.m_queue_out.pop_frontNoEx();
480 MapBlock *block = m_env.getMap().getBlockNoCreateNoEx(r.p);
482 // Delete the old mesh
483 if (block->mesh != NULL) {
489 minimap_mapblock = r.mesh->moveMinimapMapblock();
490 if (minimap_mapblock == NULL)
491 do_mapper_update = false;
493 bool is_empty = true;
494 for (int l = 0; l < MAX_TILE_LAYERS; l++)
495 if (r.mesh->getMesh(l)->getMeshBufferCount() != 0)
501 // Replace with the new mesh
502 block->mesh = r.mesh;
508 if (m_minimap && do_mapper_update)
509 m_minimap->addBlock(r.p, minimap_mapblock);
511 if (r.ack_block_to_server) {
521 if (num_processed_meshes > 0)
522 g_profiler->graphAdd("num_processed_meshes", num_processed_meshes);
528 if (m_media_downloader && m_media_downloader->isStarted()) {
529 m_media_downloader->step(this);
530 if (m_media_downloader->isDone()) {
531 delete m_media_downloader;
532 m_media_downloader = NULL;
537 If the server didn't update the inventory in a while, revert
538 the local inventory (so the player notices the lag problem
539 and knows something is wrong).
541 if(m_inventory_from_server)
543 float interval = 10.0;
544 float count_before = floor(m_inventory_from_server_age / interval);
546 m_inventory_from_server_age += dtime;
548 float count_after = floor(m_inventory_from_server_age / interval);
550 if(count_after != count_before)
552 // Do this every <interval> seconds after TOCLIENT_INVENTORY
553 // Reset the locally changed inventory to the authoritative inventory
554 LocalPlayer *player = m_env.getLocalPlayer();
555 player->inventory = *m_inventory_from_server;
556 m_inventory_updated = true;
561 Update positions of sounds attached to objects
564 for(UNORDERED_MAP<int, u16>::iterator i = m_sounds_to_objects.begin();
565 i != m_sounds_to_objects.end(); ++i) {
566 int client_id = i->first;
567 u16 object_id = i->second;
568 ClientActiveObject *cao = m_env.getActiveObject(object_id);
571 v3f pos = cao->getPosition();
572 m_sound->updateSoundPosition(client_id, pos);
577 Handle removed remotely initiated sounds
579 m_removed_sounds_check_timer += dtime;
580 if(m_removed_sounds_check_timer >= 2.32) {
581 m_removed_sounds_check_timer = 0;
582 // Find removed sounds and clear references to them
583 std::vector<s32> removed_server_ids;
584 for(UNORDERED_MAP<s32, int>::iterator i = m_sounds_server_to_client.begin();
585 i != m_sounds_server_to_client.end();) {
586 s32 server_id = i->first;
587 int client_id = i->second;
589 if(!m_sound->soundExists(client_id)) {
590 m_sounds_server_to_client.erase(server_id);
591 m_sounds_client_to_server.erase(client_id);
592 m_sounds_to_objects.erase(client_id);
593 removed_server_ids.push_back(server_id);
598 if(!removed_server_ids.empty()) {
599 sendRemovedSounds(removed_server_ids);
603 m_mod_storage_save_timer -= dtime;
604 if (m_mod_storage_save_timer <= 0.0f) {
605 verbosestream << "Saving registered mod storages." << std::endl;
606 m_mod_storage_save_timer = g_settings->getFloat("server_map_save_interval");
607 for (UNORDERED_MAP<std::string, ModMetadata *>::const_iterator
608 it = m_mod_storages.begin(); it != m_mod_storages.end(); ++it) {
609 if (it->second->isModified()) {
610 it->second->save(getModStoragePath());
616 if (m_localdb && m_localdb_save_interval.step(dtime,
617 m_cache_save_interval)) {
618 m_localdb->endSave();
619 m_localdb->beginSave();
623 bool Client::loadMedia(const std::string &data, const std::string &filename)
625 // Silly irrlicht's const-incorrectness
626 Buffer<char> data_rw(data.c_str(), data.size());
630 const char *image_ext[] = {
631 ".png", ".jpg", ".bmp", ".tga",
632 ".pcx", ".ppm", ".psd", ".wal", ".rgb",
635 name = removeStringEnd(filename, image_ext);
638 verbosestream<<"Client: Attempting to load image "
639 <<"file \""<<filename<<"\""<<std::endl;
641 io::IFileSystem *irrfs = m_device->getFileSystem();
642 video::IVideoDriver *vdrv = m_device->getVideoDriver();
644 // Create an irrlicht memory file
645 io::IReadFile *rfile = irrfs->createMemoryReadFile(
646 *data_rw, data_rw.getSize(), "_tempreadfile");
648 FATAL_ERROR_IF(!rfile, "Could not create irrlicht memory file.");
651 video::IImage *img = vdrv->createImageFromFile(rfile);
653 errorstream<<"Client: Cannot create image from data of "
654 <<"file \""<<filename<<"\""<<std::endl;
659 m_tsrc->insertSourceImage(filename, img);
666 const char *sound_ext[] = {
667 ".0.ogg", ".1.ogg", ".2.ogg", ".3.ogg", ".4.ogg",
668 ".5.ogg", ".6.ogg", ".7.ogg", ".8.ogg", ".9.ogg",
671 name = removeStringEnd(filename, sound_ext);
674 verbosestream<<"Client: Attempting to load sound "
675 <<"file \""<<filename<<"\""<<std::endl;
676 m_sound->loadSoundData(name, data);
680 const char *model_ext[] = {
681 ".x", ".b3d", ".md2", ".obj",
684 name = removeStringEnd(filename, model_ext);
687 verbosestream<<"Client: Storing model into memory: "
688 <<"\""<<filename<<"\""<<std::endl;
689 if(m_mesh_data.count(filename))
690 errorstream<<"Multiple models with name \""<<filename.c_str()
691 <<"\" found; replacing previous model"<<std::endl;
692 m_mesh_data[filename] = data;
696 errorstream<<"Client: Don't know how to load file \""
697 <<filename<<"\""<<std::endl;
701 // Virtual methods from con::PeerHandler
702 void Client::peerAdded(con::Peer *peer)
704 infostream << "Client::peerAdded(): peer->id="
705 << peer->id << std::endl;
707 void Client::deletingPeer(con::Peer *peer, bool timeout)
709 infostream << "Client::deletingPeer(): "
710 "Server Peer is getting deleted "
711 << "(timeout=" << timeout << ")" << std::endl;
714 m_access_denied = true;
715 m_access_denied_reason = gettext("Connection timed out.");
721 u16 number of files requested
727 void Client::request_media(const std::vector<std::string> &file_requests)
729 std::ostringstream os(std::ios_base::binary);
730 writeU16(os, TOSERVER_REQUEST_MEDIA);
731 size_t file_requests_size = file_requests.size();
733 FATAL_ERROR_IF(file_requests_size > 0xFFFF, "Unsupported number of file requests");
735 // Packet dynamicly resized
736 NetworkPacket pkt(TOSERVER_REQUEST_MEDIA, 2 + 0);
738 pkt << (u16) (file_requests_size & 0xFFFF);
740 for(std::vector<std::string>::const_iterator i = file_requests.begin();
741 i != file_requests.end(); ++i) {
747 infostream << "Client: Sending media request list to server ("
748 << file_requests.size() << " files. packet size)" << std::endl;
751 void Client::initLocalMapSaving(const Address &address,
752 const std::string &hostname,
753 bool is_local_server)
755 if (!g_settings->getBool("enable_local_map_saving") || is_local_server) {
759 const std::string world_path = porting::path_user
760 + DIR_DELIM + "worlds"
761 + DIR_DELIM + "server_"
762 + hostname + "_" + std::to_string(address.getPort());
764 fs::CreateAllDirs(world_path);
766 m_localdb = new MapDatabaseSQLite3(world_path);
767 m_localdb->beginSave();
768 actionstream << "Local map saving started, map will be saved at '" << world_path << "'" << std::endl;
771 void Client::ReceiveAll()
773 DSTACK(FUNCTION_NAME);
774 u64 start_ms = porting::getTimeMs();
777 // Limit time even if there would be huge amounts of data to
779 if(porting::getTimeMs() > start_ms + 100)
784 g_profiler->graphAdd("client_received_packets", 1);
786 catch(con::NoIncomingDataException &e) {
789 catch(con::InvalidIncomingDataException &e) {
790 infostream<<"Client::ReceiveAll(): "
791 "InvalidIncomingDataException: what()="
792 <<e.what()<<std::endl;
797 void Client::Receive()
799 DSTACK(FUNCTION_NAME);
805 inline void Client::handleCommand(NetworkPacket* pkt)
807 const ToClientCommandHandler& opHandle = toClientCommandTable[pkt->getCommand()];
808 (this->*opHandle.handler)(pkt);
812 sender_peer_id given to this shall be quaranteed to be a valid peer
814 void Client::ProcessData(NetworkPacket *pkt)
816 DSTACK(FUNCTION_NAME);
818 ToClientCommand command = (ToClientCommand) pkt->getCommand();
819 u32 sender_peer_id = pkt->getPeerId();
821 //infostream<<"Client: received command="<<command<<std::endl;
822 m_packetcounter.add((u16)command);
825 If this check is removed, be sure to change the queue
826 system to know the ids
828 if(sender_peer_id != PEER_ID_SERVER) {
829 infostream << "Client::ProcessData(): Discarding data not "
830 "coming from server: peer_id=" << sender_peer_id
835 // Command must be handled into ToClientCommandHandler
836 if (command >= TOCLIENT_NUM_MSG_TYPES) {
837 infostream << "Client: Ignoring unknown command "
838 << command << std::endl;
843 * Those packets are handled before m_server_ser_ver is set, it's normal
844 * But we must use the new ToClientConnectionState in the future,
847 if(toClientCommandTable[command].state == TOCLIENT_STATE_NOT_CONNECTED) {
852 if(m_server_ser_ver == SER_FMT_VER_INVALID) {
853 infostream << "Client: Server serialization"
854 " format invalid or not initialized."
855 " Skipping incoming command=" << command << std::endl;
860 Handle runtime commands
866 void Client::Send(NetworkPacket* pkt)
868 m_con.Send(PEER_ID_SERVER,
869 serverCommandFactoryTable[pkt->getCommand()].channel,
871 serverCommandFactoryTable[pkt->getCommand()].reliable);
874 // Will fill up 12 + 12 + 4 + 4 + 4 bytes
875 void writePlayerPos(LocalPlayer *myplayer, ClientMap *clientMap, NetworkPacket *pkt)
877 v3f pf = myplayer->getPosition() * 100;
878 v3f sf = myplayer->getSpeed() * 100;
879 s32 pitch = myplayer->getPitch() * 100;
880 s32 yaw = myplayer->getYaw() * 100;
881 u32 keyPressed = myplayer->keyPressed;
882 // scaled by 80, so that pi can fit into a u8
883 u8 fov = clientMap->getCameraFov() * 80;
884 u8 wanted_range = MYMIN(255,
885 std::ceil(clientMap->getControl().wanted_range / MAP_BLOCKSIZE));
887 v3s32 position(pf.X, pf.Y, pf.Z);
888 v3s32 speed(sf.X, sf.Y, sf.Z);
892 [0] v3s32 position*100
894 [12+12] s32 pitch*100
895 [12+12+4] s32 yaw*100
896 [12+12+4+4] u32 keyPressed
897 [12+12+4+4+4] u8 fov*80
898 [12+12+4+4+4+1] u8 ceil(wanted_range / MAP_BLOCKSIZE)
900 *pkt << position << speed << pitch << yaw << keyPressed;
901 *pkt << fov << wanted_range;
904 void Client::interact(u8 action, const PointedThing& pointed)
906 if(m_state != LC_Ready) {
907 errorstream << "Client::interact() "
908 "Canceled (not connected)"
913 LocalPlayer *myplayer = m_env.getLocalPlayer();
914 if (myplayer == NULL)
921 [5] u32 length of the next item (plen)
922 [9] serialized PointedThing
923 [9 + plen] player position information
925 0: start digging (from undersurface) or use
926 1: stop digging (all parameters ignored)
928 3: place block or item (to abovesurface)
930 5: perform secondary action of item
933 NetworkPacket pkt(TOSERVER_INTERACT, 1 + 2 + 0);
936 pkt << (u16)getPlayerItem();
938 std::ostringstream tmp_os(std::ios::binary);
939 pointed.serialize(tmp_os);
941 pkt.putLongString(tmp_os.str());
943 writePlayerPos(myplayer, &m_env.getClientMap(), &pkt);
948 void Client::deleteAuthData()
953 switch (m_chosen_auth_mech) {
954 case AUTH_MECHANISM_FIRST_SRP:
956 case AUTH_MECHANISM_SRP:
957 case AUTH_MECHANISM_LEGACY_PASSWORD:
958 srp_user_delete((SRPUser *) m_auth_data);
961 case AUTH_MECHANISM_NONE:
964 m_chosen_auth_mech = AUTH_MECHANISM_NONE;
968 AuthMechanism Client::choseAuthMech(const u32 mechs)
970 if (mechs & AUTH_MECHANISM_SRP)
971 return AUTH_MECHANISM_SRP;
973 if (mechs & AUTH_MECHANISM_FIRST_SRP)
974 return AUTH_MECHANISM_FIRST_SRP;
976 if (mechs & AUTH_MECHANISM_LEGACY_PASSWORD)
977 return AUTH_MECHANISM_LEGACY_PASSWORD;
979 return AUTH_MECHANISM_NONE;
982 void Client::sendLegacyInit(const char* playerName, const char* playerPassword)
984 NetworkPacket pkt(TOSERVER_INIT_LEGACY,
985 1 + PLAYERNAME_SIZE + PASSWORD_SIZE + 2 + 2);
987 u16 proto_version_min = g_settings->getFlag("send_pre_v25_init") ?
988 CLIENT_PROTOCOL_VERSION_MIN_LEGACY : CLIENT_PROTOCOL_VERSION_MIN;
990 pkt << (u8) SER_FMT_VER_HIGHEST_READ;
991 pkt.putRawString(playerName,PLAYERNAME_SIZE);
992 pkt.putRawString(playerPassword, PASSWORD_SIZE);
993 pkt << (u16) proto_version_min << (u16) CLIENT_PROTOCOL_VERSION_MAX;
998 void Client::sendInit(const std::string &playerName)
1000 NetworkPacket pkt(TOSERVER_INIT, 1 + 2 + 2 + (1 + playerName.size()));
1002 // we don't support network compression yet
1003 u16 supp_comp_modes = NETPROTO_COMPRESSION_NONE;
1005 u16 proto_version_min = g_settings->getFlag("send_pre_v25_init") ?
1006 CLIENT_PROTOCOL_VERSION_MIN_LEGACY : CLIENT_PROTOCOL_VERSION_MIN;
1008 pkt << (u8) SER_FMT_VER_HIGHEST_READ << (u16) supp_comp_modes;
1009 pkt << (u16) proto_version_min << (u16) CLIENT_PROTOCOL_VERSION_MAX;
1015 void Client::startAuth(AuthMechanism chosen_auth_mechanism)
1017 m_chosen_auth_mech = chosen_auth_mechanism;
1019 switch (chosen_auth_mechanism) {
1020 case AUTH_MECHANISM_FIRST_SRP: {
1021 // send srp verifier to server
1022 std::string verifier;
1024 generate_srp_verifier_and_salt(getPlayerName(), m_password,
1027 NetworkPacket resp_pkt(TOSERVER_FIRST_SRP, 0);
1028 resp_pkt << salt << verifier << (u8)((m_password == "") ? 1 : 0);
1033 case AUTH_MECHANISM_SRP:
1034 case AUTH_MECHANISM_LEGACY_PASSWORD: {
1037 if (chosen_auth_mechanism == AUTH_MECHANISM_LEGACY_PASSWORD) {
1038 m_password = translate_password(getPlayerName(), m_password);
1042 std::string playername_u = lowercase(getPlayerName());
1043 m_auth_data = srp_user_new(SRP_SHA256, SRP_NG_2048,
1044 getPlayerName().c_str(), playername_u.c_str(),
1045 (const unsigned char *) m_password.c_str(),
1046 m_password.length(), NULL, NULL);
1049 SRP_Result res = srp_user_start_authentication(
1050 (struct SRPUser *) m_auth_data, NULL, NULL, 0,
1051 (unsigned char **) &bytes_A, &len_A);
1052 FATAL_ERROR_IF(res != SRP_OK, "Creating local SRP user failed.");
1054 NetworkPacket resp_pkt(TOSERVER_SRP_BYTES_A, 0);
1055 resp_pkt << std::string(bytes_A, len_A) << based_on;
1059 case AUTH_MECHANISM_NONE:
1060 break; // not handled in this method
1064 void Client::sendDeletedBlocks(std::vector<v3s16> &blocks)
1066 NetworkPacket pkt(TOSERVER_DELETEDBLOCKS, 1 + sizeof(v3s16) * blocks.size());
1068 pkt << (u8) blocks.size();
1071 for(std::vector<v3s16>::iterator
1073 j != blocks.end(); ++j) {
1081 void Client::sendGotBlocks(v3s16 block)
1083 NetworkPacket pkt(TOSERVER_GOTBLOCKS, 1 + 6);
1084 pkt << (u8) 1 << block;
1088 void Client::sendRemovedSounds(std::vector<s32> &soundList)
1090 size_t server_ids = soundList.size();
1091 assert(server_ids <= 0xFFFF);
1093 NetworkPacket pkt(TOSERVER_REMOVED_SOUNDS, 2 + server_ids * 4);
1095 pkt << (u16) (server_ids & 0xFFFF);
1097 for(std::vector<s32>::iterator i = soundList.begin();
1098 i != soundList.end(); ++i)
1104 void Client::sendNodemetaFields(v3s16 p, const std::string &formname,
1105 const StringMap &fields)
1107 size_t fields_size = fields.size();
1109 FATAL_ERROR_IF(fields_size > 0xFFFF, "Unsupported number of nodemeta fields");
1111 NetworkPacket pkt(TOSERVER_NODEMETA_FIELDS, 0);
1113 pkt << p << formname << (u16) (fields_size & 0xFFFF);
1115 StringMap::const_iterator it;
1116 for (it = fields.begin(); it != fields.end(); ++it) {
1117 const std::string &name = it->first;
1118 const std::string &value = it->second;
1120 pkt.putLongString(value);
1126 void Client::sendInventoryFields(const std::string &formname,
1127 const StringMap &fields)
1129 size_t fields_size = fields.size();
1130 FATAL_ERROR_IF(fields_size > 0xFFFF, "Unsupported number of inventory fields");
1132 NetworkPacket pkt(TOSERVER_INVENTORY_FIELDS, 0);
1133 pkt << formname << (u16) (fields_size & 0xFFFF);
1135 StringMap::const_iterator it;
1136 for (it = fields.begin(); it != fields.end(); ++it) {
1137 const std::string &name = it->first;
1138 const std::string &value = it->second;
1140 pkt.putLongString(value);
1146 void Client::sendInventoryAction(InventoryAction *a)
1148 std::ostringstream os(std::ios_base::binary);
1153 std::string s = os.str();
1155 NetworkPacket pkt(TOSERVER_INVENTORY_ACTION, s.size());
1156 pkt.putRawString(s.c_str(),s.size());
1161 void Client::sendChatMessage(const std::wstring &message)
1163 NetworkPacket pkt(TOSERVER_CHAT_MESSAGE, 2 + message.size() * sizeof(u16));
1170 void Client::sendChangePassword(const std::string &oldpassword,
1171 const std::string &newpassword)
1173 LocalPlayer *player = m_env.getLocalPlayer();
1177 std::string playername = player->getName();
1178 if (m_proto_ver >= 25) {
1179 // get into sudo mode and then send new password to server
1180 m_password = oldpassword;
1181 m_new_password = newpassword;
1182 startAuth(choseAuthMech(m_sudo_auth_methods));
1184 std::string oldpwd = translate_password(playername, oldpassword);
1185 std::string newpwd = translate_password(playername, newpassword);
1187 NetworkPacket pkt(TOSERVER_PASSWORD_LEGACY, 2 * PASSWORD_SIZE);
1189 for (u8 i = 0; i < PASSWORD_SIZE; i++) {
1190 pkt << (u8) (i < oldpwd.length() ? oldpwd[i] : 0);
1193 for (u8 i = 0; i < PASSWORD_SIZE; i++) {
1194 pkt << (u8) (i < newpwd.length() ? newpwd[i] : 0);
1201 void Client::sendDamage(u8 damage)
1203 DSTACK(FUNCTION_NAME);
1205 NetworkPacket pkt(TOSERVER_DAMAGE, sizeof(u8));
1210 void Client::sendBreath(u16 breath)
1212 DSTACK(FUNCTION_NAME);
1214 // Protocol v29 make this obsolete
1215 if (m_proto_ver >= 29)
1218 NetworkPacket pkt(TOSERVER_BREATH, sizeof(u16));
1223 void Client::sendRespawn()
1225 DSTACK(FUNCTION_NAME);
1227 NetworkPacket pkt(TOSERVER_RESPAWN, 0);
1231 void Client::sendReady()
1233 DSTACK(FUNCTION_NAME);
1235 NetworkPacket pkt(TOSERVER_CLIENT_READY,
1236 1 + 1 + 1 + 1 + 2 + sizeof(char) * strlen(g_version_hash));
1238 pkt << (u8) VERSION_MAJOR << (u8) VERSION_MINOR << (u8) VERSION_PATCH
1239 << (u8) 0 << (u16) strlen(g_version_hash);
1241 pkt.putRawString(g_version_hash, (u16) strlen(g_version_hash));
1245 void Client::sendPlayerPos()
1247 LocalPlayer *myplayer = m_env.getLocalPlayer();
1248 if(myplayer == NULL)
1251 ClientMap &map = m_env.getClientMap();
1253 u8 camera_fov = map.getCameraFov();
1254 u8 wanted_range = map.getControl().wanted_range;
1256 // Save bandwidth by only updating position when something changed
1257 if(myplayer->last_position == myplayer->getPosition() &&
1258 myplayer->last_speed == myplayer->getSpeed() &&
1259 myplayer->last_pitch == myplayer->getPitch() &&
1260 myplayer->last_yaw == myplayer->getYaw() &&
1261 myplayer->last_keyPressed == myplayer->keyPressed &&
1262 myplayer->last_camera_fov == camera_fov &&
1263 myplayer->last_wanted_range == wanted_range)
1266 myplayer->last_position = myplayer->getPosition();
1267 myplayer->last_speed = myplayer->getSpeed();
1268 myplayer->last_pitch = myplayer->getPitch();
1269 myplayer->last_yaw = myplayer->getYaw();
1270 myplayer->last_keyPressed = myplayer->keyPressed;
1271 myplayer->last_camera_fov = camera_fov;
1272 myplayer->last_wanted_range = wanted_range;
1274 //infostream << "Sending Player Position information" << std::endl;
1278 //MutexAutoLock lock(m_con_mutex); //bulk comment-out
1279 our_peer_id = m_con.GetPeerID();
1282 // Set peer id if not set already
1283 if(myplayer->peer_id == PEER_ID_INEXISTENT)
1284 myplayer->peer_id = our_peer_id;
1286 assert(myplayer->peer_id == our_peer_id);
1288 NetworkPacket pkt(TOSERVER_PLAYERPOS, 12 + 12 + 4 + 4 + 4 + 1 + 1);
1290 writePlayerPos(myplayer, &map, &pkt);
1295 void Client::sendPlayerItem(u16 item)
1297 LocalPlayer *myplayer = m_env.getLocalPlayer();
1298 if(myplayer == NULL)
1301 u16 our_peer_id = m_con.GetPeerID();
1303 // Set peer id if not set already
1304 if(myplayer->peer_id == PEER_ID_INEXISTENT)
1305 myplayer->peer_id = our_peer_id;
1306 assert(myplayer->peer_id == our_peer_id);
1308 NetworkPacket pkt(TOSERVER_PLAYERITEM, 2);
1315 void Client::removeNode(v3s16 p)
1317 std::map<v3s16, MapBlock*> modified_blocks;
1320 m_env.getMap().removeNodeAndUpdate(p, modified_blocks);
1322 catch(InvalidPositionException &e) {
1325 for(std::map<v3s16, MapBlock *>::iterator
1326 i = modified_blocks.begin();
1327 i != modified_blocks.end(); ++i) {
1328 addUpdateMeshTaskWithEdge(i->first, false, true);
1332 MapNode Client::getNode(v3s16 p, bool *is_valid_position)
1334 return m_env.getMap().getNodeNoEx(p, is_valid_position);
1337 void Client::addNode(v3s16 p, MapNode n, bool remove_metadata)
1339 //TimeTaker timer1("Client::addNode()");
1341 std::map<v3s16, MapBlock*> modified_blocks;
1344 //TimeTaker timer3("Client::addNode(): addNodeAndUpdate");
1345 m_env.getMap().addNodeAndUpdate(p, n, modified_blocks, remove_metadata);
1347 catch(InvalidPositionException &e) {
1350 for(std::map<v3s16, MapBlock *>::iterator
1351 i = modified_blocks.begin();
1352 i != modified_blocks.end(); ++i) {
1353 addUpdateMeshTaskWithEdge(i->first, false, true);
1357 void Client::setPlayerControl(PlayerControl &control)
1359 LocalPlayer *player = m_env.getLocalPlayer();
1360 assert(player != NULL);
1361 player->control = control;
1364 void Client::selectPlayerItem(u16 item)
1366 m_playeritem = item;
1367 m_inventory_updated = true;
1368 sendPlayerItem(item);
1371 // Returns true if the inventory of the local player has been
1372 // updated from the server. If it is true, it is set to false.
1373 bool Client::getLocalInventoryUpdated()
1375 bool updated = m_inventory_updated;
1376 m_inventory_updated = false;
1380 // Copies the inventory of the local player to parameter
1381 void Client::getLocalInventory(Inventory &dst)
1383 LocalPlayer *player = m_env.getLocalPlayer();
1384 assert(player != NULL);
1385 dst = player->inventory;
1388 Inventory* Client::getInventory(const InventoryLocation &loc)
1391 case InventoryLocation::UNDEFINED:
1394 case InventoryLocation::CURRENT_PLAYER:
1396 LocalPlayer *player = m_env.getLocalPlayer();
1397 assert(player != NULL);
1398 return &player->inventory;
1401 case InventoryLocation::PLAYER:
1403 // Check if we are working with local player inventory
1404 LocalPlayer *player = m_env.getLocalPlayer();
1405 if (!player || strcmp(player->getName(), loc.name.c_str()) != 0)
1407 return &player->inventory;
1410 case InventoryLocation::NODEMETA:
1412 NodeMetadata *meta = m_env.getMap().getNodeMetadata(loc.p);
1415 return meta->getInventory();
1418 case InventoryLocation::DETACHED:
1420 if (m_detached_inventories.count(loc.name) == 0)
1422 return m_detached_inventories[loc.name];
1426 FATAL_ERROR("Invalid inventory location type.");
1432 void Client::inventoryAction(InventoryAction *a)
1435 Send it to the server
1437 sendInventoryAction(a);
1440 Predict some local inventory changes
1442 a->clientApply(this, this);
1448 float Client::getAnimationTime()
1450 return m_animation_time;
1453 int Client::getCrackLevel()
1455 return m_crack_level;
1458 v3s16 Client::getCrackPos()
1463 void Client::setCrack(int level, v3s16 pos)
1465 int old_crack_level = m_crack_level;
1466 v3s16 old_crack_pos = m_crack_pos;
1468 m_crack_level = level;
1471 if(old_crack_level >= 0 && (level < 0 || pos != old_crack_pos))
1474 addUpdateMeshTaskForNode(old_crack_pos, false, true);
1476 if(level >= 0 && (old_crack_level < 0 || pos != old_crack_pos))
1479 addUpdateMeshTaskForNode(pos, false, true);
1485 LocalPlayer *player = m_env.getLocalPlayer();
1486 assert(player != NULL);
1490 bool Client::getChatMessage(std::wstring &message)
1492 if(m_chat_queue.size() == 0)
1494 message = m_chat_queue.front();
1499 void Client::typeChatMessage(const std::wstring &message)
1501 // Discard empty line
1505 // If message was ate by script API, don't send it to server
1506 if (m_script->on_sending_message(wide_to_utf8(message))) {
1511 sendChatMessage(message);
1514 if (message[0] != L'/')
1516 // compatibility code
1517 if (m_proto_ver < 29) {
1518 LocalPlayer *player = m_env.getLocalPlayer();
1519 assert(player != NULL);
1520 std::wstring name = narrow_to_wide(player->getName());
1521 pushToChatQueue((std::wstring)L"<" + name + L"> " + message);
1526 void Client::addUpdateMeshTask(v3s16 p, bool ack_to_server, bool urgent)
1528 // Check if the block exists to begin with. In the case when a non-existing
1529 // neighbor is automatically added, it may not. In that case we don't want
1530 // to tell the mesh update thread about it.
1531 MapBlock *b = m_env.getMap().getBlockNoCreateNoEx(p);
1535 m_mesh_update_thread.updateBlock(&m_env.getMap(), p, ack_to_server, urgent);
1538 void Client::addUpdateMeshTaskWithEdge(v3s16 blockpos, bool ack_to_server, bool urgent)
1541 addUpdateMeshTask(blockpos, ack_to_server, urgent);
1543 catch(InvalidPositionException &e){}
1546 for (int i=0;i<6;i++)
1549 v3s16 p = blockpos + g_6dirs[i];
1550 addUpdateMeshTask(p, false, urgent);
1552 catch(InvalidPositionException &e){}
1556 void Client::addUpdateMeshTaskForNode(v3s16 nodepos, bool ack_to_server, bool urgent)
1560 infostream<<"Client::addUpdateMeshTaskForNode(): "
1561 <<"("<<p.X<<","<<p.Y<<","<<p.Z<<")"
1565 v3s16 blockpos = getNodeBlockPos(nodepos);
1566 v3s16 blockpos_relative = blockpos * MAP_BLOCKSIZE;
1569 addUpdateMeshTask(blockpos, ack_to_server, urgent);
1571 catch(InvalidPositionException &e) {}
1574 if(nodepos.X == blockpos_relative.X){
1576 v3s16 p = blockpos + v3s16(-1,0,0);
1577 addUpdateMeshTask(p, false, urgent);
1579 catch(InvalidPositionException &e){}
1582 if(nodepos.Y == blockpos_relative.Y){
1584 v3s16 p = blockpos + v3s16(0,-1,0);
1585 addUpdateMeshTask(p, false, urgent);
1587 catch(InvalidPositionException &e){}
1590 if(nodepos.Z == blockpos_relative.Z){
1592 v3s16 p = blockpos + v3s16(0,0,-1);
1593 addUpdateMeshTask(p, false, urgent);
1595 catch(InvalidPositionException &e){}
1599 ClientEvent Client::getClientEvent()
1601 FATAL_ERROR_IF(m_client_event_queue.empty(),
1602 "Cannot getClientEvent, queue is empty.");
1604 ClientEvent event = m_client_event_queue.front();
1605 m_client_event_queue.pop();
1609 float Client::mediaReceiveProgress()
1611 if (m_media_downloader)
1612 return m_media_downloader->getProgress();
1614 return 1.0; // downloader only exists when not yet done
1617 typedef struct TextureUpdateArgs {
1618 IrrlichtDevice *device;
1619 gui::IGUIEnvironment *guienv;
1622 const wchar_t* text_base;
1623 ITextureSource *tsrc;
1624 } TextureUpdateArgs;
1626 void texture_update_progress(void *args, u32 progress, u32 max_progress)
1628 TextureUpdateArgs* targs = (TextureUpdateArgs*) args;
1629 u16 cur_percent = ceil(progress / (double) max_progress * 100.);
1631 // update the loading menu -- if neccessary
1632 bool do_draw = false;
1633 u64 time_ms = targs->last_time_ms;
1634 if (cur_percent != targs->last_percent) {
1635 targs->last_percent = cur_percent;
1636 time_ms = porting::getTimeMs();
1637 // only draw when the user will notice something:
1638 do_draw = (time_ms - targs->last_time_ms > 100);
1642 targs->last_time_ms = time_ms;
1643 std::basic_stringstream<wchar_t> strm;
1644 strm << targs->text_base << " " << targs->last_percent << "%...";
1645 draw_load_screen(strm.str(), targs->device, targs->guienv, targs->tsrc, 0,
1646 72 + (u16) ((18. / 100.) * (double) targs->last_percent), true);
1650 void Client::afterContentReceived(IrrlichtDevice *device)
1652 infostream<<"Client::afterContentReceived() started"<<std::endl;
1653 assert(m_itemdef_received); // pre-condition
1654 assert(m_nodedef_received); // pre-condition
1655 assert(mediaReceived()); // pre-condition
1657 const wchar_t* text = wgettext("Loading textures...");
1659 // Clear cached pre-scaled 2D GUI images, as this cache
1660 // might have images with the same name but different
1661 // content from previous sessions.
1662 guiScalingCacheClear(device->getVideoDriver());
1664 // Rebuild inherited images and recreate textures
1665 infostream<<"- Rebuilding images and textures"<<std::endl;
1666 draw_load_screen(text,device, guienv, m_tsrc, 0, 70);
1667 m_tsrc->rebuildImagesAndTextures();
1671 infostream<<"- Rebuilding shaders"<<std::endl;
1672 text = wgettext("Rebuilding shaders...");
1673 draw_load_screen(text, device, guienv, m_tsrc, 0, 71);
1674 m_shsrc->rebuildShaders();
1677 // Update node aliases
1678 infostream<<"- Updating node aliases"<<std::endl;
1679 text = wgettext("Initializing nodes...");
1680 draw_load_screen(text, device, guienv, m_tsrc, 0, 72);
1681 m_nodedef->updateAliases(m_itemdef);
1682 std::string texture_path = g_settings->get("texture_path");
1683 if (texture_path != "" && fs::IsDir(texture_path))
1684 m_nodedef->applyTextureOverrides(texture_path + DIR_DELIM + "override.txt");
1685 m_nodedef->setNodeRegistrationStatus(true);
1686 m_nodedef->runNodeResolveCallbacks();
1689 // Update node textures and assign shaders to each tile
1690 infostream<<"- Updating node textures"<<std::endl;
1691 TextureUpdateArgs tu_args;
1692 tu_args.device = device;
1693 tu_args.guienv = guienv;
1694 tu_args.last_time_ms = porting::getTimeMs();
1695 tu_args.last_percent = 0;
1696 tu_args.text_base = wgettext("Initializing nodes");
1697 tu_args.tsrc = m_tsrc;
1698 m_nodedef->updateTextures(this, texture_update_progress, &tu_args);
1699 delete[] tu_args.text_base;
1701 // Start mesh update thread after setting up content definitions
1702 infostream<<"- Starting mesh update thread"<<std::endl;
1703 m_mesh_update_thread.start();
1708 if (g_settings->getBool("enable_client_modding")) {
1709 m_script->on_client_ready(m_env.getLocalPlayer());
1710 m_script->on_connect();
1713 text = wgettext("Done!");
1714 draw_load_screen(text, device, guienv, m_tsrc, 0, 100);
1715 infostream<<"Client::afterContentReceived() done"<<std::endl;
1719 float Client::getRTT()
1721 return m_con.getPeerStat(PEER_ID_SERVER,con::AVG_RTT);
1724 float Client::getCurRate()
1726 return (m_con.getLocalStat(con::CUR_INC_RATE) +
1727 m_con.getLocalStat(con::CUR_DL_RATE));
1730 void Client::makeScreenshot(IrrlichtDevice *device)
1732 irr::video::IVideoDriver *driver = device->getVideoDriver();
1733 irr::video::IImage* const raw_image = driver->createScreenShot();
1738 time_t t = time(NULL);
1739 struct tm *tm = localtime(&t);
1741 char timetstamp_c[64];
1742 strftime(timetstamp_c, sizeof(timetstamp_c), "%Y%m%d_%H%M%S", tm);
1744 std::string filename_base = g_settings->get("screenshot_path")
1746 + std::string("screenshot_")
1747 + std::string(timetstamp_c);
1748 std::string filename_ext = "." + g_settings->get("screenshot_format");
1749 std::string filename;
1751 u32 quality = (u32)g_settings->getS32("screenshot_quality");
1752 quality = MYMIN(MYMAX(quality, 0), 100) / 100.0 * 255;
1754 // Try to find a unique filename
1755 unsigned serial = 0;
1757 while (serial < SCREENSHOT_MAX_SERIAL_TRIES) {
1758 filename = filename_base + (serial > 0 ? ("_" + itos(serial)) : "") + filename_ext;
1759 std::ifstream tmp(filename.c_str());
1761 break; // File did not apparently exist, we'll go with it
1765 if (serial == SCREENSHOT_MAX_SERIAL_TRIES) {
1766 infostream << "Could not find suitable filename for screenshot" << std::endl;
1768 irr::video::IImage* const image =
1769 driver->createImage(video::ECF_R8G8B8, raw_image->getDimension());
1772 raw_image->copyTo(image);
1774 std::ostringstream sstr;
1775 if (driver->writeImageToFile(image, filename.c_str(), quality)) {
1776 sstr << "Saved screenshot to '" << filename << "'";
1778 sstr << "Failed to save screenshot '" << filename << "'";
1780 pushToChatQueue(narrow_to_wide(sstr.str()));
1781 infostream << sstr.str() << std::endl;
1789 bool Client::shouldShowMinimap() const
1791 return !m_minimap_disabled_by_server;
1794 void Client::showGameChat(const bool show)
1796 m_game_ui_flags->show_chat = show;
1799 void Client::showGameHud(const bool show)
1801 m_game_ui_flags->show_hud = show;
1804 void Client::showMinimap(const bool show)
1806 m_game_ui_flags->show_minimap = show;
1809 void Client::showProfiler(const bool show)
1811 m_game_ui_flags->show_profiler_graph = show;
1814 void Client::showGameFog(const bool show)
1816 m_game_ui_flags->force_fog_off = !show;
1819 void Client::showGameDebug(const bool show)
1821 m_game_ui_flags->show_debug = show;
1824 // IGameDef interface
1826 IItemDefManager* Client::getItemDefManager()
1830 INodeDefManager* Client::getNodeDefManager()
1834 ICraftDefManager* Client::getCraftDefManager()
1837 //return m_craftdef;
1839 ITextureSource* Client::getTextureSource()
1843 IShaderSource* Client::getShaderSource()
1847 scene::ISceneManager* Client::getSceneManager()
1849 return m_device->getSceneManager();
1851 u16 Client::allocateUnknownNodeId(const std::string &name)
1853 errorstream << "Client::allocateUnknownNodeId(): "
1854 << "Client cannot allocate node IDs" << std::endl;
1855 FATAL_ERROR("Client allocated unknown node");
1857 return CONTENT_IGNORE;
1859 ISoundManager* Client::getSoundManager()
1863 MtEventManager* Client::getEventManager()
1868 ParticleManager* Client::getParticleManager()
1870 return &m_particle_manager;
1873 scene::IAnimatedMesh* Client::getMesh(const std::string &filename)
1875 StringMap::const_iterator it = m_mesh_data.find(filename);
1876 if (it == m_mesh_data.end()) {
1877 errorstream << "Client::getMesh(): Mesh not found: \"" << filename
1878 << "\"" << std::endl;
1881 const std::string &data = it->second;
1882 scene::ISceneManager *smgr = m_device->getSceneManager();
1884 // Create the mesh, remove it from cache and return it
1885 // This allows unique vertex colors and other properties for each instance
1886 Buffer<char> data_rw(data.c_str(), data.size()); // Const-incorrect Irrlicht
1887 io::IFileSystem *irrfs = m_device->getFileSystem();
1888 io::IReadFile *rfile = irrfs->createMemoryReadFile(
1889 *data_rw, data_rw.getSize(), filename.c_str());
1890 FATAL_ERROR_IF(!rfile, "Could not create/open RAM file");
1892 scene::IAnimatedMesh *mesh = smgr->getMesh(rfile);
1894 // NOTE: By playing with Irrlicht refcounts, maybe we could cache a bunch
1895 // of uniquely named instances and re-use them
1897 smgr->getMeshCache()->removeMesh(mesh);
1901 bool Client::registerModStorage(ModMetadata *storage)
1903 if (m_mod_storages.find(storage->getModName()) != m_mod_storages.end()) {
1904 errorstream << "Unable to register same mod storage twice. Storage name: "
1905 << storage->getModName() << std::endl;
1909 m_mod_storages[storage->getModName()] = storage;
1913 void Client::unregisterModStorage(const std::string &name)
1915 UNORDERED_MAP<std::string, ModMetadata *>::const_iterator it = m_mod_storages.find(name);
1916 if (it != m_mod_storages.end()) {
1917 // Save unconditionaly on unregistration
1918 it->second->save(getModStoragePath());
1919 m_mod_storages.erase(name);
1923 std::string Client::getModStoragePath() const
1925 return porting::path_user + DIR_DELIM + "client" + DIR_DELIM + "mod_storage";