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),
107 m_last_chat_message_sent(time(NULL)),
108 m_chat_message_allowance(5.0f),
110 m_password(password),
111 m_chosen_auth_mech(AUTH_MECHANISM_NONE),
113 m_access_denied(false),
114 m_access_denied_reconnect(false),
115 m_itemdef_received(false),
116 m_nodedef_received(false),
117 m_media_downloader(new ClientMediaDownloader()),
118 m_time_of_day_set(false),
119 m_last_time_of_day_f(-1),
120 m_time_of_day_update_timer(0),
121 m_recommended_send_interval(0.1),
122 m_removed_sounds_check_timer(0),
126 m_mod_storage_save_timer(10.0f),
127 m_game_ui_flags(game_ui_flags),
131 m_env.setLocalPlayer(new LocalPlayer(this, playername));
133 if (g_settings->getBool("enable_minimap")) {
134 m_minimap = new Minimap(device, this);
136 m_cache_save_interval = g_settings->getU16("server_map_save_interval");
138 m_modding_enabled = g_settings->getBool("enable_client_modding");
139 m_script = new ClientScripting(this);
140 m_env.setScript(m_script);
141 m_script->setEnv(&m_env);
144 void Client::initMods()
146 m_script->loadMod(getBuiltinLuaPath() + DIR_DELIM "init.lua", BUILTIN_MOD_NAME);
148 // If modding is not enabled, don't load mods, just builtin
149 if (!m_modding_enabled) {
153 ClientModConfiguration modconf(getClientModsLuaPath());
154 std::vector<ModSpec> mods = modconf.getMods();
155 std::vector<ModSpec> unsatisfied_mods = modconf.getUnsatisfiedMods();
156 // complain about mods with unsatisfied dependencies
157 if (!modconf.isConsistent()) {
158 modconf.printUnsatisfiedModsError();
162 infostream << "Client Loading mods: ";
163 for (std::vector<ModSpec>::const_iterator i = mods.begin();
164 i != mods.end(); ++i) {
165 infostream << (*i).name << " ";
168 infostream << std::endl;
169 // Load and run "mod" scripts
170 for (std::vector<ModSpec>::const_iterator it = mods.begin();
171 it != mods.end(); ++it) {
172 const ModSpec &mod = *it;
173 if (!string_allowed(mod.name, MODNAME_ALLOWED_CHARS)) {
174 throw ModError("Error loading mod \"" + mod.name +
175 "\": Mod name does not follow naming conventions: "
176 "Only characters [a-z0-9_] are allowed.");
178 std::string script_path = mod.path + DIR_DELIM + "init.lua";
179 infostream << " [" << padStringRight(mod.name, 12) << "] [\""
180 << script_path << "\"]" << std::endl;
181 m_script->loadMod(script_path, mod.name);
185 const std::string &Client::getBuiltinLuaPath()
187 static const std::string builtin_dir = porting::path_share + DIR_DELIM + "builtin";
191 const std::string &Client::getClientModsLuaPath()
193 static const std::string clientmods_dir = porting::path_share + DIR_DELIM + "clientmods";
194 return clientmods_dir;
197 const std::vector<ModSpec>& Client::getMods() const
199 static std::vector<ModSpec> client_modspec_temp;
200 return client_modspec_temp;
203 const ModSpec* Client::getModSpec(const std::string &modname) const
211 // Don't disable this part when modding is disabled, it's used in builtin
212 m_script->on_shutdown();
213 //request all client managed threads to stop
214 m_mesh_update_thread.stop();
215 // Save local server map
217 infostream << "Local map saving ended." << std::endl;
218 m_localdb->endSave();
224 bool Client::isShutdown()
226 return m_shutdown || !m_mesh_update_thread.isRunning();
234 m_mesh_update_thread.stop();
235 m_mesh_update_thread.wait();
236 while (!m_mesh_update_thread.m_queue_out.empty()) {
237 MeshUpdateResult r = m_mesh_update_thread.m_queue_out.pop_frontNoEx();
242 delete m_inventory_from_server;
244 // Delete detached inventories
245 for (std::unordered_map<std::string, Inventory*>::iterator
246 i = m_detached_inventories.begin();
247 i != m_detached_inventories.end(); ++i) {
251 // cleanup 3d model meshes on client shutdown
252 while (m_device->getSceneManager()->getMeshCache()->getMeshCount() != 0) {
253 scene::IAnimatedMesh *mesh =
254 m_device->getSceneManager()->getMeshCache()->getMeshByIndex(0);
257 m_device->getSceneManager()->getMeshCache()->removeMesh(mesh);
263 void Client::connect(Address address, bool is_local_server)
265 DSTACK(FUNCTION_NAME);
267 initLocalMapSaving(address, m_address_name, is_local_server);
269 m_con.SetTimeoutMs(0);
270 m_con.Connect(address);
273 void Client::step(float dtime)
275 DSTACK(FUNCTION_NAME);
281 if(m_ignore_damage_timer > dtime)
282 m_ignore_damage_timer -= dtime;
284 m_ignore_damage_timer = 0.0;
286 m_animation_time += dtime;
287 if(m_animation_time > 60.0)
288 m_animation_time -= 60.0;
290 m_time_of_day_update_timer += dtime;
298 float &counter = m_packetcounter_timer;
304 infostream << "Client packetcounter (" << m_packetcounter_timer
306 m_packetcounter.print(infostream);
307 m_packetcounter.clear();
311 // UGLY hack to fix 2 second startup delay caused by non existent
312 // server client startup synchronization in local server or singleplayer mode
313 static bool initial_step = true;
315 initial_step = false;
317 else if(m_state == LC_Created) {
318 float &counter = m_connection_reinit_timer;
323 LocalPlayer *myplayer = m_env.getLocalPlayer();
324 FATAL_ERROR_IF(myplayer == NULL, "Local player not found in environment.");
326 u16 proto_version_min = g_settings->getFlag("send_pre_v25_init") ?
327 CLIENT_PROTOCOL_VERSION_MIN_LEGACY : CLIENT_PROTOCOL_VERSION_MIN;
329 if (proto_version_min < 25) {
330 // Send TOSERVER_INIT_LEGACY
331 // [0] u16 TOSERVER_INIT_LEGACY
332 // [2] u8 SER_FMT_VER_HIGHEST_READ
333 // [3] u8[20] player_name
334 // [23] u8[28] password (new in some version)
335 // [51] u16 minimum supported network protocol version (added sometime)
336 // [53] u16 maximum supported network protocol version (added later than the previous one)
338 char pName[PLAYERNAME_SIZE];
339 char pPassword[PASSWORD_SIZE];
340 memset(pName, 0, PLAYERNAME_SIZE * sizeof(char));
341 memset(pPassword, 0, PASSWORD_SIZE * sizeof(char));
343 std::string hashed_password = translate_password(myplayer->getName(), m_password);
344 snprintf(pName, PLAYERNAME_SIZE, "%s", myplayer->getName());
345 snprintf(pPassword, PASSWORD_SIZE, "%s", hashed_password.c_str());
347 sendLegacyInit(pName, pPassword);
349 if (CLIENT_PROTOCOL_VERSION_MAX >= 25)
350 sendInit(myplayer->getName());
353 // Not connected, return
358 Do stuff if connected
362 Run Map's timers and unload unused data
364 const float map_timer_and_unload_dtime = 5.25;
365 if(m_map_timer_and_unload_interval.step(dtime, map_timer_and_unload_dtime)) {
366 ScopeProfiler sp(g_profiler, "Client: map timer and unload");
367 std::vector<v3s16> deleted_blocks;
368 m_env.getMap().timerUpdate(map_timer_and_unload_dtime,
369 g_settings->getFloat("client_unload_unused_data_timeout"),
370 g_settings->getS32("client_mapblock_limit"),
375 NOTE: This loop is intentionally iterated the way it is.
378 std::vector<v3s16>::iterator i = deleted_blocks.begin();
379 std::vector<v3s16> sendlist;
381 if(sendlist.size() == 255 || i == deleted_blocks.end()) {
392 sendDeletedBlocks(sendlist);
394 if(i == deleted_blocks.end())
400 sendlist.push_back(*i);
406 Send pending messages on out chat queue
408 if (!m_out_chat_queue.empty() && canSendChatMessage()) {
409 sendChatMessage(m_out_chat_queue.front());
410 m_out_chat_queue.pop();
416 // Control local player (0ms)
417 LocalPlayer *player = m_env.getLocalPlayer();
418 assert(player != NULL);
419 player->applyControl(dtime);
423 m_sound->step(dtime);
428 while (m_env.hasClientEnvEvents()) {
429 ClientEnvEvent envEvent = m_env.getClientEnvEvent();
431 if (envEvent.type == CEE_PLAYER_DAMAGE) {
432 if (m_ignore_damage_timer <= 0) {
433 u8 damage = envEvent.player_damage.amount;
435 if (envEvent.player_damage.send_to_server)
438 // Add to ClientEvent queue
440 event.type = CE_PLAYER_DAMAGE;
441 event.player_damage.amount = damage;
442 m_client_event_queue.push(event);
445 // Protocol v29 or greater obsoleted this event
446 else if (envEvent.type == CEE_PLAYER_BREATH && m_proto_ver < 29) {
447 u16 breath = envEvent.player_breath.amount;
455 float &counter = m_avg_rtt_timer;
459 // connectedAndInitialized() is true, peer exists.
460 float avg_rtt = getRTT();
461 infostream << "Client: avg_rtt=" << avg_rtt << std::endl;
465 Send player position to server
468 float &counter = m_playerpos_send_timer;
470 if((m_state == LC_Ready) && (counter >= m_recommended_send_interval))
478 Replace updated meshes
481 int num_processed_meshes = 0;
482 while (!m_mesh_update_thread.m_queue_out.empty())
484 num_processed_meshes++;
486 MinimapMapblock *minimap_mapblock = NULL;
487 bool do_mapper_update = true;
489 MeshUpdateResult r = m_mesh_update_thread.m_queue_out.pop_frontNoEx();
490 MapBlock *block = m_env.getMap().getBlockNoCreateNoEx(r.p);
492 // Delete the old mesh
497 minimap_mapblock = r.mesh->moveMinimapMapblock();
498 if (minimap_mapblock == NULL)
499 do_mapper_update = false;
501 bool is_empty = true;
502 for (int l = 0; l < MAX_TILE_LAYERS; l++)
503 if (r.mesh->getMesh(l)->getMeshBufferCount() != 0)
509 // Replace with the new mesh
510 block->mesh = r.mesh;
516 if (m_minimap && do_mapper_update)
517 m_minimap->addBlock(r.p, minimap_mapblock);
519 if (r.ack_block_to_server) {
529 if (num_processed_meshes > 0)
530 g_profiler->graphAdd("num_processed_meshes", num_processed_meshes);
536 if (m_media_downloader && m_media_downloader->isStarted()) {
537 m_media_downloader->step(this);
538 if (m_media_downloader->isDone()) {
539 delete m_media_downloader;
540 m_media_downloader = NULL;
545 If the server didn't update the inventory in a while, revert
546 the local inventory (so the player notices the lag problem
547 and knows something is wrong).
549 if(m_inventory_from_server)
551 float interval = 10.0;
552 float count_before = floor(m_inventory_from_server_age / interval);
554 m_inventory_from_server_age += dtime;
556 float count_after = floor(m_inventory_from_server_age / interval);
558 if(count_after != count_before)
560 // Do this every <interval> seconds after TOCLIENT_INVENTORY
561 // Reset the locally changed inventory to the authoritative inventory
562 LocalPlayer *player = m_env.getLocalPlayer();
563 player->inventory = *m_inventory_from_server;
564 m_inventory_updated = true;
569 Update positions of sounds attached to objects
572 for(std::unordered_map<int, u16>::iterator i = m_sounds_to_objects.begin();
573 i != m_sounds_to_objects.end(); ++i) {
574 int client_id = i->first;
575 u16 object_id = i->second;
576 ClientActiveObject *cao = m_env.getActiveObject(object_id);
579 v3f pos = cao->getPosition();
580 m_sound->updateSoundPosition(client_id, pos);
585 Handle removed remotely initiated sounds
587 m_removed_sounds_check_timer += dtime;
588 if(m_removed_sounds_check_timer >= 2.32) {
589 m_removed_sounds_check_timer = 0;
590 // Find removed sounds and clear references to them
591 std::vector<s32> removed_server_ids;
592 for (std::unordered_map<s32, int>::iterator i = m_sounds_server_to_client.begin();
593 i != m_sounds_server_to_client.end();) {
594 s32 server_id = i->first;
595 int client_id = i->second;
597 if(!m_sound->soundExists(client_id)) {
598 m_sounds_server_to_client.erase(server_id);
599 m_sounds_client_to_server.erase(client_id);
600 m_sounds_to_objects.erase(client_id);
601 removed_server_ids.push_back(server_id);
606 if(!removed_server_ids.empty()) {
607 sendRemovedSounds(removed_server_ids);
611 m_mod_storage_save_timer -= dtime;
612 if (m_mod_storage_save_timer <= 0.0f) {
613 verbosestream << "Saving registered mod storages." << std::endl;
614 m_mod_storage_save_timer = g_settings->getFloat("server_map_save_interval");
615 for (std::unordered_map<std::string, ModMetadata *>::const_iterator
616 it = m_mod_storages.begin(); it != m_mod_storages.end(); ++it) {
617 if (it->second->isModified()) {
618 it->second->save(getModStoragePath());
624 if (m_localdb && m_localdb_save_interval.step(dtime,
625 m_cache_save_interval)) {
626 m_localdb->endSave();
627 m_localdb->beginSave();
631 bool Client::loadMedia(const std::string &data, const std::string &filename)
633 // Silly irrlicht's const-incorrectness
634 Buffer<char> data_rw(data.c_str(), data.size());
638 const char *image_ext[] = {
639 ".png", ".jpg", ".bmp", ".tga",
640 ".pcx", ".ppm", ".psd", ".wal", ".rgb",
643 name = removeStringEnd(filename, image_ext);
646 verbosestream<<"Client: Attempting to load image "
647 <<"file \""<<filename<<"\""<<std::endl;
649 io::IFileSystem *irrfs = m_device->getFileSystem();
650 video::IVideoDriver *vdrv = m_device->getVideoDriver();
652 // Create an irrlicht memory file
653 io::IReadFile *rfile = irrfs->createMemoryReadFile(
654 *data_rw, data_rw.getSize(), "_tempreadfile");
656 FATAL_ERROR_IF(!rfile, "Could not create irrlicht memory file.");
659 video::IImage *img = vdrv->createImageFromFile(rfile);
661 errorstream<<"Client: Cannot create image from data of "
662 <<"file \""<<filename<<"\""<<std::endl;
667 m_tsrc->insertSourceImage(filename, img);
674 const char *sound_ext[] = {
675 ".0.ogg", ".1.ogg", ".2.ogg", ".3.ogg", ".4.ogg",
676 ".5.ogg", ".6.ogg", ".7.ogg", ".8.ogg", ".9.ogg",
679 name = removeStringEnd(filename, sound_ext);
682 verbosestream<<"Client: Attempting to load sound "
683 <<"file \""<<filename<<"\""<<std::endl;
684 m_sound->loadSoundData(name, data);
688 const char *model_ext[] = {
689 ".x", ".b3d", ".md2", ".obj",
692 name = removeStringEnd(filename, model_ext);
695 verbosestream<<"Client: Storing model into memory: "
696 <<"\""<<filename<<"\""<<std::endl;
697 if(m_mesh_data.count(filename))
698 errorstream<<"Multiple models with name \""<<filename.c_str()
699 <<"\" found; replacing previous model"<<std::endl;
700 m_mesh_data[filename] = data;
704 errorstream<<"Client: Don't know how to load file \""
705 <<filename<<"\""<<std::endl;
709 // Virtual methods from con::PeerHandler
710 void Client::peerAdded(con::Peer *peer)
712 infostream << "Client::peerAdded(): peer->id="
713 << peer->id << std::endl;
715 void Client::deletingPeer(con::Peer *peer, bool timeout)
717 infostream << "Client::deletingPeer(): "
718 "Server Peer is getting deleted "
719 << "(timeout=" << timeout << ")" << std::endl;
722 m_access_denied = true;
723 m_access_denied_reason = gettext("Connection timed out.");
729 u16 number of files requested
735 void Client::request_media(const std::vector<std::string> &file_requests)
737 std::ostringstream os(std::ios_base::binary);
738 writeU16(os, TOSERVER_REQUEST_MEDIA);
739 size_t file_requests_size = file_requests.size();
741 FATAL_ERROR_IF(file_requests_size > 0xFFFF, "Unsupported number of file requests");
743 // Packet dynamicly resized
744 NetworkPacket pkt(TOSERVER_REQUEST_MEDIA, 2 + 0);
746 pkt << (u16) (file_requests_size & 0xFFFF);
748 for(std::vector<std::string>::const_iterator i = file_requests.begin();
749 i != file_requests.end(); ++i) {
755 infostream << "Client: Sending media request list to server ("
756 << file_requests.size() << " files. packet size)" << std::endl;
759 void Client::initLocalMapSaving(const Address &address,
760 const std::string &hostname,
761 bool is_local_server)
763 if (!g_settings->getBool("enable_local_map_saving") || is_local_server) {
767 const std::string world_path = porting::path_user
768 + DIR_DELIM + "worlds"
769 + DIR_DELIM + "server_"
770 + hostname + "_" + std::to_string(address.getPort());
772 fs::CreateAllDirs(world_path);
774 m_localdb = new MapDatabaseSQLite3(world_path);
775 m_localdb->beginSave();
776 actionstream << "Local map saving started, map will be saved at '" << world_path << "'" << std::endl;
779 void Client::ReceiveAll()
781 DSTACK(FUNCTION_NAME);
782 u64 start_ms = porting::getTimeMs();
785 // Limit time even if there would be huge amounts of data to
787 if(porting::getTimeMs() > start_ms + 100)
792 g_profiler->graphAdd("client_received_packets", 1);
794 catch(con::NoIncomingDataException &e) {
797 catch(con::InvalidIncomingDataException &e) {
798 infostream<<"Client::ReceiveAll(): "
799 "InvalidIncomingDataException: what()="
800 <<e.what()<<std::endl;
805 void Client::Receive()
807 DSTACK(FUNCTION_NAME);
813 inline void Client::handleCommand(NetworkPacket* pkt)
815 const ToClientCommandHandler& opHandle = toClientCommandTable[pkt->getCommand()];
816 (this->*opHandle.handler)(pkt);
820 sender_peer_id given to this shall be quaranteed to be a valid peer
822 void Client::ProcessData(NetworkPacket *pkt)
824 DSTACK(FUNCTION_NAME);
826 ToClientCommand command = (ToClientCommand) pkt->getCommand();
827 u32 sender_peer_id = pkt->getPeerId();
829 //infostream<<"Client: received command="<<command<<std::endl;
830 m_packetcounter.add((u16)command);
833 If this check is removed, be sure to change the queue
834 system to know the ids
836 if(sender_peer_id != PEER_ID_SERVER) {
837 infostream << "Client::ProcessData(): Discarding data not "
838 "coming from server: peer_id=" << sender_peer_id
843 // Command must be handled into ToClientCommandHandler
844 if (command >= TOCLIENT_NUM_MSG_TYPES) {
845 infostream << "Client: Ignoring unknown command "
846 << command << std::endl;
851 * Those packets are handled before m_server_ser_ver is set, it's normal
852 * But we must use the new ToClientConnectionState in the future,
855 if(toClientCommandTable[command].state == TOCLIENT_STATE_NOT_CONNECTED) {
860 if(m_server_ser_ver == SER_FMT_VER_INVALID) {
861 infostream << "Client: Server serialization"
862 " format invalid or not initialized."
863 " Skipping incoming command=" << command << std::endl;
868 Handle runtime commands
874 void Client::Send(NetworkPacket* pkt)
876 m_con.Send(PEER_ID_SERVER,
877 serverCommandFactoryTable[pkt->getCommand()].channel,
879 serverCommandFactoryTable[pkt->getCommand()].reliable);
882 // Will fill up 12 + 12 + 4 + 4 + 4 bytes
883 void writePlayerPos(LocalPlayer *myplayer, ClientMap *clientMap, NetworkPacket *pkt)
885 v3f pf = myplayer->getPosition() * 100;
886 v3f sf = myplayer->getSpeed() * 100;
887 s32 pitch = myplayer->getPitch() * 100;
888 s32 yaw = myplayer->getYaw() * 100;
889 u32 keyPressed = myplayer->keyPressed;
890 // scaled by 80, so that pi can fit into a u8
891 u8 fov = clientMap->getCameraFov() * 80;
892 u8 wanted_range = MYMIN(255,
893 std::ceil(clientMap->getControl().wanted_range / MAP_BLOCKSIZE));
895 v3s32 position(pf.X, pf.Y, pf.Z);
896 v3s32 speed(sf.X, sf.Y, sf.Z);
900 [0] v3s32 position*100
902 [12+12] s32 pitch*100
903 [12+12+4] s32 yaw*100
904 [12+12+4+4] u32 keyPressed
905 [12+12+4+4+4] u8 fov*80
906 [12+12+4+4+4+1] u8 ceil(wanted_range / MAP_BLOCKSIZE)
908 *pkt << position << speed << pitch << yaw << keyPressed;
909 *pkt << fov << wanted_range;
912 void Client::interact(u8 action, const PointedThing& pointed)
914 if(m_state != LC_Ready) {
915 errorstream << "Client::interact() "
916 "Canceled (not connected)"
921 LocalPlayer *myplayer = m_env.getLocalPlayer();
922 if (myplayer == NULL)
929 [5] u32 length of the next item (plen)
930 [9] serialized PointedThing
931 [9 + plen] player position information
933 0: start digging (from undersurface) or use
934 1: stop digging (all parameters ignored)
936 3: place block or item (to abovesurface)
938 5: perform secondary action of item
941 NetworkPacket pkt(TOSERVER_INTERACT, 1 + 2 + 0);
944 pkt << (u16)getPlayerItem();
946 std::ostringstream tmp_os(std::ios::binary);
947 pointed.serialize(tmp_os);
949 pkt.putLongString(tmp_os.str());
951 writePlayerPos(myplayer, &m_env.getClientMap(), &pkt);
956 void Client::deleteAuthData()
961 switch (m_chosen_auth_mech) {
962 case AUTH_MECHANISM_FIRST_SRP:
964 case AUTH_MECHANISM_SRP:
965 case AUTH_MECHANISM_LEGACY_PASSWORD:
966 srp_user_delete((SRPUser *) m_auth_data);
969 case AUTH_MECHANISM_NONE:
972 m_chosen_auth_mech = AUTH_MECHANISM_NONE;
976 AuthMechanism Client::choseAuthMech(const u32 mechs)
978 if (mechs & AUTH_MECHANISM_SRP)
979 return AUTH_MECHANISM_SRP;
981 if (mechs & AUTH_MECHANISM_FIRST_SRP)
982 return AUTH_MECHANISM_FIRST_SRP;
984 if (mechs & AUTH_MECHANISM_LEGACY_PASSWORD)
985 return AUTH_MECHANISM_LEGACY_PASSWORD;
987 return AUTH_MECHANISM_NONE;
990 void Client::sendLegacyInit(const char* playerName, const char* playerPassword)
992 NetworkPacket pkt(TOSERVER_INIT_LEGACY,
993 1 + PLAYERNAME_SIZE + PASSWORD_SIZE + 2 + 2);
995 u16 proto_version_min = g_settings->getFlag("send_pre_v25_init") ?
996 CLIENT_PROTOCOL_VERSION_MIN_LEGACY : CLIENT_PROTOCOL_VERSION_MIN;
998 pkt << (u8) SER_FMT_VER_HIGHEST_READ;
999 pkt.putRawString(playerName,PLAYERNAME_SIZE);
1000 pkt.putRawString(playerPassword, PASSWORD_SIZE);
1001 pkt << (u16) proto_version_min << (u16) CLIENT_PROTOCOL_VERSION_MAX;
1006 void Client::sendInit(const std::string &playerName)
1008 NetworkPacket pkt(TOSERVER_INIT, 1 + 2 + 2 + (1 + playerName.size()));
1010 // we don't support network compression yet
1011 u16 supp_comp_modes = NETPROTO_COMPRESSION_NONE;
1013 u16 proto_version_min = g_settings->getFlag("send_pre_v25_init") ?
1014 CLIENT_PROTOCOL_VERSION_MIN_LEGACY : CLIENT_PROTOCOL_VERSION_MIN;
1016 pkt << (u8) SER_FMT_VER_HIGHEST_READ << (u16) supp_comp_modes;
1017 pkt << (u16) proto_version_min << (u16) CLIENT_PROTOCOL_VERSION_MAX;
1023 void Client::startAuth(AuthMechanism chosen_auth_mechanism)
1025 m_chosen_auth_mech = chosen_auth_mechanism;
1027 switch (chosen_auth_mechanism) {
1028 case AUTH_MECHANISM_FIRST_SRP: {
1029 // send srp verifier to server
1030 std::string verifier;
1032 generate_srp_verifier_and_salt(getPlayerName(), m_password,
1035 NetworkPacket resp_pkt(TOSERVER_FIRST_SRP, 0);
1036 resp_pkt << salt << verifier << (u8)((m_password == "") ? 1 : 0);
1041 case AUTH_MECHANISM_SRP:
1042 case AUTH_MECHANISM_LEGACY_PASSWORD: {
1045 if (chosen_auth_mechanism == AUTH_MECHANISM_LEGACY_PASSWORD) {
1046 m_password = translate_password(getPlayerName(), m_password);
1050 std::string playername_u = lowercase(getPlayerName());
1051 m_auth_data = srp_user_new(SRP_SHA256, SRP_NG_2048,
1052 getPlayerName().c_str(), playername_u.c_str(),
1053 (const unsigned char *) m_password.c_str(),
1054 m_password.length(), NULL, NULL);
1057 SRP_Result res = srp_user_start_authentication(
1058 (struct SRPUser *) m_auth_data, NULL, NULL, 0,
1059 (unsigned char **) &bytes_A, &len_A);
1060 FATAL_ERROR_IF(res != SRP_OK, "Creating local SRP user failed.");
1062 NetworkPacket resp_pkt(TOSERVER_SRP_BYTES_A, 0);
1063 resp_pkt << std::string(bytes_A, len_A) << based_on;
1067 case AUTH_MECHANISM_NONE:
1068 break; // not handled in this method
1072 void Client::sendDeletedBlocks(std::vector<v3s16> &blocks)
1074 NetworkPacket pkt(TOSERVER_DELETEDBLOCKS, 1 + sizeof(v3s16) * blocks.size());
1076 pkt << (u8) blocks.size();
1079 for(std::vector<v3s16>::iterator
1081 j != blocks.end(); ++j) {
1089 void Client::sendGotBlocks(v3s16 block)
1091 NetworkPacket pkt(TOSERVER_GOTBLOCKS, 1 + 6);
1092 pkt << (u8) 1 << block;
1096 void Client::sendRemovedSounds(std::vector<s32> &soundList)
1098 size_t server_ids = soundList.size();
1099 assert(server_ids <= 0xFFFF);
1101 NetworkPacket pkt(TOSERVER_REMOVED_SOUNDS, 2 + server_ids * 4);
1103 pkt << (u16) (server_ids & 0xFFFF);
1105 for(std::vector<s32>::iterator i = soundList.begin();
1106 i != soundList.end(); ++i)
1112 void Client::sendNodemetaFields(v3s16 p, const std::string &formname,
1113 const StringMap &fields)
1115 size_t fields_size = fields.size();
1117 FATAL_ERROR_IF(fields_size > 0xFFFF, "Unsupported number of nodemeta fields");
1119 NetworkPacket pkt(TOSERVER_NODEMETA_FIELDS, 0);
1121 pkt << p << formname << (u16) (fields_size & 0xFFFF);
1123 StringMap::const_iterator it;
1124 for (it = fields.begin(); it != fields.end(); ++it) {
1125 const std::string &name = it->first;
1126 const std::string &value = it->second;
1128 pkt.putLongString(value);
1134 void Client::sendInventoryFields(const std::string &formname,
1135 const StringMap &fields)
1137 size_t fields_size = fields.size();
1138 FATAL_ERROR_IF(fields_size > 0xFFFF, "Unsupported number of inventory fields");
1140 NetworkPacket pkt(TOSERVER_INVENTORY_FIELDS, 0);
1141 pkt << formname << (u16) (fields_size & 0xFFFF);
1143 StringMap::const_iterator it;
1144 for (it = fields.begin(); it != fields.end(); ++it) {
1145 const std::string &name = it->first;
1146 const std::string &value = it->second;
1148 pkt.putLongString(value);
1154 void Client::sendInventoryAction(InventoryAction *a)
1156 std::ostringstream os(std::ios_base::binary);
1161 std::string s = os.str();
1163 NetworkPacket pkt(TOSERVER_INVENTORY_ACTION, s.size());
1164 pkt.putRawString(s.c_str(),s.size());
1169 bool Client::canSendChatMessage() const
1171 u32 now = time(NULL);
1172 float time_passed = now - m_last_chat_message_sent;
1174 float virt_chat_message_allowance = m_chat_message_allowance + time_passed *
1175 (CLIENT_CHAT_MESSAGE_LIMIT_PER_10S / 8.0f);
1177 if (virt_chat_message_allowance < 1.0f)
1183 void Client::sendChatMessage(const std::wstring &message)
1185 const s16 max_queue_size = g_settings->getS16("max_out_chat_queue_size");
1186 if (canSendChatMessage()) {
1187 u32 now = time(NULL);
1188 float time_passed = now - m_last_chat_message_sent;
1189 m_last_chat_message_sent = time(NULL);
1191 m_chat_message_allowance += time_passed * (CLIENT_CHAT_MESSAGE_LIMIT_PER_10S / 8.0f);
1192 if (m_chat_message_allowance > CLIENT_CHAT_MESSAGE_LIMIT_PER_10S)
1193 m_chat_message_allowance = CLIENT_CHAT_MESSAGE_LIMIT_PER_10S;
1195 m_chat_message_allowance -= 1.0f;
1197 NetworkPacket pkt(TOSERVER_CHAT_MESSAGE, 2 + message.size() * sizeof(u16));
1202 } else if (m_out_chat_queue.size() < (u16) max_queue_size || max_queue_size == -1) {
1203 m_out_chat_queue.push(message);
1205 infostream << "Could not queue chat message because maximum out chat queue size ("
1206 << max_queue_size << ") is reached." << std::endl;
1210 void Client::clearOutChatQueue()
1212 m_out_chat_queue = std::queue<std::wstring>();
1215 void Client::sendChangePassword(const std::string &oldpassword,
1216 const std::string &newpassword)
1218 LocalPlayer *player = m_env.getLocalPlayer();
1222 std::string playername = player->getName();
1223 if (m_proto_ver >= 25) {
1224 // get into sudo mode and then send new password to server
1225 m_password = oldpassword;
1226 m_new_password = newpassword;
1227 startAuth(choseAuthMech(m_sudo_auth_methods));
1229 std::string oldpwd = translate_password(playername, oldpassword);
1230 std::string newpwd = translate_password(playername, newpassword);
1232 NetworkPacket pkt(TOSERVER_PASSWORD_LEGACY, 2 * PASSWORD_SIZE);
1234 for (u8 i = 0; i < PASSWORD_SIZE; i++) {
1235 pkt << (u8) (i < oldpwd.length() ? oldpwd[i] : 0);
1238 for (u8 i = 0; i < PASSWORD_SIZE; i++) {
1239 pkt << (u8) (i < newpwd.length() ? newpwd[i] : 0);
1246 void Client::sendDamage(u8 damage)
1248 DSTACK(FUNCTION_NAME);
1250 NetworkPacket pkt(TOSERVER_DAMAGE, sizeof(u8));
1255 void Client::sendBreath(u16 breath)
1257 DSTACK(FUNCTION_NAME);
1259 // Protocol v29 make this obsolete
1260 if (m_proto_ver >= 29)
1263 NetworkPacket pkt(TOSERVER_BREATH, sizeof(u16));
1268 void Client::sendRespawn()
1270 DSTACK(FUNCTION_NAME);
1272 NetworkPacket pkt(TOSERVER_RESPAWN, 0);
1276 void Client::sendReady()
1278 DSTACK(FUNCTION_NAME);
1280 NetworkPacket pkt(TOSERVER_CLIENT_READY,
1281 1 + 1 + 1 + 1 + 2 + sizeof(char) * strlen(g_version_hash));
1283 pkt << (u8) VERSION_MAJOR << (u8) VERSION_MINOR << (u8) VERSION_PATCH
1284 << (u8) 0 << (u16) strlen(g_version_hash);
1286 pkt.putRawString(g_version_hash, (u16) strlen(g_version_hash));
1290 void Client::sendPlayerPos()
1292 LocalPlayer *myplayer = m_env.getLocalPlayer();
1293 if(myplayer == NULL)
1296 ClientMap &map = m_env.getClientMap();
1298 u8 camera_fov = map.getCameraFov();
1299 u8 wanted_range = map.getControl().wanted_range;
1301 // Save bandwidth by only updating position when something changed
1302 if(myplayer->last_position == myplayer->getPosition() &&
1303 myplayer->last_speed == myplayer->getSpeed() &&
1304 myplayer->last_pitch == myplayer->getPitch() &&
1305 myplayer->last_yaw == myplayer->getYaw() &&
1306 myplayer->last_keyPressed == myplayer->keyPressed &&
1307 myplayer->last_camera_fov == camera_fov &&
1308 myplayer->last_wanted_range == wanted_range)
1311 myplayer->last_position = myplayer->getPosition();
1312 myplayer->last_speed = myplayer->getSpeed();
1313 myplayer->last_pitch = myplayer->getPitch();
1314 myplayer->last_yaw = myplayer->getYaw();
1315 myplayer->last_keyPressed = myplayer->keyPressed;
1316 myplayer->last_camera_fov = camera_fov;
1317 myplayer->last_wanted_range = wanted_range;
1319 //infostream << "Sending Player Position information" << std::endl;
1323 //MutexAutoLock lock(m_con_mutex); //bulk comment-out
1324 our_peer_id = m_con.GetPeerID();
1327 // Set peer id if not set already
1328 if(myplayer->peer_id == PEER_ID_INEXISTENT)
1329 myplayer->peer_id = our_peer_id;
1331 assert(myplayer->peer_id == our_peer_id);
1333 NetworkPacket pkt(TOSERVER_PLAYERPOS, 12 + 12 + 4 + 4 + 4 + 1 + 1);
1335 writePlayerPos(myplayer, &map, &pkt);
1340 void Client::sendPlayerItem(u16 item)
1342 LocalPlayer *myplayer = m_env.getLocalPlayer();
1343 if(myplayer == NULL)
1346 u16 our_peer_id = m_con.GetPeerID();
1348 // Set peer id if not set already
1349 if(myplayer->peer_id == PEER_ID_INEXISTENT)
1350 myplayer->peer_id = our_peer_id;
1351 assert(myplayer->peer_id == our_peer_id);
1353 NetworkPacket pkt(TOSERVER_PLAYERITEM, 2);
1360 void Client::removeNode(v3s16 p)
1362 std::map<v3s16, MapBlock*> modified_blocks;
1365 m_env.getMap().removeNodeAndUpdate(p, modified_blocks);
1367 catch(InvalidPositionException &e) {
1370 for(std::map<v3s16, MapBlock *>::iterator
1371 i = modified_blocks.begin();
1372 i != modified_blocks.end(); ++i) {
1373 addUpdateMeshTaskWithEdge(i->first, false, true);
1377 MapNode Client::getNode(v3s16 p, bool *is_valid_position)
1379 return m_env.getMap().getNodeNoEx(p, is_valid_position);
1382 void Client::addNode(v3s16 p, MapNode n, bool remove_metadata)
1384 //TimeTaker timer1("Client::addNode()");
1386 std::map<v3s16, MapBlock*> modified_blocks;
1389 //TimeTaker timer3("Client::addNode(): addNodeAndUpdate");
1390 m_env.getMap().addNodeAndUpdate(p, n, modified_blocks, remove_metadata);
1392 catch(InvalidPositionException &e) {
1395 for(std::map<v3s16, MapBlock *>::iterator
1396 i = modified_blocks.begin();
1397 i != modified_blocks.end(); ++i) {
1398 addUpdateMeshTaskWithEdge(i->first, false, true);
1402 void Client::setPlayerControl(PlayerControl &control)
1404 LocalPlayer *player = m_env.getLocalPlayer();
1405 assert(player != NULL);
1406 player->control = control;
1409 void Client::selectPlayerItem(u16 item)
1411 m_playeritem = item;
1412 m_inventory_updated = true;
1413 sendPlayerItem(item);
1416 // Returns true if the inventory of the local player has been
1417 // updated from the server. If it is true, it is set to false.
1418 bool Client::getLocalInventoryUpdated()
1420 bool updated = m_inventory_updated;
1421 m_inventory_updated = false;
1425 // Copies the inventory of the local player to parameter
1426 void Client::getLocalInventory(Inventory &dst)
1428 LocalPlayer *player = m_env.getLocalPlayer();
1429 assert(player != NULL);
1430 dst = player->inventory;
1433 Inventory* Client::getInventory(const InventoryLocation &loc)
1436 case InventoryLocation::UNDEFINED:
1439 case InventoryLocation::CURRENT_PLAYER:
1441 LocalPlayer *player = m_env.getLocalPlayer();
1442 assert(player != NULL);
1443 return &player->inventory;
1446 case InventoryLocation::PLAYER:
1448 // Check if we are working with local player inventory
1449 LocalPlayer *player = m_env.getLocalPlayer();
1450 if (!player || strcmp(player->getName(), loc.name.c_str()) != 0)
1452 return &player->inventory;
1455 case InventoryLocation::NODEMETA:
1457 NodeMetadata *meta = m_env.getMap().getNodeMetadata(loc.p);
1460 return meta->getInventory();
1463 case InventoryLocation::DETACHED:
1465 if (m_detached_inventories.count(loc.name) == 0)
1467 return m_detached_inventories[loc.name];
1471 FATAL_ERROR("Invalid inventory location type.");
1477 void Client::inventoryAction(InventoryAction *a)
1480 Send it to the server
1482 sendInventoryAction(a);
1485 Predict some local inventory changes
1487 a->clientApply(this, this);
1493 float Client::getAnimationTime()
1495 return m_animation_time;
1498 int Client::getCrackLevel()
1500 return m_crack_level;
1503 v3s16 Client::getCrackPos()
1508 void Client::setCrack(int level, v3s16 pos)
1510 int old_crack_level = m_crack_level;
1511 v3s16 old_crack_pos = m_crack_pos;
1513 m_crack_level = level;
1516 if(old_crack_level >= 0 && (level < 0 || pos != old_crack_pos))
1519 addUpdateMeshTaskForNode(old_crack_pos, false, true);
1521 if(level >= 0 && (old_crack_level < 0 || pos != old_crack_pos))
1524 addUpdateMeshTaskForNode(pos, false, true);
1530 LocalPlayer *player = m_env.getLocalPlayer();
1531 assert(player != NULL);
1535 bool Client::getChatMessage(std::wstring &message)
1537 if(m_chat_queue.size() == 0)
1539 message = m_chat_queue.front();
1544 void Client::typeChatMessage(const std::wstring &message)
1546 // Discard empty line
1550 // If message was ate by script API, don't send it to server
1551 if (m_script->on_sending_message(wide_to_utf8(message))) {
1556 sendChatMessage(message);
1559 if (message[0] != L'/')
1561 // compatibility code
1562 if (m_proto_ver < 29) {
1563 LocalPlayer *player = m_env.getLocalPlayer();
1564 assert(player != NULL);
1565 std::wstring name = narrow_to_wide(player->getName());
1566 pushToChatQueue((std::wstring)L"<" + name + L"> " + message);
1571 void Client::addUpdateMeshTask(v3s16 p, bool ack_to_server, bool urgent)
1573 // Check if the block exists to begin with. In the case when a non-existing
1574 // neighbor is automatically added, it may not. In that case we don't want
1575 // to tell the mesh update thread about it.
1576 MapBlock *b = m_env.getMap().getBlockNoCreateNoEx(p);
1580 m_mesh_update_thread.updateBlock(&m_env.getMap(), p, ack_to_server, urgent);
1583 void Client::addUpdateMeshTaskWithEdge(v3s16 blockpos, bool ack_to_server, bool urgent)
1586 addUpdateMeshTask(blockpos, ack_to_server, urgent);
1588 catch(InvalidPositionException &e){}
1591 for (int i=0;i<6;i++)
1594 v3s16 p = blockpos + g_6dirs[i];
1595 addUpdateMeshTask(p, false, urgent);
1597 catch(InvalidPositionException &e){}
1601 void Client::addUpdateMeshTaskForNode(v3s16 nodepos, bool ack_to_server, bool urgent)
1605 infostream<<"Client::addUpdateMeshTaskForNode(): "
1606 <<"("<<p.X<<","<<p.Y<<","<<p.Z<<")"
1610 v3s16 blockpos = getNodeBlockPos(nodepos);
1611 v3s16 blockpos_relative = blockpos * MAP_BLOCKSIZE;
1614 addUpdateMeshTask(blockpos, ack_to_server, urgent);
1616 catch(InvalidPositionException &e) {}
1619 if(nodepos.X == blockpos_relative.X){
1621 v3s16 p = blockpos + v3s16(-1,0,0);
1622 addUpdateMeshTask(p, false, urgent);
1624 catch(InvalidPositionException &e){}
1627 if(nodepos.Y == blockpos_relative.Y){
1629 v3s16 p = blockpos + v3s16(0,-1,0);
1630 addUpdateMeshTask(p, false, urgent);
1632 catch(InvalidPositionException &e){}
1635 if(nodepos.Z == blockpos_relative.Z){
1637 v3s16 p = blockpos + v3s16(0,0,-1);
1638 addUpdateMeshTask(p, false, urgent);
1640 catch(InvalidPositionException &e){}
1644 ClientEvent Client::getClientEvent()
1646 FATAL_ERROR_IF(m_client_event_queue.empty(),
1647 "Cannot getClientEvent, queue is empty.");
1649 ClientEvent event = m_client_event_queue.front();
1650 m_client_event_queue.pop();
1654 float Client::mediaReceiveProgress()
1656 if (m_media_downloader)
1657 return m_media_downloader->getProgress();
1659 return 1.0; // downloader only exists when not yet done
1662 typedef struct TextureUpdateArgs {
1663 IrrlichtDevice *device;
1664 gui::IGUIEnvironment *guienv;
1667 const wchar_t* text_base;
1668 ITextureSource *tsrc;
1669 } TextureUpdateArgs;
1671 void texture_update_progress(void *args, u32 progress, u32 max_progress)
1673 TextureUpdateArgs* targs = (TextureUpdateArgs*) args;
1674 u16 cur_percent = ceil(progress / (double) max_progress * 100.);
1676 // update the loading menu -- if neccessary
1677 bool do_draw = false;
1678 u64 time_ms = targs->last_time_ms;
1679 if (cur_percent != targs->last_percent) {
1680 targs->last_percent = cur_percent;
1681 time_ms = porting::getTimeMs();
1682 // only draw when the user will notice something:
1683 do_draw = (time_ms - targs->last_time_ms > 100);
1687 targs->last_time_ms = time_ms;
1688 std::basic_stringstream<wchar_t> strm;
1689 strm << targs->text_base << " " << targs->last_percent << "%...";
1690 draw_load_screen(strm.str(), targs->device, targs->guienv, targs->tsrc, 0,
1691 72 + (u16) ((18. / 100.) * (double) targs->last_percent), true);
1695 void Client::afterContentReceived(IrrlichtDevice *device)
1697 infostream<<"Client::afterContentReceived() started"<<std::endl;
1698 assert(m_itemdef_received); // pre-condition
1699 assert(m_nodedef_received); // pre-condition
1700 assert(mediaReceived()); // pre-condition
1702 const wchar_t* text = wgettext("Loading textures...");
1704 // Clear cached pre-scaled 2D GUI images, as this cache
1705 // might have images with the same name but different
1706 // content from previous sessions.
1707 guiScalingCacheClear(device->getVideoDriver());
1709 // Rebuild inherited images and recreate textures
1710 infostream<<"- Rebuilding images and textures"<<std::endl;
1711 draw_load_screen(text,device, guienv, m_tsrc, 0, 70);
1712 m_tsrc->rebuildImagesAndTextures();
1716 infostream<<"- Rebuilding shaders"<<std::endl;
1717 text = wgettext("Rebuilding shaders...");
1718 draw_load_screen(text, device, guienv, m_tsrc, 0, 71);
1719 m_shsrc->rebuildShaders();
1722 // Update node aliases
1723 infostream<<"- Updating node aliases"<<std::endl;
1724 text = wgettext("Initializing nodes...");
1725 draw_load_screen(text, device, guienv, m_tsrc, 0, 72);
1726 m_nodedef->updateAliases(m_itemdef);
1727 std::string texture_path = g_settings->get("texture_path");
1728 if (texture_path != "" && fs::IsDir(texture_path))
1729 m_nodedef->applyTextureOverrides(texture_path + DIR_DELIM + "override.txt");
1730 m_nodedef->setNodeRegistrationStatus(true);
1731 m_nodedef->runNodeResolveCallbacks();
1734 // Update node textures and assign shaders to each tile
1735 infostream<<"- Updating node textures"<<std::endl;
1736 TextureUpdateArgs tu_args;
1737 tu_args.device = device;
1738 tu_args.guienv = guienv;
1739 tu_args.last_time_ms = porting::getTimeMs();
1740 tu_args.last_percent = 0;
1741 tu_args.text_base = wgettext("Initializing nodes");
1742 tu_args.tsrc = m_tsrc;
1743 m_nodedef->updateTextures(this, texture_update_progress, &tu_args);
1744 delete[] tu_args.text_base;
1746 // Start mesh update thread after setting up content definitions
1747 infostream<<"- Starting mesh update thread"<<std::endl;
1748 m_mesh_update_thread.start();
1753 if (g_settings->getBool("enable_client_modding")) {
1754 m_script->on_client_ready(m_env.getLocalPlayer());
1755 m_script->on_connect();
1758 text = wgettext("Done!");
1759 draw_load_screen(text, device, guienv, m_tsrc, 0, 100);
1760 infostream<<"Client::afterContentReceived() done"<<std::endl;
1764 float Client::getRTT()
1766 return m_con.getPeerStat(PEER_ID_SERVER,con::AVG_RTT);
1769 float Client::getCurRate()
1771 return (m_con.getLocalStat(con::CUR_INC_RATE) +
1772 m_con.getLocalStat(con::CUR_DL_RATE));
1775 void Client::makeScreenshot(IrrlichtDevice *device)
1777 irr::video::IVideoDriver *driver = device->getVideoDriver();
1778 irr::video::IImage* const raw_image = driver->createScreenShot();
1783 time_t t = time(NULL);
1784 struct tm *tm = localtime(&t);
1786 char timetstamp_c[64];
1787 strftime(timetstamp_c, sizeof(timetstamp_c), "%Y%m%d_%H%M%S", tm);
1789 std::string filename_base = g_settings->get("screenshot_path")
1791 + std::string("screenshot_")
1792 + std::string(timetstamp_c);
1793 std::string filename_ext = "." + g_settings->get("screenshot_format");
1794 std::string filename;
1796 u32 quality = (u32)g_settings->getS32("screenshot_quality");
1797 quality = MYMIN(MYMAX(quality, 0), 100) / 100.0 * 255;
1799 // Try to find a unique filename
1800 unsigned serial = 0;
1802 while (serial < SCREENSHOT_MAX_SERIAL_TRIES) {
1803 filename = filename_base + (serial > 0 ? ("_" + itos(serial)) : "") + filename_ext;
1804 std::ifstream tmp(filename.c_str());
1806 break; // File did not apparently exist, we'll go with it
1810 if (serial == SCREENSHOT_MAX_SERIAL_TRIES) {
1811 infostream << "Could not find suitable filename for screenshot" << std::endl;
1813 irr::video::IImage* const image =
1814 driver->createImage(video::ECF_R8G8B8, raw_image->getDimension());
1817 raw_image->copyTo(image);
1819 std::ostringstream sstr;
1820 if (driver->writeImageToFile(image, filename.c_str(), quality)) {
1821 sstr << "Saved screenshot to '" << filename << "'";
1823 sstr << "Failed to save screenshot '" << filename << "'";
1825 pushToChatQueue(narrow_to_wide(sstr.str()));
1826 infostream << sstr.str() << std::endl;
1834 bool Client::shouldShowMinimap() const
1836 return !m_minimap_disabled_by_server;
1839 void Client::showGameChat(const bool show)
1841 m_game_ui_flags->show_chat = show;
1844 void Client::showGameHud(const bool show)
1846 m_game_ui_flags->show_hud = show;
1849 void Client::showMinimap(const bool show)
1851 m_game_ui_flags->show_minimap = show;
1854 void Client::showProfiler(const bool show)
1856 m_game_ui_flags->show_profiler_graph = show;
1859 void Client::showGameFog(const bool show)
1861 m_game_ui_flags->force_fog_off = !show;
1864 void Client::showGameDebug(const bool show)
1866 m_game_ui_flags->show_debug = show;
1869 // IGameDef interface
1871 IItemDefManager* Client::getItemDefManager()
1875 INodeDefManager* Client::getNodeDefManager()
1879 ICraftDefManager* Client::getCraftDefManager()
1882 //return m_craftdef;
1884 ITextureSource* Client::getTextureSource()
1888 IShaderSource* Client::getShaderSource()
1892 scene::ISceneManager* Client::getSceneManager()
1894 return m_device->getSceneManager();
1896 u16 Client::allocateUnknownNodeId(const std::string &name)
1898 errorstream << "Client::allocateUnknownNodeId(): "
1899 << "Client cannot allocate node IDs" << std::endl;
1900 FATAL_ERROR("Client allocated unknown node");
1902 return CONTENT_IGNORE;
1904 ISoundManager* Client::getSoundManager()
1908 MtEventManager* Client::getEventManager()
1913 ParticleManager* Client::getParticleManager()
1915 return &m_particle_manager;
1918 scene::IAnimatedMesh* Client::getMesh(const std::string &filename)
1920 StringMap::const_iterator it = m_mesh_data.find(filename);
1921 if (it == m_mesh_data.end()) {
1922 errorstream << "Client::getMesh(): Mesh not found: \"" << filename
1923 << "\"" << std::endl;
1926 const std::string &data = it->second;
1927 scene::ISceneManager *smgr = m_device->getSceneManager();
1929 // Create the mesh, remove it from cache and return it
1930 // This allows unique vertex colors and other properties for each instance
1931 Buffer<char> data_rw(data.c_str(), data.size()); // Const-incorrect Irrlicht
1932 io::IFileSystem *irrfs = m_device->getFileSystem();
1933 io::IReadFile *rfile = irrfs->createMemoryReadFile(
1934 *data_rw, data_rw.getSize(), filename.c_str());
1935 FATAL_ERROR_IF(!rfile, "Could not create/open RAM file");
1937 scene::IAnimatedMesh *mesh = smgr->getMesh(rfile);
1939 // NOTE: By playing with Irrlicht refcounts, maybe we could cache a bunch
1940 // of uniquely named instances and re-use them
1942 smgr->getMeshCache()->removeMesh(mesh);
1946 bool Client::registerModStorage(ModMetadata *storage)
1948 if (m_mod_storages.find(storage->getModName()) != m_mod_storages.end()) {
1949 errorstream << "Unable to register same mod storage twice. Storage name: "
1950 << storage->getModName() << std::endl;
1954 m_mod_storages[storage->getModName()] = storage;
1958 void Client::unregisterModStorage(const std::string &name)
1960 std::unordered_map<std::string, ModMetadata *>::const_iterator it =
1961 m_mod_storages.find(name);
1962 if (it != m_mod_storages.end()) {
1963 // Save unconditionaly on unregistration
1964 it->second->save(getModStoragePath());
1965 m_mod_storages.erase(name);
1969 std::string Client::getModStoragePath() const
1971 return porting::path_user + DIR_DELIM + "client" + DIR_DELIM + "mod_storage";