3 Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com>
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU Lesser General Public License as published by
7 the Free Software Foundation; either version 2.1 of the License, or
8 (at your option) any later version.
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU Lesser General Public License for more details.
15 You should have received a copy of the GNU Lesser General Public License along
16 with this program; if not, write to the Free Software Foundation, Inc.,
17 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
24 #include <IFileSystem.h>
26 #include "network/clientopcodes.h"
27 #include "network/connection.h"
28 #include "network/networkpacket.h"
29 #include "threading/mutex_auto_lock.h"
30 #include "client/clientevent.h"
31 #include "client/gameui.h"
32 #include "client/renderingengine.h"
33 #include "client/sound.h"
34 #include "client/tile.h"
35 #include "util/auth.h"
36 #include "util/directiontables.h"
37 #include "util/pointedthing.h"
38 #include "util/serialize.h"
39 #include "util/string.h"
42 #include "mapblock_mesh.h"
45 #include "modchannels.h"
46 #include "content/mods.h"
50 #include "clientmap.h"
51 #include "clientmedia.h"
53 #include "database/database-sqlite3.h"
54 #include "serialization.h"
55 #include "guiscalingfilter.h"
56 #include "script/scripting_client.h"
58 #include "chatmessage.h"
59 #include "translation.h"
61 extern gui::IGUIEnvironment* guienv;
67 u32 PacketCounter::sum() const
70 for (const auto &it : m_packets)
75 void PacketCounter::print(std::ostream &o) const
77 for (const auto &it : m_packets) {
78 auto name = it.first >= TOCLIENT_NUM_MSG_TYPES ? "?"
79 : toClientCommandTable[it.first].name;
80 o << "cmd " << it.first << " (" << name << ") count "
81 << it.second << std::endl;
90 const char *playername,
91 const std::string &password,
92 const std::string &address_name,
93 MapDrawControl &control,
94 IWritableTextureSource *tsrc,
95 IWritableShaderSource *shsrc,
96 IWritableItemDefManager *itemdef,
97 NodeDefManager *nodedef,
99 MtEventManager *event,
109 m_mesh_update_thread(this),
111 new ClientMap(this, control, 666),
114 m_particle_manager(&m_env),
115 m_con(new con::Connection(PROTOCOL_ID, 512, CONNECTION_TIMEOUT, ipv6, this)),
116 m_address_name(address_name),
117 m_server_ser_ver(SER_FMT_VER_INVALID),
118 m_last_chat_message_sent(time(NULL)),
119 m_password(password),
120 m_chosen_auth_mech(AUTH_MECHANISM_NONE),
121 m_media_downloader(new ClientMediaDownloader()),
124 m_modchannel_mgr(new ModChannelMgr())
127 m_env.setLocalPlayer(new LocalPlayer(this, playername));
129 if (g_settings->getBool("enable_minimap")) {
130 m_minimap = new Minimap(this);
133 m_cache_save_interval = g_settings->getU16("server_map_save_interval");
136 void Client::loadMods()
138 // Don't load mods twice.
139 // If client scripting is disabled by the client, don't load builtin or
140 // client-provided mods.
141 if (m_mods_loaded || !g_settings->getBool("enable_client_modding"))
144 // If client scripting is disabled by the server, don't load builtin or
145 // client-provided mods.
146 // TODO Delete this code block when server-sent CSM and verifying of builtin are
148 if (checkCSMRestrictionFlag(CSMRestrictionFlags::CSM_RF_LOAD_CLIENT_MODS)) {
149 warningstream << "Client-provided mod loading is disabled by server." <<
154 m_script = new ClientScripting(this);
155 m_env.setScript(m_script);
156 m_script->setEnv(&m_env);
159 scanModIntoMemory(BUILTIN_MOD_NAME, getBuiltinLuaPath());
160 m_script->loadModFromMemory(BUILTIN_MOD_NAME);
162 // TODO Uncomment when server-sent CSM and verifying of builtin are complete
164 // Don't load client-provided mods if disabled by server
165 if (checkCSMRestrictionFlag(CSMRestrictionFlags::CSM_RF_LOAD_CLIENT_MODS)) {
166 warningstream << "Client-provided mod loading is disabled by server." <<
168 // If builtin integrity is wrong, disconnect user
169 if (!checkBuiltinIntegrity()) {
170 // TODO disconnect user
176 ClientModConfiguration modconf(getClientModsLuaPath());
177 m_mods = modconf.getMods();
178 // complain about mods with unsatisfied dependencies
179 if (!modconf.isConsistent()) {
180 modconf.printUnsatisfiedModsError();
185 infostream << "Client loading mods: ";
186 for (const ModSpec &mod : m_mods)
187 infostream << mod.name << " ";
188 infostream << std::endl;
190 // Load "mod" scripts
191 for (const ModSpec &mod : m_mods) {
192 if (!string_allowed(mod.name, MODNAME_ALLOWED_CHARS)) {
193 throw ModError("Error loading mod \"" + mod.name +
194 "\": Mod name does not follow naming conventions: "
195 "Only characters [a-z0-9_] are allowed.");
197 scanModIntoMemory(mod.name, mod.path);
201 for (const ModSpec &mod : m_mods)
202 m_script->loadModFromMemory(mod.name);
204 // Mods are done loading. Unlock callbacks
205 m_mods_loaded = true;
207 // Run a callback when mods are loaded
208 m_script->on_mods_loaded();
210 // Create objects if they're ready
211 if (m_state == LC_Ready)
212 m_script->on_client_ready(m_env.getLocalPlayer());
214 m_script->on_camera_ready(m_camera);
216 m_script->on_minimap_ready(m_minimap);
219 bool Client::checkBuiltinIntegrity()
225 void Client::scanModSubfolder(const std::string &mod_name, const std::string &mod_path,
226 std::string mod_subpath)
228 std::string full_path = mod_path + DIR_DELIM + mod_subpath;
229 std::vector<fs::DirListNode> mod = fs::GetDirListing(full_path);
230 for (const fs::DirListNode &j : mod) {
232 scanModSubfolder(mod_name, mod_path, mod_subpath + j.name + DIR_DELIM);
235 std::replace(mod_subpath.begin(), mod_subpath.end(), DIR_DELIM_CHAR, '/');
237 std::string real_path = full_path + j.name;
238 std::string vfs_path = mod_name + ":" + mod_subpath + j.name;
239 infostream << "Client::scanModSubfolder(): Loading \"" << real_path
240 << "\" as \"" << vfs_path << "\"." << std::endl;
242 std::string contents;
243 if (!fs::ReadFile(real_path, contents)) {
244 errorstream << "Client::scanModSubfolder(): Can't read file \""
245 << real_path << "\"." << std::endl;
249 m_mod_vfs.emplace(vfs_path, contents);
253 const std::string &Client::getBuiltinLuaPath()
255 static const std::string builtin_dir = porting::path_share + DIR_DELIM + "builtin";
259 const std::string &Client::getClientModsLuaPath()
261 static const std::string clientmods_dir = porting::path_share + DIR_DELIM + "clientmods";
262 return clientmods_dir;
265 const std::vector<ModSpec>& Client::getMods() const
267 static std::vector<ModSpec> client_modspec_temp;
268 return client_modspec_temp;
271 const ModSpec* Client::getModSpec(const std::string &modname) const
280 m_script->on_shutdown();
281 //request all client managed threads to stop
282 m_mesh_update_thread.stop();
283 // Save local server map
285 infostream << "Local map saving ended." << std::endl;
286 m_localdb->endSave();
293 bool Client::isShutdown()
295 return m_shutdown || !m_mesh_update_thread.isRunning();
305 m_mesh_update_thread.stop();
306 m_mesh_update_thread.wait();
307 while (!m_mesh_update_thread.m_queue_out.empty()) {
308 MeshUpdateResult r = m_mesh_update_thread.m_queue_out.pop_frontNoEx();
313 delete m_inventory_from_server;
315 // Delete detached inventories
316 for (auto &m_detached_inventorie : m_detached_inventories) {
317 delete m_detached_inventorie.second;
320 // cleanup 3d model meshes on client shutdown
321 while (RenderingEngine::get_mesh_cache()->getMeshCount() != 0) {
322 scene::IAnimatedMesh *mesh = RenderingEngine::get_mesh_cache()->getMeshByIndex(0);
325 RenderingEngine::get_mesh_cache()->removeMesh(mesh);
331 delete m_media_downloader;
334 void Client::connect(Address address, bool is_local_server)
336 initLocalMapSaving(address, m_address_name, is_local_server);
338 // Since we use TryReceive() a timeout here would be ineffective anyway
339 m_con->SetTimeoutMs(0);
340 m_con->Connect(address);
343 void Client::step(float dtime)
349 m_animation_time += dtime;
350 if(m_animation_time > 60.0)
351 m_animation_time -= 60.0;
353 m_time_of_day_update_timer += dtime;
361 float &counter = m_packetcounter_timer;
366 u32 sum = m_packetcounter.sum();
367 float avg = sum / counter;
369 infostream << "Client packetcounter (" << counter << "s): "
370 << "sum=" << sum << " avg=" << avg << "/s" << std::endl;
371 m_packetcounter.print(infostream);
372 m_packetcounter.clear();
376 // UGLY hack to fix 2 second startup delay caused by non existent
377 // server client startup synchronization in local server or singleplayer mode
378 static bool initial_step = true;
380 initial_step = false;
382 else if(m_state == LC_Created) {
383 if (m_is_registration_confirmation_state) {
384 // Waiting confirmation
387 float &counter = m_connection_reinit_timer;
392 LocalPlayer *myplayer = m_env.getLocalPlayer();
393 FATAL_ERROR_IF(myplayer == NULL, "Local player not found in environment.");
395 sendInit(myplayer->getName());
398 // Not connected, return
403 Do stuff if connected
407 Run Map's timers and unload unused data
409 const float map_timer_and_unload_dtime = 5.25;
410 if(m_map_timer_and_unload_interval.step(dtime, map_timer_and_unload_dtime)) {
411 std::vector<v3s16> deleted_blocks;
412 m_env.getMap().timerUpdate(map_timer_and_unload_dtime,
413 g_settings->getFloat("client_unload_unused_data_timeout"),
414 g_settings->getS32("client_mapblock_limit"),
419 NOTE: This loop is intentionally iterated the way it is.
422 std::vector<v3s16>::iterator i = deleted_blocks.begin();
423 std::vector<v3s16> sendlist;
425 if(sendlist.size() == 255 || i == deleted_blocks.end()) {
436 sendDeletedBlocks(sendlist);
438 if(i == deleted_blocks.end())
444 sendlist.push_back(*i);
450 Send pending messages on out chat queue
452 if (!m_out_chat_queue.empty() && canSendChatMessage()) {
453 sendChatMessage(m_out_chat_queue.front());
454 m_out_chat_queue.pop();
460 LocalPlayer *player = m_env.getLocalPlayer();
462 // Step environment (also handles player controls)
464 m_sound->step(dtime);
469 while (m_env.hasClientEnvEvents()) {
470 ClientEnvEvent envEvent = m_env.getClientEnvEvent();
472 if (envEvent.type == CEE_PLAYER_DAMAGE) {
473 u16 damage = envEvent.player_damage.amount;
475 if (envEvent.player_damage.send_to_server)
478 // Add to ClientEvent queue
479 ClientEvent *event = new ClientEvent();
480 event->type = CE_PLAYER_DAMAGE;
481 event->player_damage.amount = damage;
482 m_client_event_queue.push(event);
489 float &counter = m_avg_rtt_timer;
493 // connectedAndInitialized() is true, peer exists.
494 float avg_rtt = getRTT();
495 infostream << "Client: avg_rtt=" << avg_rtt << std::endl;
499 Send player position to server
502 float &counter = m_playerpos_send_timer;
504 if((m_state == LC_Ready) && (counter >= m_recommended_send_interval))
512 Replace updated meshes
515 int num_processed_meshes = 0;
516 std::vector<v3s16> blocks_to_ack;
517 while (!m_mesh_update_thread.m_queue_out.empty())
519 num_processed_meshes++;
521 MinimapMapblock *minimap_mapblock = NULL;
522 bool do_mapper_update = true;
524 MeshUpdateResult r = m_mesh_update_thread.m_queue_out.pop_frontNoEx();
525 MapBlock *block = m_env.getMap().getBlockNoCreateNoEx(r.p);
527 // Delete the old mesh
529 block->mesh = nullptr;
532 minimap_mapblock = r.mesh->moveMinimapMapblock();
533 if (minimap_mapblock == NULL)
534 do_mapper_update = false;
536 bool is_empty = true;
537 for (int l = 0; l < MAX_TILE_LAYERS; l++)
538 if (r.mesh->getMesh(l)->getMeshBufferCount() != 0)
544 // Replace with the new mesh
545 block->mesh = r.mesh;
551 if (m_minimap && do_mapper_update)
552 m_minimap->addBlock(r.p, minimap_mapblock);
554 if (r.ack_block_to_server) {
555 if (blocks_to_ack.size() == 255) {
556 sendGotBlocks(blocks_to_ack);
557 blocks_to_ack.clear();
560 blocks_to_ack.emplace_back(r.p);
563 if (blocks_to_ack.size() > 0) {
564 // Acknowledge block(s)
565 sendGotBlocks(blocks_to_ack);
568 if (num_processed_meshes > 0)
569 g_profiler->graphAdd("num_processed_meshes", num_processed_meshes);
575 if (m_media_downloader && m_media_downloader->isStarted()) {
576 m_media_downloader->step(this);
577 if (m_media_downloader->isDone()) {
578 delete m_media_downloader;
579 m_media_downloader = NULL;
584 If the server didn't update the inventory in a while, revert
585 the local inventory (so the player notices the lag problem
586 and knows something is wrong).
588 if (m_inventory_from_server) {
589 float interval = 10.0f;
590 float count_before = std::floor(m_inventory_from_server_age / interval);
592 m_inventory_from_server_age += dtime;
594 float count_after = std::floor(m_inventory_from_server_age / interval);
596 if (count_after != count_before) {
597 // Do this every <interval> seconds after TOCLIENT_INVENTORY
598 // Reset the locally changed inventory to the authoritative inventory
599 player->inventory = *m_inventory_from_server;
600 m_update_wielded_item = true;
605 Update positions of sounds attached to objects
608 for (auto &m_sounds_to_object : m_sounds_to_objects) {
609 int client_id = m_sounds_to_object.first;
610 u16 object_id = m_sounds_to_object.second;
611 ClientActiveObject *cao = m_env.getActiveObject(object_id);
614 m_sound->updateSoundPosition(client_id, cao->getPosition());
619 Handle removed remotely initiated sounds
621 m_removed_sounds_check_timer += dtime;
622 if(m_removed_sounds_check_timer >= 2.32) {
623 m_removed_sounds_check_timer = 0;
624 // Find removed sounds and clear references to them
625 std::vector<s32> removed_server_ids;
626 for (std::unordered_map<s32, int>::iterator i = m_sounds_server_to_client.begin();
627 i != m_sounds_server_to_client.end();) {
628 s32 server_id = i->first;
629 int client_id = i->second;
631 if(!m_sound->soundExists(client_id)) {
632 m_sounds_server_to_client.erase(server_id);
633 m_sounds_client_to_server.erase(client_id);
634 m_sounds_to_objects.erase(client_id);
635 removed_server_ids.push_back(server_id);
640 if(!removed_server_ids.empty()) {
641 sendRemovedSounds(removed_server_ids);
645 m_mod_storage_save_timer -= dtime;
646 if (m_mod_storage_save_timer <= 0.0f) {
647 m_mod_storage_save_timer = g_settings->getFloat("server_map_save_interval");
649 for (std::unordered_map<std::string, ModMetadata *>::const_iterator
650 it = m_mod_storages.begin(); it != m_mod_storages.end(); ++it) {
651 if (it->second->isModified()) {
652 it->second->save(getModStoragePath());
657 infostream << "Saved " << n << " modified mod storages." << std::endl;
661 if (m_localdb && m_localdb_save_interval.step(dtime,
662 m_cache_save_interval)) {
663 m_localdb->endSave();
664 m_localdb->beginSave();
668 bool Client::loadMedia(const std::string &data, const std::string &filename,
669 bool from_media_push)
673 const char *image_ext[] = {
674 ".png", ".jpg", ".bmp", ".tga",
675 ".pcx", ".ppm", ".psd", ".wal", ".rgb",
678 name = removeStringEnd(filename, image_ext);
680 TRACESTREAM(<< "Client: Attempting to load image "
681 << "file \"" << filename << "\"" << std::endl);
683 io::IFileSystem *irrfs = RenderingEngine::get_filesystem();
684 video::IVideoDriver *vdrv = RenderingEngine::get_video_driver();
686 // Silly irrlicht's const-incorrectness
687 Buffer<char> data_rw(data.c_str(), data.size());
689 // Create an irrlicht memory file
690 io::IReadFile *rfile = irrfs->createMemoryReadFile(
691 *data_rw, data_rw.getSize(), "_tempreadfile");
693 FATAL_ERROR_IF(!rfile, "Could not create irrlicht memory file.");
696 video::IImage *img = vdrv->createImageFromFile(rfile);
698 errorstream<<"Client: Cannot create image from data of "
699 <<"file \""<<filename<<"\""<<std::endl;
704 m_tsrc->insertSourceImage(filename, img);
710 const char *sound_ext[] = {
711 ".0.ogg", ".1.ogg", ".2.ogg", ".3.ogg", ".4.ogg",
712 ".5.ogg", ".6.ogg", ".7.ogg", ".8.ogg", ".9.ogg",
715 name = removeStringEnd(filename, sound_ext);
717 TRACESTREAM(<< "Client: Attempting to load sound "
718 << "file \"" << filename << "\"" << std::endl);
719 return m_sound->loadSoundData(name, data);
722 const char *model_ext[] = {
723 ".x", ".b3d", ".md2", ".obj",
726 name = removeStringEnd(filename, model_ext);
728 verbosestream<<"Client: Storing model into memory: "
729 <<"\""<<filename<<"\""<<std::endl;
730 if(m_mesh_data.count(filename))
731 errorstream<<"Multiple models with name \""<<filename.c_str()
732 <<"\" found; replacing previous model"<<std::endl;
733 m_mesh_data[filename] = data;
737 const char *translate_ext[] = {
740 name = removeStringEnd(filename, translate_ext);
744 TRACESTREAM(<< "Client: Loading translation: "
745 << "\"" << filename << "\"" << std::endl);
746 g_client_translations->loadTranslation(data);
750 errorstream << "Client: Don't know how to load file \""
751 << filename << "\"" << std::endl;
755 // Virtual methods from con::PeerHandler
756 void Client::peerAdded(con::Peer *peer)
758 infostream << "Client::peerAdded(): peer->id="
759 << peer->id << std::endl;
761 void Client::deletingPeer(con::Peer *peer, bool timeout)
763 infostream << "Client::deletingPeer(): "
764 "Server Peer is getting deleted "
765 << "(timeout=" << timeout << ")" << std::endl;
768 m_access_denied = true;
769 m_access_denied_reason = gettext("Connection timed out.");
775 u16 number of files requested
781 void Client::request_media(const std::vector<std::string> &file_requests)
783 std::ostringstream os(std::ios_base::binary);
784 writeU16(os, TOSERVER_REQUEST_MEDIA);
785 size_t file_requests_size = file_requests.size();
787 FATAL_ERROR_IF(file_requests_size > 0xFFFF, "Unsupported number of file requests");
789 // Packet dynamicly resized
790 NetworkPacket pkt(TOSERVER_REQUEST_MEDIA, 2 + 0);
792 pkt << (u16) (file_requests_size & 0xFFFF);
794 for (const std::string &file_request : file_requests) {
800 infostream << "Client: Sending media request list to server ("
801 << file_requests.size() << " files. packet size)" << std::endl;
804 void Client::initLocalMapSaving(const Address &address,
805 const std::string &hostname,
806 bool is_local_server)
808 if (!g_settings->getBool("enable_local_map_saving") || is_local_server) {
812 std::string world_path;
813 #define set_world_path(hostname) \
814 world_path = porting::path_user \
815 + DIR_DELIM + "worlds" \
816 + DIR_DELIM + "server_" \
817 + hostname + "_" + std::to_string(address.getPort());
819 set_world_path(hostname);
820 if (!fs::IsDir(world_path)) {
821 std::string hostname_escaped = hostname;
822 str_replace(hostname_escaped, ':', '_');
823 set_world_path(hostname_escaped);
825 #undef set_world_path
826 fs::CreateAllDirs(world_path);
828 m_localdb = new MapDatabaseSQLite3(world_path);
829 m_localdb->beginSave();
830 actionstream << "Local map saving started, map will be saved at '" << world_path << "'" << std::endl;
833 void Client::ReceiveAll()
836 u64 start_ms = porting::getTimeMs();
837 const u64 budget = 100;
839 // Limit time even if there would be huge amounts of data to
841 if (porting::getTimeMs() > start_ms + budget) {
842 infostream << "Client::ReceiveAll(): "
843 "Packet processing budget exceeded." << std::endl;
849 if (!m_con->TryReceive(&pkt))
852 } catch (const con::InvalidIncomingDataException &e) {
853 infostream << "Client::ReceiveAll(): "
854 "InvalidIncomingDataException: what()="
855 << e.what() << std::endl;
860 inline void Client::handleCommand(NetworkPacket* pkt)
862 const ToClientCommandHandler& opHandle = toClientCommandTable[pkt->getCommand()];
863 (this->*opHandle.handler)(pkt);
867 sender_peer_id given to this shall be quaranteed to be a valid peer
869 void Client::ProcessData(NetworkPacket *pkt)
871 ToClientCommand command = (ToClientCommand) pkt->getCommand();
872 u32 sender_peer_id = pkt->getPeerId();
874 //infostream<<"Client: received command="<<command<<std::endl;
875 m_packetcounter.add((u16)command);
876 g_profiler->graphAdd("client_received_packets", 1);
879 If this check is removed, be sure to change the queue
880 system to know the ids
882 if(sender_peer_id != PEER_ID_SERVER) {
883 infostream << "Client::ProcessData(): Discarding data not "
884 "coming from server: peer_id=" << sender_peer_id
889 // Command must be handled into ToClientCommandHandler
890 if (command >= TOCLIENT_NUM_MSG_TYPES) {
891 infostream << "Client: Ignoring unknown command "
892 << command << std::endl;
897 * Those packets are handled before m_server_ser_ver is set, it's normal
898 * But we must use the new ToClientConnectionState in the future,
901 if(toClientCommandTable[command].state == TOCLIENT_STATE_NOT_CONNECTED) {
906 if(m_server_ser_ver == SER_FMT_VER_INVALID) {
907 infostream << "Client: Server serialization"
908 " format invalid or not initialized."
909 " Skipping incoming command=" << command << std::endl;
914 Handle runtime commands
920 void Client::Send(NetworkPacket* pkt)
922 m_con->Send(PEER_ID_SERVER,
923 serverCommandFactoryTable[pkt->getCommand()].channel,
925 serverCommandFactoryTable[pkt->getCommand()].reliable);
928 // Will fill up 12 + 12 + 4 + 4 + 4 bytes
929 void writePlayerPos(LocalPlayer *myplayer, ClientMap *clientMap, NetworkPacket *pkt)
931 v3f pf = myplayer->getPosition() * 100;
932 v3f sf = myplayer->getSpeed() * 100;
933 s32 pitch = myplayer->getPitch() * 100;
934 s32 yaw = myplayer->getYaw() * 100;
935 u32 keyPressed = myplayer->keyPressed;
936 // scaled by 80, so that pi can fit into a u8
937 u8 fov = clientMap->getCameraFov() * 80;
938 u8 wanted_range = MYMIN(255,
939 std::ceil(clientMap->getControl().wanted_range / MAP_BLOCKSIZE));
941 v3s32 position(pf.X, pf.Y, pf.Z);
942 v3s32 speed(sf.X, sf.Y, sf.Z);
946 [0] v3s32 position*100
948 [12+12] s32 pitch*100
949 [12+12+4] s32 yaw*100
950 [12+12+4+4] u32 keyPressed
951 [12+12+4+4+4] u8 fov*80
952 [12+12+4+4+4+1] u8 ceil(wanted_range / MAP_BLOCKSIZE)
954 *pkt << position << speed << pitch << yaw << keyPressed;
955 *pkt << fov << wanted_range;
958 void Client::interact(InteractAction action, const PointedThing& pointed)
960 if(m_state != LC_Ready) {
961 errorstream << "Client::interact() "
962 "Canceled (not connected)"
967 LocalPlayer *myplayer = m_env.getLocalPlayer();
968 if (myplayer == NULL)
975 [5] u32 length of the next item (plen)
976 [9] serialized PointedThing
977 [9 + plen] player position information
980 NetworkPacket pkt(TOSERVER_INTERACT, 1 + 2 + 0);
983 pkt << myplayer->getWieldIndex();
985 std::ostringstream tmp_os(std::ios::binary);
986 pointed.serialize(tmp_os);
988 pkt.putLongString(tmp_os.str());
990 writePlayerPos(myplayer, &m_env.getClientMap(), &pkt);
995 void Client::deleteAuthData()
1000 switch (m_chosen_auth_mech) {
1001 case AUTH_MECHANISM_FIRST_SRP:
1003 case AUTH_MECHANISM_SRP:
1004 case AUTH_MECHANISM_LEGACY_PASSWORD:
1005 srp_user_delete((SRPUser *) m_auth_data);
1008 case AUTH_MECHANISM_NONE:
1011 m_chosen_auth_mech = AUTH_MECHANISM_NONE;
1015 AuthMechanism Client::choseAuthMech(const u32 mechs)
1017 if (mechs & AUTH_MECHANISM_SRP)
1018 return AUTH_MECHANISM_SRP;
1020 if (mechs & AUTH_MECHANISM_FIRST_SRP)
1021 return AUTH_MECHANISM_FIRST_SRP;
1023 if (mechs & AUTH_MECHANISM_LEGACY_PASSWORD)
1024 return AUTH_MECHANISM_LEGACY_PASSWORD;
1026 return AUTH_MECHANISM_NONE;
1029 void Client::sendInit(const std::string &playerName)
1031 NetworkPacket pkt(TOSERVER_INIT, 1 + 2 + 2 + (1 + playerName.size()));
1033 // we don't support network compression yet
1034 u16 supp_comp_modes = NETPROTO_COMPRESSION_NONE;
1036 pkt << (u8) SER_FMT_VER_HIGHEST_READ << (u16) supp_comp_modes;
1037 pkt << (u16) CLIENT_PROTOCOL_VERSION_MIN << (u16) CLIENT_PROTOCOL_VERSION_MAX;
1043 void Client::promptConfirmRegistration(AuthMechanism chosen_auth_mechanism)
1045 m_chosen_auth_mech = chosen_auth_mechanism;
1046 m_is_registration_confirmation_state = true;
1049 void Client::confirmRegistration()
1051 m_is_registration_confirmation_state = false;
1052 startAuth(m_chosen_auth_mech);
1055 void Client::startAuth(AuthMechanism chosen_auth_mechanism)
1057 m_chosen_auth_mech = chosen_auth_mechanism;
1059 switch (chosen_auth_mechanism) {
1060 case AUTH_MECHANISM_FIRST_SRP: {
1061 // send srp verifier to server
1062 std::string verifier;
1064 generate_srp_verifier_and_salt(getPlayerName(), m_password,
1067 NetworkPacket resp_pkt(TOSERVER_FIRST_SRP, 0);
1068 resp_pkt << salt << verifier << (u8)((m_password.empty()) ? 1 : 0);
1073 case AUTH_MECHANISM_SRP:
1074 case AUTH_MECHANISM_LEGACY_PASSWORD: {
1077 if (chosen_auth_mechanism == AUTH_MECHANISM_LEGACY_PASSWORD) {
1078 m_password = translate_password(getPlayerName(), m_password);
1082 std::string playername_u = lowercase(getPlayerName());
1083 m_auth_data = srp_user_new(SRP_SHA256, SRP_NG_2048,
1084 getPlayerName().c_str(), playername_u.c_str(),
1085 (const unsigned char *) m_password.c_str(),
1086 m_password.length(), NULL, NULL);
1089 SRP_Result res = srp_user_start_authentication(
1090 (struct SRPUser *) m_auth_data, NULL, NULL, 0,
1091 (unsigned char **) &bytes_A, &len_A);
1092 FATAL_ERROR_IF(res != SRP_OK, "Creating local SRP user failed.");
1094 NetworkPacket resp_pkt(TOSERVER_SRP_BYTES_A, 0);
1095 resp_pkt << std::string(bytes_A, len_A) << based_on;
1099 case AUTH_MECHANISM_NONE:
1100 break; // not handled in this method
1104 void Client::sendDeletedBlocks(std::vector<v3s16> &blocks)
1106 NetworkPacket pkt(TOSERVER_DELETEDBLOCKS, 1 + sizeof(v3s16) * blocks.size());
1108 pkt << (u8) blocks.size();
1110 for (const v3s16 &block : blocks) {
1117 void Client::sendGotBlocks(const std::vector<v3s16> &blocks)
1119 NetworkPacket pkt(TOSERVER_GOTBLOCKS, 1 + 6 * blocks.size());
1120 pkt << (u8) blocks.size();
1121 for (const v3s16 &block : blocks)
1127 void Client::sendRemovedSounds(std::vector<s32> &soundList)
1129 size_t server_ids = soundList.size();
1130 assert(server_ids <= 0xFFFF);
1132 NetworkPacket pkt(TOSERVER_REMOVED_SOUNDS, 2 + server_ids * 4);
1134 pkt << (u16) (server_ids & 0xFFFF);
1136 for (s32 sound_id : soundList)
1142 void Client::sendNodemetaFields(v3s16 p, const std::string &formname,
1143 const StringMap &fields)
1145 size_t fields_size = fields.size();
1147 FATAL_ERROR_IF(fields_size > 0xFFFF, "Unsupported number of nodemeta fields");
1149 NetworkPacket pkt(TOSERVER_NODEMETA_FIELDS, 0);
1151 pkt << p << formname << (u16) (fields_size & 0xFFFF);
1153 StringMap::const_iterator it;
1154 for (it = fields.begin(); it != fields.end(); ++it) {
1155 const std::string &name = it->first;
1156 const std::string &value = it->second;
1158 pkt.putLongString(value);
1164 void Client::sendInventoryFields(const std::string &formname,
1165 const StringMap &fields)
1167 size_t fields_size = fields.size();
1168 FATAL_ERROR_IF(fields_size > 0xFFFF, "Unsupported number of inventory fields");
1170 NetworkPacket pkt(TOSERVER_INVENTORY_FIELDS, 0);
1171 pkt << formname << (u16) (fields_size & 0xFFFF);
1173 StringMap::const_iterator it;
1174 for (it = fields.begin(); it != fields.end(); ++it) {
1175 const std::string &name = it->first;
1176 const std::string &value = it->second;
1178 pkt.putLongString(value);
1184 void Client::sendInventoryAction(InventoryAction *a)
1186 std::ostringstream os(std::ios_base::binary);
1191 std::string s = os.str();
1193 NetworkPacket pkt(TOSERVER_INVENTORY_ACTION, s.size());
1194 pkt.putRawString(s.c_str(),s.size());
1199 bool Client::canSendChatMessage() const
1201 u32 now = time(NULL);
1202 float time_passed = now - m_last_chat_message_sent;
1204 float virt_chat_message_allowance = m_chat_message_allowance + time_passed *
1205 (CLIENT_CHAT_MESSAGE_LIMIT_PER_10S / 8.0f);
1207 if (virt_chat_message_allowance < 1.0f)
1213 void Client::sendChatMessage(const std::wstring &message)
1215 const s16 max_queue_size = g_settings->getS16("max_out_chat_queue_size");
1216 if (canSendChatMessage()) {
1217 u32 now = time(NULL);
1218 float time_passed = now - m_last_chat_message_sent;
1219 m_last_chat_message_sent = time(NULL);
1221 m_chat_message_allowance += time_passed * (CLIENT_CHAT_MESSAGE_LIMIT_PER_10S / 8.0f);
1222 if (m_chat_message_allowance > CLIENT_CHAT_MESSAGE_LIMIT_PER_10S)
1223 m_chat_message_allowance = CLIENT_CHAT_MESSAGE_LIMIT_PER_10S;
1225 m_chat_message_allowance -= 1.0f;
1227 NetworkPacket pkt(TOSERVER_CHAT_MESSAGE, 2 + message.size() * sizeof(u16));
1232 } else if (m_out_chat_queue.size() < (u16) max_queue_size || max_queue_size == -1) {
1233 m_out_chat_queue.push(message);
1235 infostream << "Could not queue chat message because maximum out chat queue size ("
1236 << max_queue_size << ") is reached." << std::endl;
1240 void Client::clearOutChatQueue()
1242 m_out_chat_queue = std::queue<std::wstring>();
1245 void Client::sendChangePassword(const std::string &oldpassword,
1246 const std::string &newpassword)
1248 LocalPlayer *player = m_env.getLocalPlayer();
1252 // get into sudo mode and then send new password to server
1253 m_password = oldpassword;
1254 m_new_password = newpassword;
1255 startAuth(choseAuthMech(m_sudo_auth_methods));
1259 void Client::sendDamage(u16 damage)
1261 NetworkPacket pkt(TOSERVER_DAMAGE, sizeof(u16));
1266 void Client::sendRespawn()
1268 NetworkPacket pkt(TOSERVER_RESPAWN, 0);
1272 void Client::sendReady()
1274 NetworkPacket pkt(TOSERVER_CLIENT_READY,
1275 1 + 1 + 1 + 1 + 2 + sizeof(char) * strlen(g_version_hash) + 2);
1277 pkt << (u8) VERSION_MAJOR << (u8) VERSION_MINOR << (u8) VERSION_PATCH
1278 << (u8) 0 << (u16) strlen(g_version_hash);
1280 pkt.putRawString(g_version_hash, (u16) strlen(g_version_hash));
1281 pkt << (u16)FORMSPEC_API_VERSION;
1285 void Client::sendPlayerPos()
1287 LocalPlayer *player = m_env.getLocalPlayer();
1291 ClientMap &map = m_env.getClientMap();
1292 u8 camera_fov = map.getCameraFov();
1293 u8 wanted_range = map.getControl().wanted_range;
1295 // Save bandwidth by only updating position when
1296 // player is not dead and something changed
1298 // FIXME: This part causes breakages in mods like 3d_armor, and has been commented for now
1299 // if (m_activeobjects_received && player->isDead())
1303 player->last_position == player->getPosition() &&
1304 player->last_speed == player->getSpeed() &&
1305 player->last_pitch == player->getPitch() &&
1306 player->last_yaw == player->getYaw() &&
1307 player->last_keyPressed == player->keyPressed &&
1308 player->last_camera_fov == camera_fov &&
1309 player->last_wanted_range == wanted_range)
1312 player->last_position = player->getPosition();
1313 player->last_speed = player->getSpeed();
1314 player->last_pitch = player->getPitch();
1315 player->last_yaw = player->getYaw();
1316 player->last_keyPressed = player->keyPressed;
1317 player->last_camera_fov = camera_fov;
1318 player->last_wanted_range = wanted_range;
1320 NetworkPacket pkt(TOSERVER_PLAYERPOS, 12 + 12 + 4 + 4 + 4 + 1 + 1);
1322 writePlayerPos(player, &map, &pkt);
1327 void Client::removeNode(v3s16 p)
1329 std::map<v3s16, MapBlock*> modified_blocks;
1332 m_env.getMap().removeNodeAndUpdate(p, modified_blocks);
1334 catch(InvalidPositionException &e) {
1337 for (const auto &modified_block : modified_blocks) {
1338 addUpdateMeshTaskWithEdge(modified_block.first, false, true);
1343 * Helper function for Client Side Modding
1344 * CSM restrictions are applied there, this should not be used for core engine
1346 * @param is_valid_position
1349 MapNode Client::CSMGetNode(v3s16 p, bool *is_valid_position)
1351 if (checkCSMRestrictionFlag(CSMRestrictionFlags::CSM_RF_LOOKUP_NODES)) {
1352 v3s16 ppos = floatToInt(m_env.getLocalPlayer()->getPosition(), BS);
1353 if ((u32) ppos.getDistanceFrom(p) > m_csm_restriction_noderange) {
1354 *is_valid_position = false;
1358 return m_env.getMap().getNode(p, is_valid_position);
1361 int Client::CSMClampRadius(v3s16 pos, int radius)
1363 if (!checkCSMRestrictionFlag(CSMRestrictionFlags::CSM_RF_LOOKUP_NODES))
1365 // This is approximate and will cause some allowed nodes to be excluded
1366 v3s16 ppos = floatToInt(m_env.getLocalPlayer()->getPosition(), BS);
1367 u32 distance = ppos.getDistanceFrom(pos);
1368 if (distance >= m_csm_restriction_noderange)
1370 return std::min<int>(radius, m_csm_restriction_noderange - distance);
1373 v3s16 Client::CSMClampPos(v3s16 pos)
1375 if (!checkCSMRestrictionFlag(CSMRestrictionFlags::CSM_RF_LOOKUP_NODES))
1377 v3s16 ppos = floatToInt(m_env.getLocalPlayer()->getPosition(), BS);
1378 const int range = m_csm_restriction_noderange;
1380 core::clamp<int>(pos.X, (int)ppos.X - range, (int)ppos.X + range),
1381 core::clamp<int>(pos.Y, (int)ppos.Y - range, (int)ppos.Y + range),
1382 core::clamp<int>(pos.Z, (int)ppos.Z - range, (int)ppos.Z + range)
1386 void Client::addNode(v3s16 p, MapNode n, bool remove_metadata)
1388 //TimeTaker timer1("Client::addNode()");
1390 std::map<v3s16, MapBlock*> modified_blocks;
1393 //TimeTaker timer3("Client::addNode(): addNodeAndUpdate");
1394 m_env.getMap().addNodeAndUpdate(p, n, modified_blocks, remove_metadata);
1396 catch(InvalidPositionException &e) {
1399 for (const auto &modified_block : modified_blocks) {
1400 addUpdateMeshTaskWithEdge(modified_block.first, false, true);
1404 void Client::setPlayerControl(PlayerControl &control)
1406 LocalPlayer *player = m_env.getLocalPlayer();
1408 player->control = control;
1411 void Client::setPlayerItem(u16 item)
1413 m_env.getLocalPlayer()->setWieldIndex(item);
1414 m_update_wielded_item = true;
1416 NetworkPacket pkt(TOSERVER_PLAYERITEM, 2);
1421 // Returns true once after the inventory of the local player
1422 // has been updated from the server.
1423 bool Client::updateWieldedItem()
1425 if (!m_update_wielded_item)
1428 m_update_wielded_item = false;
1430 LocalPlayer *player = m_env.getLocalPlayer();
1432 if (auto *list = player->inventory.getList("main"))
1433 list->setModified(false);
1434 if (auto *list = player->inventory.getList("hand"))
1435 list->setModified(false);
1440 Inventory* Client::getInventory(const InventoryLocation &loc)
1443 case InventoryLocation::UNDEFINED:
1446 case InventoryLocation::CURRENT_PLAYER:
1448 LocalPlayer *player = m_env.getLocalPlayer();
1450 return &player->inventory;
1453 case InventoryLocation::PLAYER:
1455 // Check if we are working with local player inventory
1456 LocalPlayer *player = m_env.getLocalPlayer();
1457 if (!player || strcmp(player->getName(), loc.name.c_str()) != 0)
1459 return &player->inventory;
1462 case InventoryLocation::NODEMETA:
1464 NodeMetadata *meta = m_env.getMap().getNodeMetadata(loc.p);
1467 return meta->getInventory();
1470 case InventoryLocation::DETACHED:
1472 if (m_detached_inventories.count(loc.name) == 0)
1474 return m_detached_inventories[loc.name];
1478 FATAL_ERROR("Invalid inventory location type.");
1484 void Client::inventoryAction(InventoryAction *a)
1487 Send it to the server
1489 sendInventoryAction(a);
1492 Predict some local inventory changes
1494 a->clientApply(this, this);
1500 float Client::getAnimationTime()
1502 return m_animation_time;
1505 int Client::getCrackLevel()
1507 return m_crack_level;
1510 v3s16 Client::getCrackPos()
1515 void Client::setCrack(int level, v3s16 pos)
1517 int old_crack_level = m_crack_level;
1518 v3s16 old_crack_pos = m_crack_pos;
1520 m_crack_level = level;
1523 if(old_crack_level >= 0 && (level < 0 || pos != old_crack_pos))
1526 addUpdateMeshTaskForNode(old_crack_pos, false, true);
1528 if(level >= 0 && (old_crack_level < 0 || pos != old_crack_pos))
1531 addUpdateMeshTaskForNode(pos, false, true);
1537 LocalPlayer *player = m_env.getLocalPlayer();
1542 bool Client::getChatMessage(std::wstring &res)
1544 if (m_chat_queue.empty())
1547 ChatMessage *chatMessage = m_chat_queue.front();
1552 switch (chatMessage->type) {
1553 case CHATMESSAGE_TYPE_RAW:
1554 case CHATMESSAGE_TYPE_ANNOUNCE:
1555 case CHATMESSAGE_TYPE_SYSTEM:
1556 res = chatMessage->message;
1558 case CHATMESSAGE_TYPE_NORMAL: {
1559 if (!chatMessage->sender.empty())
1560 res = L"<" + chatMessage->sender + L"> " + chatMessage->message;
1562 res = chatMessage->message;
1573 void Client::typeChatMessage(const std::wstring &message)
1575 // Discard empty line
1576 if (message.empty())
1579 // If message was consumed by script API, don't send it to server
1580 if (m_mods_loaded && m_script->on_sending_message(wide_to_utf8(message)))
1584 sendChatMessage(message);
1587 void Client::addUpdateMeshTask(v3s16 p, bool ack_to_server, bool urgent)
1589 // Check if the block exists to begin with. In the case when a non-existing
1590 // neighbor is automatically added, it may not. In that case we don't want
1591 // to tell the mesh update thread about it.
1592 MapBlock *b = m_env.getMap().getBlockNoCreateNoEx(p);
1596 m_mesh_update_thread.updateBlock(&m_env.getMap(), p, ack_to_server, urgent);
1599 void Client::addUpdateMeshTaskWithEdge(v3s16 blockpos, bool ack_to_server, bool urgent)
1602 addUpdateMeshTask(blockpos, ack_to_server, urgent);
1604 catch(InvalidPositionException &e){}
1607 for (int i=0;i<6;i++)
1610 v3s16 p = blockpos + g_6dirs[i];
1611 addUpdateMeshTask(p, false, urgent);
1613 catch(InvalidPositionException &e){}
1617 void Client::addUpdateMeshTaskForNode(v3s16 nodepos, bool ack_to_server, bool urgent)
1621 infostream<<"Client::addUpdateMeshTaskForNode(): "
1622 <<"("<<p.X<<","<<p.Y<<","<<p.Z<<")"
1626 v3s16 blockpos = getNodeBlockPos(nodepos);
1627 v3s16 blockpos_relative = blockpos * MAP_BLOCKSIZE;
1630 addUpdateMeshTask(blockpos, ack_to_server, urgent);
1632 catch(InvalidPositionException &e) {}
1635 if(nodepos.X == blockpos_relative.X){
1637 v3s16 p = blockpos + v3s16(-1,0,0);
1638 addUpdateMeshTask(p, false, urgent);
1640 catch(InvalidPositionException &e){}
1643 if(nodepos.Y == blockpos_relative.Y){
1645 v3s16 p = blockpos + v3s16(0,-1,0);
1646 addUpdateMeshTask(p, false, urgent);
1648 catch(InvalidPositionException &e){}
1651 if(nodepos.Z == blockpos_relative.Z){
1653 v3s16 p = blockpos + v3s16(0,0,-1);
1654 addUpdateMeshTask(p, false, urgent);
1656 catch(InvalidPositionException &e){}
1660 ClientEvent *Client::getClientEvent()
1662 FATAL_ERROR_IF(m_client_event_queue.empty(),
1663 "Cannot getClientEvent, queue is empty.");
1665 ClientEvent *event = m_client_event_queue.front();
1666 m_client_event_queue.pop();
1670 const Address Client::getServerAddress()
1672 return m_con->GetPeerAddress(PEER_ID_SERVER);
1675 float Client::mediaReceiveProgress()
1677 if (m_media_downloader)
1678 return m_media_downloader->getProgress();
1680 return 1.0; // downloader only exists when not yet done
1683 typedef struct TextureUpdateArgs {
1684 gui::IGUIEnvironment *guienv;
1687 const wchar_t* text_base;
1688 ITextureSource *tsrc;
1689 } TextureUpdateArgs;
1691 void texture_update_progress(void *args, u32 progress, u32 max_progress)
1693 TextureUpdateArgs* targs = (TextureUpdateArgs*) args;
1694 u16 cur_percent = ceil(progress / (double) max_progress * 100.);
1696 // update the loading menu -- if neccessary
1697 bool do_draw = false;
1698 u64 time_ms = targs->last_time_ms;
1699 if (cur_percent != targs->last_percent) {
1700 targs->last_percent = cur_percent;
1701 time_ms = porting::getTimeMs();
1702 // only draw when the user will notice something:
1703 do_draw = (time_ms - targs->last_time_ms > 100);
1707 targs->last_time_ms = time_ms;
1708 std::basic_stringstream<wchar_t> strm;
1709 strm << targs->text_base << " " << targs->last_percent << "%...";
1710 RenderingEngine::draw_load_screen(strm.str(), targs->guienv, targs->tsrc, 0,
1711 72 + (u16) ((18. / 100.) * (double) targs->last_percent), true);
1715 void Client::afterContentReceived()
1717 infostream<<"Client::afterContentReceived() started"<<std::endl;
1718 assert(m_itemdef_received); // pre-condition
1719 assert(m_nodedef_received); // pre-condition
1720 assert(mediaReceived()); // pre-condition
1722 const wchar_t* text = wgettext("Loading textures...");
1724 // Clear cached pre-scaled 2D GUI images, as this cache
1725 // might have images with the same name but different
1726 // content from previous sessions.
1727 guiScalingCacheClear();
1729 // Rebuild inherited images and recreate textures
1730 infostream<<"- Rebuilding images and textures"<<std::endl;
1731 RenderingEngine::draw_load_screen(text, guienv, m_tsrc, 0, 70);
1732 m_tsrc->rebuildImagesAndTextures();
1736 infostream<<"- Rebuilding shaders"<<std::endl;
1737 text = wgettext("Rebuilding shaders...");
1738 RenderingEngine::draw_load_screen(text, guienv, m_tsrc, 0, 71);
1739 m_shsrc->rebuildShaders();
1742 // Update node aliases
1743 infostream<<"- Updating node aliases"<<std::endl;
1744 text = wgettext("Initializing nodes...");
1745 RenderingEngine::draw_load_screen(text, guienv, m_tsrc, 0, 72);
1746 m_nodedef->updateAliases(m_itemdef);
1747 for (const auto &path : getTextureDirs()) {
1748 TextureOverrideSource override_source(path + DIR_DELIM + "override.txt");
1749 m_nodedef->applyTextureOverrides(override_source.getNodeTileOverrides());
1750 m_itemdef->applyTextureOverrides(override_source.getItemTextureOverrides());
1752 m_nodedef->setNodeRegistrationStatus(true);
1753 m_nodedef->runNodeResolveCallbacks();
1756 // Update node textures and assign shaders to each tile
1757 infostream<<"- Updating node textures"<<std::endl;
1758 TextureUpdateArgs tu_args;
1759 tu_args.guienv = guienv;
1760 tu_args.last_time_ms = porting::getTimeMs();
1761 tu_args.last_percent = 0;
1762 tu_args.text_base = wgettext("Initializing nodes");
1763 tu_args.tsrc = m_tsrc;
1764 m_nodedef->updateTextures(this, texture_update_progress, &tu_args);
1765 delete[] tu_args.text_base;
1767 // Start mesh update thread after setting up content definitions
1768 infostream<<"- Starting mesh update thread"<<std::endl;
1769 m_mesh_update_thread.start();
1775 m_script->on_client_ready(m_env.getLocalPlayer());
1777 text = wgettext("Done!");
1778 RenderingEngine::draw_load_screen(text, guienv, m_tsrc, 0, 100);
1779 infostream<<"Client::afterContentReceived() done"<<std::endl;
1783 float Client::getRTT()
1785 return m_con->getPeerStat(PEER_ID_SERVER,con::AVG_RTT);
1788 float Client::getCurRate()
1790 return (m_con->getLocalStat(con::CUR_INC_RATE) +
1791 m_con->getLocalStat(con::CUR_DL_RATE));
1794 void Client::makeScreenshot()
1796 irr::video::IVideoDriver *driver = RenderingEngine::get_video_driver();
1797 irr::video::IImage* const raw_image = driver->createScreenShot();
1802 time_t t = time(NULL);
1803 struct tm *tm = localtime(&t);
1805 char timetstamp_c[64];
1806 strftime(timetstamp_c, sizeof(timetstamp_c), "%Y%m%d_%H%M%S", tm);
1808 std::string screenshot_dir;
1810 if (fs::IsPathAbsolute(g_settings->get("screenshot_path")))
1811 screenshot_dir = g_settings->get("screenshot_path");
1813 screenshot_dir = porting::path_user + DIR_DELIM + g_settings->get("screenshot_path");
1815 std::string filename_base = screenshot_dir
1817 + std::string("screenshot_")
1818 + std::string(timetstamp_c);
1819 std::string filename_ext = "." + g_settings->get("screenshot_format");
1820 std::string filename;
1822 // Create the directory if it doesn't already exist.
1823 // Otherwise, saving the screenshot would fail.
1824 fs::CreateDir(screenshot_dir);
1826 u32 quality = (u32)g_settings->getS32("screenshot_quality");
1827 quality = MYMIN(MYMAX(quality, 0), 100) / 100.0 * 255;
1829 // Try to find a unique filename
1830 unsigned serial = 0;
1832 while (serial < SCREENSHOT_MAX_SERIAL_TRIES) {
1833 filename = filename_base + (serial > 0 ? ("_" + itos(serial)) : "") + filename_ext;
1834 std::ifstream tmp(filename.c_str());
1836 break; // File did not apparently exist, we'll go with it
1840 if (serial == SCREENSHOT_MAX_SERIAL_TRIES) {
1841 infostream << "Could not find suitable filename for screenshot" << std::endl;
1843 irr::video::IImage* const image =
1844 driver->createImage(video::ECF_R8G8B8, raw_image->getDimension());
1847 raw_image->copyTo(image);
1849 std::ostringstream sstr;
1850 if (driver->writeImageToFile(image, filename.c_str(), quality)) {
1851 sstr << "Saved screenshot to '" << filename << "'";
1853 sstr << "Failed to save screenshot '" << filename << "'";
1855 pushToChatQueue(new ChatMessage(CHATMESSAGE_TYPE_SYSTEM,
1856 narrow_to_wide(sstr.str())));
1857 infostream << sstr.str() << std::endl;
1865 bool Client::shouldShowMinimap() const
1867 return !m_minimap_disabled_by_server;
1870 void Client::pushToEventQueue(ClientEvent *event)
1872 m_client_event_queue.push(event);
1875 void Client::showMinimap(const bool show)
1877 m_game_ui->showMinimap(show);
1880 // IGameDef interface
1882 IItemDefManager* Client::getItemDefManager()
1886 const NodeDefManager* Client::getNodeDefManager()
1890 ICraftDefManager* Client::getCraftDefManager()
1893 //return m_craftdef;
1895 ITextureSource* Client::getTextureSource()
1899 IWritableShaderSource* Client::getShaderSource()
1904 u16 Client::allocateUnknownNodeId(const std::string &name)
1906 errorstream << "Client::allocateUnknownNodeId(): "
1907 << "Client cannot allocate node IDs" << std::endl;
1908 FATAL_ERROR("Client allocated unknown node");
1910 return CONTENT_IGNORE;
1912 ISoundManager* Client::getSoundManager()
1916 MtEventManager* Client::getEventManager()
1921 ParticleManager* Client::getParticleManager()
1923 return &m_particle_manager;
1926 scene::IAnimatedMesh* Client::getMesh(const std::string &filename, bool cache)
1928 StringMap::const_iterator it = m_mesh_data.find(filename);
1929 if (it == m_mesh_data.end()) {
1930 errorstream << "Client::getMesh(): Mesh not found: \"" << filename
1931 << "\"" << std::endl;
1934 const std::string &data = it->second;
1936 // Create the mesh, remove it from cache and return it
1937 // This allows unique vertex colors and other properties for each instance
1938 Buffer<char> data_rw(data.c_str(), data.size()); // Const-incorrect Irrlicht
1939 io::IReadFile *rfile = RenderingEngine::get_filesystem()->createMemoryReadFile(
1940 *data_rw, data_rw.getSize(), filename.c_str());
1941 FATAL_ERROR_IF(!rfile, "Could not create/open RAM file");
1943 scene::IAnimatedMesh *mesh = RenderingEngine::get_scene_manager()->getMesh(rfile);
1947 RenderingEngine::get_mesh_cache()->removeMesh(mesh);
1951 const std::string* Client::getModFile(std::string filename)
1953 // strip dir delimiter from beginning of path
1954 auto pos = filename.find_first_of(':');
1955 if (pos == std::string::npos)
1958 auto pos2 = filename.find_first_not_of('/', pos);
1960 filename.erase(pos, pos2 - pos);
1962 StringMap::const_iterator it = m_mod_vfs.find(filename);
1963 if (it == m_mod_vfs.end())
1968 bool Client::registerModStorage(ModMetadata *storage)
1970 if (m_mod_storages.find(storage->getModName()) != m_mod_storages.end()) {
1971 errorstream << "Unable to register same mod storage twice. Storage name: "
1972 << storage->getModName() << std::endl;
1976 m_mod_storages[storage->getModName()] = storage;
1980 void Client::unregisterModStorage(const std::string &name)
1982 std::unordered_map<std::string, ModMetadata *>::const_iterator it =
1983 m_mod_storages.find(name);
1984 if (it != m_mod_storages.end()) {
1985 // Save unconditionaly on unregistration
1986 it->second->save(getModStoragePath());
1987 m_mod_storages.erase(name);
1991 std::string Client::getModStoragePath() const
1993 return porting::path_user + DIR_DELIM + "client" + DIR_DELIM + "mod_storage";
2000 bool Client::joinModChannel(const std::string &channel)
2002 if (m_modchannel_mgr->channelRegistered(channel))
2005 NetworkPacket pkt(TOSERVER_MODCHANNEL_JOIN, 2 + channel.size());
2009 m_modchannel_mgr->joinChannel(channel, 0);
2013 bool Client::leaveModChannel(const std::string &channel)
2015 if (!m_modchannel_mgr->channelRegistered(channel))
2018 NetworkPacket pkt(TOSERVER_MODCHANNEL_LEAVE, 2 + channel.size());
2022 m_modchannel_mgr->leaveChannel(channel, 0);
2026 bool Client::sendModChannelMessage(const std::string &channel, const std::string &message)
2028 if (!m_modchannel_mgr->canWriteOnChannel(channel))
2031 if (message.size() > STRING_MAX_LEN) {
2032 warningstream << "ModChannel message too long, dropping before sending "
2033 << " (" << message.size() << " > " << STRING_MAX_LEN << ", channel: "
2034 << channel << ")" << std::endl;
2038 // @TODO: do some client rate limiting
2039 NetworkPacket pkt(TOSERVER_MODCHANNEL_MSG, 2 + channel.size() + 2 + message.size());
2040 pkt << channel << message;
2045 ModChannel* Client::getModChannel(const std::string &channel)
2047 return m_modchannel_mgr->getModChannel(channel);