3 Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com>
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU Lesser General Public License as published by
7 the Free Software Foundation; either version 2.1 of the License, or
8 (at your option) any later version.
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU Lesser General Public License for more details.
15 You should have received a copy of the GNU Lesser General Public License along
16 with this program; if not, write to the Free Software Foundation, Inc.,
17 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
24 #include <IFileSystem.h>
25 #include "threading/mutex_auto_lock.h"
26 #include "util/auth.h"
27 #include "util/directiontables.h"
28 #include "util/pointedthing.h"
29 #include "util/serialize.h"
30 #include "util/string.h"
33 #include "network/clientopcodes.h"
35 #include "mapblock_mesh.h"
41 #include "clientmap.h"
42 #include "clientmedia.h"
44 #include "drawscene.h"
45 #include "database-sqlite3.h"
46 #include "serialization.h"
47 #include "guiscalingfilter.h"
48 #include "script/clientscripting.h"
50 extern gui::IGUIEnvironment* guienv;
56 QueuedMeshUpdate::QueuedMeshUpdate():
59 ack_block_to_server(false)
63 QueuedMeshUpdate::~QueuedMeshUpdate()
73 MeshUpdateQueue::MeshUpdateQueue()
77 MeshUpdateQueue::~MeshUpdateQueue()
79 MutexAutoLock lock(m_mutex);
81 for(std::vector<QueuedMeshUpdate*>::iterator
83 i != m_queue.end(); ++i)
85 QueuedMeshUpdate *q = *i;
91 peer_id=0 adds with nobody to send to
93 void MeshUpdateQueue::addBlock(v3s16 p, MeshMakeData *data, bool ack_block_to_server, bool urgent)
95 DSTACK(FUNCTION_NAME);
97 assert(data); // pre-condition
99 MutexAutoLock lock(m_mutex);
105 Find if block is already in queue.
106 If it is, update the data and quit.
108 for(std::vector<QueuedMeshUpdate*>::iterator
110 i != m_queue.end(); ++i)
112 QueuedMeshUpdate *q = *i;
118 if(ack_block_to_server)
119 q->ack_block_to_server = true;
127 QueuedMeshUpdate *q = new QueuedMeshUpdate;
130 q->ack_block_to_server = ack_block_to_server;
131 m_queue.push_back(q);
134 // Returned pointer must be deleted
135 // Returns NULL if queue is empty
136 QueuedMeshUpdate *MeshUpdateQueue::pop()
138 MutexAutoLock lock(m_mutex);
140 bool must_be_urgent = !m_urgents.empty();
141 for(std::vector<QueuedMeshUpdate*>::iterator
143 i != m_queue.end(); ++i)
145 QueuedMeshUpdate *q = *i;
146 if(must_be_urgent && m_urgents.count(q->p) == 0)
149 m_urgents.erase(q->p);
159 void MeshUpdateThread::enqueueUpdate(v3s16 p, MeshMakeData *data,
160 bool ack_block_to_server, bool urgent)
162 m_queue_in.addBlock(p, data, ack_block_to_server, urgent);
166 void MeshUpdateThread::doUpdate()
169 while ((q = m_queue_in.pop())) {
171 ScopeProfiler sp(g_profiler, "Client: Mesh making");
173 MapBlockMesh *mesh_new = new MapBlockMesh(q->data, m_camera_offset);
178 r.ack_block_to_server = q->ack_block_to_server;
180 m_queue_out.push_back(r);
191 IrrlichtDevice *device,
192 const char *playername,
193 std::string password,
194 MapDrawControl &control,
195 IWritableTextureSource *tsrc,
196 IWritableShaderSource *shsrc,
197 IWritableItemDefManager *itemdef,
198 IWritableNodeDefManager *nodedef,
199 ISoundManager *sound,
200 MtEventManager *event,
203 m_packetcounter_timer(0.0),
204 m_connection_reinit_timer(0.1),
205 m_avg_rtt_timer(0.0),
206 m_playerpos_send_timer(0.0),
207 m_ignore_damage_timer(0.0),
214 m_mesh_update_thread(),
216 new ClientMap(this, control,
217 device->getSceneManager()->getRootSceneNode(),
218 device->getSceneManager(), 666),
219 device->getSceneManager(),
222 m_particle_manager(&m_env),
223 m_con(PROTOCOL_ID, 512, CONNECTION_TIMEOUT, ipv6, this),
226 m_minimap_disabled_by_server(false),
227 m_server_ser_ver(SER_FMT_VER_INVALID),
230 m_inventory_updated(false),
231 m_inventory_from_server(NULL),
232 m_inventory_from_server_age(0.0),
237 m_password(password),
238 m_chosen_auth_mech(AUTH_MECHANISM_NONE),
240 m_access_denied(false),
241 m_access_denied_reconnect(false),
242 m_itemdef_received(false),
243 m_nodedef_received(false),
244 m_media_downloader(new ClientMediaDownloader()),
245 m_time_of_day_set(false),
246 m_last_time_of_day_f(-1),
247 m_time_of_day_update_timer(0),
248 m_recommended_send_interval(0.1),
249 m_removed_sounds_check_timer(0),
253 m_mod_storage_save_timer(10.0f)
256 m_env.setLocalPlayer(new LocalPlayer(this, playername));
258 m_minimap = new Minimap(device, this);
259 m_cache_save_interval = g_settings->getU16("server_map_save_interval");
261 m_cache_smooth_lighting = g_settings->getBool("smooth_lighting");
262 m_cache_enable_shaders = g_settings->getBool("enable_shaders");
263 m_cache_use_tangent_vertices = m_cache_enable_shaders && (
264 g_settings->getBool("enable_bumpmapping") ||
265 g_settings->getBool("enable_parallax_occlusion"));
267 m_modding_enabled = g_settings->getBool("enable_client_modding");
268 m_script = new ClientScripting(this);
269 m_env.setScript(m_script);
270 m_script->setEnv(&m_env);
273 void Client::initMods()
275 m_script->loadMod(getBuiltinLuaPath() + DIR_DELIM "init.lua", BUILTIN_MOD_NAME);
277 // If modding is not enabled, don't load mods, just builtin
278 if (!m_modding_enabled) {
282 ClientModConfiguration modconf(getClientModsLuaPath());
283 std::vector<ModSpec> mods = modconf.getMods();
284 std::vector<ModSpec> unsatisfied_mods = modconf.getUnsatisfiedMods();
285 // complain about mods with unsatisfied dependencies
286 if (!modconf.isConsistent()) {
287 modconf.printUnsatisfiedModsError();
291 infostream << "Client Loading mods: ";
292 for (std::vector<ModSpec>::const_iterator i = mods.begin();
293 i != mods.end(); ++i) {
294 infostream << (*i).name << " ";
297 infostream << std::endl;
298 // Load and run "mod" scripts
299 for (std::vector<ModSpec>::const_iterator it = mods.begin();
300 it != mods.end(); ++it) {
301 const ModSpec &mod = *it;
302 if (!string_allowed(mod.name, MODNAME_ALLOWED_CHARS)) {
303 throw ModError("Error loading mod \"" + mod.name +
304 "\": Mod name does not follow naming conventions: "
305 "Only chararacters [a-z0-9_] are allowed.");
307 std::string script_path = mod.path + DIR_DELIM + "init.lua";
308 infostream << " [" << padStringRight(mod.name, 12) << "] [\""
309 << script_path << "\"]" << std::endl;
310 m_script->loadMod(script_path, mod.name);
314 const std::string &Client::getBuiltinLuaPath()
316 static const std::string builtin_dir = porting::path_share + DIR_DELIM + "builtin";
320 const std::string &Client::getClientModsLuaPath()
322 static const std::string clientmods_dir = porting::path_share + DIR_DELIM + "clientmods";
323 return clientmods_dir;
326 const std::vector<ModSpec>& Client::getMods() const
328 static std::vector<ModSpec> client_modspec_temp;
329 return client_modspec_temp;
332 const ModSpec* Client::getModSpec(const std::string &modname) const
339 // Don't disable this part when modding is disabled, it's used in builtin
340 m_script->on_shutdown();
341 //request all client managed threads to stop
342 m_mesh_update_thread.stop();
343 // Save local server map
345 infostream << "Local map saving ended." << std::endl;
346 m_localdb->endSave();
352 bool Client::isShutdown()
355 if (!m_mesh_update_thread.isRunning()) return true;
364 m_mesh_update_thread.stop();
365 m_mesh_update_thread.wait();
366 while (!m_mesh_update_thread.m_queue_out.empty()) {
367 MeshUpdateResult r = m_mesh_update_thread.m_queue_out.pop_frontNoEx();
372 delete m_inventory_from_server;
374 // Delete detached inventories
375 for (UNORDERED_MAP<std::string, Inventory*>::iterator
376 i = m_detached_inventories.begin();
377 i != m_detached_inventories.end(); ++i) {
381 // cleanup 3d model meshes on client shutdown
382 while (m_device->getSceneManager()->getMeshCache()->getMeshCount() != 0) {
383 scene::IAnimatedMesh *mesh =
384 m_device->getSceneManager()->getMeshCache()->getMeshByIndex(0);
387 m_device->getSceneManager()->getMeshCache()->removeMesh(mesh);
393 void Client::connect(Address address,
394 const std::string &address_name,
395 bool is_local_server)
397 DSTACK(FUNCTION_NAME);
399 initLocalMapSaving(address, address_name, is_local_server);
401 m_con.SetTimeoutMs(0);
402 m_con.Connect(address);
405 void Client::step(float dtime)
407 DSTACK(FUNCTION_NAME);
413 if(m_ignore_damage_timer > dtime)
414 m_ignore_damage_timer -= dtime;
416 m_ignore_damage_timer = 0.0;
418 m_animation_time += dtime;
419 if(m_animation_time > 60.0)
420 m_animation_time -= 60.0;
422 m_time_of_day_update_timer += dtime;
430 float &counter = m_packetcounter_timer;
436 infostream << "Client packetcounter (" << m_packetcounter_timer
438 m_packetcounter.print(infostream);
439 m_packetcounter.clear();
443 // UGLY hack to fix 2 second startup delay caused by non existent
444 // server client startup synchronization in local server or singleplayer mode
445 static bool initial_step = true;
447 initial_step = false;
449 else if(m_state == LC_Created) {
450 float &counter = m_connection_reinit_timer;
455 LocalPlayer *myplayer = m_env.getLocalPlayer();
456 FATAL_ERROR_IF(myplayer == NULL, "Local player not found in environment.");
458 u16 proto_version_min = g_settings->getFlag("send_pre_v25_init") ?
459 CLIENT_PROTOCOL_VERSION_MIN_LEGACY : CLIENT_PROTOCOL_VERSION_MIN;
461 if (proto_version_min < 25) {
462 // Send TOSERVER_INIT_LEGACY
463 // [0] u16 TOSERVER_INIT_LEGACY
464 // [2] u8 SER_FMT_VER_HIGHEST_READ
465 // [3] u8[20] player_name
466 // [23] u8[28] password (new in some version)
467 // [51] u16 minimum supported network protocol version (added sometime)
468 // [53] u16 maximum supported network protocol version (added later than the previous one)
470 char pName[PLAYERNAME_SIZE];
471 char pPassword[PASSWORD_SIZE];
472 memset(pName, 0, PLAYERNAME_SIZE * sizeof(char));
473 memset(pPassword, 0, PASSWORD_SIZE * sizeof(char));
475 std::string hashed_password = translate_password(myplayer->getName(), m_password);
476 snprintf(pName, PLAYERNAME_SIZE, "%s", myplayer->getName());
477 snprintf(pPassword, PASSWORD_SIZE, "%s", hashed_password.c_str());
479 sendLegacyInit(pName, pPassword);
481 if (CLIENT_PROTOCOL_VERSION_MAX >= 25)
482 sendInit(myplayer->getName());
485 // Not connected, return
490 Do stuff if connected
494 Run Map's timers and unload unused data
496 const float map_timer_and_unload_dtime = 5.25;
497 if(m_map_timer_and_unload_interval.step(dtime, map_timer_and_unload_dtime)) {
498 ScopeProfiler sp(g_profiler, "Client: map timer and unload");
499 std::vector<v3s16> deleted_blocks;
500 m_env.getMap().timerUpdate(map_timer_and_unload_dtime,
501 g_settings->getFloat("client_unload_unused_data_timeout"),
502 g_settings->getS32("client_mapblock_limit"),
507 NOTE: This loop is intentionally iterated the way it is.
510 std::vector<v3s16>::iterator i = deleted_blocks.begin();
511 std::vector<v3s16> sendlist;
513 if(sendlist.size() == 255 || i == deleted_blocks.end()) {
524 sendDeletedBlocks(sendlist);
526 if(i == deleted_blocks.end())
532 sendlist.push_back(*i);
540 // Control local player (0ms)
541 LocalPlayer *player = m_env.getLocalPlayer();
542 assert(player != NULL);
543 player->applyControl(dtime);
552 ClientEnvEvent event = m_env.getClientEvent();
553 if(event.type == CEE_NONE) {
556 else if(event.type == CEE_PLAYER_DAMAGE) {
557 if(m_ignore_damage_timer <= 0) {
558 u8 damage = event.player_damage.amount;
560 if(event.player_damage.send_to_server)
563 // Add to ClientEvent queue
565 event.type = CE_PLAYER_DAMAGE;
566 event.player_damage.amount = damage;
567 m_client_event_queue.push(event);
570 // Protocol v29 or greater obsoleted this event
571 else if (event.type == CEE_PLAYER_BREATH && m_proto_ver < 29) {
572 u16 breath = event.player_breath.amount;
580 float &counter = m_avg_rtt_timer;
584 // connectedAndInitialized() is true, peer exists.
585 float avg_rtt = getRTT();
586 infostream << "Client: avg_rtt=" << avg_rtt << std::endl;
590 Send player position to server
593 float &counter = m_playerpos_send_timer;
595 if((m_state == LC_Ready) && (counter >= m_recommended_send_interval))
603 Replace updated meshes
606 int num_processed_meshes = 0;
607 while (!m_mesh_update_thread.m_queue_out.empty())
609 num_processed_meshes++;
611 MinimapMapblock *minimap_mapblock = NULL;
612 bool do_mapper_update = true;
614 MeshUpdateResult r = m_mesh_update_thread.m_queue_out.pop_frontNoEx();
615 MapBlock *block = m_env.getMap().getBlockNoCreateNoEx(r.p);
617 // Delete the old mesh
618 if (block->mesh != NULL) {
624 minimap_mapblock = r.mesh->moveMinimapMapblock();
625 if (minimap_mapblock == NULL)
626 do_mapper_update = false;
629 if (r.mesh && r.mesh->getMesh()->getMeshBufferCount() == 0) {
632 // Replace with the new mesh
633 block->mesh = r.mesh;
639 if (do_mapper_update)
640 m_minimap->addBlock(r.p, minimap_mapblock);
642 if (r.ack_block_to_server) {
652 if (num_processed_meshes > 0)
653 g_profiler->graphAdd("num_processed_meshes", num_processed_meshes);
659 if (m_media_downloader && m_media_downloader->isStarted()) {
660 m_media_downloader->step(this);
661 if (m_media_downloader->isDone()) {
663 delete m_media_downloader;
664 m_media_downloader = NULL;
669 If the server didn't update the inventory in a while, revert
670 the local inventory (so the player notices the lag problem
671 and knows something is wrong).
673 if(m_inventory_from_server)
675 float interval = 10.0;
676 float count_before = floor(m_inventory_from_server_age / interval);
678 m_inventory_from_server_age += dtime;
680 float count_after = floor(m_inventory_from_server_age / interval);
682 if(count_after != count_before)
684 // Do this every <interval> seconds after TOCLIENT_INVENTORY
685 // Reset the locally changed inventory to the authoritative inventory
686 LocalPlayer *player = m_env.getLocalPlayer();
687 player->inventory = *m_inventory_from_server;
688 m_inventory_updated = true;
693 Update positions of sounds attached to objects
696 for(UNORDERED_MAP<int, u16>::iterator i = m_sounds_to_objects.begin();
697 i != m_sounds_to_objects.end(); ++i) {
698 int client_id = i->first;
699 u16 object_id = i->second;
700 ClientActiveObject *cao = m_env.getActiveObject(object_id);
703 v3f pos = cao->getPosition();
704 m_sound->updateSoundPosition(client_id, pos);
709 Handle removed remotely initiated sounds
711 m_removed_sounds_check_timer += dtime;
712 if(m_removed_sounds_check_timer >= 2.32) {
713 m_removed_sounds_check_timer = 0;
714 // Find removed sounds and clear references to them
715 std::vector<s32> removed_server_ids;
716 for(UNORDERED_MAP<s32, int>::iterator i = m_sounds_server_to_client.begin();
717 i != m_sounds_server_to_client.end();) {
718 s32 server_id = i->first;
719 int client_id = i->second;
721 if(!m_sound->soundExists(client_id)) {
722 m_sounds_server_to_client.erase(server_id);
723 m_sounds_client_to_server.erase(client_id);
724 m_sounds_to_objects.erase(client_id);
725 removed_server_ids.push_back(server_id);
730 if(!removed_server_ids.empty()) {
731 sendRemovedSounds(removed_server_ids);
735 m_mod_storage_save_timer -= dtime;
736 if (m_mod_storage_save_timer <= 0.0f) {
737 verbosestream << "Saving registered mod storages." << std::endl;
738 m_mod_storage_save_timer = g_settings->getFloat("server_map_save_interval");
739 for (UNORDERED_MAP<std::string, ModMetadata *>::const_iterator
740 it = m_mod_storages.begin(); it != m_mod_storages.end(); ++it) {
741 if (it->second->isModified()) {
742 it->second->save(getModStoragePath());
748 if (m_localdb && m_localdb_save_interval.step(dtime,
749 m_cache_save_interval)) {
750 m_localdb->endSave();
751 m_localdb->beginSave();
755 bool Client::loadMedia(const std::string &data, const std::string &filename)
757 // Silly irrlicht's const-incorrectness
758 Buffer<char> data_rw(data.c_str(), data.size());
762 const char *image_ext[] = {
763 ".png", ".jpg", ".bmp", ".tga",
764 ".pcx", ".ppm", ".psd", ".wal", ".rgb",
767 name = removeStringEnd(filename, image_ext);
770 verbosestream<<"Client: Attempting to load image "
771 <<"file \""<<filename<<"\""<<std::endl;
773 io::IFileSystem *irrfs = m_device->getFileSystem();
774 video::IVideoDriver *vdrv = m_device->getVideoDriver();
776 // Create an irrlicht memory file
777 io::IReadFile *rfile = irrfs->createMemoryReadFile(
778 *data_rw, data_rw.getSize(), "_tempreadfile");
780 FATAL_ERROR_IF(!rfile, "Could not create irrlicht memory file.");
783 video::IImage *img = vdrv->createImageFromFile(rfile);
785 errorstream<<"Client: Cannot create image from data of "
786 <<"file \""<<filename<<"\""<<std::endl;
791 m_tsrc->insertSourceImage(filename, img);
798 const char *sound_ext[] = {
799 ".0.ogg", ".1.ogg", ".2.ogg", ".3.ogg", ".4.ogg",
800 ".5.ogg", ".6.ogg", ".7.ogg", ".8.ogg", ".9.ogg",
803 name = removeStringEnd(filename, sound_ext);
806 verbosestream<<"Client: Attempting to load sound "
807 <<"file \""<<filename<<"\""<<std::endl;
808 m_sound->loadSoundData(name, data);
812 const char *model_ext[] = {
813 ".x", ".b3d", ".md2", ".obj",
816 name = removeStringEnd(filename, model_ext);
819 verbosestream<<"Client: Storing model into memory: "
820 <<"\""<<filename<<"\""<<std::endl;
821 if(m_mesh_data.count(filename))
822 errorstream<<"Multiple models with name \""<<filename.c_str()
823 <<"\" found; replacing previous model"<<std::endl;
824 m_mesh_data[filename] = data;
828 errorstream<<"Client: Don't know how to load file \""
829 <<filename<<"\""<<std::endl;
833 // Virtual methods from con::PeerHandler
834 void Client::peerAdded(con::Peer *peer)
836 infostream << "Client::peerAdded(): peer->id="
837 << peer->id << std::endl;
839 void Client::deletingPeer(con::Peer *peer, bool timeout)
841 infostream << "Client::deletingPeer(): "
842 "Server Peer is getting deleted "
843 << "(timeout=" << timeout << ")" << std::endl;
846 m_access_denied = true;
847 m_access_denied_reason = gettext("Connection timed out.");
853 u16 number of files requested
859 void Client::request_media(const std::vector<std::string> &file_requests)
861 std::ostringstream os(std::ios_base::binary);
862 writeU16(os, TOSERVER_REQUEST_MEDIA);
863 size_t file_requests_size = file_requests.size();
865 FATAL_ERROR_IF(file_requests_size > 0xFFFF, "Unsupported number of file requests");
867 // Packet dynamicly resized
868 NetworkPacket pkt(TOSERVER_REQUEST_MEDIA, 2 + 0);
870 pkt << (u16) (file_requests_size & 0xFFFF);
872 for(std::vector<std::string>::const_iterator i = file_requests.begin();
873 i != file_requests.end(); ++i) {
879 infostream << "Client: Sending media request list to server ("
880 << file_requests.size() << " files. packet size)" << std::endl;
883 void Client::received_media()
885 NetworkPacket pkt(TOSERVER_RECEIVED_MEDIA, 0);
887 infostream << "Client: Notifying server that we received all media"
891 void Client::initLocalMapSaving(const Address &address,
892 const std::string &hostname,
893 bool is_local_server)
895 if (!g_settings->getBool("enable_local_map_saving") || is_local_server) {
899 const std::string world_path = porting::path_user
900 + DIR_DELIM + "worlds"
901 + DIR_DELIM + "server_"
902 + hostname + "_" + std::to_string(address.getPort());
904 fs::CreateAllDirs(world_path);
906 m_localdb = new Database_SQLite3(world_path);
907 m_localdb->beginSave();
908 actionstream << "Local map saving started, map will be saved at '" << world_path << "'" << std::endl;
911 void Client::ReceiveAll()
913 DSTACK(FUNCTION_NAME);
914 u32 start_ms = porting::getTimeMs();
917 // Limit time even if there would be huge amounts of data to
919 if(porting::getTimeMs() > start_ms + 100)
924 g_profiler->graphAdd("client_received_packets", 1);
926 catch(con::NoIncomingDataException &e) {
929 catch(con::InvalidIncomingDataException &e) {
930 infostream<<"Client::ReceiveAll(): "
931 "InvalidIncomingDataException: what()="
932 <<e.what()<<std::endl;
937 void Client::Receive()
939 DSTACK(FUNCTION_NAME);
945 inline void Client::handleCommand(NetworkPacket* pkt)
947 const ToClientCommandHandler& opHandle = toClientCommandTable[pkt->getCommand()];
948 (this->*opHandle.handler)(pkt);
952 sender_peer_id given to this shall be quaranteed to be a valid peer
954 void Client::ProcessData(NetworkPacket *pkt)
956 DSTACK(FUNCTION_NAME);
958 ToClientCommand command = (ToClientCommand) pkt->getCommand();
959 u32 sender_peer_id = pkt->getPeerId();
961 //infostream<<"Client: received command="<<command<<std::endl;
962 m_packetcounter.add((u16)command);
965 If this check is removed, be sure to change the queue
966 system to know the ids
968 if(sender_peer_id != PEER_ID_SERVER) {
969 infostream << "Client::ProcessData(): Discarding data not "
970 "coming from server: peer_id=" << sender_peer_id
975 // Command must be handled into ToClientCommandHandler
976 if (command >= TOCLIENT_NUM_MSG_TYPES) {
977 infostream << "Client: Ignoring unknown command "
978 << command << std::endl;
983 * Those packets are handled before m_server_ser_ver is set, it's normal
984 * But we must use the new ToClientConnectionState in the future,
987 if(toClientCommandTable[command].state == TOCLIENT_STATE_NOT_CONNECTED) {
992 if(m_server_ser_ver == SER_FMT_VER_INVALID) {
993 infostream << "Client: Server serialization"
994 " format invalid or not initialized."
995 " Skipping incoming command=" << command << std::endl;
1000 Handle runtime commands
1006 void Client::Send(NetworkPacket* pkt)
1008 m_con.Send(PEER_ID_SERVER,
1009 serverCommandFactoryTable[pkt->getCommand()].channel,
1011 serverCommandFactoryTable[pkt->getCommand()].reliable);
1014 // Will fill up 12 + 12 + 4 + 4 + 4 bytes
1015 void writePlayerPos(LocalPlayer *myplayer, ClientMap *clientMap, NetworkPacket *pkt)
1017 v3f pf = myplayer->getPosition() * 100;
1018 v3f sf = myplayer->getSpeed() * 100;
1019 s32 pitch = myplayer->getPitch() * 100;
1020 s32 yaw = myplayer->getYaw() * 100;
1021 u32 keyPressed = myplayer->keyPressed;
1022 // scaled by 80, so that pi can fit into a u8
1023 u8 fov = clientMap->getCameraFov() * 80;
1024 u8 wanted_range = MYMIN(255,
1025 std::ceil(clientMap->getControl().wanted_range / MAP_BLOCKSIZE));
1027 v3s32 position(pf.X, pf.Y, pf.Z);
1028 v3s32 speed(sf.X, sf.Y, sf.Z);
1032 [0] v3s32 position*100
1033 [12] v3s32 speed*100
1034 [12+12] s32 pitch*100
1035 [12+12+4] s32 yaw*100
1036 [12+12+4+4] u32 keyPressed
1037 [12+12+4+4+4] u8 fov*80
1038 [12+12+4+4+4+1] u8 ceil(wanted_range / MAP_BLOCKSIZE)
1040 *pkt << position << speed << pitch << yaw << keyPressed;
1041 *pkt << fov << wanted_range;
1044 void Client::interact(u8 action, const PointedThing& pointed)
1046 if(m_state != LC_Ready) {
1047 errorstream << "Client::interact() "
1048 "Canceled (not connected)"
1053 LocalPlayer *myplayer = m_env.getLocalPlayer();
1054 if (myplayer == NULL)
1061 [5] u32 length of the next item (plen)
1062 [9] serialized PointedThing
1063 [9 + plen] player position information
1065 0: start digging (from undersurface) or use
1066 1: stop digging (all parameters ignored)
1067 2: digging completed
1068 3: place block or item (to abovesurface)
1070 5: perform secondary action of item
1073 NetworkPacket pkt(TOSERVER_INTERACT, 1 + 2 + 0);
1076 pkt << (u16)getPlayerItem();
1078 std::ostringstream tmp_os(std::ios::binary);
1079 pointed.serialize(tmp_os);
1081 pkt.putLongString(tmp_os.str());
1083 writePlayerPos(myplayer, &m_env.getClientMap(), &pkt);
1088 void Client::deleteAuthData()
1093 switch (m_chosen_auth_mech) {
1094 case AUTH_MECHANISM_FIRST_SRP:
1096 case AUTH_MECHANISM_SRP:
1097 case AUTH_MECHANISM_LEGACY_PASSWORD:
1098 srp_user_delete((SRPUser *) m_auth_data);
1101 case AUTH_MECHANISM_NONE:
1104 m_chosen_auth_mech = AUTH_MECHANISM_NONE;
1108 AuthMechanism Client::choseAuthMech(const u32 mechs)
1110 if (mechs & AUTH_MECHANISM_SRP)
1111 return AUTH_MECHANISM_SRP;
1113 if (mechs & AUTH_MECHANISM_FIRST_SRP)
1114 return AUTH_MECHANISM_FIRST_SRP;
1116 if (mechs & AUTH_MECHANISM_LEGACY_PASSWORD)
1117 return AUTH_MECHANISM_LEGACY_PASSWORD;
1119 return AUTH_MECHANISM_NONE;
1122 void Client::sendLegacyInit(const char* playerName, const char* playerPassword)
1124 NetworkPacket pkt(TOSERVER_INIT_LEGACY,
1125 1 + PLAYERNAME_SIZE + PASSWORD_SIZE + 2 + 2);
1127 u16 proto_version_min = g_settings->getFlag("send_pre_v25_init") ?
1128 CLIENT_PROTOCOL_VERSION_MIN_LEGACY : CLIENT_PROTOCOL_VERSION_MIN;
1130 pkt << (u8) SER_FMT_VER_HIGHEST_READ;
1131 pkt.putRawString(playerName,PLAYERNAME_SIZE);
1132 pkt.putRawString(playerPassword, PASSWORD_SIZE);
1133 pkt << (u16) proto_version_min << (u16) CLIENT_PROTOCOL_VERSION_MAX;
1138 void Client::sendInit(const std::string &playerName)
1140 NetworkPacket pkt(TOSERVER_INIT, 1 + 2 + 2 + (1 + playerName.size()));
1142 // we don't support network compression yet
1143 u16 supp_comp_modes = NETPROTO_COMPRESSION_NONE;
1145 u16 proto_version_min = g_settings->getFlag("send_pre_v25_init") ?
1146 CLIENT_PROTOCOL_VERSION_MIN_LEGACY : CLIENT_PROTOCOL_VERSION_MIN;
1148 pkt << (u8) SER_FMT_VER_HIGHEST_READ << (u16) supp_comp_modes;
1149 pkt << (u16) proto_version_min << (u16) CLIENT_PROTOCOL_VERSION_MAX;
1155 void Client::startAuth(AuthMechanism chosen_auth_mechanism)
1157 m_chosen_auth_mech = chosen_auth_mechanism;
1159 switch (chosen_auth_mechanism) {
1160 case AUTH_MECHANISM_FIRST_SRP: {
1161 // send srp verifier to server
1162 std::string verifier;
1164 generate_srp_verifier_and_salt(getPlayerName(), m_password,
1167 NetworkPacket resp_pkt(TOSERVER_FIRST_SRP, 0);
1168 resp_pkt << salt << verifier << (u8)((m_password == "") ? 1 : 0);
1173 case AUTH_MECHANISM_SRP:
1174 case AUTH_MECHANISM_LEGACY_PASSWORD: {
1177 if (chosen_auth_mechanism == AUTH_MECHANISM_LEGACY_PASSWORD) {
1178 m_password = translate_password(getPlayerName(), m_password);
1182 std::string playername_u = lowercase(getPlayerName());
1183 m_auth_data = srp_user_new(SRP_SHA256, SRP_NG_2048,
1184 getPlayerName().c_str(), playername_u.c_str(),
1185 (const unsigned char *) m_password.c_str(),
1186 m_password.length(), NULL, NULL);
1189 SRP_Result res = srp_user_start_authentication(
1190 (struct SRPUser *) m_auth_data, NULL, NULL, 0,
1191 (unsigned char **) &bytes_A, &len_A);
1192 FATAL_ERROR_IF(res != SRP_OK, "Creating local SRP user failed.");
1194 NetworkPacket resp_pkt(TOSERVER_SRP_BYTES_A, 0);
1195 resp_pkt << std::string(bytes_A, len_A) << based_on;
1199 case AUTH_MECHANISM_NONE:
1200 break; // not handled in this method
1204 void Client::sendDeletedBlocks(std::vector<v3s16> &blocks)
1206 NetworkPacket pkt(TOSERVER_DELETEDBLOCKS, 1 + sizeof(v3s16) * blocks.size());
1208 pkt << (u8) blocks.size();
1211 for(std::vector<v3s16>::iterator
1213 j != blocks.end(); ++j) {
1221 void Client::sendGotBlocks(v3s16 block)
1223 NetworkPacket pkt(TOSERVER_GOTBLOCKS, 1 + 6);
1224 pkt << (u8) 1 << block;
1228 void Client::sendRemovedSounds(std::vector<s32> &soundList)
1230 size_t server_ids = soundList.size();
1231 assert(server_ids <= 0xFFFF);
1233 NetworkPacket pkt(TOSERVER_REMOVED_SOUNDS, 2 + server_ids * 4);
1235 pkt << (u16) (server_ids & 0xFFFF);
1237 for(std::vector<s32>::iterator i = soundList.begin();
1238 i != soundList.end(); ++i)
1244 void Client::sendNodemetaFields(v3s16 p, const std::string &formname,
1245 const StringMap &fields)
1247 size_t fields_size = fields.size();
1249 FATAL_ERROR_IF(fields_size > 0xFFFF, "Unsupported number of nodemeta fields");
1251 NetworkPacket pkt(TOSERVER_NODEMETA_FIELDS, 0);
1253 pkt << p << formname << (u16) (fields_size & 0xFFFF);
1255 StringMap::const_iterator it;
1256 for (it = fields.begin(); it != fields.end(); ++it) {
1257 const std::string &name = it->first;
1258 const std::string &value = it->second;
1260 pkt.putLongString(value);
1266 void Client::sendInventoryFields(const std::string &formname,
1267 const StringMap &fields)
1269 size_t fields_size = fields.size();
1270 FATAL_ERROR_IF(fields_size > 0xFFFF, "Unsupported number of inventory fields");
1272 NetworkPacket pkt(TOSERVER_INVENTORY_FIELDS, 0);
1273 pkt << formname << (u16) (fields_size & 0xFFFF);
1275 StringMap::const_iterator it;
1276 for (it = fields.begin(); it != fields.end(); ++it) {
1277 const std::string &name = it->first;
1278 const std::string &value = it->second;
1280 pkt.putLongString(value);
1286 void Client::sendInventoryAction(InventoryAction *a)
1288 std::ostringstream os(std::ios_base::binary);
1293 std::string s = os.str();
1295 NetworkPacket pkt(TOSERVER_INVENTORY_ACTION, s.size());
1296 pkt.putRawString(s.c_str(),s.size());
1301 void Client::sendChatMessage(const std::wstring &message)
1303 NetworkPacket pkt(TOSERVER_CHAT_MESSAGE, 2 + message.size() * sizeof(u16));
1310 void Client::sendChangePassword(const std::string &oldpassword,
1311 const std::string &newpassword)
1313 LocalPlayer *player = m_env.getLocalPlayer();
1317 std::string playername = player->getName();
1318 if (m_proto_ver >= 25) {
1319 // get into sudo mode and then send new password to server
1320 m_password = oldpassword;
1321 m_new_password = newpassword;
1322 startAuth(choseAuthMech(m_sudo_auth_methods));
1324 std::string oldpwd = translate_password(playername, oldpassword);
1325 std::string newpwd = translate_password(playername, newpassword);
1327 NetworkPacket pkt(TOSERVER_PASSWORD_LEGACY, 2 * PASSWORD_SIZE);
1329 for (u8 i = 0; i < PASSWORD_SIZE; i++) {
1330 pkt << (u8) (i < oldpwd.length() ? oldpwd[i] : 0);
1333 for (u8 i = 0; i < PASSWORD_SIZE; i++) {
1334 pkt << (u8) (i < newpwd.length() ? newpwd[i] : 0);
1341 void Client::sendDamage(u8 damage)
1343 DSTACK(FUNCTION_NAME);
1345 NetworkPacket pkt(TOSERVER_DAMAGE, sizeof(u8));
1350 void Client::sendBreath(u16 breath)
1352 DSTACK(FUNCTION_NAME);
1354 // Protocol v29 make this obsolete
1355 if (m_proto_ver >= 29)
1358 NetworkPacket pkt(TOSERVER_BREATH, sizeof(u16));
1363 void Client::sendRespawn()
1365 DSTACK(FUNCTION_NAME);
1367 NetworkPacket pkt(TOSERVER_RESPAWN, 0);
1371 void Client::sendReady()
1373 DSTACK(FUNCTION_NAME);
1375 NetworkPacket pkt(TOSERVER_CLIENT_READY,
1376 1 + 1 + 1 + 1 + 2 + sizeof(char) * strlen(g_version_hash));
1378 pkt << (u8) VERSION_MAJOR << (u8) VERSION_MINOR << (u8) VERSION_PATCH
1379 << (u8) 0 << (u16) strlen(g_version_hash);
1381 pkt.putRawString(g_version_hash, (u16) strlen(g_version_hash));
1385 void Client::sendPlayerPos()
1387 LocalPlayer *myplayer = m_env.getLocalPlayer();
1388 if(myplayer == NULL)
1391 ClientMap &map = m_env.getClientMap();
1393 u8 camera_fov = map.getCameraFov();
1394 u8 wanted_range = map.getControl().wanted_range;
1396 // Save bandwidth by only updating position when something changed
1397 if(myplayer->last_position == myplayer->getPosition() &&
1398 myplayer->last_speed == myplayer->getSpeed() &&
1399 myplayer->last_pitch == myplayer->getPitch() &&
1400 myplayer->last_yaw == myplayer->getYaw() &&
1401 myplayer->last_keyPressed == myplayer->keyPressed &&
1402 myplayer->last_camera_fov == camera_fov &&
1403 myplayer->last_wanted_range == wanted_range)
1406 myplayer->last_position = myplayer->getPosition();
1407 myplayer->last_speed = myplayer->getSpeed();
1408 myplayer->last_pitch = myplayer->getPitch();
1409 myplayer->last_yaw = myplayer->getYaw();
1410 myplayer->last_keyPressed = myplayer->keyPressed;
1411 myplayer->last_camera_fov = camera_fov;
1412 myplayer->last_wanted_range = wanted_range;
1414 //infostream << "Sending Player Position information" << std::endl;
1418 //MutexAutoLock lock(m_con_mutex); //bulk comment-out
1419 our_peer_id = m_con.GetPeerID();
1422 // Set peer id if not set already
1423 if(myplayer->peer_id == PEER_ID_INEXISTENT)
1424 myplayer->peer_id = our_peer_id;
1426 assert(myplayer->peer_id == our_peer_id);
1428 NetworkPacket pkt(TOSERVER_PLAYERPOS, 12 + 12 + 4 + 4 + 4 + 1 + 1);
1430 writePlayerPos(myplayer, &map, &pkt);
1435 void Client::sendPlayerItem(u16 item)
1437 LocalPlayer *myplayer = m_env.getLocalPlayer();
1438 if(myplayer == NULL)
1441 u16 our_peer_id = m_con.GetPeerID();
1443 // Set peer id if not set already
1444 if(myplayer->peer_id == PEER_ID_INEXISTENT)
1445 myplayer->peer_id = our_peer_id;
1446 assert(myplayer->peer_id == our_peer_id);
1448 NetworkPacket pkt(TOSERVER_PLAYERITEM, 2);
1455 void Client::removeNode(v3s16 p)
1457 std::map<v3s16, MapBlock*> modified_blocks;
1460 m_env.getMap().removeNodeAndUpdate(p, modified_blocks);
1462 catch(InvalidPositionException &e) {
1465 for(std::map<v3s16, MapBlock *>::iterator
1466 i = modified_blocks.begin();
1467 i != modified_blocks.end(); ++i) {
1468 addUpdateMeshTaskWithEdge(i->first, false, true);
1472 MapNode Client::getNode(v3s16 p, bool *is_valid_position)
1474 return m_env.getMap().getNodeNoEx(p, is_valid_position);
1477 void Client::addNode(v3s16 p, MapNode n, bool remove_metadata)
1479 //TimeTaker timer1("Client::addNode()");
1481 std::map<v3s16, MapBlock*> modified_blocks;
1484 //TimeTaker timer3("Client::addNode(): addNodeAndUpdate");
1485 m_env.getMap().addNodeAndUpdate(p, n, modified_blocks, remove_metadata);
1487 catch(InvalidPositionException &e) {
1490 for(std::map<v3s16, MapBlock *>::iterator
1491 i = modified_blocks.begin();
1492 i != modified_blocks.end(); ++i) {
1493 addUpdateMeshTaskWithEdge(i->first, false, true);
1497 void Client::setPlayerControl(PlayerControl &control)
1499 LocalPlayer *player = m_env.getLocalPlayer();
1500 assert(player != NULL);
1501 player->control = control;
1504 void Client::selectPlayerItem(u16 item)
1506 m_playeritem = item;
1507 m_inventory_updated = true;
1508 sendPlayerItem(item);
1511 // Returns true if the inventory of the local player has been
1512 // updated from the server. If it is true, it is set to false.
1513 bool Client::getLocalInventoryUpdated()
1515 bool updated = m_inventory_updated;
1516 m_inventory_updated = false;
1520 // Copies the inventory of the local player to parameter
1521 void Client::getLocalInventory(Inventory &dst)
1523 LocalPlayer *player = m_env.getLocalPlayer();
1524 assert(player != NULL);
1525 dst = player->inventory;
1528 Inventory* Client::getInventory(const InventoryLocation &loc)
1531 case InventoryLocation::UNDEFINED:
1534 case InventoryLocation::CURRENT_PLAYER:
1536 LocalPlayer *player = m_env.getLocalPlayer();
1537 assert(player != NULL);
1538 return &player->inventory;
1541 case InventoryLocation::PLAYER:
1543 // Check if we are working with local player inventory
1544 LocalPlayer *player = m_env.getLocalPlayer();
1545 if (!player || strcmp(player->getName(), loc.name.c_str()) != 0)
1547 return &player->inventory;
1550 case InventoryLocation::NODEMETA:
1552 NodeMetadata *meta = m_env.getMap().getNodeMetadata(loc.p);
1555 return meta->getInventory();
1558 case InventoryLocation::DETACHED:
1560 if (m_detached_inventories.count(loc.name) == 0)
1562 return m_detached_inventories[loc.name];
1566 FATAL_ERROR("Invalid inventory location type.");
1572 void Client::inventoryAction(InventoryAction *a)
1575 Send it to the server
1577 sendInventoryAction(a);
1580 Predict some local inventory changes
1582 a->clientApply(this, this);
1588 float Client::getAnimationTime()
1590 return m_animation_time;
1593 int Client::getCrackLevel()
1595 return m_crack_level;
1598 void Client::setCrack(int level, v3s16 pos)
1600 int old_crack_level = m_crack_level;
1601 v3s16 old_crack_pos = m_crack_pos;
1603 m_crack_level = level;
1606 if(old_crack_level >= 0 && (level < 0 || pos != old_crack_pos))
1609 addUpdateMeshTaskForNode(old_crack_pos, false, true);
1611 if(level >= 0 && (old_crack_level < 0 || pos != old_crack_pos))
1614 addUpdateMeshTaskForNode(pos, false, true);
1620 LocalPlayer *player = m_env.getLocalPlayer();
1621 assert(player != NULL);
1625 bool Client::getChatMessage(std::wstring &message)
1627 if(m_chat_queue.size() == 0)
1629 message = m_chat_queue.front();
1634 void Client::typeChatMessage(const std::wstring &message)
1636 // Discard empty line
1640 // If message was ate by script API, don't send it to server
1641 if (m_script->on_sending_message(wide_to_utf8(message))) {
1646 sendChatMessage(message);
1649 if (message[0] != L'/')
1651 // compatibility code
1652 if (m_proto_ver < 29) {
1653 LocalPlayer *player = m_env.getLocalPlayer();
1654 assert(player != NULL);
1655 std::wstring name = narrow_to_wide(player->getName());
1656 pushToChatQueue((std::wstring)L"<" + name + L"> " + message);
1661 void Client::addUpdateMeshTask(v3s16 p, bool ack_to_server, bool urgent)
1663 MapBlock *b = m_env.getMap().getBlockNoCreateNoEx(p);
1668 Create a task to update the mesh of the block
1671 MeshMakeData *data = new MeshMakeData(this, m_cache_enable_shaders,
1672 m_cache_use_tangent_vertices);
1675 //TimeTaker timer("data fill");
1677 // Debug: 1-6ms, avg=2ms
1679 data->setCrack(m_crack_level, m_crack_pos);
1680 data->setSmoothLighting(m_cache_smooth_lighting);
1683 // Add task to queue
1684 m_mesh_update_thread.enqueueUpdate(p, data, ack_to_server, urgent);
1687 void Client::addUpdateMeshTaskWithEdge(v3s16 blockpos, bool ack_to_server, bool urgent)
1690 addUpdateMeshTask(blockpos, ack_to_server, urgent);
1692 catch(InvalidPositionException &e){}
1695 for (int i=0;i<6;i++)
1698 v3s16 p = blockpos + g_6dirs[i];
1699 addUpdateMeshTask(p, false, urgent);
1701 catch(InvalidPositionException &e){}
1705 void Client::addUpdateMeshTaskForNode(v3s16 nodepos, bool ack_to_server, bool urgent)
1709 infostream<<"Client::addUpdateMeshTaskForNode(): "
1710 <<"("<<p.X<<","<<p.Y<<","<<p.Z<<")"
1714 v3s16 blockpos = getNodeBlockPos(nodepos);
1715 v3s16 blockpos_relative = blockpos * MAP_BLOCKSIZE;
1718 addUpdateMeshTask(blockpos, ack_to_server, urgent);
1720 catch(InvalidPositionException &e) {}
1723 if(nodepos.X == blockpos_relative.X){
1725 v3s16 p = blockpos + v3s16(-1,0,0);
1726 addUpdateMeshTask(p, false, urgent);
1728 catch(InvalidPositionException &e){}
1731 if(nodepos.Y == blockpos_relative.Y){
1733 v3s16 p = blockpos + v3s16(0,-1,0);
1734 addUpdateMeshTask(p, false, urgent);
1736 catch(InvalidPositionException &e){}
1739 if(nodepos.Z == blockpos_relative.Z){
1741 v3s16 p = blockpos + v3s16(0,0,-1);
1742 addUpdateMeshTask(p, false, urgent);
1744 catch(InvalidPositionException &e){}
1748 ClientEvent Client::getClientEvent()
1751 if (m_client_event_queue.empty()) {
1752 event.type = CE_NONE;
1755 event = m_client_event_queue.front();
1756 m_client_event_queue.pop();
1761 float Client::mediaReceiveProgress()
1763 if (m_media_downloader)
1764 return m_media_downloader->getProgress();
1766 return 1.0; // downloader only exists when not yet done
1769 typedef struct TextureUpdateArgs {
1770 IrrlichtDevice *device;
1771 gui::IGUIEnvironment *guienv;
1774 const wchar_t* text_base;
1775 } TextureUpdateArgs;
1777 void texture_update_progress(void *args, u32 progress, u32 max_progress)
1779 TextureUpdateArgs* targs = (TextureUpdateArgs*) args;
1780 u16 cur_percent = ceil(progress / (double) max_progress * 100.);
1782 // update the loading menu -- if neccessary
1783 bool do_draw = false;
1784 u32 time_ms = targs->last_time_ms;
1785 if (cur_percent != targs->last_percent) {
1786 targs->last_percent = cur_percent;
1787 time_ms = getTimeMs();
1788 // only draw when the user will notice something:
1789 do_draw = (time_ms - targs->last_time_ms > 100);
1793 targs->last_time_ms = time_ms;
1794 std::basic_stringstream<wchar_t> strm;
1795 strm << targs->text_base << " " << targs->last_percent << "%...";
1796 draw_load_screen(strm.str(), targs->device, targs->guienv, 0,
1797 72 + (u16) ((18. / 100.) * (double) targs->last_percent));
1801 void Client::afterContentReceived(IrrlichtDevice *device)
1803 infostream<<"Client::afterContentReceived() started"<<std::endl;
1804 assert(m_itemdef_received); // pre-condition
1805 assert(m_nodedef_received); // pre-condition
1806 assert(mediaReceived()); // pre-condition
1808 const wchar_t* text = wgettext("Loading textures...");
1810 // Clear cached pre-scaled 2D GUI images, as this cache
1811 // might have images with the same name but different
1812 // content from previous sessions.
1813 guiScalingCacheClear(device->getVideoDriver());
1815 // Rebuild inherited images and recreate textures
1816 infostream<<"- Rebuilding images and textures"<<std::endl;
1817 draw_load_screen(text,device, guienv, 0, 70);
1818 m_tsrc->rebuildImagesAndTextures();
1822 infostream<<"- Rebuilding shaders"<<std::endl;
1823 text = wgettext("Rebuilding shaders...");
1824 draw_load_screen(text, device, guienv, 0, 71);
1825 m_shsrc->rebuildShaders();
1828 // Update node aliases
1829 infostream<<"- Updating node aliases"<<std::endl;
1830 text = wgettext("Initializing nodes...");
1831 draw_load_screen(text, device, guienv, 0, 72);
1832 m_nodedef->updateAliases(m_itemdef);
1833 std::string texture_path = g_settings->get("texture_path");
1834 if (texture_path != "" && fs::IsDir(texture_path))
1835 m_nodedef->applyTextureOverrides(texture_path + DIR_DELIM + "override.txt");
1836 m_nodedef->setNodeRegistrationStatus(true);
1837 m_nodedef->runNodeResolveCallbacks();
1840 // Update node textures and assign shaders to each tile
1841 infostream<<"- Updating node textures"<<std::endl;
1842 TextureUpdateArgs tu_args;
1843 tu_args.device = device;
1844 tu_args.guienv = guienv;
1845 tu_args.last_time_ms = getTimeMs();
1846 tu_args.last_percent = 0;
1847 tu_args.text_base = wgettext("Initializing nodes");
1848 m_nodedef->updateTextures(this, texture_update_progress, &tu_args);
1849 delete[] tu_args.text_base;
1851 // Start mesh update thread after setting up content definitions
1852 infostream<<"- Starting mesh update thread"<<std::endl;
1853 m_mesh_update_thread.start();
1857 text = wgettext("Done!");
1858 draw_load_screen(text, device, guienv, 0, 100);
1859 infostream<<"Client::afterContentReceived() done"<<std::endl;
1863 float Client::getRTT()
1865 return m_con.getPeerStat(PEER_ID_SERVER,con::AVG_RTT);
1868 float Client::getCurRate()
1870 return ( m_con.getLocalStat(con::CUR_INC_RATE) +
1871 m_con.getLocalStat(con::CUR_DL_RATE));
1874 void Client::makeScreenshot(IrrlichtDevice *device)
1876 irr::video::IVideoDriver *driver = device->getVideoDriver();
1877 irr::video::IImage* const raw_image = driver->createScreenShot();
1882 time_t t = time(NULL);
1883 struct tm *tm = localtime(&t);
1885 char timetstamp_c[64];
1886 strftime(timetstamp_c, sizeof(timetstamp_c), "%Y%m%d_%H%M%S", tm);
1888 std::string filename_base = g_settings->get("screenshot_path")
1890 + std::string("screenshot_")
1891 + std::string(timetstamp_c);
1892 std::string filename_ext = "." + g_settings->get("screenshot_format");
1893 std::string filename;
1895 u32 quality = (u32)g_settings->getS32("screenshot_quality");
1896 quality = MYMIN(MYMAX(quality, 0), 100) / 100.0 * 255;
1898 // Try to find a unique filename
1899 unsigned serial = 0;
1901 while (serial < SCREENSHOT_MAX_SERIAL_TRIES) {
1902 filename = filename_base + (serial > 0 ? ("_" + itos(serial)) : "") + filename_ext;
1903 std::ifstream tmp(filename.c_str());
1905 break; // File did not apparently exist, we'll go with it
1909 if (serial == SCREENSHOT_MAX_SERIAL_TRIES) {
1910 infostream << "Could not find suitable filename for screenshot" << std::endl;
1912 irr::video::IImage* const image =
1913 driver->createImage(video::ECF_R8G8B8, raw_image->getDimension());
1916 raw_image->copyTo(image);
1918 std::ostringstream sstr;
1919 if (driver->writeImageToFile(image, filename.c_str(), quality)) {
1920 sstr << "Saved screenshot to '" << filename << "'";
1922 sstr << "Failed to save screenshot '" << filename << "'";
1924 pushToChatQueue(narrow_to_wide(sstr.str()));
1925 infostream << sstr.str() << std::endl;
1933 bool Client::shouldShowMinimap() const
1935 return !m_minimap_disabled_by_server;
1938 // IGameDef interface
1940 IItemDefManager* Client::getItemDefManager()
1944 INodeDefManager* Client::getNodeDefManager()
1948 ICraftDefManager* Client::getCraftDefManager()
1951 //return m_craftdef;
1953 ITextureSource* Client::getTextureSource()
1957 IShaderSource* Client::getShaderSource()
1961 scene::ISceneManager* Client::getSceneManager()
1963 return m_device->getSceneManager();
1965 u16 Client::allocateUnknownNodeId(const std::string &name)
1967 errorstream << "Client::allocateUnknownNodeId(): "
1968 << "Client cannot allocate node IDs" << std::endl;
1969 FATAL_ERROR("Client allocated unknown node");
1971 return CONTENT_IGNORE;
1973 ISoundManager* Client::getSoundManager()
1977 MtEventManager* Client::getEventManager()
1982 ParticleManager* Client::getParticleManager()
1984 return &m_particle_manager;
1987 scene::IAnimatedMesh* Client::getMesh(const std::string &filename)
1989 StringMap::const_iterator it = m_mesh_data.find(filename);
1990 if (it == m_mesh_data.end()) {
1991 errorstream << "Client::getMesh(): Mesh not found: \"" << filename
1992 << "\"" << std::endl;
1995 const std::string &data = it->second;
1996 scene::ISceneManager *smgr = m_device->getSceneManager();
1998 // Create the mesh, remove it from cache and return it
1999 // This allows unique vertex colors and other properties for each instance
2000 Buffer<char> data_rw(data.c_str(), data.size()); // Const-incorrect Irrlicht
2001 io::IFileSystem *irrfs = m_device->getFileSystem();
2002 io::IReadFile *rfile = irrfs->createMemoryReadFile(
2003 *data_rw, data_rw.getSize(), filename.c_str());
2004 FATAL_ERROR_IF(!rfile, "Could not create/open RAM file");
2006 scene::IAnimatedMesh *mesh = smgr->getMesh(rfile);
2008 // NOTE: By playing with Irrlicht refcounts, maybe we could cache a bunch
2009 // of uniquely named instances and re-use them
2011 smgr->getMeshCache()->removeMesh(mesh);
2015 bool Client::registerModStorage(ModMetadata *storage)
2017 if (m_mod_storages.find(storage->getModName()) != m_mod_storages.end()) {
2018 errorstream << "Unable to register same mod storage twice. Storage name: "
2019 << storage->getModName() << std::endl;
2023 m_mod_storages[storage->getModName()] = storage;
2027 void Client::unregisterModStorage(const std::string &name)
2029 UNORDERED_MAP<std::string, ModMetadata *>::const_iterator it = m_mod_storages.find(name);
2030 if (it != m_mod_storages.end()) {
2031 // Save unconditionaly on unregistration
2032 it->second->save(getModStoragePath());
2033 m_mod_storages.erase(name);
2037 std::string Client::getModStoragePath() const
2039 return porting::path_user + DIR_DELIM + "client" + DIR_DELIM + "mod_storage";