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 MapDrawControl &control,
62 IWritableTextureSource *tsrc,
63 IWritableShaderSource *shsrc,
64 IWritableItemDefManager *itemdef,
65 IWritableNodeDefManager *nodedef,
67 MtEventManager *event,
69 GameUIFlags *game_ui_flags
71 m_packetcounter_timer(0.0),
72 m_connection_reinit_timer(0.1),
74 m_playerpos_send_timer(0.0),
75 m_ignore_damage_timer(0.0),
82 m_mesh_update_thread(this),
84 new ClientMap(this, control,
85 device->getSceneManager()->getRootSceneNode(),
86 device->getSceneManager(), 666),
87 device->getSceneManager(),
90 m_particle_manager(&m_env),
91 m_con(PROTOCOL_ID, 512, CONNECTION_TIMEOUT, ipv6, this),
94 m_minimap_disabled_by_server(false),
95 m_server_ser_ver(SER_FMT_VER_INVALID),
98 m_inventory_updated(false),
99 m_inventory_from_server(NULL),
100 m_inventory_from_server_age(0.0),
105 m_password(password),
106 m_chosen_auth_mech(AUTH_MECHANISM_NONE),
108 m_access_denied(false),
109 m_access_denied_reconnect(false),
110 m_itemdef_received(false),
111 m_nodedef_received(false),
112 m_media_downloader(new ClientMediaDownloader()),
113 m_time_of_day_set(false),
114 m_last_time_of_day_f(-1),
115 m_time_of_day_update_timer(0),
116 m_recommended_send_interval(0.1),
117 m_removed_sounds_check_timer(0),
121 m_mod_storage_save_timer(10.0f),
122 m_game_ui_flags(game_ui_flags),
126 m_env.setLocalPlayer(new LocalPlayer(this, playername));
128 m_minimap = new Minimap(device, this);
129 m_cache_save_interval = g_settings->getU16("server_map_save_interval");
131 m_modding_enabled = g_settings->getBool("enable_client_modding");
132 m_script = new ClientScripting(this);
133 m_env.setScript(m_script);
134 m_script->setEnv(&m_env);
137 void Client::initMods()
139 m_script->loadMod(getBuiltinLuaPath() + DIR_DELIM "init.lua", BUILTIN_MOD_NAME);
141 // If modding is not enabled, don't load mods, just builtin
142 if (!m_modding_enabled) {
146 ClientModConfiguration modconf(getClientModsLuaPath());
147 std::vector<ModSpec> mods = modconf.getMods();
148 std::vector<ModSpec> unsatisfied_mods = modconf.getUnsatisfiedMods();
149 // complain about mods with unsatisfied dependencies
150 if (!modconf.isConsistent()) {
151 modconf.printUnsatisfiedModsError();
155 infostream << "Client Loading mods: ";
156 for (std::vector<ModSpec>::const_iterator i = mods.begin();
157 i != mods.end(); ++i) {
158 infostream << (*i).name << " ";
161 infostream << std::endl;
162 // Load and run "mod" scripts
163 for (std::vector<ModSpec>::const_iterator it = mods.begin();
164 it != mods.end(); ++it) {
165 const ModSpec &mod = *it;
166 if (!string_allowed(mod.name, MODNAME_ALLOWED_CHARS)) {
167 throw ModError("Error loading mod \"" + mod.name +
168 "\": Mod name does not follow naming conventions: "
169 "Only chararacters [a-z0-9_] are allowed.");
171 std::string script_path = mod.path + DIR_DELIM + "init.lua";
172 infostream << " [" << padStringRight(mod.name, 12) << "] [\""
173 << script_path << "\"]" << std::endl;
174 m_script->loadMod(script_path, mod.name);
178 const std::string &Client::getBuiltinLuaPath()
180 static const std::string builtin_dir = porting::path_share + DIR_DELIM + "builtin";
184 const std::string &Client::getClientModsLuaPath()
186 static const std::string clientmods_dir = porting::path_share + DIR_DELIM + "clientmods";
187 return clientmods_dir;
190 const std::vector<ModSpec>& Client::getMods() const
192 static std::vector<ModSpec> client_modspec_temp;
193 return client_modspec_temp;
196 const ModSpec* Client::getModSpec(const std::string &modname) const
204 // Don't disable this part when modding is disabled, it's used in builtin
205 m_script->on_shutdown();
206 //request all client managed threads to stop
207 m_mesh_update_thread.stop();
208 // Save local server map
210 infostream << "Local map saving ended." << std::endl;
211 m_localdb->endSave();
217 bool Client::isShutdown()
219 return m_shutdown || !m_mesh_update_thread.isRunning();
227 m_mesh_update_thread.stop();
228 m_mesh_update_thread.wait();
229 while (!m_mesh_update_thread.m_queue_out.empty()) {
230 MeshUpdateResult r = m_mesh_update_thread.m_queue_out.pop_frontNoEx();
235 delete m_inventory_from_server;
237 // Delete detached inventories
238 for (UNORDERED_MAP<std::string, Inventory*>::iterator
239 i = m_detached_inventories.begin();
240 i != m_detached_inventories.end(); ++i) {
244 // cleanup 3d model meshes on client shutdown
245 while (m_device->getSceneManager()->getMeshCache()->getMeshCount() != 0) {
246 scene::IAnimatedMesh *mesh =
247 m_device->getSceneManager()->getMeshCache()->getMeshByIndex(0);
250 m_device->getSceneManager()->getMeshCache()->removeMesh(mesh);
256 void Client::connect(Address address,
257 const std::string &address_name,
258 bool is_local_server)
260 DSTACK(FUNCTION_NAME);
262 initLocalMapSaving(address, address_name, is_local_server);
264 m_con.SetTimeoutMs(0);
265 m_con.Connect(address);
268 void Client::step(float dtime)
270 DSTACK(FUNCTION_NAME);
276 if(m_ignore_damage_timer > dtime)
277 m_ignore_damage_timer -= dtime;
279 m_ignore_damage_timer = 0.0;
281 m_animation_time += dtime;
282 if(m_animation_time > 60.0)
283 m_animation_time -= 60.0;
285 m_time_of_day_update_timer += dtime;
293 float &counter = m_packetcounter_timer;
299 infostream << "Client packetcounter (" << m_packetcounter_timer
301 m_packetcounter.print(infostream);
302 m_packetcounter.clear();
306 // UGLY hack to fix 2 second startup delay caused by non existent
307 // server client startup synchronization in local server or singleplayer mode
308 static bool initial_step = true;
310 initial_step = false;
312 else if(m_state == LC_Created) {
313 float &counter = m_connection_reinit_timer;
318 LocalPlayer *myplayer = m_env.getLocalPlayer();
319 FATAL_ERROR_IF(myplayer == NULL, "Local player not found in environment.");
321 u16 proto_version_min = g_settings->getFlag("send_pre_v25_init") ?
322 CLIENT_PROTOCOL_VERSION_MIN_LEGACY : CLIENT_PROTOCOL_VERSION_MIN;
324 if (proto_version_min < 25) {
325 // Send TOSERVER_INIT_LEGACY
326 // [0] u16 TOSERVER_INIT_LEGACY
327 // [2] u8 SER_FMT_VER_HIGHEST_READ
328 // [3] u8[20] player_name
329 // [23] u8[28] password (new in some version)
330 // [51] u16 minimum supported network protocol version (added sometime)
331 // [53] u16 maximum supported network protocol version (added later than the previous one)
333 char pName[PLAYERNAME_SIZE];
334 char pPassword[PASSWORD_SIZE];
335 memset(pName, 0, PLAYERNAME_SIZE * sizeof(char));
336 memset(pPassword, 0, PASSWORD_SIZE * sizeof(char));
338 std::string hashed_password = translate_password(myplayer->getName(), m_password);
339 snprintf(pName, PLAYERNAME_SIZE, "%s", myplayer->getName());
340 snprintf(pPassword, PASSWORD_SIZE, "%s", hashed_password.c_str());
342 sendLegacyInit(pName, pPassword);
344 if (CLIENT_PROTOCOL_VERSION_MAX >= 25)
345 sendInit(myplayer->getName());
348 // Not connected, return
353 Do stuff if connected
357 Run Map's timers and unload unused data
359 const float map_timer_and_unload_dtime = 5.25;
360 if(m_map_timer_and_unload_interval.step(dtime, map_timer_and_unload_dtime)) {
361 ScopeProfiler sp(g_profiler, "Client: map timer and unload");
362 std::vector<v3s16> deleted_blocks;
363 m_env.getMap().timerUpdate(map_timer_and_unload_dtime,
364 g_settings->getFloat("client_unload_unused_data_timeout"),
365 g_settings->getS32("client_mapblock_limit"),
370 NOTE: This loop is intentionally iterated the way it is.
373 std::vector<v3s16>::iterator i = deleted_blocks.begin();
374 std::vector<v3s16> sendlist;
376 if(sendlist.size() == 255 || i == deleted_blocks.end()) {
387 sendDeletedBlocks(sendlist);
389 if(i == deleted_blocks.end())
395 sendlist.push_back(*i);
403 // Control local player (0ms)
404 LocalPlayer *player = m_env.getLocalPlayer();
405 assert(player != NULL);
406 player->applyControl(dtime);
415 ClientEnvEvent event = m_env.getClientEvent();
416 if(event.type == CEE_NONE) {
419 else if(event.type == CEE_PLAYER_DAMAGE) {
420 if(m_ignore_damage_timer <= 0) {
421 u8 damage = event.player_damage.amount;
423 if(event.player_damage.send_to_server)
426 // Add to ClientEvent queue
428 event.type = CE_PLAYER_DAMAGE;
429 event.player_damage.amount = damage;
430 m_client_event_queue.push(event);
433 // Protocol v29 or greater obsoleted this event
434 else if (event.type == CEE_PLAYER_BREATH && m_proto_ver < 29) {
435 u16 breath = event.player_breath.amount;
443 float &counter = m_avg_rtt_timer;
447 // connectedAndInitialized() is true, peer exists.
448 float avg_rtt = getRTT();
449 infostream << "Client: avg_rtt=" << avg_rtt << std::endl;
453 Send player position to server
456 float &counter = m_playerpos_send_timer;
458 if((m_state == LC_Ready) && (counter >= m_recommended_send_interval))
466 Replace updated meshes
469 int num_processed_meshes = 0;
470 while (!m_mesh_update_thread.m_queue_out.empty())
472 num_processed_meshes++;
474 MinimapMapblock *minimap_mapblock = NULL;
475 bool do_mapper_update = true;
477 MeshUpdateResult r = m_mesh_update_thread.m_queue_out.pop_frontNoEx();
478 MapBlock *block = m_env.getMap().getBlockNoCreateNoEx(r.p);
480 // Delete the old mesh
481 if (block->mesh != NULL) {
487 minimap_mapblock = r.mesh->moveMinimapMapblock();
488 if (minimap_mapblock == NULL)
489 do_mapper_update = false;
491 bool is_empty = true;
492 for (int l = 0; l < MAX_TILE_LAYERS; l++)
493 if (r.mesh->getMesh(l)->getMeshBufferCount() != 0)
499 // Replace with the new mesh
500 block->mesh = r.mesh;
506 if (do_mapper_update)
507 m_minimap->addBlock(r.p, minimap_mapblock);
509 if (r.ack_block_to_server) {
519 if (num_processed_meshes > 0)
520 g_profiler->graphAdd("num_processed_meshes", num_processed_meshes);
526 if (m_media_downloader && m_media_downloader->isStarted()) {
527 m_media_downloader->step(this);
528 if (m_media_downloader->isDone()) {
529 delete m_media_downloader;
530 m_media_downloader = NULL;
535 If the server didn't update the inventory in a while, revert
536 the local inventory (so the player notices the lag problem
537 and knows something is wrong).
539 if(m_inventory_from_server)
541 float interval = 10.0;
542 float count_before = floor(m_inventory_from_server_age / interval);
544 m_inventory_from_server_age += dtime;
546 float count_after = floor(m_inventory_from_server_age / interval);
548 if(count_after != count_before)
550 // Do this every <interval> seconds after TOCLIENT_INVENTORY
551 // Reset the locally changed inventory to the authoritative inventory
552 LocalPlayer *player = m_env.getLocalPlayer();
553 player->inventory = *m_inventory_from_server;
554 m_inventory_updated = true;
559 Update positions of sounds attached to objects
562 for(UNORDERED_MAP<int, u16>::iterator i = m_sounds_to_objects.begin();
563 i != m_sounds_to_objects.end(); ++i) {
564 int client_id = i->first;
565 u16 object_id = i->second;
566 ClientActiveObject *cao = m_env.getActiveObject(object_id);
569 v3f pos = cao->getPosition();
570 m_sound->updateSoundPosition(client_id, pos);
575 Handle removed remotely initiated sounds
577 m_removed_sounds_check_timer += dtime;
578 if(m_removed_sounds_check_timer >= 2.32) {
579 m_removed_sounds_check_timer = 0;
580 // Find removed sounds and clear references to them
581 std::vector<s32> removed_server_ids;
582 for(UNORDERED_MAP<s32, int>::iterator i = m_sounds_server_to_client.begin();
583 i != m_sounds_server_to_client.end();) {
584 s32 server_id = i->first;
585 int client_id = i->second;
587 if(!m_sound->soundExists(client_id)) {
588 m_sounds_server_to_client.erase(server_id);
589 m_sounds_client_to_server.erase(client_id);
590 m_sounds_to_objects.erase(client_id);
591 removed_server_ids.push_back(server_id);
596 if(!removed_server_ids.empty()) {
597 sendRemovedSounds(removed_server_ids);
601 m_mod_storage_save_timer -= dtime;
602 if (m_mod_storage_save_timer <= 0.0f) {
603 verbosestream << "Saving registered mod storages." << std::endl;
604 m_mod_storage_save_timer = g_settings->getFloat("server_map_save_interval");
605 for (UNORDERED_MAP<std::string, ModMetadata *>::const_iterator
606 it = m_mod_storages.begin(); it != m_mod_storages.end(); ++it) {
607 if (it->second->isModified()) {
608 it->second->save(getModStoragePath());
614 if (m_localdb && m_localdb_save_interval.step(dtime,
615 m_cache_save_interval)) {
616 m_localdb->endSave();
617 m_localdb->beginSave();
621 bool Client::loadMedia(const std::string &data, const std::string &filename)
623 // Silly irrlicht's const-incorrectness
624 Buffer<char> data_rw(data.c_str(), data.size());
628 const char *image_ext[] = {
629 ".png", ".jpg", ".bmp", ".tga",
630 ".pcx", ".ppm", ".psd", ".wal", ".rgb",
633 name = removeStringEnd(filename, image_ext);
636 verbosestream<<"Client: Attempting to load image "
637 <<"file \""<<filename<<"\""<<std::endl;
639 io::IFileSystem *irrfs = m_device->getFileSystem();
640 video::IVideoDriver *vdrv = m_device->getVideoDriver();
642 // Create an irrlicht memory file
643 io::IReadFile *rfile = irrfs->createMemoryReadFile(
644 *data_rw, data_rw.getSize(), "_tempreadfile");
646 FATAL_ERROR_IF(!rfile, "Could not create irrlicht memory file.");
649 video::IImage *img = vdrv->createImageFromFile(rfile);
651 errorstream<<"Client: Cannot create image from data of "
652 <<"file \""<<filename<<"\""<<std::endl;
657 m_tsrc->insertSourceImage(filename, img);
664 const char *sound_ext[] = {
665 ".0.ogg", ".1.ogg", ".2.ogg", ".3.ogg", ".4.ogg",
666 ".5.ogg", ".6.ogg", ".7.ogg", ".8.ogg", ".9.ogg",
669 name = removeStringEnd(filename, sound_ext);
672 verbosestream<<"Client: Attempting to load sound "
673 <<"file \""<<filename<<"\""<<std::endl;
674 m_sound->loadSoundData(name, data);
678 const char *model_ext[] = {
679 ".x", ".b3d", ".md2", ".obj",
682 name = removeStringEnd(filename, model_ext);
685 verbosestream<<"Client: Storing model into memory: "
686 <<"\""<<filename<<"\""<<std::endl;
687 if(m_mesh_data.count(filename))
688 errorstream<<"Multiple models with name \""<<filename.c_str()
689 <<"\" found; replacing previous model"<<std::endl;
690 m_mesh_data[filename] = data;
694 errorstream<<"Client: Don't know how to load file \""
695 <<filename<<"\""<<std::endl;
699 // Virtual methods from con::PeerHandler
700 void Client::peerAdded(con::Peer *peer)
702 infostream << "Client::peerAdded(): peer->id="
703 << peer->id << std::endl;
705 void Client::deletingPeer(con::Peer *peer, bool timeout)
707 infostream << "Client::deletingPeer(): "
708 "Server Peer is getting deleted "
709 << "(timeout=" << timeout << ")" << std::endl;
712 m_access_denied = true;
713 m_access_denied_reason = gettext("Connection timed out.");
719 u16 number of files requested
725 void Client::request_media(const std::vector<std::string> &file_requests)
727 std::ostringstream os(std::ios_base::binary);
728 writeU16(os, TOSERVER_REQUEST_MEDIA);
729 size_t file_requests_size = file_requests.size();
731 FATAL_ERROR_IF(file_requests_size > 0xFFFF, "Unsupported number of file requests");
733 // Packet dynamicly resized
734 NetworkPacket pkt(TOSERVER_REQUEST_MEDIA, 2 + 0);
736 pkt << (u16) (file_requests_size & 0xFFFF);
738 for(std::vector<std::string>::const_iterator i = file_requests.begin();
739 i != file_requests.end(); ++i) {
745 infostream << "Client: Sending media request list to server ("
746 << file_requests.size() << " files. packet size)" << std::endl;
749 void Client::initLocalMapSaving(const Address &address,
750 const std::string &hostname,
751 bool is_local_server)
753 if (!g_settings->getBool("enable_local_map_saving") || is_local_server) {
757 const std::string world_path = porting::path_user
758 + DIR_DELIM + "worlds"
759 + DIR_DELIM + "server_"
760 + hostname + "_" + std::to_string(address.getPort());
762 fs::CreateAllDirs(world_path);
764 m_localdb = new MapDatabaseSQLite3(world_path);
765 m_localdb->beginSave();
766 actionstream << "Local map saving started, map will be saved at '" << world_path << "'" << std::endl;
769 void Client::ReceiveAll()
771 DSTACK(FUNCTION_NAME);
772 u32 start_ms = porting::getTimeMs();
775 // Limit time even if there would be huge amounts of data to
777 if(porting::getTimeMs() > start_ms + 100)
782 g_profiler->graphAdd("client_received_packets", 1);
784 catch(con::NoIncomingDataException &e) {
787 catch(con::InvalidIncomingDataException &e) {
788 infostream<<"Client::ReceiveAll(): "
789 "InvalidIncomingDataException: what()="
790 <<e.what()<<std::endl;
795 void Client::Receive()
797 DSTACK(FUNCTION_NAME);
803 inline void Client::handleCommand(NetworkPacket* pkt)
805 const ToClientCommandHandler& opHandle = toClientCommandTable[pkt->getCommand()];
806 (this->*opHandle.handler)(pkt);
810 sender_peer_id given to this shall be quaranteed to be a valid peer
812 void Client::ProcessData(NetworkPacket *pkt)
814 DSTACK(FUNCTION_NAME);
816 ToClientCommand command = (ToClientCommand) pkt->getCommand();
817 u32 sender_peer_id = pkt->getPeerId();
819 //infostream<<"Client: received command="<<command<<std::endl;
820 m_packetcounter.add((u16)command);
823 If this check is removed, be sure to change the queue
824 system to know the ids
826 if(sender_peer_id != PEER_ID_SERVER) {
827 infostream << "Client::ProcessData(): Discarding data not "
828 "coming from server: peer_id=" << sender_peer_id
833 // Command must be handled into ToClientCommandHandler
834 if (command >= TOCLIENT_NUM_MSG_TYPES) {
835 infostream << "Client: Ignoring unknown command "
836 << command << std::endl;
841 * Those packets are handled before m_server_ser_ver is set, it's normal
842 * But we must use the new ToClientConnectionState in the future,
845 if(toClientCommandTable[command].state == TOCLIENT_STATE_NOT_CONNECTED) {
850 if(m_server_ser_ver == SER_FMT_VER_INVALID) {
851 infostream << "Client: Server serialization"
852 " format invalid or not initialized."
853 " Skipping incoming command=" << command << std::endl;
858 Handle runtime commands
864 void Client::Send(NetworkPacket* pkt)
866 m_con.Send(PEER_ID_SERVER,
867 serverCommandFactoryTable[pkt->getCommand()].channel,
869 serverCommandFactoryTable[pkt->getCommand()].reliable);
872 // Will fill up 12 + 12 + 4 + 4 + 4 bytes
873 void writePlayerPos(LocalPlayer *myplayer, ClientMap *clientMap, NetworkPacket *pkt)
875 v3f pf = myplayer->getPosition() * 100;
876 v3f sf = myplayer->getSpeed() * 100;
877 s32 pitch = myplayer->getPitch() * 100;
878 s32 yaw = myplayer->getYaw() * 100;
879 u32 keyPressed = myplayer->keyPressed;
880 // scaled by 80, so that pi can fit into a u8
881 u8 fov = clientMap->getCameraFov() * 80;
882 u8 wanted_range = MYMIN(255,
883 std::ceil(clientMap->getControl().wanted_range / MAP_BLOCKSIZE));
885 v3s32 position(pf.X, pf.Y, pf.Z);
886 v3s32 speed(sf.X, sf.Y, sf.Z);
890 [0] v3s32 position*100
892 [12+12] s32 pitch*100
893 [12+12+4] s32 yaw*100
894 [12+12+4+4] u32 keyPressed
895 [12+12+4+4+4] u8 fov*80
896 [12+12+4+4+4+1] u8 ceil(wanted_range / MAP_BLOCKSIZE)
898 *pkt << position << speed << pitch << yaw << keyPressed;
899 *pkt << fov << wanted_range;
902 void Client::interact(u8 action, const PointedThing& pointed)
904 if(m_state != LC_Ready) {
905 errorstream << "Client::interact() "
906 "Canceled (not connected)"
911 LocalPlayer *myplayer = m_env.getLocalPlayer();
912 if (myplayer == NULL)
919 [5] u32 length of the next item (plen)
920 [9] serialized PointedThing
921 [9 + plen] player position information
923 0: start digging (from undersurface) or use
924 1: stop digging (all parameters ignored)
926 3: place block or item (to abovesurface)
928 5: perform secondary action of item
931 NetworkPacket pkt(TOSERVER_INTERACT, 1 + 2 + 0);
934 pkt << (u16)getPlayerItem();
936 std::ostringstream tmp_os(std::ios::binary);
937 pointed.serialize(tmp_os);
939 pkt.putLongString(tmp_os.str());
941 writePlayerPos(myplayer, &m_env.getClientMap(), &pkt);
946 void Client::deleteAuthData()
951 switch (m_chosen_auth_mech) {
952 case AUTH_MECHANISM_FIRST_SRP:
954 case AUTH_MECHANISM_SRP:
955 case AUTH_MECHANISM_LEGACY_PASSWORD:
956 srp_user_delete((SRPUser *) m_auth_data);
959 case AUTH_MECHANISM_NONE:
962 m_chosen_auth_mech = AUTH_MECHANISM_NONE;
966 AuthMechanism Client::choseAuthMech(const u32 mechs)
968 if (mechs & AUTH_MECHANISM_SRP)
969 return AUTH_MECHANISM_SRP;
971 if (mechs & AUTH_MECHANISM_FIRST_SRP)
972 return AUTH_MECHANISM_FIRST_SRP;
974 if (mechs & AUTH_MECHANISM_LEGACY_PASSWORD)
975 return AUTH_MECHANISM_LEGACY_PASSWORD;
977 return AUTH_MECHANISM_NONE;
980 void Client::sendLegacyInit(const char* playerName, const char* playerPassword)
982 NetworkPacket pkt(TOSERVER_INIT_LEGACY,
983 1 + PLAYERNAME_SIZE + PASSWORD_SIZE + 2 + 2);
985 u16 proto_version_min = g_settings->getFlag("send_pre_v25_init") ?
986 CLIENT_PROTOCOL_VERSION_MIN_LEGACY : CLIENT_PROTOCOL_VERSION_MIN;
988 pkt << (u8) SER_FMT_VER_HIGHEST_READ;
989 pkt.putRawString(playerName,PLAYERNAME_SIZE);
990 pkt.putRawString(playerPassword, PASSWORD_SIZE);
991 pkt << (u16) proto_version_min << (u16) CLIENT_PROTOCOL_VERSION_MAX;
996 void Client::sendInit(const std::string &playerName)
998 NetworkPacket pkt(TOSERVER_INIT, 1 + 2 + 2 + (1 + playerName.size()));
1000 // we don't support network compression yet
1001 u16 supp_comp_modes = NETPROTO_COMPRESSION_NONE;
1003 u16 proto_version_min = g_settings->getFlag("send_pre_v25_init") ?
1004 CLIENT_PROTOCOL_VERSION_MIN_LEGACY : CLIENT_PROTOCOL_VERSION_MIN;
1006 pkt << (u8) SER_FMT_VER_HIGHEST_READ << (u16) supp_comp_modes;
1007 pkt << (u16) proto_version_min << (u16) CLIENT_PROTOCOL_VERSION_MAX;
1013 void Client::startAuth(AuthMechanism chosen_auth_mechanism)
1015 m_chosen_auth_mech = chosen_auth_mechanism;
1017 switch (chosen_auth_mechanism) {
1018 case AUTH_MECHANISM_FIRST_SRP: {
1019 // send srp verifier to server
1020 std::string verifier;
1022 generate_srp_verifier_and_salt(getPlayerName(), m_password,
1025 NetworkPacket resp_pkt(TOSERVER_FIRST_SRP, 0);
1026 resp_pkt << salt << verifier << (u8)((m_password == "") ? 1 : 0);
1031 case AUTH_MECHANISM_SRP:
1032 case AUTH_MECHANISM_LEGACY_PASSWORD: {
1035 if (chosen_auth_mechanism == AUTH_MECHANISM_LEGACY_PASSWORD) {
1036 m_password = translate_password(getPlayerName(), m_password);
1040 std::string playername_u = lowercase(getPlayerName());
1041 m_auth_data = srp_user_new(SRP_SHA256, SRP_NG_2048,
1042 getPlayerName().c_str(), playername_u.c_str(),
1043 (const unsigned char *) m_password.c_str(),
1044 m_password.length(), NULL, NULL);
1047 SRP_Result res = srp_user_start_authentication(
1048 (struct SRPUser *) m_auth_data, NULL, NULL, 0,
1049 (unsigned char **) &bytes_A, &len_A);
1050 FATAL_ERROR_IF(res != SRP_OK, "Creating local SRP user failed.");
1052 NetworkPacket resp_pkt(TOSERVER_SRP_BYTES_A, 0);
1053 resp_pkt << std::string(bytes_A, len_A) << based_on;
1057 case AUTH_MECHANISM_NONE:
1058 break; // not handled in this method
1062 void Client::sendDeletedBlocks(std::vector<v3s16> &blocks)
1064 NetworkPacket pkt(TOSERVER_DELETEDBLOCKS, 1 + sizeof(v3s16) * blocks.size());
1066 pkt << (u8) blocks.size();
1069 for(std::vector<v3s16>::iterator
1071 j != blocks.end(); ++j) {
1079 void Client::sendGotBlocks(v3s16 block)
1081 NetworkPacket pkt(TOSERVER_GOTBLOCKS, 1 + 6);
1082 pkt << (u8) 1 << block;
1086 void Client::sendRemovedSounds(std::vector<s32> &soundList)
1088 size_t server_ids = soundList.size();
1089 assert(server_ids <= 0xFFFF);
1091 NetworkPacket pkt(TOSERVER_REMOVED_SOUNDS, 2 + server_ids * 4);
1093 pkt << (u16) (server_ids & 0xFFFF);
1095 for(std::vector<s32>::iterator i = soundList.begin();
1096 i != soundList.end(); ++i)
1102 void Client::sendNodemetaFields(v3s16 p, const std::string &formname,
1103 const StringMap &fields)
1105 size_t fields_size = fields.size();
1107 FATAL_ERROR_IF(fields_size > 0xFFFF, "Unsupported number of nodemeta fields");
1109 NetworkPacket pkt(TOSERVER_NODEMETA_FIELDS, 0);
1111 pkt << p << formname << (u16) (fields_size & 0xFFFF);
1113 StringMap::const_iterator it;
1114 for (it = fields.begin(); it != fields.end(); ++it) {
1115 const std::string &name = it->first;
1116 const std::string &value = it->second;
1118 pkt.putLongString(value);
1124 void Client::sendInventoryFields(const std::string &formname,
1125 const StringMap &fields)
1127 size_t fields_size = fields.size();
1128 FATAL_ERROR_IF(fields_size > 0xFFFF, "Unsupported number of inventory fields");
1130 NetworkPacket pkt(TOSERVER_INVENTORY_FIELDS, 0);
1131 pkt << formname << (u16) (fields_size & 0xFFFF);
1133 StringMap::const_iterator it;
1134 for (it = fields.begin(); it != fields.end(); ++it) {
1135 const std::string &name = it->first;
1136 const std::string &value = it->second;
1138 pkt.putLongString(value);
1144 void Client::sendInventoryAction(InventoryAction *a)
1146 std::ostringstream os(std::ios_base::binary);
1151 std::string s = os.str();
1153 NetworkPacket pkt(TOSERVER_INVENTORY_ACTION, s.size());
1154 pkt.putRawString(s.c_str(),s.size());
1159 void Client::sendChatMessage(const std::wstring &message)
1161 NetworkPacket pkt(TOSERVER_CHAT_MESSAGE, 2 + message.size() * sizeof(u16));
1168 void Client::sendChangePassword(const std::string &oldpassword,
1169 const std::string &newpassword)
1171 LocalPlayer *player = m_env.getLocalPlayer();
1175 std::string playername = player->getName();
1176 if (m_proto_ver >= 25) {
1177 // get into sudo mode and then send new password to server
1178 m_password = oldpassword;
1179 m_new_password = newpassword;
1180 startAuth(choseAuthMech(m_sudo_auth_methods));
1182 std::string oldpwd = translate_password(playername, oldpassword);
1183 std::string newpwd = translate_password(playername, newpassword);
1185 NetworkPacket pkt(TOSERVER_PASSWORD_LEGACY, 2 * PASSWORD_SIZE);
1187 for (u8 i = 0; i < PASSWORD_SIZE; i++) {
1188 pkt << (u8) (i < oldpwd.length() ? oldpwd[i] : 0);
1191 for (u8 i = 0; i < PASSWORD_SIZE; i++) {
1192 pkt << (u8) (i < newpwd.length() ? newpwd[i] : 0);
1199 void Client::sendDamage(u8 damage)
1201 DSTACK(FUNCTION_NAME);
1203 NetworkPacket pkt(TOSERVER_DAMAGE, sizeof(u8));
1208 void Client::sendBreath(u16 breath)
1210 DSTACK(FUNCTION_NAME);
1212 // Protocol v29 make this obsolete
1213 if (m_proto_ver >= 29)
1216 NetworkPacket pkt(TOSERVER_BREATH, sizeof(u16));
1221 void Client::sendRespawn()
1223 DSTACK(FUNCTION_NAME);
1225 NetworkPacket pkt(TOSERVER_RESPAWN, 0);
1229 void Client::sendReady()
1231 DSTACK(FUNCTION_NAME);
1233 NetworkPacket pkt(TOSERVER_CLIENT_READY,
1234 1 + 1 + 1 + 1 + 2 + sizeof(char) * strlen(g_version_hash));
1236 pkt << (u8) VERSION_MAJOR << (u8) VERSION_MINOR << (u8) VERSION_PATCH
1237 << (u8) 0 << (u16) strlen(g_version_hash);
1239 pkt.putRawString(g_version_hash, (u16) strlen(g_version_hash));
1243 void Client::sendPlayerPos()
1245 LocalPlayer *myplayer = m_env.getLocalPlayer();
1246 if(myplayer == NULL)
1249 ClientMap &map = m_env.getClientMap();
1251 u8 camera_fov = map.getCameraFov();
1252 u8 wanted_range = map.getControl().wanted_range;
1254 // Save bandwidth by only updating position when something changed
1255 if(myplayer->last_position == myplayer->getPosition() &&
1256 myplayer->last_speed == myplayer->getSpeed() &&
1257 myplayer->last_pitch == myplayer->getPitch() &&
1258 myplayer->last_yaw == myplayer->getYaw() &&
1259 myplayer->last_keyPressed == myplayer->keyPressed &&
1260 myplayer->last_camera_fov == camera_fov &&
1261 myplayer->last_wanted_range == wanted_range)
1264 myplayer->last_position = myplayer->getPosition();
1265 myplayer->last_speed = myplayer->getSpeed();
1266 myplayer->last_pitch = myplayer->getPitch();
1267 myplayer->last_yaw = myplayer->getYaw();
1268 myplayer->last_keyPressed = myplayer->keyPressed;
1269 myplayer->last_camera_fov = camera_fov;
1270 myplayer->last_wanted_range = wanted_range;
1272 //infostream << "Sending Player Position information" << std::endl;
1276 //MutexAutoLock lock(m_con_mutex); //bulk comment-out
1277 our_peer_id = m_con.GetPeerID();
1280 // Set peer id if not set already
1281 if(myplayer->peer_id == PEER_ID_INEXISTENT)
1282 myplayer->peer_id = our_peer_id;
1284 assert(myplayer->peer_id == our_peer_id);
1286 NetworkPacket pkt(TOSERVER_PLAYERPOS, 12 + 12 + 4 + 4 + 4 + 1 + 1);
1288 writePlayerPos(myplayer, &map, &pkt);
1293 void Client::sendPlayerItem(u16 item)
1295 LocalPlayer *myplayer = m_env.getLocalPlayer();
1296 if(myplayer == NULL)
1299 u16 our_peer_id = m_con.GetPeerID();
1301 // Set peer id if not set already
1302 if(myplayer->peer_id == PEER_ID_INEXISTENT)
1303 myplayer->peer_id = our_peer_id;
1304 assert(myplayer->peer_id == our_peer_id);
1306 NetworkPacket pkt(TOSERVER_PLAYERITEM, 2);
1313 void Client::removeNode(v3s16 p)
1315 std::map<v3s16, MapBlock*> modified_blocks;
1318 m_env.getMap().removeNodeAndUpdate(p, modified_blocks);
1320 catch(InvalidPositionException &e) {
1323 for(std::map<v3s16, MapBlock *>::iterator
1324 i = modified_blocks.begin();
1325 i != modified_blocks.end(); ++i) {
1326 addUpdateMeshTaskWithEdge(i->first, false, true);
1330 MapNode Client::getNode(v3s16 p, bool *is_valid_position)
1332 return m_env.getMap().getNodeNoEx(p, is_valid_position);
1335 void Client::addNode(v3s16 p, MapNode n, bool remove_metadata)
1337 //TimeTaker timer1("Client::addNode()");
1339 std::map<v3s16, MapBlock*> modified_blocks;
1342 //TimeTaker timer3("Client::addNode(): addNodeAndUpdate");
1343 m_env.getMap().addNodeAndUpdate(p, n, modified_blocks, remove_metadata);
1345 catch(InvalidPositionException &e) {
1348 for(std::map<v3s16, MapBlock *>::iterator
1349 i = modified_blocks.begin();
1350 i != modified_blocks.end(); ++i) {
1351 addUpdateMeshTaskWithEdge(i->first, false, true);
1355 void Client::setPlayerControl(PlayerControl &control)
1357 LocalPlayer *player = m_env.getLocalPlayer();
1358 assert(player != NULL);
1359 player->control = control;
1362 void Client::selectPlayerItem(u16 item)
1364 m_playeritem = item;
1365 m_inventory_updated = true;
1366 sendPlayerItem(item);
1369 // Returns true if the inventory of the local player has been
1370 // updated from the server. If it is true, it is set to false.
1371 bool Client::getLocalInventoryUpdated()
1373 bool updated = m_inventory_updated;
1374 m_inventory_updated = false;
1378 // Copies the inventory of the local player to parameter
1379 void Client::getLocalInventory(Inventory &dst)
1381 LocalPlayer *player = m_env.getLocalPlayer();
1382 assert(player != NULL);
1383 dst = player->inventory;
1386 Inventory* Client::getInventory(const InventoryLocation &loc)
1389 case InventoryLocation::UNDEFINED:
1392 case InventoryLocation::CURRENT_PLAYER:
1394 LocalPlayer *player = m_env.getLocalPlayer();
1395 assert(player != NULL);
1396 return &player->inventory;
1399 case InventoryLocation::PLAYER:
1401 // Check if we are working with local player inventory
1402 LocalPlayer *player = m_env.getLocalPlayer();
1403 if (!player || strcmp(player->getName(), loc.name.c_str()) != 0)
1405 return &player->inventory;
1408 case InventoryLocation::NODEMETA:
1410 NodeMetadata *meta = m_env.getMap().getNodeMetadata(loc.p);
1413 return meta->getInventory();
1416 case InventoryLocation::DETACHED:
1418 if (m_detached_inventories.count(loc.name) == 0)
1420 return m_detached_inventories[loc.name];
1424 FATAL_ERROR("Invalid inventory location type.");
1430 void Client::inventoryAction(InventoryAction *a)
1433 Send it to the server
1435 sendInventoryAction(a);
1438 Predict some local inventory changes
1440 a->clientApply(this, this);
1446 float Client::getAnimationTime()
1448 return m_animation_time;
1451 int Client::getCrackLevel()
1453 return m_crack_level;
1456 v3s16 Client::getCrackPos()
1461 void Client::setCrack(int level, v3s16 pos)
1463 int old_crack_level = m_crack_level;
1464 v3s16 old_crack_pos = m_crack_pos;
1466 m_crack_level = level;
1469 if(old_crack_level >= 0 && (level < 0 || pos != old_crack_pos))
1472 addUpdateMeshTaskForNode(old_crack_pos, false, true);
1474 if(level >= 0 && (old_crack_level < 0 || pos != old_crack_pos))
1477 addUpdateMeshTaskForNode(pos, false, true);
1483 LocalPlayer *player = m_env.getLocalPlayer();
1484 assert(player != NULL);
1488 bool Client::getChatMessage(std::wstring &message)
1490 if(m_chat_queue.size() == 0)
1492 message = m_chat_queue.front();
1497 void Client::typeChatMessage(const std::wstring &message)
1499 // Discard empty line
1503 // If message was ate by script API, don't send it to server
1504 if (m_script->on_sending_message(wide_to_utf8(message))) {
1509 sendChatMessage(message);
1512 if (message[0] != L'/')
1514 // compatibility code
1515 if (m_proto_ver < 29) {
1516 LocalPlayer *player = m_env.getLocalPlayer();
1517 assert(player != NULL);
1518 std::wstring name = narrow_to_wide(player->getName());
1519 pushToChatQueue((std::wstring)L"<" + name + L"> " + message);
1524 void Client::addUpdateMeshTask(v3s16 p, bool ack_to_server, bool urgent)
1526 // Check if the block exists to begin with. In the case when a non-existing
1527 // neighbor is automatically added, it may not. In that case we don't want
1528 // to tell the mesh update thread about it.
1529 MapBlock *b = m_env.getMap().getBlockNoCreateNoEx(p);
1533 m_mesh_update_thread.updateBlock(&m_env.getMap(), p, ack_to_server, urgent);
1536 void Client::addUpdateMeshTaskWithEdge(v3s16 blockpos, bool ack_to_server, bool urgent)
1539 addUpdateMeshTask(blockpos, ack_to_server, urgent);
1541 catch(InvalidPositionException &e){}
1544 for (int i=0;i<6;i++)
1547 v3s16 p = blockpos + g_6dirs[i];
1548 addUpdateMeshTask(p, false, urgent);
1550 catch(InvalidPositionException &e){}
1554 void Client::addUpdateMeshTaskForNode(v3s16 nodepos, bool ack_to_server, bool urgent)
1558 infostream<<"Client::addUpdateMeshTaskForNode(): "
1559 <<"("<<p.X<<","<<p.Y<<","<<p.Z<<")"
1563 v3s16 blockpos = getNodeBlockPos(nodepos);
1564 v3s16 blockpos_relative = blockpos * MAP_BLOCKSIZE;
1567 addUpdateMeshTask(blockpos, ack_to_server, urgent);
1569 catch(InvalidPositionException &e) {}
1572 if(nodepos.X == blockpos_relative.X){
1574 v3s16 p = blockpos + v3s16(-1,0,0);
1575 addUpdateMeshTask(p, false, urgent);
1577 catch(InvalidPositionException &e){}
1580 if(nodepos.Y == blockpos_relative.Y){
1582 v3s16 p = blockpos + v3s16(0,-1,0);
1583 addUpdateMeshTask(p, false, urgent);
1585 catch(InvalidPositionException &e){}
1588 if(nodepos.Z == blockpos_relative.Z){
1590 v3s16 p = blockpos + v3s16(0,0,-1);
1591 addUpdateMeshTask(p, false, urgent);
1593 catch(InvalidPositionException &e){}
1597 ClientEvent Client::getClientEvent()
1600 if (m_client_event_queue.empty()) {
1601 event.type = CE_NONE;
1604 event = m_client_event_queue.front();
1605 m_client_event_queue.pop();
1610 float Client::mediaReceiveProgress()
1612 if (m_media_downloader)
1613 return m_media_downloader->getProgress();
1615 return 1.0; // downloader only exists when not yet done
1618 typedef struct TextureUpdateArgs {
1619 IrrlichtDevice *device;
1620 gui::IGUIEnvironment *guienv;
1623 const wchar_t* text_base;
1624 ITextureSource *tsrc;
1625 } TextureUpdateArgs;
1627 void texture_update_progress(void *args, u32 progress, u32 max_progress)
1629 TextureUpdateArgs* targs = (TextureUpdateArgs*) args;
1630 u16 cur_percent = ceil(progress / (double) max_progress * 100.);
1632 // update the loading menu -- if neccessary
1633 bool do_draw = false;
1634 u32 time_ms = targs->last_time_ms;
1635 if (cur_percent != targs->last_percent) {
1636 targs->last_percent = cur_percent;
1637 time_ms = porting::getTimeMs();
1638 // only draw when the user will notice something:
1639 do_draw = (time_ms - targs->last_time_ms > 100);
1643 targs->last_time_ms = time_ms;
1644 std::basic_stringstream<wchar_t> strm;
1645 strm << targs->text_base << " " << targs->last_percent << "%...";
1646 draw_load_screen(strm.str(), targs->device, targs->guienv, targs->tsrc, 0,
1647 72 + (u16) ((18. / 100.) * (double) targs->last_percent), true);
1651 void Client::afterContentReceived(IrrlichtDevice *device)
1653 infostream<<"Client::afterContentReceived() started"<<std::endl;
1654 assert(m_itemdef_received); // pre-condition
1655 assert(m_nodedef_received); // pre-condition
1656 assert(mediaReceived()); // pre-condition
1658 const wchar_t* text = wgettext("Loading textures...");
1660 // Clear cached pre-scaled 2D GUI images, as this cache
1661 // might have images with the same name but different
1662 // content from previous sessions.
1663 guiScalingCacheClear(device->getVideoDriver());
1665 // Rebuild inherited images and recreate textures
1666 infostream<<"- Rebuilding images and textures"<<std::endl;
1667 draw_load_screen(text,device, guienv, m_tsrc, 0, 70);
1668 m_tsrc->rebuildImagesAndTextures();
1672 infostream<<"- Rebuilding shaders"<<std::endl;
1673 text = wgettext("Rebuilding shaders...");
1674 draw_load_screen(text, device, guienv, m_tsrc, 0, 71);
1675 m_shsrc->rebuildShaders();
1678 // Update node aliases
1679 infostream<<"- Updating node aliases"<<std::endl;
1680 text = wgettext("Initializing nodes...");
1681 draw_load_screen(text, device, guienv, m_tsrc, 0, 72);
1682 m_nodedef->updateAliases(m_itemdef);
1683 std::string texture_path = g_settings->get("texture_path");
1684 if (texture_path != "" && fs::IsDir(texture_path))
1685 m_nodedef->applyTextureOverrides(texture_path + DIR_DELIM + "override.txt");
1686 m_nodedef->setNodeRegistrationStatus(true);
1687 m_nodedef->runNodeResolveCallbacks();
1690 // Update node textures and assign shaders to each tile
1691 infostream<<"- Updating node textures"<<std::endl;
1692 TextureUpdateArgs tu_args;
1693 tu_args.device = device;
1694 tu_args.guienv = guienv;
1695 tu_args.last_time_ms = porting::getTimeMs();
1696 tu_args.last_percent = 0;
1697 tu_args.text_base = wgettext("Initializing nodes");
1698 tu_args.tsrc = m_tsrc;
1699 m_nodedef->updateTextures(this, texture_update_progress, &tu_args);
1700 delete[] tu_args.text_base;
1702 // Start mesh update thread after setting up content definitions
1703 infostream<<"- Starting mesh update thread"<<std::endl;
1704 m_mesh_update_thread.start();
1709 if (g_settings->getBool("enable_client_modding")) {
1710 m_script->on_client_ready(m_env.getLocalPlayer());
1711 m_script->on_connect();
1714 text = wgettext("Done!");
1715 draw_load_screen(text, device, guienv, m_tsrc, 0, 100);
1716 infostream<<"Client::afterContentReceived() done"<<std::endl;
1720 float Client::getRTT()
1722 return m_con.getPeerStat(PEER_ID_SERVER,con::AVG_RTT);
1725 float Client::getCurRate()
1727 return ( m_con.getLocalStat(con::CUR_INC_RATE) +
1728 m_con.getLocalStat(con::CUR_DL_RATE));
1731 void Client::makeScreenshot(IrrlichtDevice *device)
1733 irr::video::IVideoDriver *driver = device->getVideoDriver();
1734 irr::video::IImage* const raw_image = driver->createScreenShot();
1739 time_t t = time(NULL);
1740 struct tm *tm = localtime(&t);
1742 char timetstamp_c[64];
1743 strftime(timetstamp_c, sizeof(timetstamp_c), "%Y%m%d_%H%M%S", tm);
1745 std::string filename_base = g_settings->get("screenshot_path")
1747 + std::string("screenshot_")
1748 + std::string(timetstamp_c);
1749 std::string filename_ext = "." + g_settings->get("screenshot_format");
1750 std::string filename;
1752 u32 quality = (u32)g_settings->getS32("screenshot_quality");
1753 quality = MYMIN(MYMAX(quality, 0), 100) / 100.0 * 255;
1755 // Try to find a unique filename
1756 unsigned serial = 0;
1758 while (serial < SCREENSHOT_MAX_SERIAL_TRIES) {
1759 filename = filename_base + (serial > 0 ? ("_" + itos(serial)) : "") + filename_ext;
1760 std::ifstream tmp(filename.c_str());
1762 break; // File did not apparently exist, we'll go with it
1766 if (serial == SCREENSHOT_MAX_SERIAL_TRIES) {
1767 infostream << "Could not find suitable filename for screenshot" << std::endl;
1769 irr::video::IImage* const image =
1770 driver->createImage(video::ECF_R8G8B8, raw_image->getDimension());
1773 raw_image->copyTo(image);
1775 std::ostringstream sstr;
1776 if (driver->writeImageToFile(image, filename.c_str(), quality)) {
1777 sstr << "Saved screenshot to '" << filename << "'";
1779 sstr << "Failed to save screenshot '" << filename << "'";
1781 pushToChatQueue(narrow_to_wide(sstr.str()));
1782 infostream << sstr.str() << std::endl;
1790 bool Client::shouldShowMinimap() const
1792 return !m_minimap_disabled_by_server;
1795 void Client::showGameChat(const bool show)
1797 m_game_ui_flags->show_chat = show;
1800 void Client::showGameHud(const bool show)
1802 m_game_ui_flags->show_hud = show;
1805 void Client::showMinimap(const bool show)
1807 m_game_ui_flags->show_minimap = show;
1810 void Client::showProfiler(const bool show)
1812 m_game_ui_flags->show_profiler_graph = show;
1815 void Client::showGameFog(const bool show)
1817 m_game_ui_flags->force_fog_off = !show;
1820 void Client::showGameDebug(const bool show)
1822 m_game_ui_flags->show_debug = show;
1825 // IGameDef interface
1827 IItemDefManager* Client::getItemDefManager()
1831 INodeDefManager* Client::getNodeDefManager()
1835 ICraftDefManager* Client::getCraftDefManager()
1838 //return m_craftdef;
1840 ITextureSource* Client::getTextureSource()
1844 IShaderSource* Client::getShaderSource()
1848 scene::ISceneManager* Client::getSceneManager()
1850 return m_device->getSceneManager();
1852 u16 Client::allocateUnknownNodeId(const std::string &name)
1854 errorstream << "Client::allocateUnknownNodeId(): "
1855 << "Client cannot allocate node IDs" << std::endl;
1856 FATAL_ERROR("Client allocated unknown node");
1858 return CONTENT_IGNORE;
1860 ISoundManager* Client::getSoundManager()
1864 MtEventManager* Client::getEventManager()
1869 ParticleManager* Client::getParticleManager()
1871 return &m_particle_manager;
1874 scene::IAnimatedMesh* Client::getMesh(const std::string &filename)
1876 StringMap::const_iterator it = m_mesh_data.find(filename);
1877 if (it == m_mesh_data.end()) {
1878 errorstream << "Client::getMesh(): Mesh not found: \"" << filename
1879 << "\"" << std::endl;
1882 const std::string &data = it->second;
1883 scene::ISceneManager *smgr = m_device->getSceneManager();
1885 // Create the mesh, remove it from cache and return it
1886 // This allows unique vertex colors and other properties for each instance
1887 Buffer<char> data_rw(data.c_str(), data.size()); // Const-incorrect Irrlicht
1888 io::IFileSystem *irrfs = m_device->getFileSystem();
1889 io::IReadFile *rfile = irrfs->createMemoryReadFile(
1890 *data_rw, data_rw.getSize(), filename.c_str());
1891 FATAL_ERROR_IF(!rfile, "Could not create/open RAM file");
1893 scene::IAnimatedMesh *mesh = smgr->getMesh(rfile);
1895 // NOTE: By playing with Irrlicht refcounts, maybe we could cache a bunch
1896 // of uniquely named instances and re-use them
1898 smgr->getMeshCache()->removeMesh(mesh);
1902 bool Client::registerModStorage(ModMetadata *storage)
1904 if (m_mod_storages.find(storage->getModName()) != m_mod_storages.end()) {
1905 errorstream << "Unable to register same mod storage twice. Storage name: "
1906 << storage->getModName() << std::endl;
1910 m_mod_storages[storage->getModName()] = storage;
1914 void Client::unregisterModStorage(const std::string &name)
1916 UNORDERED_MAP<std::string, ModMetadata *>::const_iterator it = m_mod_storages.find(name);
1917 if (it != m_mod_storages.end()) {
1918 // Save unconditionaly on unregistration
1919 it->second->save(getModStoragePath());
1920 m_mod_storages.erase(name);
1924 std::string Client::getModStoragePath() const
1926 return porting::path_user + DIR_DELIM + "client" + DIR_DELIM + "mod_storage";