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"
51 extern gui::IGUIEnvironment* guienv;
57 QueuedMeshUpdate::QueuedMeshUpdate():
60 ack_block_to_server(false)
64 QueuedMeshUpdate::~QueuedMeshUpdate()
74 MeshUpdateQueue::MeshUpdateQueue()
78 MeshUpdateQueue::~MeshUpdateQueue()
80 MutexAutoLock lock(m_mutex);
82 for(std::vector<QueuedMeshUpdate*>::iterator
84 i != m_queue.end(); ++i)
86 QueuedMeshUpdate *q = *i;
92 peer_id=0 adds with nobody to send to
94 void MeshUpdateQueue::addBlock(v3s16 p, MeshMakeData *data, bool ack_block_to_server, bool urgent)
96 DSTACK(FUNCTION_NAME);
98 assert(data); // pre-condition
100 MutexAutoLock lock(m_mutex);
106 Find if block is already in queue.
107 If it is, update the data and quit.
109 for(std::vector<QueuedMeshUpdate*>::iterator
111 i != m_queue.end(); ++i)
113 QueuedMeshUpdate *q = *i;
119 if(ack_block_to_server)
120 q->ack_block_to_server = true;
128 QueuedMeshUpdate *q = new QueuedMeshUpdate;
131 q->ack_block_to_server = ack_block_to_server;
132 m_queue.push_back(q);
135 // Returned pointer must be deleted
136 // Returns NULL if queue is empty
137 QueuedMeshUpdate *MeshUpdateQueue::pop()
139 MutexAutoLock lock(m_mutex);
141 bool must_be_urgent = !m_urgents.empty();
142 for(std::vector<QueuedMeshUpdate*>::iterator
144 i != m_queue.end(); ++i)
146 QueuedMeshUpdate *q = *i;
147 if(must_be_urgent && m_urgents.count(q->p) == 0)
150 m_urgents.erase(q->p);
160 MeshUpdateThread::MeshUpdateThread() : UpdateThread("Mesh")
162 m_generation_interval = g_settings->getU16("mesh_generation_interval");
163 m_generation_interval = rangelim(m_generation_interval, 0, 50);
166 void MeshUpdateThread::enqueueUpdate(v3s16 p, MeshMakeData *data,
167 bool ack_block_to_server, bool urgent)
169 m_queue_in.addBlock(p, data, ack_block_to_server, urgent);
173 void MeshUpdateThread::doUpdate()
176 while ((q = m_queue_in.pop())) {
177 if (m_generation_interval)
178 sleep_ms(m_generation_interval);
179 ScopeProfiler sp(g_profiler, "Client: Mesh making");
181 MapBlockMesh *mesh_new = new MapBlockMesh(q->data, m_camera_offset);
186 r.ack_block_to_server = q->ack_block_to_server;
188 m_queue_out.push_back(r);
199 IrrlichtDevice *device,
200 const char *playername,
201 std::string password,
202 MapDrawControl &control,
203 IWritableTextureSource *tsrc,
204 IWritableShaderSource *shsrc,
205 IWritableItemDefManager *itemdef,
206 IWritableNodeDefManager *nodedef,
207 ISoundManager *sound,
208 MtEventManager *event,
210 GameUIFlags *game_ui_flags
212 m_packetcounter_timer(0.0),
213 m_connection_reinit_timer(0.1),
214 m_avg_rtt_timer(0.0),
215 m_playerpos_send_timer(0.0),
216 m_ignore_damage_timer(0.0),
223 m_mesh_update_thread(),
225 new ClientMap(this, control,
226 device->getSceneManager()->getRootSceneNode(),
227 device->getSceneManager(), 666),
228 device->getSceneManager(),
231 m_particle_manager(&m_env),
232 m_con(PROTOCOL_ID, 512, CONNECTION_TIMEOUT, ipv6, this),
235 m_minimap_disabled_by_server(false),
236 m_server_ser_ver(SER_FMT_VER_INVALID),
239 m_inventory_updated(false),
240 m_inventory_from_server(NULL),
241 m_inventory_from_server_age(0.0),
246 m_password(password),
247 m_chosen_auth_mech(AUTH_MECHANISM_NONE),
249 m_access_denied(false),
250 m_access_denied_reconnect(false),
251 m_itemdef_received(false),
252 m_nodedef_received(false),
253 m_media_downloader(new ClientMediaDownloader()),
254 m_time_of_day_set(false),
255 m_last_time_of_day_f(-1),
256 m_time_of_day_update_timer(0),
257 m_recommended_send_interval(0.1),
258 m_removed_sounds_check_timer(0),
262 m_mod_storage_save_timer(10.0f),
263 m_game_ui_flags(game_ui_flags)
266 m_env.setLocalPlayer(new LocalPlayer(this, playername));
268 m_minimap = new Minimap(device, this);
269 m_cache_save_interval = g_settings->getU16("server_map_save_interval");
271 m_cache_smooth_lighting = g_settings->getBool("smooth_lighting");
272 m_cache_enable_shaders = g_settings->getBool("enable_shaders");
273 m_cache_use_tangent_vertices = m_cache_enable_shaders && (
274 g_settings->getBool("enable_bumpmapping") ||
275 g_settings->getBool("enable_parallax_occlusion"));
277 m_modding_enabled = g_settings->getBool("enable_client_modding");
278 m_script = new ClientScripting(this);
279 m_env.setScript(m_script);
280 m_script->setEnv(&m_env);
283 void Client::initMods()
285 m_script->loadMod(getBuiltinLuaPath() + DIR_DELIM "init.lua", BUILTIN_MOD_NAME);
287 // If modding is not enabled, don't load mods, just builtin
288 if (!m_modding_enabled) {
292 ClientModConfiguration modconf(getClientModsLuaPath());
293 std::vector<ModSpec> mods = modconf.getMods();
294 std::vector<ModSpec> unsatisfied_mods = modconf.getUnsatisfiedMods();
295 // complain about mods with unsatisfied dependencies
296 if (!modconf.isConsistent()) {
297 modconf.printUnsatisfiedModsError();
301 infostream << "Client Loading mods: ";
302 for (std::vector<ModSpec>::const_iterator i = mods.begin();
303 i != mods.end(); ++i) {
304 infostream << (*i).name << " ";
307 infostream << std::endl;
308 // Load and run "mod" scripts
309 for (std::vector<ModSpec>::const_iterator it = mods.begin();
310 it != mods.end(); ++it) {
311 const ModSpec &mod = *it;
312 if (!string_allowed(mod.name, MODNAME_ALLOWED_CHARS)) {
313 throw ModError("Error loading mod \"" + mod.name +
314 "\": Mod name does not follow naming conventions: "
315 "Only chararacters [a-z0-9_] are allowed.");
317 std::string script_path = mod.path + DIR_DELIM + "init.lua";
318 infostream << " [" << padStringRight(mod.name, 12) << "] [\""
319 << script_path << "\"]" << std::endl;
320 m_script->loadMod(script_path, mod.name);
324 const std::string &Client::getBuiltinLuaPath()
326 static const std::string builtin_dir = porting::path_share + DIR_DELIM + "builtin";
330 const std::string &Client::getClientModsLuaPath()
332 static const std::string clientmods_dir = porting::path_share + DIR_DELIM + "clientmods";
333 return clientmods_dir;
336 const std::vector<ModSpec>& Client::getMods() const
338 static std::vector<ModSpec> client_modspec_temp;
339 return client_modspec_temp;
342 const ModSpec* Client::getModSpec(const std::string &modname) const
349 // Don't disable this part when modding is disabled, it's used in builtin
350 m_script->on_shutdown();
351 //request all client managed threads to stop
352 m_mesh_update_thread.stop();
353 // Save local server map
355 infostream << "Local map saving ended." << std::endl;
356 m_localdb->endSave();
362 bool Client::isShutdown()
365 if (!m_mesh_update_thread.isRunning()) return true;
374 m_mesh_update_thread.stop();
375 m_mesh_update_thread.wait();
376 while (!m_mesh_update_thread.m_queue_out.empty()) {
377 MeshUpdateResult r = m_mesh_update_thread.m_queue_out.pop_frontNoEx();
382 delete m_inventory_from_server;
384 // Delete detached inventories
385 for (UNORDERED_MAP<std::string, Inventory*>::iterator
386 i = m_detached_inventories.begin();
387 i != m_detached_inventories.end(); ++i) {
391 // cleanup 3d model meshes on client shutdown
392 while (m_device->getSceneManager()->getMeshCache()->getMeshCount() != 0) {
393 scene::IAnimatedMesh *mesh =
394 m_device->getSceneManager()->getMeshCache()->getMeshByIndex(0);
397 m_device->getSceneManager()->getMeshCache()->removeMesh(mesh);
403 void Client::connect(Address address,
404 const std::string &address_name,
405 bool is_local_server)
407 DSTACK(FUNCTION_NAME);
409 initLocalMapSaving(address, address_name, is_local_server);
411 m_con.SetTimeoutMs(0);
412 m_con.Connect(address);
415 void Client::step(float dtime)
417 DSTACK(FUNCTION_NAME);
423 if(m_ignore_damage_timer > dtime)
424 m_ignore_damage_timer -= dtime;
426 m_ignore_damage_timer = 0.0;
428 m_animation_time += dtime;
429 if(m_animation_time > 60.0)
430 m_animation_time -= 60.0;
432 m_time_of_day_update_timer += dtime;
440 float &counter = m_packetcounter_timer;
446 infostream << "Client packetcounter (" << m_packetcounter_timer
448 m_packetcounter.print(infostream);
449 m_packetcounter.clear();
453 // UGLY hack to fix 2 second startup delay caused by non existent
454 // server client startup synchronization in local server or singleplayer mode
455 static bool initial_step = true;
457 initial_step = false;
459 else if(m_state == LC_Created) {
460 float &counter = m_connection_reinit_timer;
465 LocalPlayer *myplayer = m_env.getLocalPlayer();
466 FATAL_ERROR_IF(myplayer == NULL, "Local player not found in environment.");
468 u16 proto_version_min = g_settings->getFlag("send_pre_v25_init") ?
469 CLIENT_PROTOCOL_VERSION_MIN_LEGACY : CLIENT_PROTOCOL_VERSION_MIN;
471 if (proto_version_min < 25) {
472 // Send TOSERVER_INIT_LEGACY
473 // [0] u16 TOSERVER_INIT_LEGACY
474 // [2] u8 SER_FMT_VER_HIGHEST_READ
475 // [3] u8[20] player_name
476 // [23] u8[28] password (new in some version)
477 // [51] u16 minimum supported network protocol version (added sometime)
478 // [53] u16 maximum supported network protocol version (added later than the previous one)
480 char pName[PLAYERNAME_SIZE];
481 char pPassword[PASSWORD_SIZE];
482 memset(pName, 0, PLAYERNAME_SIZE * sizeof(char));
483 memset(pPassword, 0, PASSWORD_SIZE * sizeof(char));
485 std::string hashed_password = translate_password(myplayer->getName(), m_password);
486 snprintf(pName, PLAYERNAME_SIZE, "%s", myplayer->getName());
487 snprintf(pPassword, PASSWORD_SIZE, "%s", hashed_password.c_str());
489 sendLegacyInit(pName, pPassword);
491 if (CLIENT_PROTOCOL_VERSION_MAX >= 25)
492 sendInit(myplayer->getName());
495 // Not connected, return
500 Do stuff if connected
504 Run Map's timers and unload unused data
506 const float map_timer_and_unload_dtime = 5.25;
507 if(m_map_timer_and_unload_interval.step(dtime, map_timer_and_unload_dtime)) {
508 ScopeProfiler sp(g_profiler, "Client: map timer and unload");
509 std::vector<v3s16> deleted_blocks;
510 m_env.getMap().timerUpdate(map_timer_and_unload_dtime,
511 g_settings->getFloat("client_unload_unused_data_timeout"),
512 g_settings->getS32("client_mapblock_limit"),
517 NOTE: This loop is intentionally iterated the way it is.
520 std::vector<v3s16>::iterator i = deleted_blocks.begin();
521 std::vector<v3s16> sendlist;
523 if(sendlist.size() == 255 || i == deleted_blocks.end()) {
534 sendDeletedBlocks(sendlist);
536 if(i == deleted_blocks.end())
542 sendlist.push_back(*i);
550 // Control local player (0ms)
551 LocalPlayer *player = m_env.getLocalPlayer();
552 assert(player != NULL);
553 player->applyControl(dtime);
562 ClientEnvEvent event = m_env.getClientEvent();
563 if(event.type == CEE_NONE) {
566 else if(event.type == CEE_PLAYER_DAMAGE) {
567 if(m_ignore_damage_timer <= 0) {
568 u8 damage = event.player_damage.amount;
570 if(event.player_damage.send_to_server)
573 // Add to ClientEvent queue
575 event.type = CE_PLAYER_DAMAGE;
576 event.player_damage.amount = damage;
577 m_client_event_queue.push(event);
580 // Protocol v29 or greater obsoleted this event
581 else if (event.type == CEE_PLAYER_BREATH && m_proto_ver < 29) {
582 u16 breath = event.player_breath.amount;
590 float &counter = m_avg_rtt_timer;
594 // connectedAndInitialized() is true, peer exists.
595 float avg_rtt = getRTT();
596 infostream << "Client: avg_rtt=" << avg_rtt << std::endl;
600 Send player position to server
603 float &counter = m_playerpos_send_timer;
605 if((m_state == LC_Ready) && (counter >= m_recommended_send_interval))
613 Replace updated meshes
616 int num_processed_meshes = 0;
617 while (!m_mesh_update_thread.m_queue_out.empty())
619 num_processed_meshes++;
621 MinimapMapblock *minimap_mapblock = NULL;
622 bool do_mapper_update = true;
624 MeshUpdateResult r = m_mesh_update_thread.m_queue_out.pop_frontNoEx();
625 MapBlock *block = m_env.getMap().getBlockNoCreateNoEx(r.p);
627 // Delete the old mesh
628 if (block->mesh != NULL) {
634 minimap_mapblock = r.mesh->moveMinimapMapblock();
635 if (minimap_mapblock == NULL)
636 do_mapper_update = false;
639 if (r.mesh && r.mesh->getMesh()->getMeshBufferCount() == 0) {
642 // Replace with the new mesh
643 block->mesh = r.mesh;
649 if (do_mapper_update)
650 m_minimap->addBlock(r.p, minimap_mapblock);
652 if (r.ack_block_to_server) {
662 if (num_processed_meshes > 0)
663 g_profiler->graphAdd("num_processed_meshes", num_processed_meshes);
669 if (m_media_downloader && m_media_downloader->isStarted()) {
670 m_media_downloader->step(this);
671 if (m_media_downloader->isDone()) {
673 delete m_media_downloader;
674 m_media_downloader = NULL;
679 If the server didn't update the inventory in a while, revert
680 the local inventory (so the player notices the lag problem
681 and knows something is wrong).
683 if(m_inventory_from_server)
685 float interval = 10.0;
686 float count_before = floor(m_inventory_from_server_age / interval);
688 m_inventory_from_server_age += dtime;
690 float count_after = floor(m_inventory_from_server_age / interval);
692 if(count_after != count_before)
694 // Do this every <interval> seconds after TOCLIENT_INVENTORY
695 // Reset the locally changed inventory to the authoritative inventory
696 LocalPlayer *player = m_env.getLocalPlayer();
697 player->inventory = *m_inventory_from_server;
698 m_inventory_updated = true;
703 Update positions of sounds attached to objects
706 for(UNORDERED_MAP<int, u16>::iterator i = m_sounds_to_objects.begin();
707 i != m_sounds_to_objects.end(); ++i) {
708 int client_id = i->first;
709 u16 object_id = i->second;
710 ClientActiveObject *cao = m_env.getActiveObject(object_id);
713 v3f pos = cao->getPosition();
714 m_sound->updateSoundPosition(client_id, pos);
719 Handle removed remotely initiated sounds
721 m_removed_sounds_check_timer += dtime;
722 if(m_removed_sounds_check_timer >= 2.32) {
723 m_removed_sounds_check_timer = 0;
724 // Find removed sounds and clear references to them
725 std::vector<s32> removed_server_ids;
726 for(UNORDERED_MAP<s32, int>::iterator i = m_sounds_server_to_client.begin();
727 i != m_sounds_server_to_client.end();) {
728 s32 server_id = i->first;
729 int client_id = i->second;
731 if(!m_sound->soundExists(client_id)) {
732 m_sounds_server_to_client.erase(server_id);
733 m_sounds_client_to_server.erase(client_id);
734 m_sounds_to_objects.erase(client_id);
735 removed_server_ids.push_back(server_id);
740 if(!removed_server_ids.empty()) {
741 sendRemovedSounds(removed_server_ids);
745 m_mod_storage_save_timer -= dtime;
746 if (m_mod_storage_save_timer <= 0.0f) {
747 verbosestream << "Saving registered mod storages." << std::endl;
748 m_mod_storage_save_timer = g_settings->getFloat("server_map_save_interval");
749 for (UNORDERED_MAP<std::string, ModMetadata *>::const_iterator
750 it = m_mod_storages.begin(); it != m_mod_storages.end(); ++it) {
751 if (it->second->isModified()) {
752 it->second->save(getModStoragePath());
758 if (m_localdb && m_localdb_save_interval.step(dtime,
759 m_cache_save_interval)) {
760 m_localdb->endSave();
761 m_localdb->beginSave();
765 bool Client::loadMedia(const std::string &data, const std::string &filename)
767 // Silly irrlicht's const-incorrectness
768 Buffer<char> data_rw(data.c_str(), data.size());
772 const char *image_ext[] = {
773 ".png", ".jpg", ".bmp", ".tga",
774 ".pcx", ".ppm", ".psd", ".wal", ".rgb",
777 name = removeStringEnd(filename, image_ext);
780 verbosestream<<"Client: Attempting to load image "
781 <<"file \""<<filename<<"\""<<std::endl;
783 io::IFileSystem *irrfs = m_device->getFileSystem();
784 video::IVideoDriver *vdrv = m_device->getVideoDriver();
786 // Create an irrlicht memory file
787 io::IReadFile *rfile = irrfs->createMemoryReadFile(
788 *data_rw, data_rw.getSize(), "_tempreadfile");
790 FATAL_ERROR_IF(!rfile, "Could not create irrlicht memory file.");
793 video::IImage *img = vdrv->createImageFromFile(rfile);
795 errorstream<<"Client: Cannot create image from data of "
796 <<"file \""<<filename<<"\""<<std::endl;
801 m_tsrc->insertSourceImage(filename, img);
808 const char *sound_ext[] = {
809 ".0.ogg", ".1.ogg", ".2.ogg", ".3.ogg", ".4.ogg",
810 ".5.ogg", ".6.ogg", ".7.ogg", ".8.ogg", ".9.ogg",
813 name = removeStringEnd(filename, sound_ext);
816 verbosestream<<"Client: Attempting to load sound "
817 <<"file \""<<filename<<"\""<<std::endl;
818 m_sound->loadSoundData(name, data);
822 const char *model_ext[] = {
823 ".x", ".b3d", ".md2", ".obj",
826 name = removeStringEnd(filename, model_ext);
829 verbosestream<<"Client: Storing model into memory: "
830 <<"\""<<filename<<"\""<<std::endl;
831 if(m_mesh_data.count(filename))
832 errorstream<<"Multiple models with name \""<<filename.c_str()
833 <<"\" found; replacing previous model"<<std::endl;
834 m_mesh_data[filename] = data;
838 errorstream<<"Client: Don't know how to load file \""
839 <<filename<<"\""<<std::endl;
843 // Virtual methods from con::PeerHandler
844 void Client::peerAdded(con::Peer *peer)
846 infostream << "Client::peerAdded(): peer->id="
847 << peer->id << std::endl;
849 void Client::deletingPeer(con::Peer *peer, bool timeout)
851 infostream << "Client::deletingPeer(): "
852 "Server Peer is getting deleted "
853 << "(timeout=" << timeout << ")" << std::endl;
856 m_access_denied = true;
857 m_access_denied_reason = gettext("Connection timed out.");
863 u16 number of files requested
869 void Client::request_media(const std::vector<std::string> &file_requests)
871 std::ostringstream os(std::ios_base::binary);
872 writeU16(os, TOSERVER_REQUEST_MEDIA);
873 size_t file_requests_size = file_requests.size();
875 FATAL_ERROR_IF(file_requests_size > 0xFFFF, "Unsupported number of file requests");
877 // Packet dynamicly resized
878 NetworkPacket pkt(TOSERVER_REQUEST_MEDIA, 2 + 0);
880 pkt << (u16) (file_requests_size & 0xFFFF);
882 for(std::vector<std::string>::const_iterator i = file_requests.begin();
883 i != file_requests.end(); ++i) {
889 infostream << "Client: Sending media request list to server ("
890 << file_requests.size() << " files. packet size)" << std::endl;
893 void Client::received_media()
895 NetworkPacket pkt(TOSERVER_RECEIVED_MEDIA, 0);
897 infostream << "Client: Notifying server that we received all media"
901 void Client::initLocalMapSaving(const Address &address,
902 const std::string &hostname,
903 bool is_local_server)
905 if (!g_settings->getBool("enable_local_map_saving") || is_local_server) {
909 const std::string world_path = porting::path_user
910 + DIR_DELIM + "worlds"
911 + DIR_DELIM + "server_"
912 + hostname + "_" + std::to_string(address.getPort());
914 fs::CreateAllDirs(world_path);
916 m_localdb = new Database_SQLite3(world_path);
917 m_localdb->beginSave();
918 actionstream << "Local map saving started, map will be saved at '" << world_path << "'" << std::endl;
921 void Client::ReceiveAll()
923 DSTACK(FUNCTION_NAME);
924 u32 start_ms = porting::getTimeMs();
927 // Limit time even if there would be huge amounts of data to
929 if(porting::getTimeMs() > start_ms + 100)
934 g_profiler->graphAdd("client_received_packets", 1);
936 catch(con::NoIncomingDataException &e) {
939 catch(con::InvalidIncomingDataException &e) {
940 infostream<<"Client::ReceiveAll(): "
941 "InvalidIncomingDataException: what()="
942 <<e.what()<<std::endl;
947 void Client::Receive()
949 DSTACK(FUNCTION_NAME);
955 inline void Client::handleCommand(NetworkPacket* pkt)
957 const ToClientCommandHandler& opHandle = toClientCommandTable[pkt->getCommand()];
958 (this->*opHandle.handler)(pkt);
962 sender_peer_id given to this shall be quaranteed to be a valid peer
964 void Client::ProcessData(NetworkPacket *pkt)
966 DSTACK(FUNCTION_NAME);
968 ToClientCommand command = (ToClientCommand) pkt->getCommand();
969 u32 sender_peer_id = pkt->getPeerId();
971 //infostream<<"Client: received command="<<command<<std::endl;
972 m_packetcounter.add((u16)command);
975 If this check is removed, be sure to change the queue
976 system to know the ids
978 if(sender_peer_id != PEER_ID_SERVER) {
979 infostream << "Client::ProcessData(): Discarding data not "
980 "coming from server: peer_id=" << sender_peer_id
985 // Command must be handled into ToClientCommandHandler
986 if (command >= TOCLIENT_NUM_MSG_TYPES) {
987 infostream << "Client: Ignoring unknown command "
988 << command << std::endl;
993 * Those packets are handled before m_server_ser_ver is set, it's normal
994 * But we must use the new ToClientConnectionState in the future,
997 if(toClientCommandTable[command].state == TOCLIENT_STATE_NOT_CONNECTED) {
1002 if(m_server_ser_ver == SER_FMT_VER_INVALID) {
1003 infostream << "Client: Server serialization"
1004 " format invalid or not initialized."
1005 " Skipping incoming command=" << command << std::endl;
1010 Handle runtime commands
1016 void Client::Send(NetworkPacket* pkt)
1018 m_con.Send(PEER_ID_SERVER,
1019 serverCommandFactoryTable[pkt->getCommand()].channel,
1021 serverCommandFactoryTable[pkt->getCommand()].reliable);
1024 // Will fill up 12 + 12 + 4 + 4 + 4 bytes
1025 void writePlayerPos(LocalPlayer *myplayer, ClientMap *clientMap, NetworkPacket *pkt)
1027 v3f pf = myplayer->getPosition() * 100;
1028 v3f sf = myplayer->getSpeed() * 100;
1029 s32 pitch = myplayer->getPitch() * 100;
1030 s32 yaw = myplayer->getYaw() * 100;
1031 u32 keyPressed = myplayer->keyPressed;
1032 // scaled by 80, so that pi can fit into a u8
1033 u8 fov = clientMap->getCameraFov() * 80;
1034 u8 wanted_range = MYMIN(255,
1035 std::ceil(clientMap->getControl().wanted_range / MAP_BLOCKSIZE));
1037 v3s32 position(pf.X, pf.Y, pf.Z);
1038 v3s32 speed(sf.X, sf.Y, sf.Z);
1042 [0] v3s32 position*100
1043 [12] v3s32 speed*100
1044 [12+12] s32 pitch*100
1045 [12+12+4] s32 yaw*100
1046 [12+12+4+4] u32 keyPressed
1047 [12+12+4+4+4] u8 fov*80
1048 [12+12+4+4+4+1] u8 ceil(wanted_range / MAP_BLOCKSIZE)
1050 *pkt << position << speed << pitch << yaw << keyPressed;
1051 *pkt << fov << wanted_range;
1054 void Client::interact(u8 action, const PointedThing& pointed)
1056 if(m_state != LC_Ready) {
1057 errorstream << "Client::interact() "
1058 "Canceled (not connected)"
1063 LocalPlayer *myplayer = m_env.getLocalPlayer();
1064 if (myplayer == NULL)
1071 [5] u32 length of the next item (plen)
1072 [9] serialized PointedThing
1073 [9 + plen] player position information
1075 0: start digging (from undersurface) or use
1076 1: stop digging (all parameters ignored)
1077 2: digging completed
1078 3: place block or item (to abovesurface)
1080 5: perform secondary action of item
1083 NetworkPacket pkt(TOSERVER_INTERACT, 1 + 2 + 0);
1086 pkt << (u16)getPlayerItem();
1088 std::ostringstream tmp_os(std::ios::binary);
1089 pointed.serialize(tmp_os);
1091 pkt.putLongString(tmp_os.str());
1093 writePlayerPos(myplayer, &m_env.getClientMap(), &pkt);
1098 void Client::deleteAuthData()
1103 switch (m_chosen_auth_mech) {
1104 case AUTH_MECHANISM_FIRST_SRP:
1106 case AUTH_MECHANISM_SRP:
1107 case AUTH_MECHANISM_LEGACY_PASSWORD:
1108 srp_user_delete((SRPUser *) m_auth_data);
1111 case AUTH_MECHANISM_NONE:
1114 m_chosen_auth_mech = AUTH_MECHANISM_NONE;
1118 AuthMechanism Client::choseAuthMech(const u32 mechs)
1120 if (mechs & AUTH_MECHANISM_SRP)
1121 return AUTH_MECHANISM_SRP;
1123 if (mechs & AUTH_MECHANISM_FIRST_SRP)
1124 return AUTH_MECHANISM_FIRST_SRP;
1126 if (mechs & AUTH_MECHANISM_LEGACY_PASSWORD)
1127 return AUTH_MECHANISM_LEGACY_PASSWORD;
1129 return AUTH_MECHANISM_NONE;
1132 void Client::sendLegacyInit(const char* playerName, const char* playerPassword)
1134 NetworkPacket pkt(TOSERVER_INIT_LEGACY,
1135 1 + PLAYERNAME_SIZE + PASSWORD_SIZE + 2 + 2);
1137 u16 proto_version_min = g_settings->getFlag("send_pre_v25_init") ?
1138 CLIENT_PROTOCOL_VERSION_MIN_LEGACY : CLIENT_PROTOCOL_VERSION_MIN;
1140 pkt << (u8) SER_FMT_VER_HIGHEST_READ;
1141 pkt.putRawString(playerName,PLAYERNAME_SIZE);
1142 pkt.putRawString(playerPassword, PASSWORD_SIZE);
1143 pkt << (u16) proto_version_min << (u16) CLIENT_PROTOCOL_VERSION_MAX;
1148 void Client::sendInit(const std::string &playerName)
1150 NetworkPacket pkt(TOSERVER_INIT, 1 + 2 + 2 + (1 + playerName.size()));
1152 // we don't support network compression yet
1153 u16 supp_comp_modes = NETPROTO_COMPRESSION_NONE;
1155 u16 proto_version_min = g_settings->getFlag("send_pre_v25_init") ?
1156 CLIENT_PROTOCOL_VERSION_MIN_LEGACY : CLIENT_PROTOCOL_VERSION_MIN;
1158 pkt << (u8) SER_FMT_VER_HIGHEST_READ << (u16) supp_comp_modes;
1159 pkt << (u16) proto_version_min << (u16) CLIENT_PROTOCOL_VERSION_MAX;
1165 void Client::startAuth(AuthMechanism chosen_auth_mechanism)
1167 m_chosen_auth_mech = chosen_auth_mechanism;
1169 switch (chosen_auth_mechanism) {
1170 case AUTH_MECHANISM_FIRST_SRP: {
1171 // send srp verifier to server
1172 std::string verifier;
1174 generate_srp_verifier_and_salt(getPlayerName(), m_password,
1177 NetworkPacket resp_pkt(TOSERVER_FIRST_SRP, 0);
1178 resp_pkt << salt << verifier << (u8)((m_password == "") ? 1 : 0);
1183 case AUTH_MECHANISM_SRP:
1184 case AUTH_MECHANISM_LEGACY_PASSWORD: {
1187 if (chosen_auth_mechanism == AUTH_MECHANISM_LEGACY_PASSWORD) {
1188 m_password = translate_password(getPlayerName(), m_password);
1192 std::string playername_u = lowercase(getPlayerName());
1193 m_auth_data = srp_user_new(SRP_SHA256, SRP_NG_2048,
1194 getPlayerName().c_str(), playername_u.c_str(),
1195 (const unsigned char *) m_password.c_str(),
1196 m_password.length(), NULL, NULL);
1199 SRP_Result res = srp_user_start_authentication(
1200 (struct SRPUser *) m_auth_data, NULL, NULL, 0,
1201 (unsigned char **) &bytes_A, &len_A);
1202 FATAL_ERROR_IF(res != SRP_OK, "Creating local SRP user failed.");
1204 NetworkPacket resp_pkt(TOSERVER_SRP_BYTES_A, 0);
1205 resp_pkt << std::string(bytes_A, len_A) << based_on;
1209 case AUTH_MECHANISM_NONE:
1210 break; // not handled in this method
1214 void Client::sendDeletedBlocks(std::vector<v3s16> &blocks)
1216 NetworkPacket pkt(TOSERVER_DELETEDBLOCKS, 1 + sizeof(v3s16) * blocks.size());
1218 pkt << (u8) blocks.size();
1221 for(std::vector<v3s16>::iterator
1223 j != blocks.end(); ++j) {
1231 void Client::sendGotBlocks(v3s16 block)
1233 NetworkPacket pkt(TOSERVER_GOTBLOCKS, 1 + 6);
1234 pkt << (u8) 1 << block;
1238 void Client::sendRemovedSounds(std::vector<s32> &soundList)
1240 size_t server_ids = soundList.size();
1241 assert(server_ids <= 0xFFFF);
1243 NetworkPacket pkt(TOSERVER_REMOVED_SOUNDS, 2 + server_ids * 4);
1245 pkt << (u16) (server_ids & 0xFFFF);
1247 for(std::vector<s32>::iterator i = soundList.begin();
1248 i != soundList.end(); ++i)
1254 void Client::sendNodemetaFields(v3s16 p, const std::string &formname,
1255 const StringMap &fields)
1257 size_t fields_size = fields.size();
1259 FATAL_ERROR_IF(fields_size > 0xFFFF, "Unsupported number of nodemeta fields");
1261 NetworkPacket pkt(TOSERVER_NODEMETA_FIELDS, 0);
1263 pkt << p << formname << (u16) (fields_size & 0xFFFF);
1265 StringMap::const_iterator it;
1266 for (it = fields.begin(); it != fields.end(); ++it) {
1267 const std::string &name = it->first;
1268 const std::string &value = it->second;
1270 pkt.putLongString(value);
1276 void Client::sendInventoryFields(const std::string &formname,
1277 const StringMap &fields)
1279 size_t fields_size = fields.size();
1280 FATAL_ERROR_IF(fields_size > 0xFFFF, "Unsupported number of inventory fields");
1282 NetworkPacket pkt(TOSERVER_INVENTORY_FIELDS, 0);
1283 pkt << formname << (u16) (fields_size & 0xFFFF);
1285 StringMap::const_iterator it;
1286 for (it = fields.begin(); it != fields.end(); ++it) {
1287 const std::string &name = it->first;
1288 const std::string &value = it->second;
1290 pkt.putLongString(value);
1296 void Client::sendInventoryAction(InventoryAction *a)
1298 std::ostringstream os(std::ios_base::binary);
1303 std::string s = os.str();
1305 NetworkPacket pkt(TOSERVER_INVENTORY_ACTION, s.size());
1306 pkt.putRawString(s.c_str(),s.size());
1311 void Client::sendChatMessage(const std::wstring &message)
1313 NetworkPacket pkt(TOSERVER_CHAT_MESSAGE, 2 + message.size() * sizeof(u16));
1320 void Client::sendChangePassword(const std::string &oldpassword,
1321 const std::string &newpassword)
1323 LocalPlayer *player = m_env.getLocalPlayer();
1327 std::string playername = player->getName();
1328 if (m_proto_ver >= 25) {
1329 // get into sudo mode and then send new password to server
1330 m_password = oldpassword;
1331 m_new_password = newpassword;
1332 startAuth(choseAuthMech(m_sudo_auth_methods));
1334 std::string oldpwd = translate_password(playername, oldpassword);
1335 std::string newpwd = translate_password(playername, newpassword);
1337 NetworkPacket pkt(TOSERVER_PASSWORD_LEGACY, 2 * PASSWORD_SIZE);
1339 for (u8 i = 0; i < PASSWORD_SIZE; i++) {
1340 pkt << (u8) (i < oldpwd.length() ? oldpwd[i] : 0);
1343 for (u8 i = 0; i < PASSWORD_SIZE; i++) {
1344 pkt << (u8) (i < newpwd.length() ? newpwd[i] : 0);
1351 void Client::sendDamage(u8 damage)
1353 DSTACK(FUNCTION_NAME);
1355 NetworkPacket pkt(TOSERVER_DAMAGE, sizeof(u8));
1360 void Client::sendBreath(u16 breath)
1362 DSTACK(FUNCTION_NAME);
1364 // Protocol v29 make this obsolete
1365 if (m_proto_ver >= 29)
1368 NetworkPacket pkt(TOSERVER_BREATH, sizeof(u16));
1373 void Client::sendRespawn()
1375 DSTACK(FUNCTION_NAME);
1377 NetworkPacket pkt(TOSERVER_RESPAWN, 0);
1381 void Client::sendReady()
1383 DSTACK(FUNCTION_NAME);
1385 NetworkPacket pkt(TOSERVER_CLIENT_READY,
1386 1 + 1 + 1 + 1 + 2 + sizeof(char) * strlen(g_version_hash));
1388 pkt << (u8) VERSION_MAJOR << (u8) VERSION_MINOR << (u8) VERSION_PATCH
1389 << (u8) 0 << (u16) strlen(g_version_hash);
1391 pkt.putRawString(g_version_hash, (u16) strlen(g_version_hash));
1395 void Client::sendPlayerPos()
1397 LocalPlayer *myplayer = m_env.getLocalPlayer();
1398 if(myplayer == NULL)
1401 ClientMap &map = m_env.getClientMap();
1403 u8 camera_fov = map.getCameraFov();
1404 u8 wanted_range = map.getControl().wanted_range;
1406 // Save bandwidth by only updating position when something changed
1407 if(myplayer->last_position == myplayer->getPosition() &&
1408 myplayer->last_speed == myplayer->getSpeed() &&
1409 myplayer->last_pitch == myplayer->getPitch() &&
1410 myplayer->last_yaw == myplayer->getYaw() &&
1411 myplayer->last_keyPressed == myplayer->keyPressed &&
1412 myplayer->last_camera_fov == camera_fov &&
1413 myplayer->last_wanted_range == wanted_range)
1416 myplayer->last_position = myplayer->getPosition();
1417 myplayer->last_speed = myplayer->getSpeed();
1418 myplayer->last_pitch = myplayer->getPitch();
1419 myplayer->last_yaw = myplayer->getYaw();
1420 myplayer->last_keyPressed = myplayer->keyPressed;
1421 myplayer->last_camera_fov = camera_fov;
1422 myplayer->last_wanted_range = wanted_range;
1424 //infostream << "Sending Player Position information" << std::endl;
1428 //MutexAutoLock lock(m_con_mutex); //bulk comment-out
1429 our_peer_id = m_con.GetPeerID();
1432 // Set peer id if not set already
1433 if(myplayer->peer_id == PEER_ID_INEXISTENT)
1434 myplayer->peer_id = our_peer_id;
1436 assert(myplayer->peer_id == our_peer_id);
1438 NetworkPacket pkt(TOSERVER_PLAYERPOS, 12 + 12 + 4 + 4 + 4 + 1 + 1);
1440 writePlayerPos(myplayer, &map, &pkt);
1445 void Client::sendPlayerItem(u16 item)
1447 LocalPlayer *myplayer = m_env.getLocalPlayer();
1448 if(myplayer == NULL)
1451 u16 our_peer_id = m_con.GetPeerID();
1453 // Set peer id if not set already
1454 if(myplayer->peer_id == PEER_ID_INEXISTENT)
1455 myplayer->peer_id = our_peer_id;
1456 assert(myplayer->peer_id == our_peer_id);
1458 NetworkPacket pkt(TOSERVER_PLAYERITEM, 2);
1465 void Client::removeNode(v3s16 p)
1467 std::map<v3s16, MapBlock*> modified_blocks;
1470 m_env.getMap().removeNodeAndUpdate(p, modified_blocks);
1472 catch(InvalidPositionException &e) {
1475 for(std::map<v3s16, MapBlock *>::iterator
1476 i = modified_blocks.begin();
1477 i != modified_blocks.end(); ++i) {
1478 addUpdateMeshTaskWithEdge(i->first, false, true);
1482 MapNode Client::getNode(v3s16 p, bool *is_valid_position)
1484 return m_env.getMap().getNodeNoEx(p, is_valid_position);
1487 void Client::addNode(v3s16 p, MapNode n, bool remove_metadata)
1489 //TimeTaker timer1("Client::addNode()");
1491 std::map<v3s16, MapBlock*> modified_blocks;
1494 //TimeTaker timer3("Client::addNode(): addNodeAndUpdate");
1495 m_env.getMap().addNodeAndUpdate(p, n, modified_blocks, remove_metadata);
1497 catch(InvalidPositionException &e) {
1500 for(std::map<v3s16, MapBlock *>::iterator
1501 i = modified_blocks.begin();
1502 i != modified_blocks.end(); ++i) {
1503 addUpdateMeshTaskWithEdge(i->first, false, true);
1507 void Client::setPlayerControl(PlayerControl &control)
1509 LocalPlayer *player = m_env.getLocalPlayer();
1510 assert(player != NULL);
1511 player->control = control;
1514 void Client::selectPlayerItem(u16 item)
1516 m_playeritem = item;
1517 m_inventory_updated = true;
1518 sendPlayerItem(item);
1521 // Returns true if the inventory of the local player has been
1522 // updated from the server. If it is true, it is set to false.
1523 bool Client::getLocalInventoryUpdated()
1525 bool updated = m_inventory_updated;
1526 m_inventory_updated = false;
1530 // Copies the inventory of the local player to parameter
1531 void Client::getLocalInventory(Inventory &dst)
1533 LocalPlayer *player = m_env.getLocalPlayer();
1534 assert(player != NULL);
1535 dst = player->inventory;
1538 Inventory* Client::getInventory(const InventoryLocation &loc)
1541 case InventoryLocation::UNDEFINED:
1544 case InventoryLocation::CURRENT_PLAYER:
1546 LocalPlayer *player = m_env.getLocalPlayer();
1547 assert(player != NULL);
1548 return &player->inventory;
1551 case InventoryLocation::PLAYER:
1553 // Check if we are working with local player inventory
1554 LocalPlayer *player = m_env.getLocalPlayer();
1555 if (!player || strcmp(player->getName(), loc.name.c_str()) != 0)
1557 return &player->inventory;
1560 case InventoryLocation::NODEMETA:
1562 NodeMetadata *meta = m_env.getMap().getNodeMetadata(loc.p);
1565 return meta->getInventory();
1568 case InventoryLocation::DETACHED:
1570 if (m_detached_inventories.count(loc.name) == 0)
1572 return m_detached_inventories[loc.name];
1576 FATAL_ERROR("Invalid inventory location type.");
1582 void Client::inventoryAction(InventoryAction *a)
1585 Send it to the server
1587 sendInventoryAction(a);
1590 Predict some local inventory changes
1592 a->clientApply(this, this);
1598 float Client::getAnimationTime()
1600 return m_animation_time;
1603 int Client::getCrackLevel()
1605 return m_crack_level;
1608 void Client::setCrack(int level, v3s16 pos)
1610 int old_crack_level = m_crack_level;
1611 v3s16 old_crack_pos = m_crack_pos;
1613 m_crack_level = level;
1616 if(old_crack_level >= 0 && (level < 0 || pos != old_crack_pos))
1619 addUpdateMeshTaskForNode(old_crack_pos, false, true);
1621 if(level >= 0 && (old_crack_level < 0 || pos != old_crack_pos))
1624 addUpdateMeshTaskForNode(pos, false, true);
1630 LocalPlayer *player = m_env.getLocalPlayer();
1631 assert(player != NULL);
1635 bool Client::getChatMessage(std::wstring &message)
1637 if(m_chat_queue.size() == 0)
1639 message = m_chat_queue.front();
1644 void Client::typeChatMessage(const std::wstring &message)
1646 // Discard empty line
1650 // If message was ate by script API, don't send it to server
1651 if (m_script->on_sending_message(wide_to_utf8(message))) {
1656 sendChatMessage(message);
1659 if (message[0] != L'/')
1661 // compatibility code
1662 if (m_proto_ver < 29) {
1663 LocalPlayer *player = m_env.getLocalPlayer();
1664 assert(player != NULL);
1665 std::wstring name = narrow_to_wide(player->getName());
1666 pushToChatQueue((std::wstring)L"<" + name + L"> " + message);
1671 void Client::addUpdateMeshTask(v3s16 p, bool ack_to_server, bool urgent)
1673 MapBlock *b = m_env.getMap().getBlockNoCreateNoEx(p);
1678 Create a task to update the mesh of the block
1681 MeshMakeData *data = new MeshMakeData(this, m_cache_enable_shaders,
1682 m_cache_use_tangent_vertices);
1685 //TimeTaker timer("data fill");
1687 // Debug: 1-6ms, avg=2ms
1689 data->setCrack(m_crack_level, m_crack_pos);
1690 data->setSmoothLighting(m_cache_smooth_lighting);
1693 // Add task to queue
1694 m_mesh_update_thread.enqueueUpdate(p, data, ack_to_server, urgent);
1697 void Client::addUpdateMeshTaskWithEdge(v3s16 blockpos, bool ack_to_server, bool urgent)
1700 addUpdateMeshTask(blockpos, ack_to_server, urgent);
1702 catch(InvalidPositionException &e){}
1705 for (int i=0;i<6;i++)
1708 v3s16 p = blockpos + g_6dirs[i];
1709 addUpdateMeshTask(p, false, urgent);
1711 catch(InvalidPositionException &e){}
1715 void Client::addUpdateMeshTaskForNode(v3s16 nodepos, bool ack_to_server, bool urgent)
1719 infostream<<"Client::addUpdateMeshTaskForNode(): "
1720 <<"("<<p.X<<","<<p.Y<<","<<p.Z<<")"
1724 v3s16 blockpos = getNodeBlockPos(nodepos);
1725 v3s16 blockpos_relative = blockpos * MAP_BLOCKSIZE;
1728 addUpdateMeshTask(blockpos, ack_to_server, urgent);
1730 catch(InvalidPositionException &e) {}
1733 if(nodepos.X == blockpos_relative.X){
1735 v3s16 p = blockpos + v3s16(-1,0,0);
1736 addUpdateMeshTask(p, false, urgent);
1738 catch(InvalidPositionException &e){}
1741 if(nodepos.Y == blockpos_relative.Y){
1743 v3s16 p = blockpos + v3s16(0,-1,0);
1744 addUpdateMeshTask(p, false, urgent);
1746 catch(InvalidPositionException &e){}
1749 if(nodepos.Z == blockpos_relative.Z){
1751 v3s16 p = blockpos + v3s16(0,0,-1);
1752 addUpdateMeshTask(p, false, urgent);
1754 catch(InvalidPositionException &e){}
1758 ClientEvent Client::getClientEvent()
1761 if (m_client_event_queue.empty()) {
1762 event.type = CE_NONE;
1765 event = m_client_event_queue.front();
1766 m_client_event_queue.pop();
1771 float Client::mediaReceiveProgress()
1773 if (m_media_downloader)
1774 return m_media_downloader->getProgress();
1776 return 1.0; // downloader only exists when not yet done
1779 typedef struct TextureUpdateArgs {
1780 IrrlichtDevice *device;
1781 gui::IGUIEnvironment *guienv;
1784 const wchar_t* text_base;
1785 } TextureUpdateArgs;
1787 void texture_update_progress(void *args, u32 progress, u32 max_progress)
1789 TextureUpdateArgs* targs = (TextureUpdateArgs*) args;
1790 u16 cur_percent = ceil(progress / (double) max_progress * 100.);
1792 // update the loading menu -- if neccessary
1793 bool do_draw = false;
1794 u32 time_ms = targs->last_time_ms;
1795 if (cur_percent != targs->last_percent) {
1796 targs->last_percent = cur_percent;
1797 time_ms = getTimeMs();
1798 // only draw when the user will notice something:
1799 do_draw = (time_ms - targs->last_time_ms > 100);
1803 targs->last_time_ms = time_ms;
1804 std::basic_stringstream<wchar_t> strm;
1805 strm << targs->text_base << " " << targs->last_percent << "%...";
1806 draw_load_screen(strm.str(), targs->device, targs->guienv, 0,
1807 72 + (u16) ((18. / 100.) * (double) targs->last_percent));
1811 void Client::afterContentReceived(IrrlichtDevice *device)
1813 infostream<<"Client::afterContentReceived() started"<<std::endl;
1814 assert(m_itemdef_received); // pre-condition
1815 assert(m_nodedef_received); // pre-condition
1816 assert(mediaReceived()); // pre-condition
1818 const wchar_t* text = wgettext("Loading textures...");
1820 // Clear cached pre-scaled 2D GUI images, as this cache
1821 // might have images with the same name but different
1822 // content from previous sessions.
1823 guiScalingCacheClear(device->getVideoDriver());
1825 // Rebuild inherited images and recreate textures
1826 infostream<<"- Rebuilding images and textures"<<std::endl;
1827 draw_load_screen(text,device, guienv, 0, 70);
1828 m_tsrc->rebuildImagesAndTextures();
1832 infostream<<"- Rebuilding shaders"<<std::endl;
1833 text = wgettext("Rebuilding shaders...");
1834 draw_load_screen(text, device, guienv, 0, 71);
1835 m_shsrc->rebuildShaders();
1838 // Update node aliases
1839 infostream<<"- Updating node aliases"<<std::endl;
1840 text = wgettext("Initializing nodes...");
1841 draw_load_screen(text, device, guienv, 0, 72);
1842 m_nodedef->updateAliases(m_itemdef);
1843 std::string texture_path = g_settings->get("texture_path");
1844 if (texture_path != "" && fs::IsDir(texture_path))
1845 m_nodedef->applyTextureOverrides(texture_path + DIR_DELIM + "override.txt");
1846 m_nodedef->setNodeRegistrationStatus(true);
1847 m_nodedef->runNodeResolveCallbacks();
1850 // Update node textures and assign shaders to each tile
1851 infostream<<"- Updating node textures"<<std::endl;
1852 TextureUpdateArgs tu_args;
1853 tu_args.device = device;
1854 tu_args.guienv = guienv;
1855 tu_args.last_time_ms = getTimeMs();
1856 tu_args.last_percent = 0;
1857 tu_args.text_base = wgettext("Initializing nodes");
1858 m_nodedef->updateTextures(this, texture_update_progress, &tu_args);
1859 delete[] tu_args.text_base;
1861 // Start mesh update thread after setting up content definitions
1862 infostream<<"- Starting mesh update thread"<<std::endl;
1863 m_mesh_update_thread.start();
1867 text = wgettext("Done!");
1868 draw_load_screen(text, device, guienv, 0, 100);
1869 infostream<<"Client::afterContentReceived() done"<<std::endl;
1873 float Client::getRTT()
1875 return m_con.getPeerStat(PEER_ID_SERVER,con::AVG_RTT);
1878 float Client::getCurRate()
1880 return ( m_con.getLocalStat(con::CUR_INC_RATE) +
1881 m_con.getLocalStat(con::CUR_DL_RATE));
1884 void Client::makeScreenshot(IrrlichtDevice *device)
1886 irr::video::IVideoDriver *driver = device->getVideoDriver();
1887 irr::video::IImage* const raw_image = driver->createScreenShot();
1892 time_t t = time(NULL);
1893 struct tm *tm = localtime(&t);
1895 char timetstamp_c[64];
1896 strftime(timetstamp_c, sizeof(timetstamp_c), "%Y%m%d_%H%M%S", tm);
1898 std::string filename_base = g_settings->get("screenshot_path")
1900 + std::string("screenshot_")
1901 + std::string(timetstamp_c);
1902 std::string filename_ext = "." + g_settings->get("screenshot_format");
1903 std::string filename;
1905 u32 quality = (u32)g_settings->getS32("screenshot_quality");
1906 quality = MYMIN(MYMAX(quality, 0), 100) / 100.0 * 255;
1908 // Try to find a unique filename
1909 unsigned serial = 0;
1911 while (serial < SCREENSHOT_MAX_SERIAL_TRIES) {
1912 filename = filename_base + (serial > 0 ? ("_" + itos(serial)) : "") + filename_ext;
1913 std::ifstream tmp(filename.c_str());
1915 break; // File did not apparently exist, we'll go with it
1919 if (serial == SCREENSHOT_MAX_SERIAL_TRIES) {
1920 infostream << "Could not find suitable filename for screenshot" << std::endl;
1922 irr::video::IImage* const image =
1923 driver->createImage(video::ECF_R8G8B8, raw_image->getDimension());
1926 raw_image->copyTo(image);
1928 std::ostringstream sstr;
1929 if (driver->writeImageToFile(image, filename.c_str(), quality)) {
1930 sstr << "Saved screenshot to '" << filename << "'";
1932 sstr << "Failed to save screenshot '" << filename << "'";
1934 pushToChatQueue(narrow_to_wide(sstr.str()));
1935 infostream << sstr.str() << std::endl;
1943 bool Client::shouldShowMinimap() const
1945 return !m_minimap_disabled_by_server;
1948 void Client::showGameChat(const bool show)
1950 m_game_ui_flags->show_chat = show;
1953 void Client::showGameHud(const bool show)
1955 m_game_ui_flags->show_hud = show;
1958 void Client::showMinimap(const bool show)
1960 m_game_ui_flags->show_minimap = show;
1963 void Client::showProfiler(const bool show)
1965 m_game_ui_flags->show_profiler_graph = show;
1968 void Client::showGameFog(const bool show)
1970 m_game_ui_flags->force_fog_off = !show;
1973 void Client::showGameDebug(const bool show)
1975 m_game_ui_flags->show_debug = show;
1978 // IGameDef interface
1980 IItemDefManager* Client::getItemDefManager()
1984 INodeDefManager* Client::getNodeDefManager()
1988 ICraftDefManager* Client::getCraftDefManager()
1991 //return m_craftdef;
1993 ITextureSource* Client::getTextureSource()
1997 IShaderSource* Client::getShaderSource()
2001 scene::ISceneManager* Client::getSceneManager()
2003 return m_device->getSceneManager();
2005 u16 Client::allocateUnknownNodeId(const std::string &name)
2007 errorstream << "Client::allocateUnknownNodeId(): "
2008 << "Client cannot allocate node IDs" << std::endl;
2009 FATAL_ERROR("Client allocated unknown node");
2011 return CONTENT_IGNORE;
2013 ISoundManager* Client::getSoundManager()
2017 MtEventManager* Client::getEventManager()
2022 ParticleManager* Client::getParticleManager()
2024 return &m_particle_manager;
2027 scene::IAnimatedMesh* Client::getMesh(const std::string &filename)
2029 StringMap::const_iterator it = m_mesh_data.find(filename);
2030 if (it == m_mesh_data.end()) {
2031 errorstream << "Client::getMesh(): Mesh not found: \"" << filename
2032 << "\"" << std::endl;
2035 const std::string &data = it->second;
2036 scene::ISceneManager *smgr = m_device->getSceneManager();
2038 // Create the mesh, remove it from cache and return it
2039 // This allows unique vertex colors and other properties for each instance
2040 Buffer<char> data_rw(data.c_str(), data.size()); // Const-incorrect Irrlicht
2041 io::IFileSystem *irrfs = m_device->getFileSystem();
2042 io::IReadFile *rfile = irrfs->createMemoryReadFile(
2043 *data_rw, data_rw.getSize(), filename.c_str());
2044 FATAL_ERROR_IF(!rfile, "Could not create/open RAM file");
2046 scene::IAnimatedMesh *mesh = smgr->getMesh(rfile);
2048 // NOTE: By playing with Irrlicht refcounts, maybe we could cache a bunch
2049 // of uniquely named instances and re-use them
2051 smgr->getMeshCache()->removeMesh(mesh);
2055 bool Client::registerModStorage(ModMetadata *storage)
2057 if (m_mod_storages.find(storage->getModName()) != m_mod_storages.end()) {
2058 errorstream << "Unable to register same mod storage twice. Storage name: "
2059 << storage->getModName() << std::endl;
2063 m_mod_storages[storage->getModName()] = storage;
2067 void Client::unregisterModStorage(const std::string &name)
2069 UNORDERED_MAP<std::string, ModMetadata *>::const_iterator it = m_mod_storages.find(name);
2070 if (it != m_mod_storages.end()) {
2071 // Save unconditionaly on unregistration
2072 it->second->save(getModStoragePath());
2073 m_mod_storages.erase(name);
2077 std::string Client::getModStoragePath() const
2079 return porting::path_user + DIR_DELIM + "client" + DIR_DELIM + "mod_storage";