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>
26 #include "network/clientopcodes.h"
27 #include "network/connection.h"
28 #include "network/networkpacket.h"
29 #include "threading/mutex_auto_lock.h"
30 #include "client/renderingengine.h"
31 #include "util/auth.h"
32 #include "util/directiontables.h"
33 #include "util/pointedthing.h"
34 #include "util/serialize.h"
35 #include "util/string.h"
38 #include "mapblock_mesh.h"
45 #include "clientmap.h"
46 #include "clientmedia.h"
48 #include "database-sqlite3.h"
49 #include "serialization.h"
50 #include "guiscalingfilter.h"
51 #include "script/scripting_client.h"
53 #include "chatmessage.h"
54 #include "translation.h"
56 extern gui::IGUIEnvironment* guienv;
63 const char *playername,
64 const std::string &password,
65 const std::string &address_name,
66 MapDrawControl &control,
67 IWritableTextureSource *tsrc,
68 IWritableShaderSource *shsrc,
69 IWritableItemDefManager *itemdef,
70 IWritableNodeDefManager *nodedef,
72 MtEventManager *event,
74 GameUIFlags *game_ui_flags
82 m_mesh_update_thread(this),
84 new ClientMap(this, control, 666),
87 m_particle_manager(&m_env),
88 m_con(new con::Connection(PROTOCOL_ID, 512, CONNECTION_TIMEOUT, ipv6, this)),
89 m_address_name(address_name),
90 m_server_ser_ver(SER_FMT_VER_INVALID),
91 m_last_chat_message_sent(time(NULL)),
93 m_chosen_auth_mech(AUTH_MECHANISM_NONE),
94 m_media_downloader(new ClientMediaDownloader()),
96 m_game_ui_flags(game_ui_flags)
99 m_env.setLocalPlayer(new LocalPlayer(this, playername));
101 if (g_settings->getBool("enable_minimap")) {
102 m_minimap = new Minimap(this);
104 m_cache_save_interval = g_settings->getU16("server_map_save_interval");
106 m_modding_enabled = g_settings->getBool("enable_client_modding");
107 m_script = new ClientScripting(this);
108 m_env.setScript(m_script);
109 m_script->setEnv(&m_env);
112 void Client::loadMods()
115 scanModIntoMemory(BUILTIN_MOD_NAME, getBuiltinLuaPath());
117 // If modding is not enabled, don't load mods, just builtin
118 if (!m_modding_enabled) {
121 ClientModConfiguration modconf(getClientModsLuaPath());
122 m_mods = modconf.getMods();
123 std::vector<ModSpec> unsatisfied_mods = modconf.getUnsatisfiedMods();
124 // complain about mods with unsatisfied dependencies
125 if (!modconf.isConsistent()) {
126 modconf.printUnsatisfiedModsError();
130 infostream << "Client Loading mods: ";
131 for (const ModSpec &mod : m_mods)
132 infostream << mod.name << " ";
133 infostream << std::endl;
135 // Load and run "mod" scripts
136 for (const ModSpec &mod : m_mods) {
137 if (!string_allowed(mod.name, MODNAME_ALLOWED_CHARS)) {
138 throw ModError("Error loading mod \"" + mod.name +
139 "\": Mod name does not follow naming conventions: "
140 "Only characters [a-z0-9_] are allowed.");
142 scanModIntoMemory(mod.name, mod.path);
146 void Client::scanModSubfolder(const std::string &mod_name, const std::string &mod_path,
147 std::string mod_subpath)
149 std::string full_path = mod_path + DIR_DELIM + mod_subpath;
150 std::vector<fs::DirListNode> mod = fs::GetDirListing(full_path);
151 for (const fs::DirListNode &j : mod) {
152 std::string filename = j.name;
154 scanModSubfolder(mod_name, mod_path, mod_subpath
155 + filename + DIR_DELIM);
158 std::replace( mod_subpath.begin(), mod_subpath.end(), DIR_DELIM_CHAR, '/');
159 m_mod_files[mod_name + ":" + mod_subpath + filename] = full_path + filename;
163 void Client::initMods()
165 m_script->loadModFromMemory(BUILTIN_MOD_NAME);
167 // If modding is not enabled, don't load mods, just builtin
168 if (!m_modding_enabled) {
172 // Load and run "mod" scripts
173 for (const ModSpec &mod : m_mods)
174 m_script->loadModFromMemory(mod.name);
177 const std::string &Client::getBuiltinLuaPath()
179 static const std::string builtin_dir = porting::path_share + DIR_DELIM + "builtin";
183 const std::string &Client::getClientModsLuaPath()
185 static const std::string clientmods_dir = porting::path_share + DIR_DELIM + "clientmods";
186 return clientmods_dir;
189 const std::vector<ModSpec>& Client::getMods() const
191 static std::vector<ModSpec> client_modspec_temp;
192 return client_modspec_temp;
195 const ModSpec* Client::getModSpec(const std::string &modname) const
203 // Don't disable this part when modding is disabled, it's used in builtin
204 m_script->on_shutdown();
205 //request all client managed threads to stop
206 m_mesh_update_thread.stop();
207 // Save local server map
209 infostream << "Local map saving ended." << std::endl;
210 m_localdb->endSave();
216 bool Client::isShutdown()
218 return m_shutdown || !m_mesh_update_thread.isRunning();
226 m_mesh_update_thread.stop();
227 m_mesh_update_thread.wait();
228 while (!m_mesh_update_thread.m_queue_out.empty()) {
229 MeshUpdateResult r = m_mesh_update_thread.m_queue_out.pop_frontNoEx();
234 delete m_inventory_from_server;
236 // Delete detached inventories
237 for (auto &m_detached_inventorie : m_detached_inventories) {
238 delete m_detached_inventorie.second;
241 // cleanup 3d model meshes on client shutdown
242 while (RenderingEngine::get_mesh_cache()->getMeshCount() != 0) {
243 scene::IAnimatedMesh *mesh = RenderingEngine::get_mesh_cache()->getMeshByIndex(0);
246 RenderingEngine::get_mesh_cache()->removeMesh(mesh);
252 void Client::connect(Address address, bool is_local_server)
254 DSTACK(FUNCTION_NAME);
256 initLocalMapSaving(address, m_address_name, is_local_server);
258 m_con->SetTimeoutMs(0);
259 m_con->Connect(address);
262 void Client::step(float dtime)
264 DSTACK(FUNCTION_NAME);
270 if(m_ignore_damage_timer > dtime)
271 m_ignore_damage_timer -= dtime;
273 m_ignore_damage_timer = 0.0;
275 m_animation_time += dtime;
276 if(m_animation_time > 60.0)
277 m_animation_time -= 60.0;
279 m_time_of_day_update_timer += dtime;
287 float &counter = m_packetcounter_timer;
293 infostream << "Client packetcounter (" << m_packetcounter_timer
295 m_packetcounter.print(infostream);
296 m_packetcounter.clear();
300 // UGLY hack to fix 2 second startup delay caused by non existent
301 // server client startup synchronization in local server or singleplayer mode
302 static bool initial_step = true;
304 initial_step = false;
306 else if(m_state == LC_Created) {
307 float &counter = m_connection_reinit_timer;
312 LocalPlayer *myplayer = m_env.getLocalPlayer();
313 FATAL_ERROR_IF(myplayer == NULL, "Local player not found in environment.");
315 u16 proto_version_min = g_settings->getFlag("send_pre_v25_init") ?
316 CLIENT_PROTOCOL_VERSION_MIN_LEGACY : CLIENT_PROTOCOL_VERSION_MIN;
318 if (proto_version_min < 25) {
319 // Send TOSERVER_INIT_LEGACY
320 // [0] u16 TOSERVER_INIT_LEGACY
321 // [2] u8 SER_FMT_VER_HIGHEST_READ
322 // [3] u8[20] player_name
323 // [23] u8[28] password (new in some version)
324 // [51] u16 minimum supported network protocol version (added sometime)
325 // [53] u16 maximum supported network protocol version (added later than the previous one)
327 char pName[PLAYERNAME_SIZE];
328 char pPassword[PASSWORD_SIZE];
329 memset(pName, 0, PLAYERNAME_SIZE * sizeof(char));
330 memset(pPassword, 0, PASSWORD_SIZE * sizeof(char));
332 std::string hashed_password = translate_password(myplayer->getName(), m_password);
333 snprintf(pName, PLAYERNAME_SIZE, "%s", myplayer->getName());
334 snprintf(pPassword, PASSWORD_SIZE, "%s", hashed_password.c_str());
336 sendLegacyInit(pName, pPassword);
338 if (CLIENT_PROTOCOL_VERSION_MAX >= 25)
339 sendInit(myplayer->getName());
342 // Not connected, return
347 Do stuff if connected
351 Run Map's timers and unload unused data
353 const float map_timer_and_unload_dtime = 5.25;
354 if(m_map_timer_and_unload_interval.step(dtime, map_timer_and_unload_dtime)) {
355 ScopeProfiler sp(g_profiler, "Client: map timer and unload");
356 std::vector<v3s16> deleted_blocks;
357 m_env.getMap().timerUpdate(map_timer_and_unload_dtime,
358 g_settings->getFloat("client_unload_unused_data_timeout"),
359 g_settings->getS32("client_mapblock_limit"),
364 NOTE: This loop is intentionally iterated the way it is.
367 std::vector<v3s16>::iterator i = deleted_blocks.begin();
368 std::vector<v3s16> sendlist;
370 if(sendlist.size() == 255 || i == deleted_blocks.end()) {
381 sendDeletedBlocks(sendlist);
383 if(i == deleted_blocks.end())
389 sendlist.push_back(*i);
395 Send pending messages on out chat queue
397 if (!m_out_chat_queue.empty() && canSendChatMessage()) {
398 sendChatMessage(m_out_chat_queue.front());
399 m_out_chat_queue.pop();
405 // Control local player (0ms)
406 LocalPlayer *player = m_env.getLocalPlayer();
408 player->applyControl(dtime, &m_env);
412 m_sound->step(dtime);
417 while (m_env.hasClientEnvEvents()) {
418 ClientEnvEvent envEvent = m_env.getClientEnvEvent();
420 if (envEvent.type == CEE_PLAYER_DAMAGE) {
421 if (m_ignore_damage_timer <= 0) {
422 u8 damage = envEvent.player_damage.amount;
424 if (envEvent.player_damage.send_to_server)
427 // Add to ClientEvent queue
429 event.type = CE_PLAYER_DAMAGE;
430 event.player_damage.amount = damage;
431 m_client_event_queue.push(event);
434 // Protocol v29 or greater obsoleted this event
435 else if (envEvent.type == CEE_PLAYER_BREATH && m_proto_ver < 29) {
436 u16 breath = envEvent.player_breath.amount;
444 float &counter = m_avg_rtt_timer;
448 // connectedAndInitialized() is true, peer exists.
449 float avg_rtt = getRTT();
450 infostream << "Client: avg_rtt=" << avg_rtt << std::endl;
454 Send player position to server
457 float &counter = m_playerpos_send_timer;
459 if((m_state == LC_Ready) && (counter >= m_recommended_send_interval))
467 Replace updated meshes
470 int num_processed_meshes = 0;
471 while (!m_mesh_update_thread.m_queue_out.empty())
473 num_processed_meshes++;
475 MinimapMapblock *minimap_mapblock = NULL;
476 bool do_mapper_update = true;
478 MeshUpdateResult r = m_mesh_update_thread.m_queue_out.pop_frontNoEx();
479 MapBlock *block = m_env.getMap().getBlockNoCreateNoEx(r.p);
481 // Delete the old mesh
483 block->mesh = nullptr;
486 minimap_mapblock = r.mesh->moveMinimapMapblock();
487 if (minimap_mapblock == NULL)
488 do_mapper_update = false;
490 bool is_empty = true;
491 for (int l = 0; l < MAX_TILE_LAYERS; l++)
492 if (r.mesh->getMesh(l)->getMeshBufferCount() != 0)
498 // Replace with the new mesh
499 block->mesh = r.mesh;
505 if (m_minimap && do_mapper_update)
506 m_minimap->addBlock(r.p, minimap_mapblock);
508 if (r.ack_block_to_server) {
518 if (num_processed_meshes > 0)
519 g_profiler->graphAdd("num_processed_meshes", num_processed_meshes);
525 if (m_media_downloader && m_media_downloader->isStarted()) {
526 m_media_downloader->step(this);
527 if (m_media_downloader->isDone()) {
528 delete m_media_downloader;
529 m_media_downloader = NULL;
534 If the server didn't update the inventory in a while, revert
535 the local inventory (so the player notices the lag problem
536 and knows something is wrong).
538 if(m_inventory_from_server)
540 float interval = 10.0;
541 float count_before = floor(m_inventory_from_server_age / interval);
543 m_inventory_from_server_age += dtime;
545 float count_after = floor(m_inventory_from_server_age / interval);
547 if(count_after != count_before)
549 // Do this every <interval> seconds after TOCLIENT_INVENTORY
550 // Reset the locally changed inventory to the authoritative inventory
551 LocalPlayer *player = m_env.getLocalPlayer();
552 player->inventory = *m_inventory_from_server;
553 m_inventory_updated = true;
558 Update positions of sounds attached to objects
561 for (auto &m_sounds_to_object : m_sounds_to_objects) {
562 int client_id = m_sounds_to_object.first;
563 u16 object_id = m_sounds_to_object.second;
564 ClientActiveObject *cao = m_env.getActiveObject(object_id);
567 m_sound->updateSoundPosition(client_id, cao->getPosition());
572 Handle removed remotely initiated sounds
574 m_removed_sounds_check_timer += dtime;
575 if(m_removed_sounds_check_timer >= 2.32) {
576 m_removed_sounds_check_timer = 0;
577 // Find removed sounds and clear references to them
578 std::vector<s32> removed_server_ids;
579 for (std::unordered_map<s32, int>::iterator i = m_sounds_server_to_client.begin();
580 i != m_sounds_server_to_client.end();) {
581 s32 server_id = i->first;
582 int client_id = i->second;
584 if(!m_sound->soundExists(client_id)) {
585 m_sounds_server_to_client.erase(server_id);
586 m_sounds_client_to_server.erase(client_id);
587 m_sounds_to_objects.erase(client_id);
588 removed_server_ids.push_back(server_id);
593 if(!removed_server_ids.empty()) {
594 sendRemovedSounds(removed_server_ids);
598 m_mod_storage_save_timer -= dtime;
599 if (m_mod_storage_save_timer <= 0.0f) {
600 verbosestream << "Saving registered mod storages." << std::endl;
601 m_mod_storage_save_timer = g_settings->getFloat("server_map_save_interval");
602 for (std::unordered_map<std::string, ModMetadata *>::const_iterator
603 it = m_mod_storages.begin(); it != m_mod_storages.end(); ++it) {
604 if (it->second->isModified()) {
605 it->second->save(getModStoragePath());
611 if (m_localdb && m_localdb_save_interval.step(dtime,
612 m_cache_save_interval)) {
613 m_localdb->endSave();
614 m_localdb->beginSave();
618 bool Client::loadMedia(const std::string &data, const std::string &filename)
620 // Silly irrlicht's const-incorrectness
621 Buffer<char> data_rw(data.c_str(), data.size());
625 const char *image_ext[] = {
626 ".png", ".jpg", ".bmp", ".tga",
627 ".pcx", ".ppm", ".psd", ".wal", ".rgb",
630 name = removeStringEnd(filename, image_ext);
632 verbosestream<<"Client: Attempting to load image "
633 <<"file \""<<filename<<"\""<<std::endl;
635 io::IFileSystem *irrfs = RenderingEngine::get_filesystem();
636 video::IVideoDriver *vdrv = RenderingEngine::get_video_driver();
638 // Create an irrlicht memory file
639 io::IReadFile *rfile = irrfs->createMemoryReadFile(
640 *data_rw, data_rw.getSize(), "_tempreadfile");
642 FATAL_ERROR_IF(!rfile, "Could not create irrlicht memory file.");
645 video::IImage *img = vdrv->createImageFromFile(rfile);
647 errorstream<<"Client: Cannot create image from data of "
648 <<"file \""<<filename<<"\""<<std::endl;
653 m_tsrc->insertSourceImage(filename, img);
659 const char *sound_ext[] = {
660 ".0.ogg", ".1.ogg", ".2.ogg", ".3.ogg", ".4.ogg",
661 ".5.ogg", ".6.ogg", ".7.ogg", ".8.ogg", ".9.ogg",
664 name = removeStringEnd(filename, sound_ext);
666 verbosestream<<"Client: Attempting to load sound "
667 <<"file \""<<filename<<"\""<<std::endl;
668 m_sound->loadSoundData(name, data);
672 const char *model_ext[] = {
673 ".x", ".b3d", ".md2", ".obj",
677 name = removeStringEnd(filename, model_ext);
679 verbosestream<<"Client: Storing model into memory: "
680 <<"\""<<filename<<"\""<<std::endl;
681 if(m_mesh_data.count(filename))
682 errorstream<<"Multiple models with name \""<<filename.c_str()
683 <<"\" found; replacing previous model"<<std::endl;
684 m_mesh_data[filename] = data;
688 const char *translate_ext[] = {
691 name = removeStringEnd(filename, translate_ext);
693 verbosestream << "Client: Loading translation: "
694 << "\"" << filename << "\"" << std::endl;
695 g_translations->loadTranslation(data);
699 errorstream << "Client: Don't know how to load file \""
700 << filename << "\"" << std::endl;
704 // Virtual methods from con::PeerHandler
705 void Client::peerAdded(con::Peer *peer)
707 infostream << "Client::peerAdded(): peer->id="
708 << peer->id << std::endl;
710 void Client::deletingPeer(con::Peer *peer, bool timeout)
712 infostream << "Client::deletingPeer(): "
713 "Server Peer is getting deleted "
714 << "(timeout=" << timeout << ")" << std::endl;
717 m_access_denied = true;
718 m_access_denied_reason = gettext("Connection timed out.");
724 u16 number of files requested
730 void Client::request_media(const std::vector<std::string> &file_requests)
732 std::ostringstream os(std::ios_base::binary);
733 writeU16(os, TOSERVER_REQUEST_MEDIA);
734 size_t file_requests_size = file_requests.size();
736 FATAL_ERROR_IF(file_requests_size > 0xFFFF, "Unsupported number of file requests");
738 // Packet dynamicly resized
739 NetworkPacket pkt(TOSERVER_REQUEST_MEDIA, 2 + 0);
741 pkt << (u16) (file_requests_size & 0xFFFF);
743 for (const std::string &file_request : file_requests) {
749 infostream << "Client: Sending media request list to server ("
750 << file_requests.size() << " files. packet size)" << std::endl;
753 void Client::initLocalMapSaving(const Address &address,
754 const std::string &hostname,
755 bool is_local_server)
757 if (!g_settings->getBool("enable_local_map_saving") || is_local_server) {
761 const std::string world_path = porting::path_user
762 + DIR_DELIM + "worlds"
763 + DIR_DELIM + "server_"
764 + hostname + "_" + std::to_string(address.getPort());
766 fs::CreateAllDirs(world_path);
768 m_localdb = new MapDatabaseSQLite3(world_path);
769 m_localdb->beginSave();
770 actionstream << "Local map saving started, map will be saved at '" << world_path << "'" << std::endl;
773 void Client::ReceiveAll()
775 DSTACK(FUNCTION_NAME);
776 u64 start_ms = porting::getTimeMs();
779 // Limit time even if there would be huge amounts of data to
781 if(porting::getTimeMs() > start_ms + 100)
786 g_profiler->graphAdd("client_received_packets", 1);
788 catch(con::NoIncomingDataException &e) {
791 catch(con::InvalidIncomingDataException &e) {
792 infostream<<"Client::ReceiveAll(): "
793 "InvalidIncomingDataException: what()="
794 <<e.what()<<std::endl;
799 void Client::Receive()
801 DSTACK(FUNCTION_NAME);
803 m_con->Receive(&pkt);
807 inline void Client::handleCommand(NetworkPacket* pkt)
809 const ToClientCommandHandler& opHandle = toClientCommandTable[pkt->getCommand()];
810 (this->*opHandle.handler)(pkt);
814 sender_peer_id given to this shall be quaranteed to be a valid peer
816 void Client::ProcessData(NetworkPacket *pkt)
818 DSTACK(FUNCTION_NAME);
820 ToClientCommand command = (ToClientCommand) pkt->getCommand();
821 u32 sender_peer_id = pkt->getPeerId();
823 //infostream<<"Client: received command="<<command<<std::endl;
824 m_packetcounter.add((u16)command);
827 If this check is removed, be sure to change the queue
828 system to know the ids
830 if(sender_peer_id != PEER_ID_SERVER) {
831 infostream << "Client::ProcessData(): Discarding data not "
832 "coming from server: peer_id=" << sender_peer_id
837 // Command must be handled into ToClientCommandHandler
838 if (command >= TOCLIENT_NUM_MSG_TYPES) {
839 infostream << "Client: Ignoring unknown command "
840 << command << std::endl;
845 * Those packets are handled before m_server_ser_ver is set, it's normal
846 * But we must use the new ToClientConnectionState in the future,
849 if(toClientCommandTable[command].state == TOCLIENT_STATE_NOT_CONNECTED) {
854 if(m_server_ser_ver == SER_FMT_VER_INVALID) {
855 infostream << "Client: Server serialization"
856 " format invalid or not initialized."
857 " Skipping incoming command=" << command << std::endl;
862 Handle runtime commands
868 void Client::Send(NetworkPacket* pkt)
870 m_con->Send(PEER_ID_SERVER,
871 serverCommandFactoryTable[pkt->getCommand()].channel,
873 serverCommandFactoryTable[pkt->getCommand()].reliable);
876 // Will fill up 12 + 12 + 4 + 4 + 4 bytes
877 void writePlayerPos(LocalPlayer *myplayer, ClientMap *clientMap, NetworkPacket *pkt)
879 v3f pf = myplayer->getPosition() * 100;
880 v3f sf = myplayer->getSpeed() * 100;
881 s32 pitch = myplayer->getPitch() * 100;
882 s32 yaw = myplayer->getYaw() * 100;
883 u32 keyPressed = myplayer->keyPressed;
884 // scaled by 80, so that pi can fit into a u8
885 u8 fov = clientMap->getCameraFov() * 80;
886 u8 wanted_range = MYMIN(255,
887 std::ceil(clientMap->getControl().wanted_range / MAP_BLOCKSIZE));
889 v3s32 position(pf.X, pf.Y, pf.Z);
890 v3s32 speed(sf.X, sf.Y, sf.Z);
894 [0] v3s32 position*100
896 [12+12] s32 pitch*100
897 [12+12+4] s32 yaw*100
898 [12+12+4+4] u32 keyPressed
899 [12+12+4+4+4] u8 fov*80
900 [12+12+4+4+4+1] u8 ceil(wanted_range / MAP_BLOCKSIZE)
902 *pkt << position << speed << pitch << yaw << keyPressed;
903 *pkt << fov << wanted_range;
906 void Client::interact(u8 action, const PointedThing& pointed)
908 if(m_state != LC_Ready) {
909 errorstream << "Client::interact() "
910 "Canceled (not connected)"
915 LocalPlayer *myplayer = m_env.getLocalPlayer();
916 if (myplayer == NULL)
923 [5] u32 length of the next item (plen)
924 [9] serialized PointedThing
925 [9 + plen] player position information
927 0: start digging (from undersurface) or use
928 1: stop digging (all parameters ignored)
930 3: place block or item (to abovesurface)
932 5: perform secondary action of item
935 NetworkPacket pkt(TOSERVER_INTERACT, 1 + 2 + 0);
938 pkt << (u16)getPlayerItem();
940 std::ostringstream tmp_os(std::ios::binary);
941 pointed.serialize(tmp_os);
943 pkt.putLongString(tmp_os.str());
945 writePlayerPos(myplayer, &m_env.getClientMap(), &pkt);
950 void Client::deleteAuthData()
955 switch (m_chosen_auth_mech) {
956 case AUTH_MECHANISM_FIRST_SRP:
958 case AUTH_MECHANISM_SRP:
959 case AUTH_MECHANISM_LEGACY_PASSWORD:
960 srp_user_delete((SRPUser *) m_auth_data);
963 case AUTH_MECHANISM_NONE:
966 m_chosen_auth_mech = AUTH_MECHANISM_NONE;
970 AuthMechanism Client::choseAuthMech(const u32 mechs)
972 if (mechs & AUTH_MECHANISM_SRP)
973 return AUTH_MECHANISM_SRP;
975 if (mechs & AUTH_MECHANISM_FIRST_SRP)
976 return AUTH_MECHANISM_FIRST_SRP;
978 if (mechs & AUTH_MECHANISM_LEGACY_PASSWORD)
979 return AUTH_MECHANISM_LEGACY_PASSWORD;
981 return AUTH_MECHANISM_NONE;
984 void Client::sendLegacyInit(const char* playerName, const char* playerPassword)
986 NetworkPacket pkt(TOSERVER_INIT_LEGACY,
987 1 + PLAYERNAME_SIZE + PASSWORD_SIZE + 2 + 2);
989 u16 proto_version_min = g_settings->getFlag("send_pre_v25_init") ?
990 CLIENT_PROTOCOL_VERSION_MIN_LEGACY : CLIENT_PROTOCOL_VERSION_MIN;
992 pkt << (u8) SER_FMT_VER_HIGHEST_READ;
993 pkt.putRawString(playerName,PLAYERNAME_SIZE);
994 pkt.putRawString(playerPassword, PASSWORD_SIZE);
995 pkt << (u16) proto_version_min << (u16) CLIENT_PROTOCOL_VERSION_MAX;
1000 void Client::sendInit(const std::string &playerName)
1002 NetworkPacket pkt(TOSERVER_INIT, 1 + 2 + 2 + (1 + playerName.size()));
1004 // we don't support network compression yet
1005 u16 supp_comp_modes = NETPROTO_COMPRESSION_NONE;
1007 u16 proto_version_min = g_settings->getFlag("send_pre_v25_init") ?
1008 CLIENT_PROTOCOL_VERSION_MIN_LEGACY : CLIENT_PROTOCOL_VERSION_MIN;
1010 pkt << (u8) SER_FMT_VER_HIGHEST_READ << (u16) supp_comp_modes;
1011 pkt << (u16) proto_version_min << (u16) CLIENT_PROTOCOL_VERSION_MAX;
1017 void Client::startAuth(AuthMechanism chosen_auth_mechanism)
1019 m_chosen_auth_mech = chosen_auth_mechanism;
1021 switch (chosen_auth_mechanism) {
1022 case AUTH_MECHANISM_FIRST_SRP: {
1023 // send srp verifier to server
1024 std::string verifier;
1026 generate_srp_verifier_and_salt(getPlayerName(), m_password,
1029 NetworkPacket resp_pkt(TOSERVER_FIRST_SRP, 0);
1030 resp_pkt << salt << verifier << (u8)((m_password.empty()) ? 1 : 0);
1035 case AUTH_MECHANISM_SRP:
1036 case AUTH_MECHANISM_LEGACY_PASSWORD: {
1039 if (chosen_auth_mechanism == AUTH_MECHANISM_LEGACY_PASSWORD) {
1040 m_password = translate_password(getPlayerName(), m_password);
1044 std::string playername_u = lowercase(getPlayerName());
1045 m_auth_data = srp_user_new(SRP_SHA256, SRP_NG_2048,
1046 getPlayerName().c_str(), playername_u.c_str(),
1047 (const unsigned char *) m_password.c_str(),
1048 m_password.length(), NULL, NULL);
1051 SRP_Result res = srp_user_start_authentication(
1052 (struct SRPUser *) m_auth_data, NULL, NULL, 0,
1053 (unsigned char **) &bytes_A, &len_A);
1054 FATAL_ERROR_IF(res != SRP_OK, "Creating local SRP user failed.");
1056 NetworkPacket resp_pkt(TOSERVER_SRP_BYTES_A, 0);
1057 resp_pkt << std::string(bytes_A, len_A) << based_on;
1061 case AUTH_MECHANISM_NONE:
1062 break; // not handled in this method
1066 void Client::sendDeletedBlocks(std::vector<v3s16> &blocks)
1068 NetworkPacket pkt(TOSERVER_DELETEDBLOCKS, 1 + sizeof(v3s16) * blocks.size());
1070 pkt << (u8) blocks.size();
1072 for (const v3s16 &block : blocks) {
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 (int sound_id : soundList)
1101 void Client::sendNodemetaFields(v3s16 p, const std::string &formname,
1102 const StringMap &fields)
1104 size_t fields_size = fields.size();
1106 FATAL_ERROR_IF(fields_size > 0xFFFF, "Unsupported number of nodemeta fields");
1108 NetworkPacket pkt(TOSERVER_NODEMETA_FIELDS, 0);
1110 pkt << p << formname << (u16) (fields_size & 0xFFFF);
1112 StringMap::const_iterator it;
1113 for (it = fields.begin(); it != fields.end(); ++it) {
1114 const std::string &name = it->first;
1115 const std::string &value = it->second;
1117 pkt.putLongString(value);
1123 void Client::sendInventoryFields(const std::string &formname,
1124 const StringMap &fields)
1126 size_t fields_size = fields.size();
1127 FATAL_ERROR_IF(fields_size > 0xFFFF, "Unsupported number of inventory fields");
1129 NetworkPacket pkt(TOSERVER_INVENTORY_FIELDS, 0);
1130 pkt << formname << (u16) (fields_size & 0xFFFF);
1132 StringMap::const_iterator it;
1133 for (it = fields.begin(); it != fields.end(); ++it) {
1134 const std::string &name = it->first;
1135 const std::string &value = it->second;
1137 pkt.putLongString(value);
1143 void Client::sendInventoryAction(InventoryAction *a)
1145 std::ostringstream os(std::ios_base::binary);
1150 std::string s = os.str();
1152 NetworkPacket pkt(TOSERVER_INVENTORY_ACTION, s.size());
1153 pkt.putRawString(s.c_str(),s.size());
1158 bool Client::canSendChatMessage() const
1160 u32 now = time(NULL);
1161 float time_passed = now - m_last_chat_message_sent;
1163 float virt_chat_message_allowance = m_chat_message_allowance + time_passed *
1164 (CLIENT_CHAT_MESSAGE_LIMIT_PER_10S / 8.0f);
1166 if (virt_chat_message_allowance < 1.0f)
1172 void Client::sendChatMessage(const std::wstring &message)
1174 const s16 max_queue_size = g_settings->getS16("max_out_chat_queue_size");
1175 if (canSendChatMessage()) {
1176 u32 now = time(NULL);
1177 float time_passed = now - m_last_chat_message_sent;
1178 m_last_chat_message_sent = time(NULL);
1180 m_chat_message_allowance += time_passed * (CLIENT_CHAT_MESSAGE_LIMIT_PER_10S / 8.0f);
1181 if (m_chat_message_allowance > CLIENT_CHAT_MESSAGE_LIMIT_PER_10S)
1182 m_chat_message_allowance = CLIENT_CHAT_MESSAGE_LIMIT_PER_10S;
1184 m_chat_message_allowance -= 1.0f;
1186 NetworkPacket pkt(TOSERVER_CHAT_MESSAGE, 2 + message.size() * sizeof(u16));
1191 } else if (m_out_chat_queue.size() < (u16) max_queue_size || max_queue_size == -1) {
1192 m_out_chat_queue.push(message);
1194 infostream << "Could not queue chat message because maximum out chat queue size ("
1195 << max_queue_size << ") is reached." << std::endl;
1199 void Client::clearOutChatQueue()
1201 m_out_chat_queue = std::queue<std::wstring>();
1204 void Client::sendChangePassword(const std::string &oldpassword,
1205 const std::string &newpassword)
1207 LocalPlayer *player = m_env.getLocalPlayer();
1211 std::string playername = player->getName();
1212 if (m_proto_ver >= 25) {
1213 // get into sudo mode and then send new password to server
1214 m_password = oldpassword;
1215 m_new_password = newpassword;
1216 startAuth(choseAuthMech(m_sudo_auth_methods));
1218 std::string oldpwd = translate_password(playername, oldpassword);
1219 std::string newpwd = translate_password(playername, newpassword);
1221 NetworkPacket pkt(TOSERVER_PASSWORD_LEGACY, 2 * PASSWORD_SIZE);
1223 for (u8 i = 0; i < PASSWORD_SIZE; i++) {
1224 pkt << (u8) (i < oldpwd.length() ? oldpwd[i] : 0);
1227 for (u8 i = 0; i < PASSWORD_SIZE; i++) {
1228 pkt << (u8) (i < newpwd.length() ? newpwd[i] : 0);
1235 void Client::sendDamage(u8 damage)
1237 DSTACK(FUNCTION_NAME);
1239 NetworkPacket pkt(TOSERVER_DAMAGE, sizeof(u8));
1244 void Client::sendBreath(u16 breath)
1246 DSTACK(FUNCTION_NAME);
1248 // Protocol v29 make this obsolete
1249 if (m_proto_ver >= 29)
1252 NetworkPacket pkt(TOSERVER_BREATH, sizeof(u16));
1257 void Client::sendRespawn()
1259 DSTACK(FUNCTION_NAME);
1261 NetworkPacket pkt(TOSERVER_RESPAWN, 0);
1265 void Client::sendReady()
1267 DSTACK(FUNCTION_NAME);
1269 NetworkPacket pkt(TOSERVER_CLIENT_READY,
1270 1 + 1 + 1 + 1 + 2 + sizeof(char) * strlen(g_version_hash));
1272 pkt << (u8) VERSION_MAJOR << (u8) VERSION_MINOR << (u8) VERSION_PATCH
1273 << (u8) 0 << (u16) strlen(g_version_hash);
1275 pkt.putRawString(g_version_hash, (u16) strlen(g_version_hash));
1279 void Client::sendPlayerPos()
1281 LocalPlayer *myplayer = m_env.getLocalPlayer();
1282 if(myplayer == NULL)
1285 ClientMap &map = m_env.getClientMap();
1287 u8 camera_fov = map.getCameraFov();
1288 u8 wanted_range = map.getControl().wanted_range;
1290 // Save bandwidth by only updating position when something changed
1291 if(myplayer->last_position == myplayer->getPosition() &&
1292 myplayer->last_speed == myplayer->getSpeed() &&
1293 myplayer->last_pitch == myplayer->getPitch() &&
1294 myplayer->last_yaw == myplayer->getYaw() &&
1295 myplayer->last_keyPressed == myplayer->keyPressed &&
1296 myplayer->last_camera_fov == camera_fov &&
1297 myplayer->last_wanted_range == wanted_range)
1300 myplayer->last_position = myplayer->getPosition();
1301 myplayer->last_speed = myplayer->getSpeed();
1302 myplayer->last_pitch = myplayer->getPitch();
1303 myplayer->last_yaw = myplayer->getYaw();
1304 myplayer->last_keyPressed = myplayer->keyPressed;
1305 myplayer->last_camera_fov = camera_fov;
1306 myplayer->last_wanted_range = wanted_range;
1308 //infostream << "Sending Player Position information" << std::endl;
1312 //MutexAutoLock lock(m_con_mutex); //bulk comment-out
1313 our_peer_id = m_con->GetPeerID();
1316 // Set peer id if not set already
1317 if(myplayer->peer_id == PEER_ID_INEXISTENT)
1318 myplayer->peer_id = our_peer_id;
1320 assert(myplayer->peer_id == our_peer_id);
1322 NetworkPacket pkt(TOSERVER_PLAYERPOS, 12 + 12 + 4 + 4 + 4 + 1 + 1);
1324 writePlayerPos(myplayer, &map, &pkt);
1329 void Client::sendPlayerItem(u16 item)
1331 LocalPlayer *myplayer = m_env.getLocalPlayer();
1332 if(myplayer == NULL)
1335 u16 our_peer_id = m_con->GetPeerID();
1337 // Set peer id if not set already
1338 if(myplayer->peer_id == PEER_ID_INEXISTENT)
1339 myplayer->peer_id = our_peer_id;
1340 assert(myplayer->peer_id == our_peer_id);
1342 NetworkPacket pkt(TOSERVER_PLAYERITEM, 2);
1349 void Client::removeNode(v3s16 p)
1351 std::map<v3s16, MapBlock*> modified_blocks;
1354 m_env.getMap().removeNodeAndUpdate(p, modified_blocks);
1356 catch(InvalidPositionException &e) {
1359 for (const auto &modified_block : modified_blocks) {
1360 addUpdateMeshTaskWithEdge(modified_block.first, false, true);
1365 * Helper function for Client Side Modding
1366 * Flavour is applied there, this should not be used for core engine
1368 * @param is_valid_position
1371 MapNode Client::getNode(v3s16 p, bool *is_valid_position)
1373 if (checkCSMFlavourLimit(CSMFlavourLimit::CSM_FL_LOOKUP_NODES)) {
1374 v3s16 ppos = floatToInt(m_env.getLocalPlayer()->getPosition(), BS);
1375 if ((u32) ppos.getDistanceFrom(p) > m_csm_noderange_limit) {
1376 *is_valid_position = false;
1380 return m_env.getMap().getNodeNoEx(p, is_valid_position);
1383 void Client::addNode(v3s16 p, MapNode n, bool remove_metadata)
1385 //TimeTaker timer1("Client::addNode()");
1387 std::map<v3s16, MapBlock*> modified_blocks;
1390 //TimeTaker timer3("Client::addNode(): addNodeAndUpdate");
1391 m_env.getMap().addNodeAndUpdate(p, n, modified_blocks, remove_metadata);
1393 catch(InvalidPositionException &e) {
1396 for (const auto &modified_block : modified_blocks) {
1397 addUpdateMeshTaskWithEdge(modified_block.first, false, true);
1401 void Client::setPlayerControl(PlayerControl &control)
1403 LocalPlayer *player = m_env.getLocalPlayer();
1405 player->control = control;
1408 void Client::selectPlayerItem(u16 item)
1410 m_playeritem = item;
1411 m_inventory_updated = true;
1412 sendPlayerItem(item);
1415 // Returns true if the inventory of the local player has been
1416 // updated from the server. If it is true, it is set to false.
1417 bool Client::getLocalInventoryUpdated()
1419 bool updated = m_inventory_updated;
1420 m_inventory_updated = false;
1424 // Copies the inventory of the local player to parameter
1425 void Client::getLocalInventory(Inventory &dst)
1427 LocalPlayer *player = m_env.getLocalPlayer();
1429 dst = player->inventory;
1432 Inventory* Client::getInventory(const InventoryLocation &loc)
1435 case InventoryLocation::UNDEFINED:
1438 case InventoryLocation::CURRENT_PLAYER:
1440 LocalPlayer *player = m_env.getLocalPlayer();
1442 return &player->inventory;
1445 case InventoryLocation::PLAYER:
1447 // Check if we are working with local player inventory
1448 LocalPlayer *player = m_env.getLocalPlayer();
1449 if (!player || strcmp(player->getName(), loc.name.c_str()) != 0)
1451 return &player->inventory;
1454 case InventoryLocation::NODEMETA:
1456 NodeMetadata *meta = m_env.getMap().getNodeMetadata(loc.p);
1459 return meta->getInventory();
1462 case InventoryLocation::DETACHED:
1464 if (m_detached_inventories.count(loc.name) == 0)
1466 return m_detached_inventories[loc.name];
1470 FATAL_ERROR("Invalid inventory location type.");
1476 void Client::inventoryAction(InventoryAction *a)
1479 Send it to the server
1481 sendInventoryAction(a);
1484 Predict some local inventory changes
1486 a->clientApply(this, this);
1492 float Client::getAnimationTime()
1494 return m_animation_time;
1497 int Client::getCrackLevel()
1499 return m_crack_level;
1502 v3s16 Client::getCrackPos()
1507 void Client::setCrack(int level, v3s16 pos)
1509 int old_crack_level = m_crack_level;
1510 v3s16 old_crack_pos = m_crack_pos;
1512 m_crack_level = level;
1515 if(old_crack_level >= 0 && (level < 0 || pos != old_crack_pos))
1518 addUpdateMeshTaskForNode(old_crack_pos, false, true);
1520 if(level >= 0 && (old_crack_level < 0 || pos != old_crack_pos))
1523 addUpdateMeshTaskForNode(pos, false, true);
1529 LocalPlayer *player = m_env.getLocalPlayer();
1534 bool Client::getChatMessage(std::wstring &res)
1536 if (m_chat_queue.empty())
1539 ChatMessage *chatMessage = m_chat_queue.front();
1544 switch (chatMessage->type) {
1545 case CHATMESSAGE_TYPE_RAW:
1546 case CHATMESSAGE_TYPE_ANNOUNCE:
1547 case CHATMESSAGE_TYPE_SYSTEM:
1548 res = chatMessage->message;
1550 case CHATMESSAGE_TYPE_NORMAL: {
1551 if (!chatMessage->sender.empty())
1552 res = L"<" + chatMessage->sender + L"> " + chatMessage->message;
1554 res = chatMessage->message;
1565 void Client::typeChatMessage(const std::wstring &message)
1567 // Discard empty line
1568 if (message.empty())
1571 // If message was ate by script API, don't send it to server
1572 if (m_script->on_sending_message(wide_to_utf8(message))) {
1577 sendChatMessage(message);
1580 if (message[0] != L'/') {
1581 // compatibility code
1582 if (m_proto_ver < 29) {
1583 LocalPlayer *player = m_env.getLocalPlayer();
1585 std::wstring name = narrow_to_wide(player->getName());
1586 pushToChatQueue(new ChatMessage(CHATMESSAGE_TYPE_NORMAL, message, name));
1591 void Client::addUpdateMeshTask(v3s16 p, bool ack_to_server, bool urgent)
1593 // Check if the block exists to begin with. In the case when a non-existing
1594 // neighbor is automatically added, it may not. In that case we don't want
1595 // to tell the mesh update thread about it.
1596 MapBlock *b = m_env.getMap().getBlockNoCreateNoEx(p);
1600 m_mesh_update_thread.updateBlock(&m_env.getMap(), p, ack_to_server, urgent);
1603 void Client::addUpdateMeshTaskWithEdge(v3s16 blockpos, bool ack_to_server, bool urgent)
1606 addUpdateMeshTask(blockpos, ack_to_server, urgent);
1608 catch(InvalidPositionException &e){}
1611 for (int i=0;i<6;i++)
1614 v3s16 p = blockpos + g_6dirs[i];
1615 addUpdateMeshTask(p, false, urgent);
1617 catch(InvalidPositionException &e){}
1621 void Client::addUpdateMeshTaskForNode(v3s16 nodepos, bool ack_to_server, bool urgent)
1625 infostream<<"Client::addUpdateMeshTaskForNode(): "
1626 <<"("<<p.X<<","<<p.Y<<","<<p.Z<<")"
1630 v3s16 blockpos = getNodeBlockPos(nodepos);
1631 v3s16 blockpos_relative = blockpos * MAP_BLOCKSIZE;
1634 addUpdateMeshTask(blockpos, ack_to_server, urgent);
1636 catch(InvalidPositionException &e) {}
1639 if(nodepos.X == blockpos_relative.X){
1641 v3s16 p = blockpos + v3s16(-1,0,0);
1642 addUpdateMeshTask(p, false, urgent);
1644 catch(InvalidPositionException &e){}
1647 if(nodepos.Y == blockpos_relative.Y){
1649 v3s16 p = blockpos + v3s16(0,-1,0);
1650 addUpdateMeshTask(p, false, urgent);
1652 catch(InvalidPositionException &e){}
1655 if(nodepos.Z == blockpos_relative.Z){
1657 v3s16 p = blockpos + v3s16(0,0,-1);
1658 addUpdateMeshTask(p, false, urgent);
1660 catch(InvalidPositionException &e){}
1664 ClientEvent Client::getClientEvent()
1666 FATAL_ERROR_IF(m_client_event_queue.empty(),
1667 "Cannot getClientEvent, queue is empty.");
1669 ClientEvent event = m_client_event_queue.front();
1670 m_client_event_queue.pop();
1674 bool Client::connectedToServer()
1676 return m_con->Connected();
1679 const Address Client::getServerAddress()
1681 return m_con->GetPeerAddress(PEER_ID_SERVER);
1684 float Client::mediaReceiveProgress()
1686 if (m_media_downloader)
1687 return m_media_downloader->getProgress();
1689 return 1.0; // downloader only exists when not yet done
1692 typedef struct TextureUpdateArgs {
1693 gui::IGUIEnvironment *guienv;
1696 const wchar_t* text_base;
1697 ITextureSource *tsrc;
1698 } TextureUpdateArgs;
1700 void texture_update_progress(void *args, u32 progress, u32 max_progress)
1702 TextureUpdateArgs* targs = (TextureUpdateArgs*) args;
1703 u16 cur_percent = ceil(progress / (double) max_progress * 100.);
1705 // update the loading menu -- if neccessary
1706 bool do_draw = false;
1707 u64 time_ms = targs->last_time_ms;
1708 if (cur_percent != targs->last_percent) {
1709 targs->last_percent = cur_percent;
1710 time_ms = porting::getTimeMs();
1711 // only draw when the user will notice something:
1712 do_draw = (time_ms - targs->last_time_ms > 100);
1716 targs->last_time_ms = time_ms;
1717 std::basic_stringstream<wchar_t> strm;
1718 strm << targs->text_base << " " << targs->last_percent << "%...";
1719 RenderingEngine::draw_load_screen(strm.str(), targs->guienv, targs->tsrc, 0,
1720 72 + (u16) ((18. / 100.) * (double) targs->last_percent), true);
1724 void Client::afterContentReceived()
1726 infostream<<"Client::afterContentReceived() started"<<std::endl;
1727 assert(m_itemdef_received); // pre-condition
1728 assert(m_nodedef_received); // pre-condition
1729 assert(mediaReceived()); // pre-condition
1731 const wchar_t* text = wgettext("Loading textures...");
1733 // Clear cached pre-scaled 2D GUI images, as this cache
1734 // might have images with the same name but different
1735 // content from previous sessions.
1736 guiScalingCacheClear();
1738 // Rebuild inherited images and recreate textures
1739 infostream<<"- Rebuilding images and textures"<<std::endl;
1740 RenderingEngine::draw_load_screen(text, guienv, m_tsrc, 0, 70);
1741 m_tsrc->rebuildImagesAndTextures();
1745 infostream<<"- Rebuilding shaders"<<std::endl;
1746 text = wgettext("Rebuilding shaders...");
1747 RenderingEngine::draw_load_screen(text, guienv, m_tsrc, 0, 71);
1748 m_shsrc->rebuildShaders();
1751 // Update node aliases
1752 infostream<<"- Updating node aliases"<<std::endl;
1753 text = wgettext("Initializing nodes...");
1754 RenderingEngine::draw_load_screen(text, guienv, m_tsrc, 0, 72);
1755 m_nodedef->updateAliases(m_itemdef);
1756 std::string texture_path = g_settings->get("texture_path");
1757 if (!texture_path.empty() && fs::IsDir(texture_path))
1758 m_nodedef->applyTextureOverrides(texture_path + DIR_DELIM + "override.txt");
1759 m_nodedef->setNodeRegistrationStatus(true);
1760 m_nodedef->runNodeResolveCallbacks();
1763 // Update node textures and assign shaders to each tile
1764 infostream<<"- Updating node textures"<<std::endl;
1765 TextureUpdateArgs tu_args;
1766 tu_args.guienv = guienv;
1767 tu_args.last_time_ms = porting::getTimeMs();
1768 tu_args.last_percent = 0;
1769 tu_args.text_base = wgettext("Initializing nodes");
1770 tu_args.tsrc = m_tsrc;
1771 m_nodedef->updateTextures(this, texture_update_progress, &tu_args);
1772 delete[] tu_args.text_base;
1774 // Start mesh update thread after setting up content definitions
1775 infostream<<"- Starting mesh update thread"<<std::endl;
1776 m_mesh_update_thread.start();
1781 if (g_settings->getBool("enable_client_modding")) {
1782 m_script->on_client_ready(m_env.getLocalPlayer());
1783 m_script->on_connect();
1786 text = wgettext("Done!");
1787 RenderingEngine::draw_load_screen(text, guienv, m_tsrc, 0, 100);
1788 infostream<<"Client::afterContentReceived() done"<<std::endl;
1792 float Client::getRTT()
1794 return m_con->getPeerStat(PEER_ID_SERVER,con::AVG_RTT);
1797 float Client::getCurRate()
1799 return (m_con->getLocalStat(con::CUR_INC_RATE) +
1800 m_con->getLocalStat(con::CUR_DL_RATE));
1803 void Client::makeScreenshot()
1805 irr::video::IVideoDriver *driver = RenderingEngine::get_video_driver();
1806 irr::video::IImage* const raw_image = driver->createScreenShot();
1811 time_t t = time(NULL);
1812 struct tm *tm = localtime(&t);
1814 char timetstamp_c[64];
1815 strftime(timetstamp_c, sizeof(timetstamp_c), "%Y%m%d_%H%M%S", tm);
1817 std::string filename_base = g_settings->get("screenshot_path")
1819 + std::string("screenshot_")
1820 + std::string(timetstamp_c);
1821 std::string filename_ext = "." + g_settings->get("screenshot_format");
1822 std::string filename;
1824 u32 quality = (u32)g_settings->getS32("screenshot_quality");
1825 quality = MYMIN(MYMAX(quality, 0), 100) / 100.0 * 255;
1827 // Try to find a unique filename
1828 unsigned serial = 0;
1830 while (serial < SCREENSHOT_MAX_SERIAL_TRIES) {
1831 filename = filename_base + (serial > 0 ? ("_" + itos(serial)) : "") + filename_ext;
1832 std::ifstream tmp(filename.c_str());
1834 break; // File did not apparently exist, we'll go with it
1838 if (serial == SCREENSHOT_MAX_SERIAL_TRIES) {
1839 infostream << "Could not find suitable filename for screenshot" << std::endl;
1841 irr::video::IImage* const image =
1842 driver->createImage(video::ECF_R8G8B8, raw_image->getDimension());
1845 raw_image->copyTo(image);
1847 std::ostringstream sstr;
1848 if (driver->writeImageToFile(image, filename.c_str(), quality)) {
1849 sstr << "Saved screenshot to '" << filename << "'";
1851 sstr << "Failed to save screenshot '" << filename << "'";
1853 pushToChatQueue(new ChatMessage(CHATMESSAGE_TYPE_SYSTEM,
1854 narrow_to_wide(sstr.str())));
1855 infostream << sstr.str() << std::endl;
1863 bool Client::shouldShowMinimap() const
1865 return !m_minimap_disabled_by_server;
1868 void Client::showGameChat(const bool show)
1870 m_game_ui_flags->show_chat = show;
1873 void Client::showGameHud(const bool show)
1875 m_game_ui_flags->show_hud = show;
1878 void Client::showMinimap(const bool show)
1880 m_game_ui_flags->show_minimap = show;
1883 void Client::showProfiler(const bool show)
1885 m_game_ui_flags->show_profiler_graph = show;
1888 void Client::showGameFog(const bool show)
1890 m_game_ui_flags->force_fog_off = !show;
1893 void Client::showGameDebug(const bool show)
1895 m_game_ui_flags->show_debug = show;
1898 // IGameDef interface
1900 IItemDefManager* Client::getItemDefManager()
1904 INodeDefManager* Client::getNodeDefManager()
1908 ICraftDefManager* Client::getCraftDefManager()
1911 //return m_craftdef;
1913 ITextureSource* Client::getTextureSource()
1917 IShaderSource* Client::getShaderSource()
1922 u16 Client::allocateUnknownNodeId(const std::string &name)
1924 errorstream << "Client::allocateUnknownNodeId(): "
1925 << "Client cannot allocate node IDs" << std::endl;
1926 FATAL_ERROR("Client allocated unknown node");
1928 return CONTENT_IGNORE;
1930 ISoundManager* Client::getSoundManager()
1934 MtEventManager* Client::getEventManager()
1939 ParticleManager* Client::getParticleManager()
1941 return &m_particle_manager;
1944 scene::IAnimatedMesh* Client::getMesh(const std::string &filename)
1946 StringMap::const_iterator it = m_mesh_data.find(filename);
1947 if (it == m_mesh_data.end()) {
1948 errorstream << "Client::getMesh(): Mesh not found: \"" << filename
1949 << "\"" << std::endl;
1952 const std::string &data = it->second;
1954 // Create the mesh, remove it from cache and return it
1955 // This allows unique vertex colors and other properties for each instance
1956 Buffer<char> data_rw(data.c_str(), data.size()); // Const-incorrect Irrlicht
1957 io::IReadFile *rfile = RenderingEngine::get_filesystem()->createMemoryReadFile(
1958 *data_rw, data_rw.getSize(), filename.c_str());
1959 FATAL_ERROR_IF(!rfile, "Could not create/open RAM file");
1961 scene::IAnimatedMesh *mesh = RenderingEngine::get_scene_manager()->getMesh(rfile);
1963 // NOTE: By playing with Irrlicht refcounts, maybe we could cache a bunch
1964 // of uniquely named instances and re-use them
1966 RenderingEngine::get_mesh_cache()->removeMesh(mesh);
1970 const std::string* Client::getModFile(const std::string &filename)
1972 StringMap::const_iterator it = m_mod_files.find(filename);
1973 if (it == m_mod_files.end()) {
1974 errorstream << "Client::getModFile(): File not found: \"" << filename
1975 << "\"" << std::endl;
1981 bool Client::registerModStorage(ModMetadata *storage)
1983 if (m_mod_storages.find(storage->getModName()) != m_mod_storages.end()) {
1984 errorstream << "Unable to register same mod storage twice. Storage name: "
1985 << storage->getModName() << std::endl;
1989 m_mod_storages[storage->getModName()] = storage;
1993 void Client::unregisterModStorage(const std::string &name)
1995 std::unordered_map<std::string, ModMetadata *>::const_iterator it =
1996 m_mod_storages.find(name);
1997 if (it != m_mod_storages.end()) {
1998 // Save unconditionaly on unregistration
1999 it->second->save(getModStoragePath());
2000 m_mod_storages.erase(name);
2004 std::string Client::getModStoragePath() const
2006 return porting::path_user + DIR_DELIM + "client" + DIR_DELIM + "mod_storage";