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 "client/renderingengine.h"
27 #include "util/auth.h"
28 #include "util/directiontables.h"
29 #include "util/pointedthing.h"
30 #include "util/serialize.h"
31 #include "util/string.h"
34 #include "network/clientopcodes.h"
36 #include "mapblock_mesh.h"
42 #include "clientmap.h"
43 #include "clientmedia.h"
45 #include "database-sqlite3.h"
46 #include "serialization.h"
47 #include "guiscalingfilter.h"
48 #include "script/scripting_client.h"
51 extern gui::IGUIEnvironment* guienv;
58 const char *playername,
59 const std::string &password,
60 const std::string &address_name,
61 MapDrawControl &control,
62 IWritableTextureSource *tsrc,
63 IWritableShaderSource *shsrc,
64 IWritableItemDefManager *itemdef,
65 IWritableNodeDefManager *nodedef,
67 MtEventManager *event,
69 GameUIFlags *game_ui_flags
77 m_mesh_update_thread(this),
79 new ClientMap(this, control, 666),
82 m_particle_manager(&m_env),
83 m_con(PROTOCOL_ID, 512, CONNECTION_TIMEOUT, ipv6, this),
84 m_address_name(address_name),
85 m_server_ser_ver(SER_FMT_VER_INVALID),
87 m_chosen_auth_mech(AUTH_MECHANISM_NONE),
88 m_media_downloader(new ClientMediaDownloader()),
90 m_game_ui_flags(game_ui_flags)
93 m_env.setLocalPlayer(new LocalPlayer(this, playername));
95 if (g_settings->getBool("enable_minimap")) {
96 m_minimap = new Minimap(this);
98 m_cache_save_interval = g_settings->getU16("server_map_save_interval");
100 m_modding_enabled = g_settings->getBool("enable_client_modding");
101 m_script = new ClientScripting(this);
102 m_env.setScript(m_script);
103 m_script->setEnv(&m_env);
106 void Client::loadMods()
109 scanModIntoMemory(BUILTIN_MOD_NAME, getBuiltinLuaPath());
111 // If modding is not enabled, don't load mods, just builtin
112 if (!m_modding_enabled) {
115 ClientModConfiguration modconf(getClientModsLuaPath());
116 m_mods = modconf.getMods();
117 std::vector<ModSpec> unsatisfied_mods = modconf.getUnsatisfiedMods();
118 // complain about mods with unsatisfied dependencies
119 if (!modconf.isConsistent()) {
120 modconf.printUnsatisfiedModsError();
124 infostream << "Client Loading mods: ";
125 for (const ModSpec &mod : m_mods)
126 infostream << mod.name << " ";
127 infostream << std::endl;
129 // Load and run "mod" scripts
130 for (const ModSpec &mod : m_mods) {
131 if (!string_allowed(mod.name, MODNAME_ALLOWED_CHARS)) {
132 throw ModError("Error loading mod \"" + mod.name +
133 "\": Mod name does not follow naming conventions: "
134 "Only characters [a-z0-9_] are allowed.");
136 scanModIntoMemory(mod.name, mod.path);
140 void Client::scanModSubfolder(const std::string &mod_name, const std::string &mod_path,
141 std::string mod_subpath)
143 std::string full_path = mod_path + DIR_DELIM + mod_subpath;
144 std::vector<fs::DirListNode> mod = fs::GetDirListing(full_path);
145 for (unsigned int j=0; j < mod.size(); j++){
146 std::string filename = mod[j].name;
148 scanModSubfolder(mod_name, mod_path, mod_subpath
149 + filename + DIR_DELIM);
152 std::replace( mod_subpath.begin(), mod_subpath.end(), DIR_DELIM_CHAR, '/');
153 m_mod_files[mod_name + ":" + mod_subpath + filename] = full_path + filename;
157 void Client::initMods()
159 m_script->loadModFromMemory(BUILTIN_MOD_NAME);
161 // If modding is not enabled, don't load mods, just builtin
162 if (!m_modding_enabled) {
166 // Load and run "mod" scripts
167 for (const ModSpec &mod : m_mods)
168 m_script->loadModFromMemory(mod.name);
171 const std::string &Client::getBuiltinLuaPath()
173 static const std::string builtin_dir = porting::path_share + DIR_DELIM + "builtin";
177 const std::string &Client::getClientModsLuaPath()
179 static const std::string clientmods_dir = porting::path_share + DIR_DELIM + "clientmods";
180 return clientmods_dir;
183 const std::vector<ModSpec>& Client::getMods() const
185 static std::vector<ModSpec> client_modspec_temp;
186 return client_modspec_temp;
189 const ModSpec* Client::getModSpec(const std::string &modname) const
197 // Don't disable this part when modding is disabled, it's used in builtin
198 m_script->on_shutdown();
199 //request all client managed threads to stop
200 m_mesh_update_thread.stop();
201 // Save local server map
203 infostream << "Local map saving ended." << std::endl;
204 m_localdb->endSave();
210 bool Client::isShutdown()
212 return m_shutdown || !m_mesh_update_thread.isRunning();
220 m_mesh_update_thread.stop();
221 m_mesh_update_thread.wait();
222 while (!m_mesh_update_thread.m_queue_out.empty()) {
223 MeshUpdateResult r = m_mesh_update_thread.m_queue_out.pop_frontNoEx();
228 delete m_inventory_from_server;
230 // Delete detached inventories
231 for (std::unordered_map<std::string, Inventory*>::iterator
232 i = m_detached_inventories.begin();
233 i != m_detached_inventories.end(); ++i) {
237 // cleanup 3d model meshes on client shutdown
238 while (RenderingEngine::get_mesh_cache()->getMeshCount() != 0) {
239 scene::IAnimatedMesh *mesh = RenderingEngine::get_mesh_cache()->getMeshByIndex(0);
242 RenderingEngine::get_mesh_cache()->removeMesh(mesh);
248 void Client::connect(Address address, bool is_local_server)
250 DSTACK(FUNCTION_NAME);
252 initLocalMapSaving(address, m_address_name, is_local_server);
254 m_con.SetTimeoutMs(0);
255 m_con.Connect(address);
258 void Client::step(float dtime)
260 DSTACK(FUNCTION_NAME);
266 if(m_ignore_damage_timer > dtime)
267 m_ignore_damage_timer -= dtime;
269 m_ignore_damage_timer = 0.0;
271 m_animation_time += dtime;
272 if(m_animation_time > 60.0)
273 m_animation_time -= 60.0;
275 m_time_of_day_update_timer += dtime;
283 float &counter = m_packetcounter_timer;
289 infostream << "Client packetcounter (" << m_packetcounter_timer
291 m_packetcounter.print(infostream);
292 m_packetcounter.clear();
296 // UGLY hack to fix 2 second startup delay caused by non existent
297 // server client startup synchronization in local server or singleplayer mode
298 static bool initial_step = true;
300 initial_step = false;
302 else if(m_state == LC_Created) {
303 float &counter = m_connection_reinit_timer;
308 LocalPlayer *myplayer = m_env.getLocalPlayer();
309 FATAL_ERROR_IF(myplayer == NULL, "Local player not found in environment.");
311 u16 proto_version_min = g_settings->getFlag("send_pre_v25_init") ?
312 CLIENT_PROTOCOL_VERSION_MIN_LEGACY : CLIENT_PROTOCOL_VERSION_MIN;
314 if (proto_version_min < 25) {
315 // Send TOSERVER_INIT_LEGACY
316 // [0] u16 TOSERVER_INIT_LEGACY
317 // [2] u8 SER_FMT_VER_HIGHEST_READ
318 // [3] u8[20] player_name
319 // [23] u8[28] password (new in some version)
320 // [51] u16 minimum supported network protocol version (added sometime)
321 // [53] u16 maximum supported network protocol version (added later than the previous one)
323 char pName[PLAYERNAME_SIZE];
324 char pPassword[PASSWORD_SIZE];
325 memset(pName, 0, PLAYERNAME_SIZE * sizeof(char));
326 memset(pPassword, 0, PASSWORD_SIZE * sizeof(char));
328 std::string hashed_password = translate_password(myplayer->getName(), m_password);
329 snprintf(pName, PLAYERNAME_SIZE, "%s", myplayer->getName());
330 snprintf(pPassword, PASSWORD_SIZE, "%s", hashed_password.c_str());
332 sendLegacyInit(pName, pPassword);
334 if (CLIENT_PROTOCOL_VERSION_MAX >= 25)
335 sendInit(myplayer->getName());
338 // Not connected, return
343 Do stuff if connected
347 Run Map's timers and unload unused data
349 const float map_timer_and_unload_dtime = 5.25;
350 if(m_map_timer_and_unload_interval.step(dtime, map_timer_and_unload_dtime)) {
351 ScopeProfiler sp(g_profiler, "Client: map timer and unload");
352 std::vector<v3s16> deleted_blocks;
353 m_env.getMap().timerUpdate(map_timer_and_unload_dtime,
354 g_settings->getFloat("client_unload_unused_data_timeout"),
355 g_settings->getS32("client_mapblock_limit"),
360 NOTE: This loop is intentionally iterated the way it is.
363 std::vector<v3s16>::iterator i = deleted_blocks.begin();
364 std::vector<v3s16> sendlist;
366 if(sendlist.size() == 255 || i == deleted_blocks.end()) {
377 sendDeletedBlocks(sendlist);
379 if(i == deleted_blocks.end())
385 sendlist.push_back(*i);
393 // Control local player (0ms)
394 LocalPlayer *player = m_env.getLocalPlayer();
396 player->applyControl(dtime);
400 m_sound->step(dtime);
405 while (m_env.hasClientEnvEvents()) {
406 ClientEnvEvent envEvent = m_env.getClientEnvEvent();
408 if (envEvent.type == CEE_PLAYER_DAMAGE) {
409 if (m_ignore_damage_timer <= 0) {
410 u8 damage = envEvent.player_damage.amount;
412 if (envEvent.player_damage.send_to_server)
415 // Add to ClientEvent queue
417 event.type = CE_PLAYER_DAMAGE;
418 event.player_damage.amount = damage;
419 m_client_event_queue.push(event);
422 // Protocol v29 or greater obsoleted this event
423 else if (envEvent.type == CEE_PLAYER_BREATH && m_proto_ver < 29) {
424 u16 breath = envEvent.player_breath.amount;
432 float &counter = m_avg_rtt_timer;
436 // connectedAndInitialized() is true, peer exists.
437 float avg_rtt = getRTT();
438 infostream << "Client: avg_rtt=" << avg_rtt << std::endl;
442 Send player position to server
445 float &counter = m_playerpos_send_timer;
447 if((m_state == LC_Ready) && (counter >= m_recommended_send_interval))
455 Replace updated meshes
458 int num_processed_meshes = 0;
459 while (!m_mesh_update_thread.m_queue_out.empty())
461 num_processed_meshes++;
463 MinimapMapblock *minimap_mapblock = NULL;
464 bool do_mapper_update = true;
466 MeshUpdateResult r = m_mesh_update_thread.m_queue_out.pop_frontNoEx();
467 MapBlock *block = m_env.getMap().getBlockNoCreateNoEx(r.p);
469 // Delete the old mesh
471 block->mesh = nullptr;
474 minimap_mapblock = r.mesh->moveMinimapMapblock();
475 if (minimap_mapblock == NULL)
476 do_mapper_update = false;
478 bool is_empty = true;
479 for (int l = 0; l < MAX_TILE_LAYERS; l++)
480 if (r.mesh->getMesh(l)->getMeshBufferCount() != 0)
486 // Replace with the new mesh
487 block->mesh = r.mesh;
493 if (m_minimap && do_mapper_update)
494 m_minimap->addBlock(r.p, minimap_mapblock);
496 if (r.ack_block_to_server) {
506 if (num_processed_meshes > 0)
507 g_profiler->graphAdd("num_processed_meshes", num_processed_meshes);
513 if (m_media_downloader && m_media_downloader->isStarted()) {
514 m_media_downloader->step(this);
515 if (m_media_downloader->isDone()) {
516 delete m_media_downloader;
517 m_media_downloader = NULL;
522 If the server didn't update the inventory in a while, revert
523 the local inventory (so the player notices the lag problem
524 and knows something is wrong).
526 if(m_inventory_from_server)
528 float interval = 10.0;
529 float count_before = floor(m_inventory_from_server_age / interval);
531 m_inventory_from_server_age += dtime;
533 float count_after = floor(m_inventory_from_server_age / interval);
535 if(count_after != count_before)
537 // Do this every <interval> seconds after TOCLIENT_INVENTORY
538 // Reset the locally changed inventory to the authoritative inventory
539 LocalPlayer *player = m_env.getLocalPlayer();
540 player->inventory = *m_inventory_from_server;
541 m_inventory_updated = true;
546 Update positions of sounds attached to objects
549 for(std::unordered_map<int, u16>::iterator i = m_sounds_to_objects.begin();
550 i != m_sounds_to_objects.end(); ++i) {
551 int client_id = i->first;
552 u16 object_id = i->second;
553 ClientActiveObject *cao = m_env.getActiveObject(object_id);
556 v3f pos = cao->getPosition();
557 m_sound->updateSoundPosition(client_id, pos);
562 Handle removed remotely initiated sounds
564 m_removed_sounds_check_timer += dtime;
565 if(m_removed_sounds_check_timer >= 2.32) {
566 m_removed_sounds_check_timer = 0;
567 // Find removed sounds and clear references to them
568 std::vector<s32> removed_server_ids;
569 for (std::unordered_map<s32, int>::iterator i = m_sounds_server_to_client.begin();
570 i != m_sounds_server_to_client.end();) {
571 s32 server_id = i->first;
572 int client_id = i->second;
574 if(!m_sound->soundExists(client_id)) {
575 m_sounds_server_to_client.erase(server_id);
576 m_sounds_client_to_server.erase(client_id);
577 m_sounds_to_objects.erase(client_id);
578 removed_server_ids.push_back(server_id);
583 if(!removed_server_ids.empty()) {
584 sendRemovedSounds(removed_server_ids);
588 m_mod_storage_save_timer -= dtime;
589 if (m_mod_storage_save_timer <= 0.0f) {
590 verbosestream << "Saving registered mod storages." << std::endl;
591 m_mod_storage_save_timer = g_settings->getFloat("server_map_save_interval");
592 for (std::unordered_map<std::string, ModMetadata *>::const_iterator
593 it = m_mod_storages.begin(); it != m_mod_storages.end(); ++it) {
594 if (it->second->isModified()) {
595 it->second->save(getModStoragePath());
601 if (m_localdb && m_localdb_save_interval.step(dtime,
602 m_cache_save_interval)) {
603 m_localdb->endSave();
604 m_localdb->beginSave();
608 bool Client::loadMedia(const std::string &data, const std::string &filename)
610 // Silly irrlicht's const-incorrectness
611 Buffer<char> data_rw(data.c_str(), data.size());
615 const char *image_ext[] = {
616 ".png", ".jpg", ".bmp", ".tga",
617 ".pcx", ".ppm", ".psd", ".wal", ".rgb",
620 name = removeStringEnd(filename, image_ext);
623 verbosestream<<"Client: Attempting to load image "
624 <<"file \""<<filename<<"\""<<std::endl;
626 io::IFileSystem *irrfs = RenderingEngine::get_filesystem();
627 video::IVideoDriver *vdrv = RenderingEngine::get_video_driver();
629 // Create an irrlicht memory file
630 io::IReadFile *rfile = irrfs->createMemoryReadFile(
631 *data_rw, data_rw.getSize(), "_tempreadfile");
633 FATAL_ERROR_IF(!rfile, "Could not create irrlicht memory file.");
636 video::IImage *img = vdrv->createImageFromFile(rfile);
638 errorstream<<"Client: Cannot create image from data of "
639 <<"file \""<<filename<<"\""<<std::endl;
644 m_tsrc->insertSourceImage(filename, img);
651 const char *sound_ext[] = {
652 ".0.ogg", ".1.ogg", ".2.ogg", ".3.ogg", ".4.ogg",
653 ".5.ogg", ".6.ogg", ".7.ogg", ".8.ogg", ".9.ogg",
656 name = removeStringEnd(filename, sound_ext);
659 verbosestream<<"Client: Attempting to load sound "
660 <<"file \""<<filename<<"\""<<std::endl;
661 m_sound->loadSoundData(name, data);
665 const char *model_ext[] = {
666 ".x", ".b3d", ".md2", ".obj",
669 name = removeStringEnd(filename, model_ext);
672 verbosestream<<"Client: Storing model into memory: "
673 <<"\""<<filename<<"\""<<std::endl;
674 if(m_mesh_data.count(filename))
675 errorstream<<"Multiple models with name \""<<filename.c_str()
676 <<"\" found; replacing previous model"<<std::endl;
677 m_mesh_data[filename] = data;
681 errorstream<<"Client: Don't know how to load file \""
682 <<filename<<"\""<<std::endl;
686 // Virtual methods from con::PeerHandler
687 void Client::peerAdded(con::Peer *peer)
689 infostream << "Client::peerAdded(): peer->id="
690 << peer->id << std::endl;
692 void Client::deletingPeer(con::Peer *peer, bool timeout)
694 infostream << "Client::deletingPeer(): "
695 "Server Peer is getting deleted "
696 << "(timeout=" << timeout << ")" << std::endl;
699 m_access_denied = true;
700 m_access_denied_reason = gettext("Connection timed out.");
706 u16 number of files requested
712 void Client::request_media(const std::vector<std::string> &file_requests)
714 std::ostringstream os(std::ios_base::binary);
715 writeU16(os, TOSERVER_REQUEST_MEDIA);
716 size_t file_requests_size = file_requests.size();
718 FATAL_ERROR_IF(file_requests_size > 0xFFFF, "Unsupported number of file requests");
720 // Packet dynamicly resized
721 NetworkPacket pkt(TOSERVER_REQUEST_MEDIA, 2 + 0);
723 pkt << (u16) (file_requests_size & 0xFFFF);
725 for(std::vector<std::string>::const_iterator i = file_requests.begin();
726 i != file_requests.end(); ++i) {
732 infostream << "Client: Sending media request list to server ("
733 << file_requests.size() << " files. packet size)" << std::endl;
736 void Client::initLocalMapSaving(const Address &address,
737 const std::string &hostname,
738 bool is_local_server)
740 if (!g_settings->getBool("enable_local_map_saving") || is_local_server) {
744 const std::string world_path = porting::path_user
745 + DIR_DELIM + "worlds"
746 + DIR_DELIM + "server_"
747 + hostname + "_" + std::to_string(address.getPort());
749 fs::CreateAllDirs(world_path);
751 m_localdb = new MapDatabaseSQLite3(world_path);
752 m_localdb->beginSave();
753 actionstream << "Local map saving started, map will be saved at '" << world_path << "'" << std::endl;
756 void Client::ReceiveAll()
758 DSTACK(FUNCTION_NAME);
759 u64 start_ms = porting::getTimeMs();
762 // Limit time even if there would be huge amounts of data to
764 if(porting::getTimeMs() > start_ms + 100)
769 g_profiler->graphAdd("client_received_packets", 1);
771 catch(con::NoIncomingDataException &e) {
774 catch(con::InvalidIncomingDataException &e) {
775 infostream<<"Client::ReceiveAll(): "
776 "InvalidIncomingDataException: what()="
777 <<e.what()<<std::endl;
782 void Client::Receive()
784 DSTACK(FUNCTION_NAME);
790 inline void Client::handleCommand(NetworkPacket* pkt)
792 const ToClientCommandHandler& opHandle = toClientCommandTable[pkt->getCommand()];
793 (this->*opHandle.handler)(pkt);
797 sender_peer_id given to this shall be quaranteed to be a valid peer
799 void Client::ProcessData(NetworkPacket *pkt)
801 DSTACK(FUNCTION_NAME);
803 ToClientCommand command = (ToClientCommand) pkt->getCommand();
804 u32 sender_peer_id = pkt->getPeerId();
806 //infostream<<"Client: received command="<<command<<std::endl;
807 m_packetcounter.add((u16)command);
810 If this check is removed, be sure to change the queue
811 system to know the ids
813 if(sender_peer_id != PEER_ID_SERVER) {
814 infostream << "Client::ProcessData(): Discarding data not "
815 "coming from server: peer_id=" << sender_peer_id
820 // Command must be handled into ToClientCommandHandler
821 if (command >= TOCLIENT_NUM_MSG_TYPES) {
822 infostream << "Client: Ignoring unknown command "
823 << command << std::endl;
828 * Those packets are handled before m_server_ser_ver is set, it's normal
829 * But we must use the new ToClientConnectionState in the future,
832 if(toClientCommandTable[command].state == TOCLIENT_STATE_NOT_CONNECTED) {
837 if(m_server_ser_ver == SER_FMT_VER_INVALID) {
838 infostream << "Client: Server serialization"
839 " format invalid or not initialized."
840 " Skipping incoming command=" << command << std::endl;
845 Handle runtime commands
851 void Client::Send(NetworkPacket* pkt)
853 m_con.Send(PEER_ID_SERVER,
854 serverCommandFactoryTable[pkt->getCommand()].channel,
856 serverCommandFactoryTable[pkt->getCommand()].reliable);
859 // Will fill up 12 + 12 + 4 + 4 + 4 bytes
860 void writePlayerPos(LocalPlayer *myplayer, ClientMap *clientMap, NetworkPacket *pkt)
862 v3f pf = myplayer->getPosition() * 100;
863 v3f sf = myplayer->getSpeed() * 100;
864 s32 pitch = myplayer->getPitch() * 100;
865 s32 yaw = myplayer->getYaw() * 100;
866 u32 keyPressed = myplayer->keyPressed;
867 // scaled by 80, so that pi can fit into a u8
868 u8 fov = clientMap->getCameraFov() * 80;
869 u8 wanted_range = MYMIN(255,
870 std::ceil(clientMap->getControl().wanted_range / MAP_BLOCKSIZE));
872 v3s32 position(pf.X, pf.Y, pf.Z);
873 v3s32 speed(sf.X, sf.Y, sf.Z);
877 [0] v3s32 position*100
879 [12+12] s32 pitch*100
880 [12+12+4] s32 yaw*100
881 [12+12+4+4] u32 keyPressed
882 [12+12+4+4+4] u8 fov*80
883 [12+12+4+4+4+1] u8 ceil(wanted_range / MAP_BLOCKSIZE)
885 *pkt << position << speed << pitch << yaw << keyPressed;
886 *pkt << fov << wanted_range;
889 void Client::interact(u8 action, const PointedThing& pointed)
891 if(m_state != LC_Ready) {
892 errorstream << "Client::interact() "
893 "Canceled (not connected)"
898 LocalPlayer *myplayer = m_env.getLocalPlayer();
899 if (myplayer == NULL)
906 [5] u32 length of the next item (plen)
907 [9] serialized PointedThing
908 [9 + plen] player position information
910 0: start digging (from undersurface) or use
911 1: stop digging (all parameters ignored)
913 3: place block or item (to abovesurface)
915 5: perform secondary action of item
918 NetworkPacket pkt(TOSERVER_INTERACT, 1 + 2 + 0);
921 pkt << (u16)getPlayerItem();
923 std::ostringstream tmp_os(std::ios::binary);
924 pointed.serialize(tmp_os);
926 pkt.putLongString(tmp_os.str());
928 writePlayerPos(myplayer, &m_env.getClientMap(), &pkt);
933 void Client::deleteAuthData()
938 switch (m_chosen_auth_mech) {
939 case AUTH_MECHANISM_FIRST_SRP:
941 case AUTH_MECHANISM_SRP:
942 case AUTH_MECHANISM_LEGACY_PASSWORD:
943 srp_user_delete((SRPUser *) m_auth_data);
946 case AUTH_MECHANISM_NONE:
949 m_chosen_auth_mech = AUTH_MECHANISM_NONE;
953 AuthMechanism Client::choseAuthMech(const u32 mechs)
955 if (mechs & AUTH_MECHANISM_SRP)
956 return AUTH_MECHANISM_SRP;
958 if (mechs & AUTH_MECHANISM_FIRST_SRP)
959 return AUTH_MECHANISM_FIRST_SRP;
961 if (mechs & AUTH_MECHANISM_LEGACY_PASSWORD)
962 return AUTH_MECHANISM_LEGACY_PASSWORD;
964 return AUTH_MECHANISM_NONE;
967 void Client::sendLegacyInit(const char* playerName, const char* playerPassword)
969 NetworkPacket pkt(TOSERVER_INIT_LEGACY,
970 1 + PLAYERNAME_SIZE + PASSWORD_SIZE + 2 + 2);
972 u16 proto_version_min = g_settings->getFlag("send_pre_v25_init") ?
973 CLIENT_PROTOCOL_VERSION_MIN_LEGACY : CLIENT_PROTOCOL_VERSION_MIN;
975 pkt << (u8) SER_FMT_VER_HIGHEST_READ;
976 pkt.putRawString(playerName,PLAYERNAME_SIZE);
977 pkt.putRawString(playerPassword, PASSWORD_SIZE);
978 pkt << (u16) proto_version_min << (u16) CLIENT_PROTOCOL_VERSION_MAX;
983 void Client::sendInit(const std::string &playerName)
985 NetworkPacket pkt(TOSERVER_INIT, 1 + 2 + 2 + (1 + playerName.size()));
987 // we don't support network compression yet
988 u16 supp_comp_modes = NETPROTO_COMPRESSION_NONE;
990 u16 proto_version_min = g_settings->getFlag("send_pre_v25_init") ?
991 CLIENT_PROTOCOL_VERSION_MIN_LEGACY : CLIENT_PROTOCOL_VERSION_MIN;
993 pkt << (u8) SER_FMT_VER_HIGHEST_READ << (u16) supp_comp_modes;
994 pkt << (u16) proto_version_min << (u16) CLIENT_PROTOCOL_VERSION_MAX;
1000 void Client::startAuth(AuthMechanism chosen_auth_mechanism)
1002 m_chosen_auth_mech = chosen_auth_mechanism;
1004 switch (chosen_auth_mechanism) {
1005 case AUTH_MECHANISM_FIRST_SRP: {
1006 // send srp verifier to server
1007 std::string verifier;
1009 generate_srp_verifier_and_salt(getPlayerName(), m_password,
1012 NetworkPacket resp_pkt(TOSERVER_FIRST_SRP, 0);
1013 resp_pkt << salt << verifier << (u8)((m_password == "") ? 1 : 0);
1018 case AUTH_MECHANISM_SRP:
1019 case AUTH_MECHANISM_LEGACY_PASSWORD: {
1022 if (chosen_auth_mechanism == AUTH_MECHANISM_LEGACY_PASSWORD) {
1023 m_password = translate_password(getPlayerName(), m_password);
1027 std::string playername_u = lowercase(getPlayerName());
1028 m_auth_data = srp_user_new(SRP_SHA256, SRP_NG_2048,
1029 getPlayerName().c_str(), playername_u.c_str(),
1030 (const unsigned char *) m_password.c_str(),
1031 m_password.length(), NULL, NULL);
1034 SRP_Result res = srp_user_start_authentication(
1035 (struct SRPUser *) m_auth_data, NULL, NULL, 0,
1036 (unsigned char **) &bytes_A, &len_A);
1037 FATAL_ERROR_IF(res != SRP_OK, "Creating local SRP user failed.");
1039 NetworkPacket resp_pkt(TOSERVER_SRP_BYTES_A, 0);
1040 resp_pkt << std::string(bytes_A, len_A) << based_on;
1044 case AUTH_MECHANISM_NONE:
1045 break; // not handled in this method
1049 void Client::sendDeletedBlocks(std::vector<v3s16> &blocks)
1051 NetworkPacket pkt(TOSERVER_DELETEDBLOCKS, 1 + sizeof(v3s16) * blocks.size());
1053 pkt << (u8) blocks.size();
1056 for(std::vector<v3s16>::iterator
1058 j != blocks.end(); ++j) {
1066 void Client::sendGotBlocks(v3s16 block)
1068 NetworkPacket pkt(TOSERVER_GOTBLOCKS, 1 + 6);
1069 pkt << (u8) 1 << block;
1073 void Client::sendRemovedSounds(std::vector<s32> &soundList)
1075 size_t server_ids = soundList.size();
1076 assert(server_ids <= 0xFFFF);
1078 NetworkPacket pkt(TOSERVER_REMOVED_SOUNDS, 2 + server_ids * 4);
1080 pkt << (u16) (server_ids & 0xFFFF);
1082 for(std::vector<s32>::iterator i = soundList.begin();
1083 i != soundList.end(); ++i)
1089 void Client::sendNodemetaFields(v3s16 p, const std::string &formname,
1090 const StringMap &fields)
1092 size_t fields_size = fields.size();
1094 FATAL_ERROR_IF(fields_size > 0xFFFF, "Unsupported number of nodemeta fields");
1096 NetworkPacket pkt(TOSERVER_NODEMETA_FIELDS, 0);
1098 pkt << p << formname << (u16) (fields_size & 0xFFFF);
1100 StringMap::const_iterator it;
1101 for (it = fields.begin(); it != fields.end(); ++it) {
1102 const std::string &name = it->first;
1103 const std::string &value = it->second;
1105 pkt.putLongString(value);
1111 void Client::sendInventoryFields(const std::string &formname,
1112 const StringMap &fields)
1114 size_t fields_size = fields.size();
1115 FATAL_ERROR_IF(fields_size > 0xFFFF, "Unsupported number of inventory fields");
1117 NetworkPacket pkt(TOSERVER_INVENTORY_FIELDS, 0);
1118 pkt << formname << (u16) (fields_size & 0xFFFF);
1120 StringMap::const_iterator it;
1121 for (it = fields.begin(); it != fields.end(); ++it) {
1122 const std::string &name = it->first;
1123 const std::string &value = it->second;
1125 pkt.putLongString(value);
1131 void Client::sendInventoryAction(InventoryAction *a)
1133 std::ostringstream os(std::ios_base::binary);
1138 std::string s = os.str();
1140 NetworkPacket pkt(TOSERVER_INVENTORY_ACTION, s.size());
1141 pkt.putRawString(s.c_str(),s.size());
1146 void Client::sendChatMessage(const std::wstring &message)
1148 NetworkPacket pkt(TOSERVER_CHAT_MESSAGE, 2 + message.size() * sizeof(u16));
1155 void Client::sendChangePassword(const std::string &oldpassword,
1156 const std::string &newpassword)
1158 LocalPlayer *player = m_env.getLocalPlayer();
1162 std::string playername = player->getName();
1163 if (m_proto_ver >= 25) {
1164 // get into sudo mode and then send new password to server
1165 m_password = oldpassword;
1166 m_new_password = newpassword;
1167 startAuth(choseAuthMech(m_sudo_auth_methods));
1169 std::string oldpwd = translate_password(playername, oldpassword);
1170 std::string newpwd = translate_password(playername, newpassword);
1172 NetworkPacket pkt(TOSERVER_PASSWORD_LEGACY, 2 * PASSWORD_SIZE);
1174 for (u8 i = 0; i < PASSWORD_SIZE; i++) {
1175 pkt << (u8) (i < oldpwd.length() ? oldpwd[i] : 0);
1178 for (u8 i = 0; i < PASSWORD_SIZE; i++) {
1179 pkt << (u8) (i < newpwd.length() ? newpwd[i] : 0);
1186 void Client::sendDamage(u8 damage)
1188 DSTACK(FUNCTION_NAME);
1190 NetworkPacket pkt(TOSERVER_DAMAGE, sizeof(u8));
1195 void Client::sendBreath(u16 breath)
1197 DSTACK(FUNCTION_NAME);
1199 // Protocol v29 make this obsolete
1200 if (m_proto_ver >= 29)
1203 NetworkPacket pkt(TOSERVER_BREATH, sizeof(u16));
1208 void Client::sendRespawn()
1210 DSTACK(FUNCTION_NAME);
1212 NetworkPacket pkt(TOSERVER_RESPAWN, 0);
1216 void Client::sendReady()
1218 DSTACK(FUNCTION_NAME);
1220 NetworkPacket pkt(TOSERVER_CLIENT_READY,
1221 1 + 1 + 1 + 1 + 2 + sizeof(char) * strlen(g_version_hash));
1223 pkt << (u8) VERSION_MAJOR << (u8) VERSION_MINOR << (u8) VERSION_PATCH
1224 << (u8) 0 << (u16) strlen(g_version_hash);
1226 pkt.putRawString(g_version_hash, (u16) strlen(g_version_hash));
1230 void Client::sendPlayerPos()
1232 LocalPlayer *myplayer = m_env.getLocalPlayer();
1233 if(myplayer == NULL)
1236 ClientMap &map = m_env.getClientMap();
1238 u8 camera_fov = map.getCameraFov();
1239 u8 wanted_range = map.getControl().wanted_range;
1241 // Save bandwidth by only updating position when something changed
1242 if(myplayer->last_position == myplayer->getPosition() &&
1243 myplayer->last_speed == myplayer->getSpeed() &&
1244 myplayer->last_pitch == myplayer->getPitch() &&
1245 myplayer->last_yaw == myplayer->getYaw() &&
1246 myplayer->last_keyPressed == myplayer->keyPressed &&
1247 myplayer->last_camera_fov == camera_fov &&
1248 myplayer->last_wanted_range == wanted_range)
1251 myplayer->last_position = myplayer->getPosition();
1252 myplayer->last_speed = myplayer->getSpeed();
1253 myplayer->last_pitch = myplayer->getPitch();
1254 myplayer->last_yaw = myplayer->getYaw();
1255 myplayer->last_keyPressed = myplayer->keyPressed;
1256 myplayer->last_camera_fov = camera_fov;
1257 myplayer->last_wanted_range = wanted_range;
1259 //infostream << "Sending Player Position information" << std::endl;
1263 //MutexAutoLock lock(m_con_mutex); //bulk comment-out
1264 our_peer_id = m_con.GetPeerID();
1267 // Set peer id if not set already
1268 if(myplayer->peer_id == PEER_ID_INEXISTENT)
1269 myplayer->peer_id = our_peer_id;
1271 assert(myplayer->peer_id == our_peer_id);
1273 NetworkPacket pkt(TOSERVER_PLAYERPOS, 12 + 12 + 4 + 4 + 4 + 1 + 1);
1275 writePlayerPos(myplayer, &map, &pkt);
1280 void Client::sendPlayerItem(u16 item)
1282 LocalPlayer *myplayer = m_env.getLocalPlayer();
1283 if(myplayer == NULL)
1286 u16 our_peer_id = m_con.GetPeerID();
1288 // Set peer id if not set already
1289 if(myplayer->peer_id == PEER_ID_INEXISTENT)
1290 myplayer->peer_id = our_peer_id;
1291 assert(myplayer->peer_id == our_peer_id);
1293 NetworkPacket pkt(TOSERVER_PLAYERITEM, 2);
1300 void Client::removeNode(v3s16 p)
1302 std::map<v3s16, MapBlock*> modified_blocks;
1305 m_env.getMap().removeNodeAndUpdate(p, modified_blocks);
1307 catch(InvalidPositionException &e) {
1310 for(std::map<v3s16, MapBlock *>::iterator
1311 i = modified_blocks.begin();
1312 i != modified_blocks.end(); ++i) {
1313 addUpdateMeshTaskWithEdge(i->first, false, true);
1317 MapNode Client::getNode(v3s16 p, bool *is_valid_position)
1319 return m_env.getMap().getNodeNoEx(p, is_valid_position);
1322 void Client::addNode(v3s16 p, MapNode n, bool remove_metadata)
1324 //TimeTaker timer1("Client::addNode()");
1326 std::map<v3s16, MapBlock*> modified_blocks;
1329 //TimeTaker timer3("Client::addNode(): addNodeAndUpdate");
1330 m_env.getMap().addNodeAndUpdate(p, n, modified_blocks, remove_metadata);
1332 catch(InvalidPositionException &e) {
1335 for(std::map<v3s16, MapBlock *>::iterator
1336 i = modified_blocks.begin();
1337 i != modified_blocks.end(); ++i) {
1338 addUpdateMeshTaskWithEdge(i->first, false, true);
1342 void Client::setPlayerControl(PlayerControl &control)
1344 LocalPlayer *player = m_env.getLocalPlayer();
1346 player->control = control;
1349 void Client::selectPlayerItem(u16 item)
1351 m_playeritem = item;
1352 m_inventory_updated = true;
1353 sendPlayerItem(item);
1356 // Returns true if the inventory of the local player has been
1357 // updated from the server. If it is true, it is set to false.
1358 bool Client::getLocalInventoryUpdated()
1360 bool updated = m_inventory_updated;
1361 m_inventory_updated = false;
1365 // Copies the inventory of the local player to parameter
1366 void Client::getLocalInventory(Inventory &dst)
1368 LocalPlayer *player = m_env.getLocalPlayer();
1370 dst = player->inventory;
1373 Inventory* Client::getInventory(const InventoryLocation &loc)
1376 case InventoryLocation::UNDEFINED:
1379 case InventoryLocation::CURRENT_PLAYER:
1381 LocalPlayer *player = m_env.getLocalPlayer();
1383 return &player->inventory;
1386 case InventoryLocation::PLAYER:
1388 // Check if we are working with local player inventory
1389 LocalPlayer *player = m_env.getLocalPlayer();
1390 if (!player || strcmp(player->getName(), loc.name.c_str()) != 0)
1392 return &player->inventory;
1395 case InventoryLocation::NODEMETA:
1397 NodeMetadata *meta = m_env.getMap().getNodeMetadata(loc.p);
1400 return meta->getInventory();
1403 case InventoryLocation::DETACHED:
1405 if (m_detached_inventories.count(loc.name) == 0)
1407 return m_detached_inventories[loc.name];
1411 FATAL_ERROR("Invalid inventory location type.");
1417 void Client::inventoryAction(InventoryAction *a)
1420 Send it to the server
1422 sendInventoryAction(a);
1425 Predict some local inventory changes
1427 a->clientApply(this, this);
1433 float Client::getAnimationTime()
1435 return m_animation_time;
1438 int Client::getCrackLevel()
1440 return m_crack_level;
1443 v3s16 Client::getCrackPos()
1448 void Client::setCrack(int level, v3s16 pos)
1450 int old_crack_level = m_crack_level;
1451 v3s16 old_crack_pos = m_crack_pos;
1453 m_crack_level = level;
1456 if(old_crack_level >= 0 && (level < 0 || pos != old_crack_pos))
1459 addUpdateMeshTaskForNode(old_crack_pos, false, true);
1461 if(level >= 0 && (old_crack_level < 0 || pos != old_crack_pos))
1464 addUpdateMeshTaskForNode(pos, false, true);
1470 LocalPlayer *player = m_env.getLocalPlayer();
1475 bool Client::getChatMessage(std::wstring &message)
1477 if(m_chat_queue.size() == 0)
1479 message = m_chat_queue.front();
1484 void Client::typeChatMessage(const std::wstring &message)
1486 // Discard empty line
1490 // If message was ate by script API, don't send it to server
1491 if (m_script->on_sending_message(wide_to_utf8(message))) {
1496 sendChatMessage(message);
1499 if (message[0] != L'/')
1501 // compatibility code
1502 if (m_proto_ver < 29) {
1503 LocalPlayer *player = m_env.getLocalPlayer();
1505 std::wstring name = narrow_to_wide(player->getName());
1506 pushToChatQueue((std::wstring)L"<" + name + L"> " + message);
1511 void Client::addUpdateMeshTask(v3s16 p, bool ack_to_server, bool urgent)
1513 // Check if the block exists to begin with. In the case when a non-existing
1514 // neighbor is automatically added, it may not. In that case we don't want
1515 // to tell the mesh update thread about it.
1516 MapBlock *b = m_env.getMap().getBlockNoCreateNoEx(p);
1520 m_mesh_update_thread.updateBlock(&m_env.getMap(), p, ack_to_server, urgent);
1523 void Client::addUpdateMeshTaskWithEdge(v3s16 blockpos, bool ack_to_server, bool urgent)
1526 addUpdateMeshTask(blockpos, ack_to_server, urgent);
1528 catch(InvalidPositionException &e){}
1531 for (int i=0;i<6;i++)
1534 v3s16 p = blockpos + g_6dirs[i];
1535 addUpdateMeshTask(p, false, urgent);
1537 catch(InvalidPositionException &e){}
1541 void Client::addUpdateMeshTaskForNode(v3s16 nodepos, bool ack_to_server, bool urgent)
1545 infostream<<"Client::addUpdateMeshTaskForNode(): "
1546 <<"("<<p.X<<","<<p.Y<<","<<p.Z<<")"
1550 v3s16 blockpos = getNodeBlockPos(nodepos);
1551 v3s16 blockpos_relative = blockpos * MAP_BLOCKSIZE;
1554 addUpdateMeshTask(blockpos, ack_to_server, urgent);
1556 catch(InvalidPositionException &e) {}
1559 if(nodepos.X == blockpos_relative.X){
1561 v3s16 p = blockpos + v3s16(-1,0,0);
1562 addUpdateMeshTask(p, false, urgent);
1564 catch(InvalidPositionException &e){}
1567 if(nodepos.Y == blockpos_relative.Y){
1569 v3s16 p = blockpos + v3s16(0,-1,0);
1570 addUpdateMeshTask(p, false, urgent);
1572 catch(InvalidPositionException &e){}
1575 if(nodepos.Z == blockpos_relative.Z){
1577 v3s16 p = blockpos + v3s16(0,0,-1);
1578 addUpdateMeshTask(p, false, urgent);
1580 catch(InvalidPositionException &e){}
1584 ClientEvent Client::getClientEvent()
1586 FATAL_ERROR_IF(m_client_event_queue.empty(),
1587 "Cannot getClientEvent, queue is empty.");
1589 ClientEvent event = m_client_event_queue.front();
1590 m_client_event_queue.pop();
1594 float Client::mediaReceiveProgress()
1596 if (m_media_downloader)
1597 return m_media_downloader->getProgress();
1599 return 1.0; // downloader only exists when not yet done
1602 typedef struct TextureUpdateArgs {
1603 gui::IGUIEnvironment *guienv;
1606 const wchar_t* text_base;
1607 ITextureSource *tsrc;
1608 } TextureUpdateArgs;
1610 void texture_update_progress(void *args, u32 progress, u32 max_progress)
1612 TextureUpdateArgs* targs = (TextureUpdateArgs*) args;
1613 u16 cur_percent = ceil(progress / (double) max_progress * 100.);
1615 // update the loading menu -- if neccessary
1616 bool do_draw = false;
1617 u64 time_ms = targs->last_time_ms;
1618 if (cur_percent != targs->last_percent) {
1619 targs->last_percent = cur_percent;
1620 time_ms = porting::getTimeMs();
1621 // only draw when the user will notice something:
1622 do_draw = (time_ms - targs->last_time_ms > 100);
1626 targs->last_time_ms = time_ms;
1627 std::basic_stringstream<wchar_t> strm;
1628 strm << targs->text_base << " " << targs->last_percent << "%...";
1629 RenderingEngine::draw_load_screen(strm.str(), targs->guienv, targs->tsrc, 0,
1630 72 + (u16) ((18. / 100.) * (double) targs->last_percent), true);
1634 void Client::afterContentReceived()
1636 infostream<<"Client::afterContentReceived() started"<<std::endl;
1637 assert(m_itemdef_received); // pre-condition
1638 assert(m_nodedef_received); // pre-condition
1639 assert(mediaReceived()); // pre-condition
1641 const wchar_t* text = wgettext("Loading textures...");
1643 // Clear cached pre-scaled 2D GUI images, as this cache
1644 // might have images with the same name but different
1645 // content from previous sessions.
1646 guiScalingCacheClear();
1648 // Rebuild inherited images and recreate textures
1649 infostream<<"- Rebuilding images and textures"<<std::endl;
1650 RenderingEngine::draw_load_screen(text, guienv, m_tsrc, 0, 70);
1651 m_tsrc->rebuildImagesAndTextures();
1655 infostream<<"- Rebuilding shaders"<<std::endl;
1656 text = wgettext("Rebuilding shaders...");
1657 RenderingEngine::draw_load_screen(text, guienv, m_tsrc, 0, 71);
1658 m_shsrc->rebuildShaders();
1661 // Update node aliases
1662 infostream<<"- Updating node aliases"<<std::endl;
1663 text = wgettext("Initializing nodes...");
1664 RenderingEngine::draw_load_screen(text, guienv, m_tsrc, 0, 72);
1665 m_nodedef->updateAliases(m_itemdef);
1666 std::string texture_path = g_settings->get("texture_path");
1667 if (texture_path != "" && fs::IsDir(texture_path))
1668 m_nodedef->applyTextureOverrides(texture_path + DIR_DELIM + "override.txt");
1669 m_nodedef->setNodeRegistrationStatus(true);
1670 m_nodedef->runNodeResolveCallbacks();
1673 // Update node textures and assign shaders to each tile
1674 infostream<<"- Updating node textures"<<std::endl;
1675 TextureUpdateArgs tu_args;
1676 tu_args.guienv = guienv;
1677 tu_args.last_time_ms = porting::getTimeMs();
1678 tu_args.last_percent = 0;
1679 tu_args.text_base = wgettext("Initializing nodes");
1680 tu_args.tsrc = m_tsrc;
1681 m_nodedef->updateTextures(this, texture_update_progress, &tu_args);
1682 delete[] tu_args.text_base;
1684 // Start mesh update thread after setting up content definitions
1685 infostream<<"- Starting mesh update thread"<<std::endl;
1686 m_mesh_update_thread.start();
1691 if (g_settings->getBool("enable_client_modding")) {
1692 m_script->on_client_ready(m_env.getLocalPlayer());
1693 m_script->on_connect();
1696 text = wgettext("Done!");
1697 RenderingEngine::draw_load_screen(text, guienv, m_tsrc, 0, 100);
1698 infostream<<"Client::afterContentReceived() done"<<std::endl;
1702 float Client::getRTT()
1704 return m_con.getPeerStat(PEER_ID_SERVER,con::AVG_RTT);
1707 float Client::getCurRate()
1709 return (m_con.getLocalStat(con::CUR_INC_RATE) +
1710 m_con.getLocalStat(con::CUR_DL_RATE));
1713 void Client::makeScreenshot()
1715 irr::video::IVideoDriver *driver = RenderingEngine::get_video_driver();
1716 irr::video::IImage* const raw_image = driver->createScreenShot();
1721 time_t t = time(NULL);
1722 struct tm *tm = localtime(&t);
1724 char timetstamp_c[64];
1725 strftime(timetstamp_c, sizeof(timetstamp_c), "%Y%m%d_%H%M%S", tm);
1727 std::string filename_base = g_settings->get("screenshot_path")
1729 + std::string("screenshot_")
1730 + std::string(timetstamp_c);
1731 std::string filename_ext = "." + g_settings->get("screenshot_format");
1732 std::string filename;
1734 u32 quality = (u32)g_settings->getS32("screenshot_quality");
1735 quality = MYMIN(MYMAX(quality, 0), 100) / 100.0 * 255;
1737 // Try to find a unique filename
1738 unsigned serial = 0;
1740 while (serial < SCREENSHOT_MAX_SERIAL_TRIES) {
1741 filename = filename_base + (serial > 0 ? ("_" + itos(serial)) : "") + filename_ext;
1742 std::ifstream tmp(filename.c_str());
1744 break; // File did not apparently exist, we'll go with it
1748 if (serial == SCREENSHOT_MAX_SERIAL_TRIES) {
1749 infostream << "Could not find suitable filename for screenshot" << std::endl;
1751 irr::video::IImage* const image =
1752 driver->createImage(video::ECF_R8G8B8, raw_image->getDimension());
1755 raw_image->copyTo(image);
1757 std::ostringstream sstr;
1758 if (driver->writeImageToFile(image, filename.c_str(), quality)) {
1759 sstr << "Saved screenshot to '" << filename << "'";
1761 sstr << "Failed to save screenshot '" << filename << "'";
1763 pushToChatQueue(narrow_to_wide(sstr.str()));
1764 infostream << sstr.str() << std::endl;
1772 bool Client::shouldShowMinimap() const
1774 return !m_minimap_disabled_by_server;
1777 void Client::showGameChat(const bool show)
1779 m_game_ui_flags->show_chat = show;
1782 void Client::showGameHud(const bool show)
1784 m_game_ui_flags->show_hud = show;
1787 void Client::showMinimap(const bool show)
1789 m_game_ui_flags->show_minimap = show;
1792 void Client::showProfiler(const bool show)
1794 m_game_ui_flags->show_profiler_graph = show;
1797 void Client::showGameFog(const bool show)
1799 m_game_ui_flags->force_fog_off = !show;
1802 void Client::showGameDebug(const bool show)
1804 m_game_ui_flags->show_debug = show;
1807 // IGameDef interface
1809 IItemDefManager* Client::getItemDefManager()
1813 INodeDefManager* Client::getNodeDefManager()
1817 ICraftDefManager* Client::getCraftDefManager()
1820 //return m_craftdef;
1822 ITextureSource* Client::getTextureSource()
1826 IShaderSource* Client::getShaderSource()
1831 u16 Client::allocateUnknownNodeId(const std::string &name)
1833 errorstream << "Client::allocateUnknownNodeId(): "
1834 << "Client cannot allocate node IDs" << std::endl;
1835 FATAL_ERROR("Client allocated unknown node");
1837 return CONTENT_IGNORE;
1839 ISoundManager* Client::getSoundManager()
1843 MtEventManager* Client::getEventManager()
1848 ParticleManager* Client::getParticleManager()
1850 return &m_particle_manager;
1853 scene::IAnimatedMesh* Client::getMesh(const std::string &filename)
1855 StringMap::const_iterator it = m_mesh_data.find(filename);
1856 if (it == m_mesh_data.end()) {
1857 errorstream << "Client::getMesh(): Mesh not found: \"" << filename
1858 << "\"" << std::endl;
1861 const std::string &data = it->second;
1863 // Create the mesh, remove it from cache and return it
1864 // This allows unique vertex colors and other properties for each instance
1865 Buffer<char> data_rw(data.c_str(), data.size()); // Const-incorrect Irrlicht
1866 io::IReadFile *rfile = RenderingEngine::get_filesystem()->createMemoryReadFile(
1867 *data_rw, data_rw.getSize(), filename.c_str());
1868 FATAL_ERROR_IF(!rfile, "Could not create/open RAM file");
1870 scene::IAnimatedMesh *mesh = RenderingEngine::get_scene_manager()->getMesh(rfile);
1872 // NOTE: By playing with Irrlicht refcounts, maybe we could cache a bunch
1873 // of uniquely named instances and re-use them
1875 RenderingEngine::get_mesh_cache()->removeMesh(mesh);
1879 const std::string* Client::getModFile(const std::string &filename)
1881 StringMap::const_iterator it = m_mod_files.find(filename);
1882 if (it == m_mod_files.end()) {
1883 errorstream << "Client::getModFile(): File not found: \"" << filename
1884 << "\"" << std::endl;
1890 bool Client::registerModStorage(ModMetadata *storage)
1892 if (m_mod_storages.find(storage->getModName()) != m_mod_storages.end()) {
1893 errorstream << "Unable to register same mod storage twice. Storage name: "
1894 << storage->getModName() << std::endl;
1898 m_mod_storages[storage->getModName()] = storage;
1902 void Client::unregisterModStorage(const std::string &name)
1904 std::unordered_map<std::string, ModMetadata *>::const_iterator it =
1905 m_mod_storages.find(name);
1906 if (it != m_mod_storages.end()) {
1907 // Save unconditionaly on unregistration
1908 it->second->save(getModStoragePath());
1909 m_mod_storages.erase(name);
1913 std::string Client::getModStoragePath() const
1915 return porting::path_user + DIR_DELIM + "client" + DIR_DELIM + "mod_storage";