3 Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com>
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU Lesser General Public License as published by
7 the Free Software Foundation; either version 2.1 of the License, or
8 (at your option) any later version.
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU Lesser General Public License for more details.
15 You should have received a copy of the GNU Lesser General Public License along
16 with this program; if not, write to the Free Software Foundation, Inc.,
17 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
24 #include <IFileSystem.h>
25 #include "threading/mutex_auto_lock.h"
26 #include "util/auth.h"
27 #include "util/directiontables.h"
28 #include "util/pointedthing.h"
29 #include "util/serialize.h"
30 #include "util/string.h"
33 #include "network/clientopcodes.h"
35 #include "mapblock_mesh.h"
41 #include "clientmap.h"
42 #include "clientmedia.h"
44 #include "drawscene.h"
45 #include "database-sqlite3.h"
46 #include "serialization.h"
47 #include "guiscalingfilter.h"
48 #include "script/clientscripting.h"
50 extern gui::IGUIEnvironment* guienv;
56 QueuedMeshUpdate::QueuedMeshUpdate():
59 ack_block_to_server(false)
63 QueuedMeshUpdate::~QueuedMeshUpdate()
73 MeshUpdateQueue::MeshUpdateQueue()
77 MeshUpdateQueue::~MeshUpdateQueue()
79 MutexAutoLock lock(m_mutex);
81 for(std::vector<QueuedMeshUpdate*>::iterator
83 i != m_queue.end(); ++i)
85 QueuedMeshUpdate *q = *i;
91 peer_id=0 adds with nobody to send to
93 void MeshUpdateQueue::addBlock(v3s16 p, MeshMakeData *data, bool ack_block_to_server, bool urgent)
95 DSTACK(FUNCTION_NAME);
97 assert(data); // pre-condition
99 MutexAutoLock lock(m_mutex);
105 Find if block is already in queue.
106 If it is, update the data and quit.
108 for(std::vector<QueuedMeshUpdate*>::iterator
110 i != m_queue.end(); ++i)
112 QueuedMeshUpdate *q = *i;
118 if(ack_block_to_server)
119 q->ack_block_to_server = true;
127 QueuedMeshUpdate *q = new QueuedMeshUpdate;
130 q->ack_block_to_server = ack_block_to_server;
131 m_queue.push_back(q);
134 // Returned pointer must be deleted
135 // Returns NULL if queue is empty
136 QueuedMeshUpdate *MeshUpdateQueue::pop()
138 MutexAutoLock lock(m_mutex);
140 bool must_be_urgent = !m_urgents.empty();
141 for(std::vector<QueuedMeshUpdate*>::iterator
143 i != m_queue.end(); ++i)
145 QueuedMeshUpdate *q = *i;
146 if(must_be_urgent && m_urgents.count(q->p) == 0)
149 m_urgents.erase(q->p);
159 void MeshUpdateThread::enqueueUpdate(v3s16 p, MeshMakeData *data,
160 bool ack_block_to_server, bool urgent)
162 m_queue_in.addBlock(p, data, ack_block_to_server, urgent);
166 void MeshUpdateThread::doUpdate()
169 while ((q = m_queue_in.pop())) {
171 ScopeProfiler sp(g_profiler, "Client: Mesh making");
173 MapBlockMesh *mesh_new = new MapBlockMesh(q->data, m_camera_offset);
178 r.ack_block_to_server = q->ack_block_to_server;
180 m_queue_out.push_back(r);
191 IrrlichtDevice *device,
192 const char *playername,
193 std::string password,
194 MapDrawControl &control,
195 IWritableTextureSource *tsrc,
196 IWritableShaderSource *shsrc,
197 IWritableItemDefManager *itemdef,
198 IWritableNodeDefManager *nodedef,
199 ISoundManager *sound,
200 MtEventManager *event,
203 m_packetcounter_timer(0.0),
204 m_connection_reinit_timer(0.1),
205 m_avg_rtt_timer(0.0),
206 m_playerpos_send_timer(0.0),
207 m_ignore_damage_timer(0.0),
214 m_mesh_update_thread(),
216 new ClientMap(this, control,
217 device->getSceneManager()->getRootSceneNode(),
218 device->getSceneManager(), 666),
219 device->getSceneManager(),
222 m_particle_manager(&m_env),
223 m_con(PROTOCOL_ID, 512, CONNECTION_TIMEOUT, ipv6, this),
226 m_minimap_disabled_by_server(false),
227 m_server_ser_ver(SER_FMT_VER_INVALID),
230 m_inventory_updated(false),
231 m_inventory_from_server(NULL),
232 m_inventory_from_server_age(0.0),
237 m_password(password),
238 m_chosen_auth_mech(AUTH_MECHANISM_NONE),
240 m_access_denied(false),
241 m_access_denied_reconnect(false),
242 m_itemdef_received(false),
243 m_nodedef_received(false),
244 m_media_downloader(new ClientMediaDownloader()),
245 m_time_of_day_set(false),
246 m_last_time_of_day_f(-1),
247 m_time_of_day_update_timer(0),
248 m_recommended_send_interval(0.1),
249 m_removed_sounds_check_timer(0),
255 m_env.setLocalPlayer(new LocalPlayer(this, playername));
257 m_mapper = new Mapper(device, this);
258 m_cache_save_interval = g_settings->getU16("server_map_save_interval");
260 m_cache_smooth_lighting = g_settings->getBool("smooth_lighting");
261 m_cache_enable_shaders = g_settings->getBool("enable_shaders");
262 m_cache_use_tangent_vertices = m_cache_enable_shaders && (
263 g_settings->getBool("enable_bumpmapping") ||
264 g_settings->getBool("enable_parallax_occlusion"));
266 m_modding_enabled = g_settings->getBool("enable_client_modding");
267 m_script = new ClientScripting(this);
268 m_env.setScript(m_script);
271 void Client::initMods()
273 m_script->loadMod(getBuiltinLuaPath() + DIR_DELIM "init.lua", BUILTIN_MOD_NAME);
275 // If modding is not enabled, don't load mods, just builtin
276 if (!m_modding_enabled) {
280 ClientModConfiguration modconf(getClientModsLuaPath());
281 std::vector<ModSpec> mods = modconf.getMods();
282 std::vector<ModSpec> unsatisfied_mods = modconf.getUnsatisfiedMods();
283 // complain about mods with unsatisfied dependencies
284 if (!modconf.isConsistent()) {
285 modconf.printUnsatisfiedModsError();
289 infostream << "Client Loading mods: ";
290 for (std::vector<ModSpec>::const_iterator i = mods.begin();
291 i != mods.end(); ++i) {
292 infostream << (*i).name << " ";
295 infostream << std::endl;
296 // Load and run "mod" scripts
297 for (std::vector<ModSpec>::const_iterator it = mods.begin();
298 it != mods.end(); ++it) {
299 const ModSpec &mod = *it;
300 if (!string_allowed(mod.name, MODNAME_ALLOWED_CHARS)) {
301 throw ModError("Error loading mod \"" + mod.name +
302 "\": Mod name does not follow naming conventions: "
303 "Only chararacters [a-z0-9_] are allowed.");
305 std::string script_path = mod.path + DIR_DELIM + "init.lua";
306 infostream << " [" << padStringRight(mod.name, 12) << "] [\""
307 << script_path << "\"]" << std::endl;
308 m_script->loadMod(script_path, mod.name);
312 const std::string &Client::getBuiltinLuaPath()
314 static const std::string builtin_dir = porting::path_share + DIR_DELIM + "builtin";
318 const std::string &Client::getClientModsLuaPath()
320 static const std::string clientmods_dir = porting::path_share + DIR_DELIM + "clientmods";
321 return clientmods_dir;
324 const std::vector<ModSpec>& Client::getMods() const
326 static std::vector<ModSpec> client_modspec_temp;
327 return client_modspec_temp;
330 const ModSpec* Client::getModSpec(const std::string &modname) const
337 // Don't disable this part when modding is disabled, it's used in builtin
338 m_script->on_shutdown();
339 //request all client managed threads to stop
340 m_mesh_update_thread.stop();
341 // Save local server map
343 infostream << "Local map saving ended." << std::endl;
344 m_localdb->endSave();
350 bool Client::isShutdown()
353 if (!m_mesh_update_thread.isRunning()) return true;
362 m_mesh_update_thread.stop();
363 m_mesh_update_thread.wait();
364 while (!m_mesh_update_thread.m_queue_out.empty()) {
365 MeshUpdateResult r = m_mesh_update_thread.m_queue_out.pop_frontNoEx();
370 delete m_inventory_from_server;
372 // Delete detached inventories
373 for (UNORDERED_MAP<std::string, Inventory*>::iterator
374 i = m_detached_inventories.begin();
375 i != m_detached_inventories.end(); ++i) {
379 // cleanup 3d model meshes on client shutdown
380 while (m_device->getSceneManager()->getMeshCache()->getMeshCount() != 0) {
381 scene::IAnimatedMesh *mesh =
382 m_device->getSceneManager()->getMeshCache()->getMeshByIndex(0);
385 m_device->getSceneManager()->getMeshCache()->removeMesh(mesh);
391 void Client::connect(Address address,
392 const std::string &address_name,
393 bool is_local_server)
395 DSTACK(FUNCTION_NAME);
397 initLocalMapSaving(address, address_name, is_local_server);
399 m_con.SetTimeoutMs(0);
400 m_con.Connect(address);
403 void Client::step(float dtime)
405 DSTACK(FUNCTION_NAME);
411 if(m_ignore_damage_timer > dtime)
412 m_ignore_damage_timer -= dtime;
414 m_ignore_damage_timer = 0.0;
416 m_animation_time += dtime;
417 if(m_animation_time > 60.0)
418 m_animation_time -= 60.0;
420 m_time_of_day_update_timer += dtime;
428 float &counter = m_packetcounter_timer;
434 infostream << "Client packetcounter (" << m_packetcounter_timer
436 m_packetcounter.print(infostream);
437 m_packetcounter.clear();
441 // UGLY hack to fix 2 second startup delay caused by non existent
442 // server client startup synchronization in local server or singleplayer mode
443 static bool initial_step = true;
445 initial_step = false;
447 else if(m_state == LC_Created) {
448 float &counter = m_connection_reinit_timer;
453 LocalPlayer *myplayer = m_env.getLocalPlayer();
454 FATAL_ERROR_IF(myplayer == NULL, "Local player not found in environment.");
456 u16 proto_version_min = g_settings->getFlag("send_pre_v25_init") ?
457 CLIENT_PROTOCOL_VERSION_MIN_LEGACY : CLIENT_PROTOCOL_VERSION_MIN;
459 if (proto_version_min < 25) {
460 // Send TOSERVER_INIT_LEGACY
461 // [0] u16 TOSERVER_INIT_LEGACY
462 // [2] u8 SER_FMT_VER_HIGHEST_READ
463 // [3] u8[20] player_name
464 // [23] u8[28] password (new in some version)
465 // [51] u16 minimum supported network protocol version (added sometime)
466 // [53] u16 maximum supported network protocol version (added later than the previous one)
468 char pName[PLAYERNAME_SIZE];
469 char pPassword[PASSWORD_SIZE];
470 memset(pName, 0, PLAYERNAME_SIZE * sizeof(char));
471 memset(pPassword, 0, PASSWORD_SIZE * sizeof(char));
473 std::string hashed_password = translate_password(myplayer->getName(), m_password);
474 snprintf(pName, PLAYERNAME_SIZE, "%s", myplayer->getName());
475 snprintf(pPassword, PASSWORD_SIZE, "%s", hashed_password.c_str());
477 sendLegacyInit(pName, pPassword);
479 if (CLIENT_PROTOCOL_VERSION_MAX >= 25)
480 sendInit(myplayer->getName());
483 // Not connected, return
488 Do stuff if connected
492 Run Map's timers and unload unused data
494 const float map_timer_and_unload_dtime = 5.25;
495 if(m_map_timer_and_unload_interval.step(dtime, map_timer_and_unload_dtime)) {
496 ScopeProfiler sp(g_profiler, "Client: map timer and unload");
497 std::vector<v3s16> deleted_blocks;
498 m_env.getMap().timerUpdate(map_timer_and_unload_dtime,
499 g_settings->getFloat("client_unload_unused_data_timeout"),
500 g_settings->getS32("client_mapblock_limit"),
505 NOTE: This loop is intentionally iterated the way it is.
508 std::vector<v3s16>::iterator i = deleted_blocks.begin();
509 std::vector<v3s16> sendlist;
511 if(sendlist.size() == 255 || i == deleted_blocks.end()) {
522 sendDeletedBlocks(sendlist);
524 if(i == deleted_blocks.end())
530 sendlist.push_back(*i);
538 // Control local player (0ms)
539 LocalPlayer *player = m_env.getLocalPlayer();
540 assert(player != NULL);
541 player->applyControl(dtime);
550 ClientEnvEvent event = m_env.getClientEvent();
551 if(event.type == CEE_NONE) {
554 else if(event.type == CEE_PLAYER_DAMAGE) {
555 if(m_ignore_damage_timer <= 0) {
556 u8 damage = event.player_damage.amount;
558 if(event.player_damage.send_to_server)
561 // Add to ClientEvent queue
563 event.type = CE_PLAYER_DAMAGE;
564 event.player_damage.amount = damage;
565 m_client_event_queue.push(event);
568 // Protocol v29 or greater obsoleted this event
569 else if (event.type == CEE_PLAYER_BREATH && m_proto_ver < 29) {
570 u16 breath = event.player_breath.amount;
578 float &counter = m_avg_rtt_timer;
582 // connectedAndInitialized() is true, peer exists.
583 float avg_rtt = getRTT();
584 infostream << "Client: avg_rtt=" << avg_rtt << std::endl;
588 Send player position to server
591 float &counter = m_playerpos_send_timer;
593 if((m_state == LC_Ready) && (counter >= m_recommended_send_interval))
601 Replace updated meshes
604 int num_processed_meshes = 0;
605 while (!m_mesh_update_thread.m_queue_out.empty())
607 num_processed_meshes++;
609 MinimapMapblock *minimap_mapblock = NULL;
610 bool do_mapper_update = true;
612 MeshUpdateResult r = m_mesh_update_thread.m_queue_out.pop_frontNoEx();
613 MapBlock *block = m_env.getMap().getBlockNoCreateNoEx(r.p);
615 // Delete the old mesh
616 if (block->mesh != NULL) {
622 minimap_mapblock = r.mesh->moveMinimapMapblock();
623 if (minimap_mapblock == NULL)
624 do_mapper_update = false;
627 if (r.mesh && r.mesh->getMesh()->getMeshBufferCount() == 0) {
630 // Replace with the new mesh
631 block->mesh = r.mesh;
637 if (do_mapper_update)
638 m_mapper->addBlock(r.p, minimap_mapblock);
640 if (r.ack_block_to_server) {
650 if (num_processed_meshes > 0)
651 g_profiler->graphAdd("num_processed_meshes", num_processed_meshes);
657 if (m_media_downloader && m_media_downloader->isStarted()) {
658 m_media_downloader->step(this);
659 if (m_media_downloader->isDone()) {
661 delete m_media_downloader;
662 m_media_downloader = NULL;
667 If the server didn't update the inventory in a while, revert
668 the local inventory (so the player notices the lag problem
669 and knows something is wrong).
671 if(m_inventory_from_server)
673 float interval = 10.0;
674 float count_before = floor(m_inventory_from_server_age / interval);
676 m_inventory_from_server_age += dtime;
678 float count_after = floor(m_inventory_from_server_age / interval);
680 if(count_after != count_before)
682 // Do this every <interval> seconds after TOCLIENT_INVENTORY
683 // Reset the locally changed inventory to the authoritative inventory
684 LocalPlayer *player = m_env.getLocalPlayer();
685 player->inventory = *m_inventory_from_server;
686 m_inventory_updated = true;
691 Update positions of sounds attached to objects
694 for(UNORDERED_MAP<int, u16>::iterator i = m_sounds_to_objects.begin();
695 i != m_sounds_to_objects.end(); ++i) {
696 int client_id = i->first;
697 u16 object_id = i->second;
698 ClientActiveObject *cao = m_env.getActiveObject(object_id);
701 v3f pos = cao->getPosition();
702 m_sound->updateSoundPosition(client_id, pos);
707 Handle removed remotely initiated sounds
709 m_removed_sounds_check_timer += dtime;
710 if(m_removed_sounds_check_timer >= 2.32) {
711 m_removed_sounds_check_timer = 0;
712 // Find removed sounds and clear references to them
713 std::vector<s32> removed_server_ids;
714 for(UNORDERED_MAP<s32, int>::iterator i = m_sounds_server_to_client.begin();
715 i != m_sounds_server_to_client.end();) {
716 s32 server_id = i->first;
717 int client_id = i->second;
719 if(!m_sound->soundExists(client_id)) {
720 m_sounds_server_to_client.erase(server_id);
721 m_sounds_client_to_server.erase(client_id);
722 m_sounds_to_objects.erase(client_id);
723 removed_server_ids.push_back(server_id);
728 if(!removed_server_ids.empty()) {
729 sendRemovedSounds(removed_server_ids);
734 if (m_localdb && m_localdb_save_interval.step(dtime,
735 m_cache_save_interval)) {
736 m_localdb->endSave();
737 m_localdb->beginSave();
741 bool Client::loadMedia(const std::string &data, const std::string &filename)
743 // Silly irrlicht's const-incorrectness
744 Buffer<char> data_rw(data.c_str(), data.size());
748 const char *image_ext[] = {
749 ".png", ".jpg", ".bmp", ".tga",
750 ".pcx", ".ppm", ".psd", ".wal", ".rgb",
753 name = removeStringEnd(filename, image_ext);
756 verbosestream<<"Client: Attempting to load image "
757 <<"file \""<<filename<<"\""<<std::endl;
759 io::IFileSystem *irrfs = m_device->getFileSystem();
760 video::IVideoDriver *vdrv = m_device->getVideoDriver();
762 // Create an irrlicht memory file
763 io::IReadFile *rfile = irrfs->createMemoryReadFile(
764 *data_rw, data_rw.getSize(), "_tempreadfile");
766 FATAL_ERROR_IF(!rfile, "Could not create irrlicht memory file.");
769 video::IImage *img = vdrv->createImageFromFile(rfile);
771 errorstream<<"Client: Cannot create image from data of "
772 <<"file \""<<filename<<"\""<<std::endl;
777 m_tsrc->insertSourceImage(filename, img);
784 const char *sound_ext[] = {
785 ".0.ogg", ".1.ogg", ".2.ogg", ".3.ogg", ".4.ogg",
786 ".5.ogg", ".6.ogg", ".7.ogg", ".8.ogg", ".9.ogg",
789 name = removeStringEnd(filename, sound_ext);
792 verbosestream<<"Client: Attempting to load sound "
793 <<"file \""<<filename<<"\""<<std::endl;
794 m_sound->loadSoundData(name, data);
798 const char *model_ext[] = {
799 ".x", ".b3d", ".md2", ".obj",
802 name = removeStringEnd(filename, model_ext);
805 verbosestream<<"Client: Storing model into memory: "
806 <<"\""<<filename<<"\""<<std::endl;
807 if(m_mesh_data.count(filename))
808 errorstream<<"Multiple models with name \""<<filename.c_str()
809 <<"\" found; replacing previous model"<<std::endl;
810 m_mesh_data[filename] = data;
814 errorstream<<"Client: Don't know how to load file \""
815 <<filename<<"\""<<std::endl;
819 // Virtual methods from con::PeerHandler
820 void Client::peerAdded(con::Peer *peer)
822 infostream << "Client::peerAdded(): peer->id="
823 << peer->id << std::endl;
825 void Client::deletingPeer(con::Peer *peer, bool timeout)
827 infostream << "Client::deletingPeer(): "
828 "Server Peer is getting deleted "
829 << "(timeout=" << timeout << ")" << std::endl;
832 m_access_denied = true;
833 m_access_denied_reason = gettext("Connection timed out.");
839 u16 number of files requested
845 void Client::request_media(const std::vector<std::string> &file_requests)
847 std::ostringstream os(std::ios_base::binary);
848 writeU16(os, TOSERVER_REQUEST_MEDIA);
849 size_t file_requests_size = file_requests.size();
851 FATAL_ERROR_IF(file_requests_size > 0xFFFF, "Unsupported number of file requests");
853 // Packet dynamicly resized
854 NetworkPacket pkt(TOSERVER_REQUEST_MEDIA, 2 + 0);
856 pkt << (u16) (file_requests_size & 0xFFFF);
858 for(std::vector<std::string>::const_iterator i = file_requests.begin();
859 i != file_requests.end(); ++i) {
865 infostream << "Client: Sending media request list to server ("
866 << file_requests.size() << " files. packet size)" << std::endl;
869 void Client::received_media()
871 NetworkPacket pkt(TOSERVER_RECEIVED_MEDIA, 0);
873 infostream << "Client: Notifying server that we received all media"
877 void Client::initLocalMapSaving(const Address &address,
878 const std::string &hostname,
879 bool is_local_server)
881 if (!g_settings->getBool("enable_local_map_saving") || is_local_server) {
885 const std::string world_path = porting::path_user
886 + DIR_DELIM + "worlds"
887 + DIR_DELIM + "server_"
888 + hostname + "_" + std::to_string(address.getPort());
890 fs::CreateAllDirs(world_path);
892 m_localdb = new Database_SQLite3(world_path);
893 m_localdb->beginSave();
894 actionstream << "Local map saving started, map will be saved at '" << world_path << "'" << std::endl;
897 void Client::ReceiveAll()
899 DSTACK(FUNCTION_NAME);
900 u32 start_ms = porting::getTimeMs();
903 // Limit time even if there would be huge amounts of data to
905 if(porting::getTimeMs() > start_ms + 100)
910 g_profiler->graphAdd("client_received_packets", 1);
912 catch(con::NoIncomingDataException &e) {
915 catch(con::InvalidIncomingDataException &e) {
916 infostream<<"Client::ReceiveAll(): "
917 "InvalidIncomingDataException: what()="
918 <<e.what()<<std::endl;
923 void Client::Receive()
925 DSTACK(FUNCTION_NAME);
931 inline void Client::handleCommand(NetworkPacket* pkt)
933 const ToClientCommandHandler& opHandle = toClientCommandTable[pkt->getCommand()];
934 (this->*opHandle.handler)(pkt);
938 sender_peer_id given to this shall be quaranteed to be a valid peer
940 void Client::ProcessData(NetworkPacket *pkt)
942 DSTACK(FUNCTION_NAME);
944 ToClientCommand command = (ToClientCommand) pkt->getCommand();
945 u32 sender_peer_id = pkt->getPeerId();
947 //infostream<<"Client: received command="<<command<<std::endl;
948 m_packetcounter.add((u16)command);
951 If this check is removed, be sure to change the queue
952 system to know the ids
954 if(sender_peer_id != PEER_ID_SERVER) {
955 infostream << "Client::ProcessData(): Discarding data not "
956 "coming from server: peer_id=" << sender_peer_id
961 // Command must be handled into ToClientCommandHandler
962 if (command >= TOCLIENT_NUM_MSG_TYPES) {
963 infostream << "Client: Ignoring unknown command "
964 << command << std::endl;
969 * Those packets are handled before m_server_ser_ver is set, it's normal
970 * But we must use the new ToClientConnectionState in the future,
973 if(toClientCommandTable[command].state == TOCLIENT_STATE_NOT_CONNECTED) {
978 if(m_server_ser_ver == SER_FMT_VER_INVALID) {
979 infostream << "Client: Server serialization"
980 " format invalid or not initialized."
981 " Skipping incoming command=" << command << std::endl;
986 Handle runtime commands
992 void Client::Send(NetworkPacket* pkt)
994 m_con.Send(PEER_ID_SERVER,
995 serverCommandFactoryTable[pkt->getCommand()].channel,
997 serverCommandFactoryTable[pkt->getCommand()].reliable);
1000 // Will fill up 12 + 12 + 4 + 4 + 4 bytes
1001 void writePlayerPos(LocalPlayer *myplayer, ClientMap *clientMap, NetworkPacket *pkt)
1003 v3f pf = myplayer->getPosition() * 100;
1004 v3f sf = myplayer->getSpeed() * 100;
1005 s32 pitch = myplayer->getPitch() * 100;
1006 s32 yaw = myplayer->getYaw() * 100;
1007 u32 keyPressed = myplayer->keyPressed;
1008 // scaled by 80, so that pi can fit into a u8
1009 u8 fov = clientMap->getCameraFov() * 80;
1010 u8 wanted_range = MYMIN(255,
1011 std::ceil(clientMap->getControl().wanted_range / MAP_BLOCKSIZE));
1013 v3s32 position(pf.X, pf.Y, pf.Z);
1014 v3s32 speed(sf.X, sf.Y, sf.Z);
1018 [0] v3s32 position*100
1019 [12] v3s32 speed*100
1020 [12+12] s32 pitch*100
1021 [12+12+4] s32 yaw*100
1022 [12+12+4+4] u32 keyPressed
1023 [12+12+4+4+4] u8 fov*80
1024 [12+12+4+4+4+1] u8 ceil(wanted_range / MAP_BLOCKSIZE)
1026 *pkt << position << speed << pitch << yaw << keyPressed;
1027 *pkt << fov << wanted_range;
1030 void Client::interact(u8 action, const PointedThing& pointed)
1032 if(m_state != LC_Ready) {
1033 errorstream << "Client::interact() "
1034 "Canceled (not connected)"
1039 LocalPlayer *myplayer = m_env.getLocalPlayer();
1040 if (myplayer == NULL)
1047 [5] u32 length of the next item (plen)
1048 [9] serialized PointedThing
1049 [9 + plen] player position information
1051 0: start digging (from undersurface) or use
1052 1: stop digging (all parameters ignored)
1053 2: digging completed
1054 3: place block or item (to abovesurface)
1056 5: perform secondary action of item
1059 NetworkPacket pkt(TOSERVER_INTERACT, 1 + 2 + 0);
1062 pkt << (u16)getPlayerItem();
1064 std::ostringstream tmp_os(std::ios::binary);
1065 pointed.serialize(tmp_os);
1067 pkt.putLongString(tmp_os.str());
1069 writePlayerPos(myplayer, &m_env.getClientMap(), &pkt);
1074 void Client::deleteAuthData()
1079 switch (m_chosen_auth_mech) {
1080 case AUTH_MECHANISM_FIRST_SRP:
1082 case AUTH_MECHANISM_SRP:
1083 case AUTH_MECHANISM_LEGACY_PASSWORD:
1084 srp_user_delete((SRPUser *) m_auth_data);
1087 case AUTH_MECHANISM_NONE:
1090 m_chosen_auth_mech = AUTH_MECHANISM_NONE;
1094 AuthMechanism Client::choseAuthMech(const u32 mechs)
1096 if (mechs & AUTH_MECHANISM_SRP)
1097 return AUTH_MECHANISM_SRP;
1099 if (mechs & AUTH_MECHANISM_FIRST_SRP)
1100 return AUTH_MECHANISM_FIRST_SRP;
1102 if (mechs & AUTH_MECHANISM_LEGACY_PASSWORD)
1103 return AUTH_MECHANISM_LEGACY_PASSWORD;
1105 return AUTH_MECHANISM_NONE;
1108 void Client::sendLegacyInit(const char* playerName, const char* playerPassword)
1110 NetworkPacket pkt(TOSERVER_INIT_LEGACY,
1111 1 + PLAYERNAME_SIZE + PASSWORD_SIZE + 2 + 2);
1113 u16 proto_version_min = g_settings->getFlag("send_pre_v25_init") ?
1114 CLIENT_PROTOCOL_VERSION_MIN_LEGACY : CLIENT_PROTOCOL_VERSION_MIN;
1116 pkt << (u8) SER_FMT_VER_HIGHEST_READ;
1117 pkt.putRawString(playerName,PLAYERNAME_SIZE);
1118 pkt.putRawString(playerPassword, PASSWORD_SIZE);
1119 pkt << (u16) proto_version_min << (u16) CLIENT_PROTOCOL_VERSION_MAX;
1124 void Client::sendInit(const std::string &playerName)
1126 NetworkPacket pkt(TOSERVER_INIT, 1 + 2 + 2 + (1 + playerName.size()));
1128 // we don't support network compression yet
1129 u16 supp_comp_modes = NETPROTO_COMPRESSION_NONE;
1131 u16 proto_version_min = g_settings->getFlag("send_pre_v25_init") ?
1132 CLIENT_PROTOCOL_VERSION_MIN_LEGACY : CLIENT_PROTOCOL_VERSION_MIN;
1134 pkt << (u8) SER_FMT_VER_HIGHEST_READ << (u16) supp_comp_modes;
1135 pkt << (u16) proto_version_min << (u16) CLIENT_PROTOCOL_VERSION_MAX;
1141 void Client::startAuth(AuthMechanism chosen_auth_mechanism)
1143 m_chosen_auth_mech = chosen_auth_mechanism;
1145 switch (chosen_auth_mechanism) {
1146 case AUTH_MECHANISM_FIRST_SRP: {
1147 // send srp verifier to server
1148 std::string verifier;
1150 generate_srp_verifier_and_salt(getPlayerName(), m_password,
1153 NetworkPacket resp_pkt(TOSERVER_FIRST_SRP, 0);
1154 resp_pkt << salt << verifier << (u8)((m_password == "") ? 1 : 0);
1159 case AUTH_MECHANISM_SRP:
1160 case AUTH_MECHANISM_LEGACY_PASSWORD: {
1163 if (chosen_auth_mechanism == AUTH_MECHANISM_LEGACY_PASSWORD) {
1164 m_password = translate_password(getPlayerName(), m_password);
1168 std::string playername_u = lowercase(getPlayerName());
1169 m_auth_data = srp_user_new(SRP_SHA256, SRP_NG_2048,
1170 getPlayerName().c_str(), playername_u.c_str(),
1171 (const unsigned char *) m_password.c_str(),
1172 m_password.length(), NULL, NULL);
1175 SRP_Result res = srp_user_start_authentication(
1176 (struct SRPUser *) m_auth_data, NULL, NULL, 0,
1177 (unsigned char **) &bytes_A, &len_A);
1178 FATAL_ERROR_IF(res != SRP_OK, "Creating local SRP user failed.");
1180 NetworkPacket resp_pkt(TOSERVER_SRP_BYTES_A, 0);
1181 resp_pkt << std::string(bytes_A, len_A) << based_on;
1185 case AUTH_MECHANISM_NONE:
1186 break; // not handled in this method
1190 void Client::sendDeletedBlocks(std::vector<v3s16> &blocks)
1192 NetworkPacket pkt(TOSERVER_DELETEDBLOCKS, 1 + sizeof(v3s16) * blocks.size());
1194 pkt << (u8) blocks.size();
1197 for(std::vector<v3s16>::iterator
1199 j != blocks.end(); ++j) {
1207 void Client::sendGotBlocks(v3s16 block)
1209 NetworkPacket pkt(TOSERVER_GOTBLOCKS, 1 + 6);
1210 pkt << (u8) 1 << block;
1214 void Client::sendRemovedSounds(std::vector<s32> &soundList)
1216 size_t server_ids = soundList.size();
1217 assert(server_ids <= 0xFFFF);
1219 NetworkPacket pkt(TOSERVER_REMOVED_SOUNDS, 2 + server_ids * 4);
1221 pkt << (u16) (server_ids & 0xFFFF);
1223 for(std::vector<s32>::iterator i = soundList.begin();
1224 i != soundList.end(); ++i)
1230 void Client::sendNodemetaFields(v3s16 p, const std::string &formname,
1231 const StringMap &fields)
1233 size_t fields_size = fields.size();
1235 FATAL_ERROR_IF(fields_size > 0xFFFF, "Unsupported number of nodemeta fields");
1237 NetworkPacket pkt(TOSERVER_NODEMETA_FIELDS, 0);
1239 pkt << p << formname << (u16) (fields_size & 0xFFFF);
1241 StringMap::const_iterator it;
1242 for (it = fields.begin(); it != fields.end(); ++it) {
1243 const std::string &name = it->first;
1244 const std::string &value = it->second;
1246 pkt.putLongString(value);
1252 void Client::sendInventoryFields(const std::string &formname,
1253 const StringMap &fields)
1255 size_t fields_size = fields.size();
1256 FATAL_ERROR_IF(fields_size > 0xFFFF, "Unsupported number of inventory fields");
1258 NetworkPacket pkt(TOSERVER_INVENTORY_FIELDS, 0);
1259 pkt << formname << (u16) (fields_size & 0xFFFF);
1261 StringMap::const_iterator it;
1262 for (it = fields.begin(); it != fields.end(); ++it) {
1263 const std::string &name = it->first;
1264 const std::string &value = it->second;
1266 pkt.putLongString(value);
1272 void Client::sendInventoryAction(InventoryAction *a)
1274 std::ostringstream os(std::ios_base::binary);
1279 std::string s = os.str();
1281 NetworkPacket pkt(TOSERVER_INVENTORY_ACTION, s.size());
1282 pkt.putRawString(s.c_str(),s.size());
1287 void Client::sendChatMessage(const std::wstring &message)
1289 NetworkPacket pkt(TOSERVER_CHAT_MESSAGE, 2 + message.size() * sizeof(u16));
1296 void Client::sendChangePassword(const std::string &oldpassword,
1297 const std::string &newpassword)
1299 LocalPlayer *player = m_env.getLocalPlayer();
1303 std::string playername = player->getName();
1304 if (m_proto_ver >= 25) {
1305 // get into sudo mode and then send new password to server
1306 m_password = oldpassword;
1307 m_new_password = newpassword;
1308 startAuth(choseAuthMech(m_sudo_auth_methods));
1310 std::string oldpwd = translate_password(playername, oldpassword);
1311 std::string newpwd = translate_password(playername, newpassword);
1313 NetworkPacket pkt(TOSERVER_PASSWORD_LEGACY, 2 * PASSWORD_SIZE);
1315 for (u8 i = 0; i < PASSWORD_SIZE; i++) {
1316 pkt << (u8) (i < oldpwd.length() ? oldpwd[i] : 0);
1319 for (u8 i = 0; i < PASSWORD_SIZE; i++) {
1320 pkt << (u8) (i < newpwd.length() ? newpwd[i] : 0);
1327 void Client::sendDamage(u8 damage)
1329 DSTACK(FUNCTION_NAME);
1331 NetworkPacket pkt(TOSERVER_DAMAGE, sizeof(u8));
1336 void Client::sendBreath(u16 breath)
1338 DSTACK(FUNCTION_NAME);
1340 // Protocol v29 make this obsolete
1341 if (m_proto_ver >= 29)
1344 NetworkPacket pkt(TOSERVER_BREATH, sizeof(u16));
1349 void Client::sendRespawn()
1351 DSTACK(FUNCTION_NAME);
1353 NetworkPacket pkt(TOSERVER_RESPAWN, 0);
1357 void Client::sendReady()
1359 DSTACK(FUNCTION_NAME);
1361 NetworkPacket pkt(TOSERVER_CLIENT_READY,
1362 1 + 1 + 1 + 1 + 2 + sizeof(char) * strlen(g_version_hash));
1364 pkt << (u8) VERSION_MAJOR << (u8) VERSION_MINOR << (u8) VERSION_PATCH
1365 << (u8) 0 << (u16) strlen(g_version_hash);
1367 pkt.putRawString(g_version_hash, (u16) strlen(g_version_hash));
1371 void Client::sendPlayerPos()
1373 LocalPlayer *myplayer = m_env.getLocalPlayer();
1374 if(myplayer == NULL)
1377 ClientMap &map = m_env.getClientMap();
1379 u8 camera_fov = map.getCameraFov();
1380 u8 wanted_range = map.getControl().wanted_range;
1382 // Save bandwidth by only updating position when something changed
1383 if(myplayer->last_position == myplayer->getPosition() &&
1384 myplayer->last_speed == myplayer->getSpeed() &&
1385 myplayer->last_pitch == myplayer->getPitch() &&
1386 myplayer->last_yaw == myplayer->getYaw() &&
1387 myplayer->last_keyPressed == myplayer->keyPressed &&
1388 myplayer->last_camera_fov == camera_fov &&
1389 myplayer->last_wanted_range == wanted_range)
1392 myplayer->last_position = myplayer->getPosition();
1393 myplayer->last_speed = myplayer->getSpeed();
1394 myplayer->last_pitch = myplayer->getPitch();
1395 myplayer->last_yaw = myplayer->getYaw();
1396 myplayer->last_keyPressed = myplayer->keyPressed;
1397 myplayer->last_camera_fov = camera_fov;
1398 myplayer->last_wanted_range = wanted_range;
1400 //infostream << "Sending Player Position information" << std::endl;
1404 //MutexAutoLock lock(m_con_mutex); //bulk comment-out
1405 our_peer_id = m_con.GetPeerID();
1408 // Set peer id if not set already
1409 if(myplayer->peer_id == PEER_ID_INEXISTENT)
1410 myplayer->peer_id = our_peer_id;
1412 assert(myplayer->peer_id == our_peer_id);
1414 NetworkPacket pkt(TOSERVER_PLAYERPOS, 12 + 12 + 4 + 4 + 4 + 1 + 1);
1416 writePlayerPos(myplayer, &map, &pkt);
1421 void Client::sendPlayerItem(u16 item)
1423 LocalPlayer *myplayer = m_env.getLocalPlayer();
1424 if(myplayer == NULL)
1427 u16 our_peer_id = m_con.GetPeerID();
1429 // Set peer id if not set already
1430 if(myplayer->peer_id == PEER_ID_INEXISTENT)
1431 myplayer->peer_id = our_peer_id;
1432 assert(myplayer->peer_id == our_peer_id);
1434 NetworkPacket pkt(TOSERVER_PLAYERITEM, 2);
1441 void Client::removeNode(v3s16 p)
1443 std::map<v3s16, MapBlock*> modified_blocks;
1446 m_env.getMap().removeNodeAndUpdate(p, modified_blocks);
1448 catch(InvalidPositionException &e) {
1451 for(std::map<v3s16, MapBlock *>::iterator
1452 i = modified_blocks.begin();
1453 i != modified_blocks.end(); ++i) {
1454 addUpdateMeshTaskWithEdge(i->first, false, true);
1458 MapNode Client::getNode(v3s16 p, bool *is_valid_position)
1460 return m_env.getMap().getNodeNoEx(p, is_valid_position);
1463 void Client::addNode(v3s16 p, MapNode n, bool remove_metadata)
1465 //TimeTaker timer1("Client::addNode()");
1467 std::map<v3s16, MapBlock*> modified_blocks;
1470 //TimeTaker timer3("Client::addNode(): addNodeAndUpdate");
1471 m_env.getMap().addNodeAndUpdate(p, n, modified_blocks, remove_metadata);
1473 catch(InvalidPositionException &e) {
1476 for(std::map<v3s16, MapBlock *>::iterator
1477 i = modified_blocks.begin();
1478 i != modified_blocks.end(); ++i) {
1479 addUpdateMeshTaskWithEdge(i->first, false, true);
1483 void Client::setPlayerControl(PlayerControl &control)
1485 LocalPlayer *player = m_env.getLocalPlayer();
1486 assert(player != NULL);
1487 player->control = control;
1490 void Client::selectPlayerItem(u16 item)
1492 m_playeritem = item;
1493 m_inventory_updated = true;
1494 sendPlayerItem(item);
1497 // Returns true if the inventory of the local player has been
1498 // updated from the server. If it is true, it is set to false.
1499 bool Client::getLocalInventoryUpdated()
1501 bool updated = m_inventory_updated;
1502 m_inventory_updated = false;
1506 // Copies the inventory of the local player to parameter
1507 void Client::getLocalInventory(Inventory &dst)
1509 LocalPlayer *player = m_env.getLocalPlayer();
1510 assert(player != NULL);
1511 dst = player->inventory;
1514 Inventory* Client::getInventory(const InventoryLocation &loc)
1517 case InventoryLocation::UNDEFINED:
1520 case InventoryLocation::CURRENT_PLAYER:
1522 LocalPlayer *player = m_env.getLocalPlayer();
1523 assert(player != NULL);
1524 return &player->inventory;
1527 case InventoryLocation::PLAYER:
1529 // Check if we are working with local player inventory
1530 LocalPlayer *player = m_env.getLocalPlayer();
1531 if (!player || strcmp(player->getName(), loc.name.c_str()) != 0)
1533 return &player->inventory;
1536 case InventoryLocation::NODEMETA:
1538 NodeMetadata *meta = m_env.getMap().getNodeMetadata(loc.p);
1541 return meta->getInventory();
1544 case InventoryLocation::DETACHED:
1546 if (m_detached_inventories.count(loc.name) == 0)
1548 return m_detached_inventories[loc.name];
1552 FATAL_ERROR("Invalid inventory location type.");
1558 void Client::inventoryAction(InventoryAction *a)
1561 Send it to the server
1563 sendInventoryAction(a);
1566 Predict some local inventory changes
1568 a->clientApply(this, this);
1574 float Client::getAnimationTime()
1576 return m_animation_time;
1579 int Client::getCrackLevel()
1581 return m_crack_level;
1584 void Client::setCrack(int level, v3s16 pos)
1586 int old_crack_level = m_crack_level;
1587 v3s16 old_crack_pos = m_crack_pos;
1589 m_crack_level = level;
1592 if(old_crack_level >= 0 && (level < 0 || pos != old_crack_pos))
1595 addUpdateMeshTaskForNode(old_crack_pos, false, true);
1597 if(level >= 0 && (old_crack_level < 0 || pos != old_crack_pos))
1600 addUpdateMeshTaskForNode(pos, false, true);
1606 LocalPlayer *player = m_env.getLocalPlayer();
1607 assert(player != NULL);
1611 bool Client::getChatMessage(std::wstring &message)
1613 if(m_chat_queue.size() == 0)
1615 message = m_chat_queue.front();
1620 void Client::typeChatMessage(const std::wstring &message)
1622 // Discard empty line
1626 // If message was ate by script API, don't send it to server
1627 if (m_script->on_sending_message(wide_to_utf8(message))) {
1632 sendChatMessage(message);
1635 if (message[0] != L'/')
1637 // compatibility code
1638 if (m_proto_ver < 29) {
1639 LocalPlayer *player = m_env.getLocalPlayer();
1640 assert(player != NULL);
1641 std::wstring name = narrow_to_wide(player->getName());
1642 pushToChatQueue((std::wstring)L"<" + name + L"> " + message);
1647 void Client::addUpdateMeshTask(v3s16 p, bool ack_to_server, bool urgent)
1649 MapBlock *b = m_env.getMap().getBlockNoCreateNoEx(p);
1654 Create a task to update the mesh of the block
1657 MeshMakeData *data = new MeshMakeData(this, m_cache_enable_shaders,
1658 m_cache_use_tangent_vertices);
1661 //TimeTaker timer("data fill");
1663 // Debug: 1-6ms, avg=2ms
1665 data->setCrack(m_crack_level, m_crack_pos);
1666 data->setSmoothLighting(m_cache_smooth_lighting);
1669 // Add task to queue
1670 m_mesh_update_thread.enqueueUpdate(p, data, ack_to_server, urgent);
1673 void Client::addUpdateMeshTaskWithEdge(v3s16 blockpos, bool ack_to_server, bool urgent)
1676 addUpdateMeshTask(blockpos, ack_to_server, urgent);
1678 catch(InvalidPositionException &e){}
1681 for (int i=0;i<6;i++)
1684 v3s16 p = blockpos + g_6dirs[i];
1685 addUpdateMeshTask(p, false, urgent);
1687 catch(InvalidPositionException &e){}
1691 void Client::addUpdateMeshTaskForNode(v3s16 nodepos, bool ack_to_server, bool urgent)
1695 infostream<<"Client::addUpdateMeshTaskForNode(): "
1696 <<"("<<p.X<<","<<p.Y<<","<<p.Z<<")"
1700 v3s16 blockpos = getNodeBlockPos(nodepos);
1701 v3s16 blockpos_relative = blockpos * MAP_BLOCKSIZE;
1704 addUpdateMeshTask(blockpos, ack_to_server, urgent);
1706 catch(InvalidPositionException &e) {}
1709 if(nodepos.X == blockpos_relative.X){
1711 v3s16 p = blockpos + v3s16(-1,0,0);
1712 addUpdateMeshTask(p, false, urgent);
1714 catch(InvalidPositionException &e){}
1717 if(nodepos.Y == blockpos_relative.Y){
1719 v3s16 p = blockpos + v3s16(0,-1,0);
1720 addUpdateMeshTask(p, false, urgent);
1722 catch(InvalidPositionException &e){}
1725 if(nodepos.Z == blockpos_relative.Z){
1727 v3s16 p = blockpos + v3s16(0,0,-1);
1728 addUpdateMeshTask(p, false, urgent);
1730 catch(InvalidPositionException &e){}
1734 ClientEvent Client::getClientEvent()
1737 if (m_client_event_queue.empty()) {
1738 event.type = CE_NONE;
1741 event = m_client_event_queue.front();
1742 m_client_event_queue.pop();
1747 float Client::mediaReceiveProgress()
1749 if (m_media_downloader)
1750 return m_media_downloader->getProgress();
1752 return 1.0; // downloader only exists when not yet done
1755 typedef struct TextureUpdateArgs {
1756 IrrlichtDevice *device;
1757 gui::IGUIEnvironment *guienv;
1760 const wchar_t* text_base;
1761 } TextureUpdateArgs;
1763 void texture_update_progress(void *args, u32 progress, u32 max_progress)
1765 TextureUpdateArgs* targs = (TextureUpdateArgs*) args;
1766 u16 cur_percent = ceil(progress / (double) max_progress * 100.);
1768 // update the loading menu -- if neccessary
1769 bool do_draw = false;
1770 u32 time_ms = targs->last_time_ms;
1771 if (cur_percent != targs->last_percent) {
1772 targs->last_percent = cur_percent;
1773 time_ms = getTimeMs();
1774 // only draw when the user will notice something:
1775 do_draw = (time_ms - targs->last_time_ms > 100);
1779 targs->last_time_ms = time_ms;
1780 std::basic_stringstream<wchar_t> strm;
1781 strm << targs->text_base << " " << targs->last_percent << "%...";
1782 draw_load_screen(strm.str(), targs->device, targs->guienv, 0,
1783 72 + (u16) ((18. / 100.) * (double) targs->last_percent));
1787 void Client::afterContentReceived(IrrlichtDevice *device)
1789 infostream<<"Client::afterContentReceived() started"<<std::endl;
1790 assert(m_itemdef_received); // pre-condition
1791 assert(m_nodedef_received); // pre-condition
1792 assert(mediaReceived()); // pre-condition
1794 const wchar_t* text = wgettext("Loading textures...");
1796 // Clear cached pre-scaled 2D GUI images, as this cache
1797 // might have images with the same name but different
1798 // content from previous sessions.
1799 guiScalingCacheClear(device->getVideoDriver());
1801 // Rebuild inherited images and recreate textures
1802 infostream<<"- Rebuilding images and textures"<<std::endl;
1803 draw_load_screen(text,device, guienv, 0, 70);
1804 m_tsrc->rebuildImagesAndTextures();
1808 infostream<<"- Rebuilding shaders"<<std::endl;
1809 text = wgettext("Rebuilding shaders...");
1810 draw_load_screen(text, device, guienv, 0, 71);
1811 m_shsrc->rebuildShaders();
1814 // Update node aliases
1815 infostream<<"- Updating node aliases"<<std::endl;
1816 text = wgettext("Initializing nodes...");
1817 draw_load_screen(text, device, guienv, 0, 72);
1818 m_nodedef->updateAliases(m_itemdef);
1819 std::string texture_path = g_settings->get("texture_path");
1820 if (texture_path != "" && fs::IsDir(texture_path))
1821 m_nodedef->applyTextureOverrides(texture_path + DIR_DELIM + "override.txt");
1822 m_nodedef->setNodeRegistrationStatus(true);
1823 m_nodedef->runNodeResolveCallbacks();
1826 // Update node textures and assign shaders to each tile
1827 infostream<<"- Updating node textures"<<std::endl;
1828 TextureUpdateArgs tu_args;
1829 tu_args.device = device;
1830 tu_args.guienv = guienv;
1831 tu_args.last_time_ms = getTimeMs();
1832 tu_args.last_percent = 0;
1833 tu_args.text_base = wgettext("Initializing nodes");
1834 m_nodedef->updateTextures(this, texture_update_progress, &tu_args);
1835 delete[] tu_args.text_base;
1837 // Start mesh update thread after setting up content definitions
1838 infostream<<"- Starting mesh update thread"<<std::endl;
1839 m_mesh_update_thread.start();
1843 text = wgettext("Done!");
1844 draw_load_screen(text, device, guienv, 0, 100);
1845 infostream<<"Client::afterContentReceived() done"<<std::endl;
1849 float Client::getRTT(void)
1851 return m_con.getPeerStat(PEER_ID_SERVER,con::AVG_RTT);
1854 float Client::getCurRate(void)
1856 return ( m_con.getLocalStat(con::CUR_INC_RATE) +
1857 m_con.getLocalStat(con::CUR_DL_RATE));
1860 float Client::getAvgRate(void)
1862 return ( m_con.getLocalStat(con::AVG_INC_RATE) +
1863 m_con.getLocalStat(con::AVG_DL_RATE));
1866 void Client::makeScreenshot(IrrlichtDevice *device)
1868 irr::video::IVideoDriver *driver = device->getVideoDriver();
1869 irr::video::IImage* const raw_image = driver->createScreenShot();
1874 time_t t = time(NULL);
1875 struct tm *tm = localtime(&t);
1877 char timetstamp_c[64];
1878 strftime(timetstamp_c, sizeof(timetstamp_c), "%Y%m%d_%H%M%S", tm);
1880 std::string filename_base = g_settings->get("screenshot_path")
1882 + std::string("screenshot_")
1883 + std::string(timetstamp_c);
1884 std::string filename_ext = "." + g_settings->get("screenshot_format");
1885 std::string filename;
1887 u32 quality = (u32)g_settings->getS32("screenshot_quality");
1888 quality = MYMIN(MYMAX(quality, 0), 100) / 100.0 * 255;
1890 // Try to find a unique filename
1891 unsigned serial = 0;
1893 while (serial < SCREENSHOT_MAX_SERIAL_TRIES) {
1894 filename = filename_base + (serial > 0 ? ("_" + itos(serial)) : "") + filename_ext;
1895 std::ifstream tmp(filename.c_str());
1897 break; // File did not apparently exist, we'll go with it
1901 if (serial == SCREENSHOT_MAX_SERIAL_TRIES) {
1902 infostream << "Could not find suitable filename for screenshot" << std::endl;
1904 irr::video::IImage* const image =
1905 driver->createImage(video::ECF_R8G8B8, raw_image->getDimension());
1908 raw_image->copyTo(image);
1910 std::ostringstream sstr;
1911 if (driver->writeImageToFile(image, filename.c_str(), quality)) {
1912 sstr << "Saved screenshot to '" << filename << "'";
1914 sstr << "Failed to save screenshot '" << filename << "'";
1916 pushToChatQueue(narrow_to_wide(sstr.str()));
1917 infostream << sstr.str() << std::endl;
1925 // IGameDef interface
1927 IItemDefManager* Client::getItemDefManager()
1931 INodeDefManager* Client::getNodeDefManager()
1935 ICraftDefManager* Client::getCraftDefManager()
1938 //return m_craftdef;
1940 ITextureSource* Client::getTextureSource()
1944 IShaderSource* Client::getShaderSource()
1948 scene::ISceneManager* Client::getSceneManager()
1950 return m_device->getSceneManager();
1952 u16 Client::allocateUnknownNodeId(const std::string &name)
1954 errorstream << "Client::allocateUnknownNodeId(): "
1955 << "Client cannot allocate node IDs" << std::endl;
1956 FATAL_ERROR("Client allocated unknown node");
1958 return CONTENT_IGNORE;
1960 ISoundManager* Client::getSoundManager()
1964 MtEventManager* Client::getEventManager()
1969 ParticleManager* Client::getParticleManager()
1971 return &m_particle_manager;
1974 scene::IAnimatedMesh* Client::getMesh(const std::string &filename)
1976 StringMap::const_iterator it = m_mesh_data.find(filename);
1977 if (it == m_mesh_data.end()) {
1978 errorstream << "Client::getMesh(): Mesh not found: \"" << filename
1979 << "\"" << std::endl;
1982 const std::string &data = it->second;
1983 scene::ISceneManager *smgr = m_device->getSceneManager();
1985 // Create the mesh, remove it from cache and return it
1986 // This allows unique vertex colors and other properties for each instance
1987 Buffer<char> data_rw(data.c_str(), data.size()); // Const-incorrect Irrlicht
1988 io::IFileSystem *irrfs = m_device->getFileSystem();
1989 io::IReadFile *rfile = irrfs->createMemoryReadFile(
1990 *data_rw, data_rw.getSize(), filename.c_str());
1991 FATAL_ERROR_IF(!rfile, "Could not create/open RAM file");
1993 scene::IAnimatedMesh *mesh = smgr->getMesh(rfile);
1995 // NOTE: By playing with Irrlicht refcounts, maybe we could cache a bunch
1996 // of uniquely named instances and re-use them
1998 smgr->getMeshCache()->removeMesh(mesh);