]> git.lizzy.rs Git - minetest.git/blob - src/client/client.cpp
Handle mesh load failure without crashing
[minetest.git] / src / client / client.cpp
1 /*
2 Minetest
3 Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com>
4
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.
9
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.
14
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.
18 */
19
20 #include <iostream>
21 #include <algorithm>
22 #include <sstream>
23 #include <cmath>
24 #include <IFileSystem.h>
25 #include "client.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"
40 #include "util/srp.h"
41 #include "filesys.h"
42 #include "mapblock_mesh.h"
43 #include "mapblock.h"
44 #include "minimap.h"
45 #include "modchannels.h"
46 #include "content/mods.h"
47 #include "profiler.h"
48 #include "shader.h"
49 #include "gettext.h"
50 #include "clientmap.h"
51 #include "clientmedia.h"
52 #include "version.h"
53 #include "database/database-sqlite3.h"
54 #include "serialization.h"
55 #include "guiscalingfilter.h"
56 #include "script/scripting_client.h"
57 #include "game.h"
58 #include "chatmessage.h"
59 #include "translation.h"
60
61 extern gui::IGUIEnvironment* guienv;
62
63 /*
64         Utility classes
65 */
66
67 u32 PacketCounter::sum() const
68 {
69         u32 n = 0;
70         for (const auto &it : m_packets)
71                 n += it.second;
72         return n;
73 }
74
75 void PacketCounter::print(std::ostream &o) const
76 {
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;
82         }
83 }
84
85 /*
86         Client
87 */
88
89 Client::Client(
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,
98                 ISoundManager *sound,
99                 MtEventManager *event,
100                 bool ipv6,
101                 GameUI *game_ui
102 ):
103         m_tsrc(tsrc),
104         m_shsrc(shsrc),
105         m_itemdef(itemdef),
106         m_nodedef(nodedef),
107         m_sound(sound),
108         m_event(event),
109         m_mesh_update_thread(this),
110         m_env(
111                 new ClientMap(this, control, 666),
112                 tsrc, this
113         ),
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()),
122         m_state(LC_Created),
123         m_game_ui(game_ui),
124         m_modchannel_mgr(new ModChannelMgr())
125 {
126         // Add local player
127         m_env.setLocalPlayer(new LocalPlayer(this, playername));
128
129         if (g_settings->getBool("enable_minimap")) {
130                 m_minimap = new Minimap(this);
131         }
132
133         m_cache_save_interval = g_settings->getU16("server_map_save_interval");
134 }
135
136 void Client::loadMods()
137 {
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"))
142                 return;
143
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
147         // complete.
148         if (checkCSMRestrictionFlag(CSMRestrictionFlags::CSM_RF_LOAD_CLIENT_MODS)) {
149                 warningstream << "Client-provided mod loading is disabled by server." <<
150                         std::endl;
151                 return;
152         }
153
154         m_script = new ClientScripting(this);
155         m_env.setScript(m_script);
156         m_script->setEnv(&m_env);
157
158         // Load builtin
159         scanModIntoMemory(BUILTIN_MOD_NAME, getBuiltinLuaPath());
160         m_script->loadModFromMemory(BUILTIN_MOD_NAME);
161
162         ClientModConfiguration modconf(getClientModsLuaPath());
163         m_mods = modconf.getMods();
164         // complain about mods with unsatisfied dependencies
165         if (!modconf.isConsistent()) {
166                 modconf.printUnsatisfiedModsError();
167                 return;
168         }
169
170         // Print mods
171         infostream << "Client loading mods: ";
172         for (const ModSpec &mod : m_mods)
173                 infostream << mod.name << " ";
174         infostream << std::endl;
175
176         // Load "mod" scripts
177         for (const ModSpec &mod : m_mods) {
178                 if (!string_allowed(mod.name, MODNAME_ALLOWED_CHARS)) {
179                         throw ModError("Error loading mod \"" + mod.name +
180                                 "\": Mod name does not follow naming conventions: "
181                                         "Only characters [a-z0-9_] are allowed.");
182                 }
183                 scanModIntoMemory(mod.name, mod.path);
184         }
185
186         // Run them
187         for (const ModSpec &mod : m_mods)
188                 m_script->loadModFromMemory(mod.name);
189
190         // Mods are done loading. Unlock callbacks
191         m_mods_loaded = true;
192
193         // Run a callback when mods are loaded
194         m_script->on_mods_loaded();
195
196         // Create objects if they're ready
197         if (m_state == LC_Ready)
198                 m_script->on_client_ready(m_env.getLocalPlayer());
199         if (m_camera)
200                 m_script->on_camera_ready(m_camera);
201         if (m_minimap)
202                 m_script->on_minimap_ready(m_minimap);
203 }
204
205 void Client::scanModSubfolder(const std::string &mod_name, const std::string &mod_path,
206                         std::string mod_subpath)
207 {
208         std::string full_path = mod_path + DIR_DELIM + mod_subpath;
209         std::vector<fs::DirListNode> mod = fs::GetDirListing(full_path);
210         for (const fs::DirListNode &j : mod) {
211                 if (j.dir) {
212                         scanModSubfolder(mod_name, mod_path, mod_subpath + j.name + DIR_DELIM);
213                         continue;
214                 }
215                 std::replace(mod_subpath.begin(), mod_subpath.end(), DIR_DELIM_CHAR, '/');
216
217                 std::string real_path = full_path + j.name;
218                 std::string vfs_path = mod_name + ":" + mod_subpath + j.name;
219                 infostream << "Client::scanModSubfolder(): Loading \"" << real_path
220                                 << "\" as \"" << vfs_path << "\"." << std::endl;
221
222                 std::string contents;
223                 if (!fs::ReadFile(real_path, contents)) {
224                         errorstream << "Client::scanModSubfolder(): Can't read file \""
225                                         << real_path << "\"." << std::endl;
226                         continue;
227                 }
228
229                 m_mod_vfs.emplace(vfs_path, contents);
230         }
231 }
232
233 const std::string &Client::getBuiltinLuaPath()
234 {
235         static const std::string builtin_dir = porting::path_share + DIR_DELIM + "builtin";
236         return builtin_dir;
237 }
238
239 const std::string &Client::getClientModsLuaPath()
240 {
241         static const std::string clientmods_dir = porting::path_share + DIR_DELIM + "clientmods";
242         return clientmods_dir;
243 }
244
245 const std::vector<ModSpec>& Client::getMods() const
246 {
247         static std::vector<ModSpec> client_modspec_temp;
248         return client_modspec_temp;
249 }
250
251 const ModSpec* Client::getModSpec(const std::string &modname) const
252 {
253         return NULL;
254 }
255
256 void Client::Stop()
257 {
258         m_shutdown = true;
259         if (m_mods_loaded)
260                 m_script->on_shutdown();
261         //request all client managed threads to stop
262         m_mesh_update_thread.stop();
263         // Save local server map
264         if (m_localdb) {
265                 infostream << "Local map saving ended." << std::endl;
266                 m_localdb->endSave();
267         }
268
269         if (m_mods_loaded)
270                 delete m_script;
271 }
272
273 bool Client::isShutdown()
274 {
275         return m_shutdown || !m_mesh_update_thread.isRunning();
276 }
277
278 Client::~Client()
279 {
280         m_shutdown = true;
281         m_con->Disconnect();
282
283         deleteAuthData();
284
285         m_mesh_update_thread.stop();
286         m_mesh_update_thread.wait();
287         while (!m_mesh_update_thread.m_queue_out.empty()) {
288                 MeshUpdateResult r = m_mesh_update_thread.m_queue_out.pop_frontNoEx();
289                 delete r.mesh;
290         }
291
292
293         delete m_inventory_from_server;
294
295         // Delete detached inventories
296         for (auto &m_detached_inventorie : m_detached_inventories) {
297                 delete m_detached_inventorie.second;
298         }
299
300         // cleanup 3d model meshes on client shutdown
301         while (RenderingEngine::get_mesh_cache()->getMeshCount() != 0) {
302                 scene::IAnimatedMesh *mesh = RenderingEngine::get_mesh_cache()->getMeshByIndex(0);
303
304                 if (mesh)
305                         RenderingEngine::get_mesh_cache()->removeMesh(mesh);
306         }
307
308         delete m_minimap;
309         m_minimap = nullptr;
310
311         delete m_media_downloader;
312 }
313
314 void Client::connect(Address address, bool is_local_server)
315 {
316         initLocalMapSaving(address, m_address_name, is_local_server);
317
318         // Since we use TryReceive() a timeout here would be ineffective anyway
319         m_con->SetTimeoutMs(0);
320         m_con->Connect(address);
321 }
322
323 void Client::step(float dtime)
324 {
325         // Limit a bit
326         if (dtime > 2.0)
327                 dtime = 2.0;
328
329         m_animation_time += dtime;
330         if(m_animation_time > 60.0)
331                 m_animation_time -= 60.0;
332
333         m_time_of_day_update_timer += dtime;
334
335         ReceiveAll();
336
337         /*
338                 Packet counter
339         */
340         {
341                 float &counter = m_packetcounter_timer;
342                 counter -= dtime;
343                 if(counter <= 0.0f)
344                 {
345                         counter = 30.0f;
346                         u32 sum = m_packetcounter.sum();
347                         float avg = sum / counter;
348
349                         infostream << "Client packetcounter (" << counter << "s): "
350                                         << "sum=" << sum << " avg=" << avg << "/s" << std::endl;
351                         m_packetcounter.print(infostream);
352                         m_packetcounter.clear();
353                 }
354         }
355
356         // UGLY hack to fix 2 second startup delay caused by non existent
357         // server client startup synchronization in local server or singleplayer mode
358         static bool initial_step = true;
359         if (initial_step) {
360                 initial_step = false;
361         }
362         else if(m_state == LC_Created) {
363                 if (m_is_registration_confirmation_state) {
364                         // Waiting confirmation
365                         return;
366                 }
367                 float &counter = m_connection_reinit_timer;
368                 counter -= dtime;
369                 if(counter <= 0.0) {
370                         counter = 2.0;
371
372                         LocalPlayer *myplayer = m_env.getLocalPlayer();
373                         FATAL_ERROR_IF(myplayer == NULL, "Local player not found in environment.");
374
375                         sendInit(myplayer->getName());
376                 }
377
378                 // Not connected, return
379                 return;
380         }
381
382         /*
383                 Do stuff if connected
384         */
385
386         /*
387                 Run Map's timers and unload unused data
388         */
389         const float map_timer_and_unload_dtime = 5.25;
390         if(m_map_timer_and_unload_interval.step(dtime, map_timer_and_unload_dtime)) {
391                 std::vector<v3s16> deleted_blocks;
392                 m_env.getMap().timerUpdate(map_timer_and_unload_dtime,
393                         g_settings->getFloat("client_unload_unused_data_timeout"),
394                         g_settings->getS32("client_mapblock_limit"),
395                         &deleted_blocks);
396
397                 /*
398                         Send info to server
399                         NOTE: This loop is intentionally iterated the way it is.
400                 */
401
402                 std::vector<v3s16>::iterator i = deleted_blocks.begin();
403                 std::vector<v3s16> sendlist;
404                 for(;;) {
405                         if(sendlist.size() == 255 || i == deleted_blocks.end()) {
406                                 if(sendlist.empty())
407                                         break;
408                                 /*
409                                         [0] u16 command
410                                         [2] u8 count
411                                         [3] v3s16 pos_0
412                                         [3+6] v3s16 pos_1
413                                         ...
414                                 */
415
416                                 sendDeletedBlocks(sendlist);
417
418                                 if(i == deleted_blocks.end())
419                                         break;
420
421                                 sendlist.clear();
422                         }
423
424                         sendlist.push_back(*i);
425                         ++i;
426                 }
427         }
428
429         /*
430                 Send pending messages on out chat queue
431         */
432         if (!m_out_chat_queue.empty() && canSendChatMessage()) {
433                 sendChatMessage(m_out_chat_queue.front());
434                 m_out_chat_queue.pop();
435         }
436
437         /*
438                 Handle environment
439         */
440         LocalPlayer *player = m_env.getLocalPlayer();
441
442         // Step environment (also handles player controls)
443         m_env.step(dtime);
444         m_sound->step(dtime);
445
446         /*
447                 Get events
448         */
449         while (m_env.hasClientEnvEvents()) {
450                 ClientEnvEvent envEvent = m_env.getClientEnvEvent();
451
452                 if (envEvent.type == CEE_PLAYER_DAMAGE) {
453                         u16 damage = envEvent.player_damage.amount;
454
455                         if (envEvent.player_damage.send_to_server)
456                                 sendDamage(damage);
457
458                         // Add to ClientEvent queue
459                         ClientEvent *event = new ClientEvent();
460                         event->type = CE_PLAYER_DAMAGE;
461                         event->player_damage.amount = damage;
462                         m_client_event_queue.push(event);
463                 }
464         }
465
466         /*
467                 Print some info
468         */
469         float &counter = m_avg_rtt_timer;
470         counter += dtime;
471         if(counter >= 10) {
472                 counter = 0.0;
473                 // connectedAndInitialized() is true, peer exists.
474                 float avg_rtt = getRTT();
475                 infostream << "Client: avg_rtt=" << avg_rtt << std::endl;
476         }
477
478         /*
479                 Send player position to server
480         */
481         {
482                 float &counter = m_playerpos_send_timer;
483                 counter += dtime;
484                 if((m_state == LC_Ready) && (counter >= m_recommended_send_interval))
485                 {
486                         counter = 0.0;
487                         sendPlayerPos();
488                 }
489         }
490
491         /*
492                 Replace updated meshes
493         */
494         {
495                 int num_processed_meshes = 0;
496                 std::vector<v3s16> blocks_to_ack;
497                 while (!m_mesh_update_thread.m_queue_out.empty())
498                 {
499                         num_processed_meshes++;
500
501                         MinimapMapblock *minimap_mapblock = NULL;
502                         bool do_mapper_update = true;
503
504                         MeshUpdateResult r = m_mesh_update_thread.m_queue_out.pop_frontNoEx();
505                         MapBlock *block = m_env.getMap().getBlockNoCreateNoEx(r.p);
506                         if (block) {
507                                 // Delete the old mesh
508                                 delete block->mesh;
509                                 block->mesh = nullptr;
510
511                                 if (r.mesh) {
512                                         minimap_mapblock = r.mesh->moveMinimapMapblock();
513                                         if (minimap_mapblock == NULL)
514                                                 do_mapper_update = false;
515
516                                         bool is_empty = true;
517                                         for (int l = 0; l < MAX_TILE_LAYERS; l++)
518                                                 if (r.mesh->getMesh(l)->getMeshBufferCount() != 0)
519                                                         is_empty = false;
520
521                                         if (is_empty)
522                                                 delete r.mesh;
523                                         else
524                                                 // Replace with the new mesh
525                                                 block->mesh = r.mesh;
526                                 }
527                         } else {
528                                 delete r.mesh;
529                         }
530
531                         if (m_minimap && do_mapper_update)
532                                 m_minimap->addBlock(r.p, minimap_mapblock);
533
534                         if (r.ack_block_to_server) {
535                                 if (blocks_to_ack.size() == 255) {
536                                         sendGotBlocks(blocks_to_ack);
537                                         blocks_to_ack.clear();
538                                 }
539
540                                 blocks_to_ack.emplace_back(r.p);
541                         }
542                 }
543                 if (blocks_to_ack.size() > 0) {
544                                 // Acknowledge block(s)
545                                 sendGotBlocks(blocks_to_ack);
546                 }
547
548                 if (num_processed_meshes > 0)
549                         g_profiler->graphAdd("num_processed_meshes", num_processed_meshes);
550         }
551
552         /*
553                 Load fetched media
554         */
555         if (m_media_downloader && m_media_downloader->isStarted()) {
556                 m_media_downloader->step(this);
557                 if (m_media_downloader->isDone()) {
558                         delete m_media_downloader;
559                         m_media_downloader = NULL;
560                 }
561         }
562
563         /*
564                 If the server didn't update the inventory in a while, revert
565                 the local inventory (so the player notices the lag problem
566                 and knows something is wrong).
567         */
568         if (m_inventory_from_server) {
569                 float interval = 10.0f;
570                 float count_before = std::floor(m_inventory_from_server_age / interval);
571
572                 m_inventory_from_server_age += dtime;
573
574                 float count_after = std::floor(m_inventory_from_server_age / interval);
575
576                 if (count_after != count_before) {
577                         // Do this every <interval> seconds after TOCLIENT_INVENTORY
578                         // Reset the locally changed inventory to the authoritative inventory
579                         player->inventory = *m_inventory_from_server;
580                         m_update_wielded_item = true;
581                 }
582         }
583
584         /*
585                 Update positions of sounds attached to objects
586         */
587         {
588                 for (auto &m_sounds_to_object : m_sounds_to_objects) {
589                         int client_id = m_sounds_to_object.first;
590                         u16 object_id = m_sounds_to_object.second;
591                         ClientActiveObject *cao = m_env.getActiveObject(object_id);
592                         if (!cao)
593                                 continue;
594                         m_sound->updateSoundPosition(client_id, cao->getPosition());
595                 }
596         }
597
598         /*
599                 Handle removed remotely initiated sounds
600         */
601         m_removed_sounds_check_timer += dtime;
602         if(m_removed_sounds_check_timer >= 2.32) {
603                 m_removed_sounds_check_timer = 0;
604                 // Find removed sounds and clear references to them
605                 std::vector<s32> removed_server_ids;
606                 for (std::unordered_map<s32, int>::iterator i = m_sounds_server_to_client.begin();
607                                 i != m_sounds_server_to_client.end();) {
608                         s32 server_id = i->first;
609                         int client_id = i->second;
610                         ++i;
611                         if(!m_sound->soundExists(client_id)) {
612                                 m_sounds_server_to_client.erase(server_id);
613                                 m_sounds_client_to_server.erase(client_id);
614                                 m_sounds_to_objects.erase(client_id);
615                                 removed_server_ids.push_back(server_id);
616                         }
617                 }
618
619                 // Sync to server
620                 if(!removed_server_ids.empty()) {
621                         sendRemovedSounds(removed_server_ids);
622                 }
623         }
624
625         m_mod_storage_save_timer -= dtime;
626         if (m_mod_storage_save_timer <= 0.0f) {
627                 m_mod_storage_save_timer = g_settings->getFloat("server_map_save_interval");
628                 int n = 0;
629                 for (std::unordered_map<std::string, ModMetadata *>::const_iterator
630                                 it = m_mod_storages.begin(); it != m_mod_storages.end(); ++it) {
631                         if (it->second->isModified()) {
632                                 it->second->save(getModStoragePath());
633                                 n++;
634                         }
635                 }
636                 if (n > 0)
637                         infostream << "Saved " << n << " modified mod storages." << std::endl;
638         }
639
640         // Write server map
641         if (m_localdb && m_localdb_save_interval.step(dtime,
642                         m_cache_save_interval)) {
643                 m_localdb->endSave();
644                 m_localdb->beginSave();
645         }
646 }
647
648 bool Client::loadMedia(const std::string &data, const std::string &filename,
649         bool from_media_push)
650 {
651         std::string name;
652
653         const char *image_ext[] = {
654                 ".png", ".jpg", ".bmp", ".tga",
655                 ".pcx", ".ppm", ".psd", ".wal", ".rgb",
656                 NULL
657         };
658         name = removeStringEnd(filename, image_ext);
659         if (!name.empty()) {
660                 TRACESTREAM(<< "Client: Attempting to load image "
661                         << "file \"" << filename << "\"" << std::endl);
662
663                 io::IFileSystem *irrfs = RenderingEngine::get_filesystem();
664                 video::IVideoDriver *vdrv = RenderingEngine::get_video_driver();
665
666                 // Silly irrlicht's const-incorrectness
667                 Buffer<char> data_rw(data.c_str(), data.size());
668
669                 // Create an irrlicht memory file
670                 io::IReadFile *rfile = irrfs->createMemoryReadFile(
671                                 *data_rw, data_rw.getSize(), "_tempreadfile");
672
673                 FATAL_ERROR_IF(!rfile, "Could not create irrlicht memory file.");
674
675                 // Read image
676                 video::IImage *img = vdrv->createImageFromFile(rfile);
677                 if (!img) {
678                         errorstream<<"Client: Cannot create image from data of "
679                                         <<"file \""<<filename<<"\""<<std::endl;
680                         rfile->drop();
681                         return false;
682                 }
683
684                 m_tsrc->insertSourceImage(filename, img);
685                 img->drop();
686                 rfile->drop();
687                 return true;
688         }
689
690         const char *sound_ext[] = {
691                 ".0.ogg", ".1.ogg", ".2.ogg", ".3.ogg", ".4.ogg",
692                 ".5.ogg", ".6.ogg", ".7.ogg", ".8.ogg", ".9.ogg",
693                 ".ogg", NULL
694         };
695         name = removeStringEnd(filename, sound_ext);
696         if (!name.empty()) {
697                 TRACESTREAM(<< "Client: Attempting to load sound "
698                         << "file \"" << filename << "\"" << std::endl);
699                 return m_sound->loadSoundData(name, data);
700         }
701
702         const char *model_ext[] = {
703                 ".x", ".b3d", ".md2", ".obj",
704                 NULL
705         };
706         name = removeStringEnd(filename, model_ext);
707         if (!name.empty()) {
708                 verbosestream<<"Client: Storing model into memory: "
709                                 <<"\""<<filename<<"\""<<std::endl;
710                 if(m_mesh_data.count(filename))
711                         errorstream<<"Multiple models with name \""<<filename.c_str()
712                                         <<"\" found; replacing previous model"<<std::endl;
713                 m_mesh_data[filename] = data;
714                 return true;
715         }
716
717         const char *translate_ext[] = {
718                 ".tr", NULL
719         };
720         name = removeStringEnd(filename, translate_ext);
721         if (!name.empty()) {
722                 if (from_media_push)
723                         return false;
724                 TRACESTREAM(<< "Client: Loading translation: "
725                                 << "\"" << filename << "\"" << std::endl);
726                 g_client_translations->loadTranslation(data);
727                 return true;
728         }
729
730         errorstream << "Client: Don't know how to load file \""
731                 << filename << "\"" << std::endl;
732         return false;
733 }
734
735 // Virtual methods from con::PeerHandler
736 void Client::peerAdded(con::Peer *peer)
737 {
738         infostream << "Client::peerAdded(): peer->id="
739                         << peer->id << std::endl;
740 }
741 void Client::deletingPeer(con::Peer *peer, bool timeout)
742 {
743         infostream << "Client::deletingPeer(): "
744                         "Server Peer is getting deleted "
745                         << "(timeout=" << timeout << ")" << std::endl;
746
747         if (timeout) {
748                 m_access_denied = true;
749                 m_access_denied_reason = gettext("Connection timed out.");
750         }
751 }
752
753 /*
754         u16 command
755         u16 number of files requested
756         for each file {
757                 u16 length of name
758                 string name
759         }
760 */
761 void Client::request_media(const std::vector<std::string> &file_requests)
762 {
763         std::ostringstream os(std::ios_base::binary);
764         writeU16(os, TOSERVER_REQUEST_MEDIA);
765         size_t file_requests_size = file_requests.size();
766
767         FATAL_ERROR_IF(file_requests_size > 0xFFFF, "Unsupported number of file requests");
768
769         // Packet dynamicly resized
770         NetworkPacket pkt(TOSERVER_REQUEST_MEDIA, 2 + 0);
771
772         pkt << (u16) (file_requests_size & 0xFFFF);
773
774         for (const std::string &file_request : file_requests) {
775                 pkt << file_request;
776         }
777
778         Send(&pkt);
779
780         infostream << "Client: Sending media request list to server ("
781                         << file_requests.size() << " files. packet size)" << std::endl;
782 }
783
784 void Client::initLocalMapSaving(const Address &address,
785                 const std::string &hostname,
786                 bool is_local_server)
787 {
788         if (!g_settings->getBool("enable_local_map_saving") || is_local_server) {
789                 return;
790         }
791
792         std::string world_path;
793 #define set_world_path(hostname) \
794         world_path = porting::path_user \
795                 + DIR_DELIM + "worlds" \
796                 + DIR_DELIM + "server_" \
797                 + hostname + "_" + std::to_string(address.getPort());
798
799         set_world_path(hostname);
800         if (!fs::IsDir(world_path)) {
801                 std::string hostname_escaped = hostname;
802                 str_replace(hostname_escaped, ':', '_');
803                 set_world_path(hostname_escaped);
804         }
805 #undef set_world_path
806         fs::CreateAllDirs(world_path);
807
808         m_localdb = new MapDatabaseSQLite3(world_path);
809         m_localdb->beginSave();
810         actionstream << "Local map saving started, map will be saved at '" << world_path << "'" << std::endl;
811 }
812
813 void Client::ReceiveAll()
814 {
815         NetworkPacket pkt;
816         u64 start_ms = porting::getTimeMs();
817         const u64 budget = 100;
818         for(;;) {
819                 // Limit time even if there would be huge amounts of data to
820                 // process
821                 if (porting::getTimeMs() > start_ms + budget) {
822                         infostream << "Client::ReceiveAll(): "
823                                         "Packet processing budget exceeded." << std::endl;
824                         break;
825                 }
826
827                 pkt.clear();
828                 try {
829                         if (!m_con->TryReceive(&pkt))
830                                 break;
831                         ProcessData(&pkt);
832                 } catch (const con::InvalidIncomingDataException &e) {
833                         infostream << "Client::ReceiveAll(): "
834                                         "InvalidIncomingDataException: what()="
835                                          << e.what() << std::endl;
836                 }
837         }
838 }
839
840 inline void Client::handleCommand(NetworkPacket* pkt)
841 {
842         const ToClientCommandHandler& opHandle = toClientCommandTable[pkt->getCommand()];
843         (this->*opHandle.handler)(pkt);
844 }
845
846 /*
847         sender_peer_id given to this shall be quaranteed to be a valid peer
848 */
849 void Client::ProcessData(NetworkPacket *pkt)
850 {
851         ToClientCommand command = (ToClientCommand) pkt->getCommand();
852         u32 sender_peer_id = pkt->getPeerId();
853
854         //infostream<<"Client: received command="<<command<<std::endl;
855         m_packetcounter.add((u16)command);
856         g_profiler->graphAdd("client_received_packets", 1);
857
858         /*
859                 If this check is removed, be sure to change the queue
860                 system to know the ids
861         */
862         if(sender_peer_id != PEER_ID_SERVER) {
863                 infostream << "Client::ProcessData(): Discarding data not "
864                         "coming from server: peer_id=" << sender_peer_id
865                         << std::endl;
866                 return;
867         }
868
869         // Command must be handled into ToClientCommandHandler
870         if (command >= TOCLIENT_NUM_MSG_TYPES) {
871                 infostream << "Client: Ignoring unknown command "
872                         << command << std::endl;
873                 return;
874         }
875
876         /*
877          * Those packets are handled before m_server_ser_ver is set, it's normal
878          * But we must use the new ToClientConnectionState in the future,
879          * as a byte mask
880          */
881         if(toClientCommandTable[command].state == TOCLIENT_STATE_NOT_CONNECTED) {
882                 handleCommand(pkt);
883                 return;
884         }
885
886         if(m_server_ser_ver == SER_FMT_VER_INVALID) {
887                 infostream << "Client: Server serialization"
888                                 " format invalid or not initialized."
889                                 " Skipping incoming command=" << command << std::endl;
890                 return;
891         }
892
893         /*
894           Handle runtime commands
895         */
896
897         handleCommand(pkt);
898 }
899
900 void Client::Send(NetworkPacket* pkt)
901 {
902         m_con->Send(PEER_ID_SERVER,
903                 serverCommandFactoryTable[pkt->getCommand()].channel,
904                 pkt,
905                 serverCommandFactoryTable[pkt->getCommand()].reliable);
906 }
907
908 // Will fill up 12 + 12 + 4 + 4 + 4 bytes
909 void writePlayerPos(LocalPlayer *myplayer, ClientMap *clientMap, NetworkPacket *pkt)
910 {
911         v3f pf           = myplayer->getPosition() * 100;
912         v3f sf           = myplayer->getSpeed() * 100;
913         s32 pitch        = myplayer->getPitch() * 100;
914         s32 yaw          = myplayer->getYaw() * 100;
915         u32 keyPressed   = myplayer->keyPressed;
916         // scaled by 80, so that pi can fit into a u8
917         u8 fov           = clientMap->getCameraFov() * 80;
918         u8 wanted_range  = MYMIN(255,
919                         std::ceil(clientMap->getControl().wanted_range / MAP_BLOCKSIZE));
920
921         v3s32 position(pf.X, pf.Y, pf.Z);
922         v3s32 speed(sf.X, sf.Y, sf.Z);
923
924         /*
925                 Format:
926                 [0] v3s32 position*100
927                 [12] v3s32 speed*100
928                 [12+12] s32 pitch*100
929                 [12+12+4] s32 yaw*100
930                 [12+12+4+4] u32 keyPressed
931                 [12+12+4+4+4] u8 fov*80
932                 [12+12+4+4+4+1] u8 ceil(wanted_range / MAP_BLOCKSIZE)
933         */
934         *pkt << position << speed << pitch << yaw << keyPressed;
935         *pkt << fov << wanted_range;
936 }
937
938 void Client::interact(InteractAction action, const PointedThing& pointed)
939 {
940         if(m_state != LC_Ready) {
941                 errorstream << "Client::interact() "
942                                 "Canceled (not connected)"
943                                 << std::endl;
944                 return;
945         }
946
947         LocalPlayer *myplayer = m_env.getLocalPlayer();
948         if (myplayer == NULL)
949                 return;
950
951         /*
952                 [0] u16 command
953                 [2] u8 action
954                 [3] u16 item
955                 [5] u32 length of the next item (plen)
956                 [9] serialized PointedThing
957                 [9 + plen] player position information
958         */
959
960         NetworkPacket pkt(TOSERVER_INTERACT, 1 + 2 + 0);
961
962         pkt << (u8)action;
963         pkt << myplayer->getWieldIndex();
964
965         std::ostringstream tmp_os(std::ios::binary);
966         pointed.serialize(tmp_os);
967
968         pkt.putLongString(tmp_os.str());
969
970         writePlayerPos(myplayer, &m_env.getClientMap(), &pkt);
971
972         Send(&pkt);
973 }
974
975 void Client::deleteAuthData()
976 {
977         if (!m_auth_data)
978                 return;
979
980         switch (m_chosen_auth_mech) {
981                 case AUTH_MECHANISM_FIRST_SRP:
982                         break;
983                 case AUTH_MECHANISM_SRP:
984                 case AUTH_MECHANISM_LEGACY_PASSWORD:
985                         srp_user_delete((SRPUser *) m_auth_data);
986                         m_auth_data = NULL;
987                         break;
988                 case AUTH_MECHANISM_NONE:
989                         break;
990         }
991         m_chosen_auth_mech = AUTH_MECHANISM_NONE;
992 }
993
994
995 AuthMechanism Client::choseAuthMech(const u32 mechs)
996 {
997         if (mechs & AUTH_MECHANISM_SRP)
998                 return AUTH_MECHANISM_SRP;
999
1000         if (mechs & AUTH_MECHANISM_FIRST_SRP)
1001                 return AUTH_MECHANISM_FIRST_SRP;
1002
1003         if (mechs & AUTH_MECHANISM_LEGACY_PASSWORD)
1004                 return AUTH_MECHANISM_LEGACY_PASSWORD;
1005
1006         return AUTH_MECHANISM_NONE;
1007 }
1008
1009 void Client::sendInit(const std::string &playerName)
1010 {
1011         NetworkPacket pkt(TOSERVER_INIT, 1 + 2 + 2 + (1 + playerName.size()));
1012
1013         // we don't support network compression yet
1014         u16 supp_comp_modes = NETPROTO_COMPRESSION_NONE;
1015
1016         pkt << (u8) SER_FMT_VER_HIGHEST_READ << (u16) supp_comp_modes;
1017         pkt << (u16) CLIENT_PROTOCOL_VERSION_MIN << (u16) CLIENT_PROTOCOL_VERSION_MAX;
1018         pkt << playerName;
1019
1020         Send(&pkt);
1021 }
1022
1023 void Client::promptConfirmRegistration(AuthMechanism chosen_auth_mechanism)
1024 {
1025         m_chosen_auth_mech = chosen_auth_mechanism;
1026         m_is_registration_confirmation_state = true;
1027 }
1028
1029 void Client::confirmRegistration()
1030 {
1031         m_is_registration_confirmation_state = false;
1032         startAuth(m_chosen_auth_mech);
1033 }
1034
1035 void Client::startAuth(AuthMechanism chosen_auth_mechanism)
1036 {
1037         m_chosen_auth_mech = chosen_auth_mechanism;
1038
1039         switch (chosen_auth_mechanism) {
1040                 case AUTH_MECHANISM_FIRST_SRP: {
1041                         // send srp verifier to server
1042                         std::string verifier;
1043                         std::string salt;
1044                         generate_srp_verifier_and_salt(getPlayerName(), m_password,
1045                                 &verifier, &salt);
1046
1047                         NetworkPacket resp_pkt(TOSERVER_FIRST_SRP, 0);
1048                         resp_pkt << salt << verifier << (u8)((m_password.empty()) ? 1 : 0);
1049
1050                         Send(&resp_pkt);
1051                         break;
1052                 }
1053                 case AUTH_MECHANISM_SRP:
1054                 case AUTH_MECHANISM_LEGACY_PASSWORD: {
1055                         u8 based_on = 1;
1056
1057                         if (chosen_auth_mechanism == AUTH_MECHANISM_LEGACY_PASSWORD) {
1058                                 m_password = translate_password(getPlayerName(), m_password);
1059                                 based_on = 0;
1060                         }
1061
1062                         std::string playername_u = lowercase(getPlayerName());
1063                         m_auth_data = srp_user_new(SRP_SHA256, SRP_NG_2048,
1064                                 getPlayerName().c_str(), playername_u.c_str(),
1065                                 (const unsigned char *) m_password.c_str(),
1066                                 m_password.length(), NULL, NULL);
1067                         char *bytes_A = 0;
1068                         size_t len_A = 0;
1069                         SRP_Result res = srp_user_start_authentication(
1070                                 (struct SRPUser *) m_auth_data, NULL, NULL, 0,
1071                                 (unsigned char **) &bytes_A, &len_A);
1072                         FATAL_ERROR_IF(res != SRP_OK, "Creating local SRP user failed.");
1073
1074                         NetworkPacket resp_pkt(TOSERVER_SRP_BYTES_A, 0);
1075                         resp_pkt << std::string(bytes_A, len_A) << based_on;
1076                         Send(&resp_pkt);
1077                         break;
1078                 }
1079                 case AUTH_MECHANISM_NONE:
1080                         break; // not handled in this method
1081         }
1082 }
1083
1084 void Client::sendDeletedBlocks(std::vector<v3s16> &blocks)
1085 {
1086         NetworkPacket pkt(TOSERVER_DELETEDBLOCKS, 1 + sizeof(v3s16) * blocks.size());
1087
1088         pkt << (u8) blocks.size();
1089
1090         for (const v3s16 &block : blocks) {
1091                 pkt << block;
1092         }
1093
1094         Send(&pkt);
1095 }
1096
1097 void Client::sendGotBlocks(const std::vector<v3s16> &blocks)
1098 {
1099         NetworkPacket pkt(TOSERVER_GOTBLOCKS, 1 + 6 * blocks.size());
1100         pkt << (u8) blocks.size();
1101         for (const v3s16 &block : blocks)
1102                 pkt << block;
1103
1104         Send(&pkt);
1105 }
1106
1107 void Client::sendRemovedSounds(std::vector<s32> &soundList)
1108 {
1109         size_t server_ids = soundList.size();
1110         assert(server_ids <= 0xFFFF);
1111
1112         NetworkPacket pkt(TOSERVER_REMOVED_SOUNDS, 2 + server_ids * 4);
1113
1114         pkt << (u16) (server_ids & 0xFFFF);
1115
1116         for (s32 sound_id : soundList)
1117                 pkt << sound_id;
1118
1119         Send(&pkt);
1120 }
1121
1122 void Client::sendNodemetaFields(v3s16 p, const std::string &formname,
1123                 const StringMap &fields)
1124 {
1125         size_t fields_size = fields.size();
1126
1127         FATAL_ERROR_IF(fields_size > 0xFFFF, "Unsupported number of nodemeta fields");
1128
1129         NetworkPacket pkt(TOSERVER_NODEMETA_FIELDS, 0);
1130
1131         pkt << p << formname << (u16) (fields_size & 0xFFFF);
1132
1133         StringMap::const_iterator it;
1134         for (it = fields.begin(); it != fields.end(); ++it) {
1135                 const std::string &name = it->first;
1136                 const std::string &value = it->second;
1137                 pkt << name;
1138                 pkt.putLongString(value);
1139         }
1140
1141         Send(&pkt);
1142 }
1143
1144 void Client::sendInventoryFields(const std::string &formname,
1145                 const StringMap &fields)
1146 {
1147         size_t fields_size = fields.size();
1148         FATAL_ERROR_IF(fields_size > 0xFFFF, "Unsupported number of inventory fields");
1149
1150         NetworkPacket pkt(TOSERVER_INVENTORY_FIELDS, 0);
1151         pkt << formname << (u16) (fields_size & 0xFFFF);
1152
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;
1157                 pkt << name;
1158                 pkt.putLongString(value);
1159         }
1160
1161         Send(&pkt);
1162 }
1163
1164 void Client::sendInventoryAction(InventoryAction *a)
1165 {
1166         std::ostringstream os(std::ios_base::binary);
1167
1168         a->serialize(os);
1169
1170         // Make data buffer
1171         std::string s = os.str();
1172
1173         NetworkPacket pkt(TOSERVER_INVENTORY_ACTION, s.size());
1174         pkt.putRawString(s.c_str(),s.size());
1175
1176         Send(&pkt);
1177 }
1178
1179 bool Client::canSendChatMessage() const
1180 {
1181         u32 now = time(NULL);
1182         float time_passed = now - m_last_chat_message_sent;
1183
1184         float virt_chat_message_allowance = m_chat_message_allowance + time_passed *
1185                         (CLIENT_CHAT_MESSAGE_LIMIT_PER_10S / 8.0f);
1186
1187         if (virt_chat_message_allowance < 1.0f)
1188                 return false;
1189
1190         return true;
1191 }
1192
1193 void Client::sendChatMessage(const std::wstring &message)
1194 {
1195         const s16 max_queue_size = g_settings->getS16("max_out_chat_queue_size");
1196         if (canSendChatMessage()) {
1197                 u32 now = time(NULL);
1198                 float time_passed = now - m_last_chat_message_sent;
1199                 m_last_chat_message_sent = now;
1200
1201                 m_chat_message_allowance += time_passed * (CLIENT_CHAT_MESSAGE_LIMIT_PER_10S / 8.0f);
1202                 if (m_chat_message_allowance > CLIENT_CHAT_MESSAGE_LIMIT_PER_10S)
1203                         m_chat_message_allowance = CLIENT_CHAT_MESSAGE_LIMIT_PER_10S;
1204
1205                 m_chat_message_allowance -= 1.0f;
1206
1207                 NetworkPacket pkt(TOSERVER_CHAT_MESSAGE, 2 + message.size() * sizeof(u16));
1208
1209                 pkt << message;
1210
1211                 Send(&pkt);
1212         } else if (m_out_chat_queue.size() < (u16) max_queue_size || max_queue_size == -1) {
1213                 m_out_chat_queue.push(message);
1214         } else {
1215                 infostream << "Could not queue chat message because maximum out chat queue size ("
1216                                 << max_queue_size << ") is reached." << std::endl;
1217         }
1218 }
1219
1220 void Client::clearOutChatQueue()
1221 {
1222         m_out_chat_queue = std::queue<std::wstring>();
1223 }
1224
1225 void Client::sendChangePassword(const std::string &oldpassword,
1226         const std::string &newpassword)
1227 {
1228         LocalPlayer *player = m_env.getLocalPlayer();
1229         if (player == NULL)
1230                 return;
1231
1232         // get into sudo mode and then send new password to server
1233         m_password = oldpassword;
1234         m_new_password = newpassword;
1235         startAuth(choseAuthMech(m_sudo_auth_methods));
1236 }
1237
1238
1239 void Client::sendDamage(u16 damage)
1240 {
1241         NetworkPacket pkt(TOSERVER_DAMAGE, sizeof(u16));
1242         pkt << damage;
1243         Send(&pkt);
1244 }
1245
1246 void Client::sendRespawn()
1247 {
1248         NetworkPacket pkt(TOSERVER_RESPAWN, 0);
1249         Send(&pkt);
1250 }
1251
1252 void Client::sendReady()
1253 {
1254         NetworkPacket pkt(TOSERVER_CLIENT_READY,
1255                         1 + 1 + 1 + 1 + 2 + sizeof(char) * strlen(g_version_hash) + 2);
1256
1257         pkt << (u8) VERSION_MAJOR << (u8) VERSION_MINOR << (u8) VERSION_PATCH
1258                 << (u8) 0 << (u16) strlen(g_version_hash);
1259
1260         pkt.putRawString(g_version_hash, (u16) strlen(g_version_hash));
1261         pkt << (u16)FORMSPEC_API_VERSION;
1262         Send(&pkt);
1263 }
1264
1265 void Client::sendPlayerPos()
1266 {
1267         LocalPlayer *player = m_env.getLocalPlayer();
1268         if (!player)
1269                 return;
1270
1271         ClientMap &map = m_env.getClientMap();
1272         u8 camera_fov   = map.getCameraFov();
1273         u8 wanted_range = map.getControl().wanted_range;
1274
1275         // Save bandwidth by only updating position when
1276         // player is not dead and something changed
1277
1278         if (m_activeobjects_received && player->isDead())
1279                 return;
1280
1281         if (
1282                         player->last_position     == player->getPosition() &&
1283                         player->last_speed        == player->getSpeed()    &&
1284                         player->last_pitch        == player->getPitch()    &&
1285                         player->last_yaw          == player->getYaw()      &&
1286                         player->last_keyPressed   == player->keyPressed    &&
1287                         player->last_camera_fov   == camera_fov            &&
1288                         player->last_wanted_range == wanted_range)
1289                 return;
1290
1291         player->last_position     = player->getPosition();
1292         player->last_speed        = player->getSpeed();
1293         player->last_pitch        = player->getPitch();
1294         player->last_yaw          = player->getYaw();
1295         player->last_keyPressed   = player->keyPressed;
1296         player->last_camera_fov   = camera_fov;
1297         player->last_wanted_range = wanted_range;
1298
1299         NetworkPacket pkt(TOSERVER_PLAYERPOS, 12 + 12 + 4 + 4 + 4 + 1 + 1);
1300
1301         writePlayerPos(player, &map, &pkt);
1302
1303         Send(&pkt);
1304 }
1305
1306 void Client::removeNode(v3s16 p)
1307 {
1308         std::map<v3s16, MapBlock*> modified_blocks;
1309
1310         try {
1311                 m_env.getMap().removeNodeAndUpdate(p, modified_blocks);
1312         }
1313         catch(InvalidPositionException &e) {
1314         }
1315
1316         for (const auto &modified_block : modified_blocks) {
1317                 addUpdateMeshTaskWithEdge(modified_block.first, false, true);
1318         }
1319 }
1320
1321 /**
1322  * Helper function for Client Side Modding
1323  * CSM restrictions are applied there, this should not be used for core engine
1324  * @param p
1325  * @param is_valid_position
1326  * @return
1327  */
1328 MapNode Client::CSMGetNode(v3s16 p, bool *is_valid_position)
1329 {
1330         if (checkCSMRestrictionFlag(CSMRestrictionFlags::CSM_RF_LOOKUP_NODES)) {
1331                 v3s16 ppos = floatToInt(m_env.getLocalPlayer()->getPosition(), BS);
1332                 if ((u32) ppos.getDistanceFrom(p) > m_csm_restriction_noderange) {
1333                         *is_valid_position = false;
1334                         return {};
1335                 }
1336         }
1337         return m_env.getMap().getNode(p, is_valid_position);
1338 }
1339
1340 int Client::CSMClampRadius(v3s16 pos, int radius)
1341 {
1342         if (!checkCSMRestrictionFlag(CSMRestrictionFlags::CSM_RF_LOOKUP_NODES))
1343                 return radius;
1344         // This is approximate and will cause some allowed nodes to be excluded
1345         v3s16 ppos = floatToInt(m_env.getLocalPlayer()->getPosition(), BS);
1346         u32 distance = ppos.getDistanceFrom(pos);
1347         if (distance >= m_csm_restriction_noderange)
1348                 return 0;
1349         return std::min<int>(radius, m_csm_restriction_noderange - distance);
1350 }
1351
1352 v3s16 Client::CSMClampPos(v3s16 pos)
1353 {
1354         if (!checkCSMRestrictionFlag(CSMRestrictionFlags::CSM_RF_LOOKUP_NODES))
1355                 return pos;
1356         v3s16 ppos = floatToInt(m_env.getLocalPlayer()->getPosition(), BS);
1357         const int range = m_csm_restriction_noderange;
1358         return v3s16(
1359                 core::clamp<int>(pos.X, (int)ppos.X - range, (int)ppos.X + range),
1360                 core::clamp<int>(pos.Y, (int)ppos.Y - range, (int)ppos.Y + range),
1361                 core::clamp<int>(pos.Z, (int)ppos.Z - range, (int)ppos.Z + range)
1362         );
1363 }
1364
1365 void Client::addNode(v3s16 p, MapNode n, bool remove_metadata)
1366 {
1367         //TimeTaker timer1("Client::addNode()");
1368
1369         std::map<v3s16, MapBlock*> modified_blocks;
1370
1371         try {
1372                 //TimeTaker timer3("Client::addNode(): addNodeAndUpdate");
1373                 m_env.getMap().addNodeAndUpdate(p, n, modified_blocks, remove_metadata);
1374         }
1375         catch(InvalidPositionException &e) {
1376         }
1377
1378         for (const auto &modified_block : modified_blocks) {
1379                 addUpdateMeshTaskWithEdge(modified_block.first, false, true);
1380         }
1381 }
1382
1383 void Client::setPlayerControl(PlayerControl &control)
1384 {
1385         LocalPlayer *player = m_env.getLocalPlayer();
1386         assert(player);
1387         player->control = control;
1388 }
1389
1390 void Client::setPlayerItem(u16 item)
1391 {
1392         m_env.getLocalPlayer()->setWieldIndex(item);
1393         m_update_wielded_item = true;
1394
1395         NetworkPacket pkt(TOSERVER_PLAYERITEM, 2);
1396         pkt << item;
1397         Send(&pkt);
1398 }
1399
1400 // Returns true once after the inventory of the local player
1401 // has been updated from the server.
1402 bool Client::updateWieldedItem()
1403 {
1404         if (!m_update_wielded_item)
1405                 return false;
1406
1407         m_update_wielded_item = false;
1408
1409         LocalPlayer *player = m_env.getLocalPlayer();
1410         assert(player);
1411         if (auto *list = player->inventory.getList("main"))
1412                 list->setModified(false);
1413         if (auto *list = player->inventory.getList("hand"))
1414                 list->setModified(false);
1415
1416         return true;
1417 }
1418
1419 Inventory* Client::getInventory(const InventoryLocation &loc)
1420 {
1421         switch(loc.type){
1422         case InventoryLocation::UNDEFINED:
1423         {}
1424         break;
1425         case InventoryLocation::CURRENT_PLAYER:
1426         {
1427                 LocalPlayer *player = m_env.getLocalPlayer();
1428                 assert(player);
1429                 return &player->inventory;
1430         }
1431         break;
1432         case InventoryLocation::PLAYER:
1433         {
1434                 // Check if we are working with local player inventory
1435                 LocalPlayer *player = m_env.getLocalPlayer();
1436                 if (!player || strcmp(player->getName(), loc.name.c_str()) != 0)
1437                         return NULL;
1438                 return &player->inventory;
1439         }
1440         break;
1441         case InventoryLocation::NODEMETA:
1442         {
1443                 NodeMetadata *meta = m_env.getMap().getNodeMetadata(loc.p);
1444                 if(!meta)
1445                         return NULL;
1446                 return meta->getInventory();
1447         }
1448         break;
1449         case InventoryLocation::DETACHED:
1450         {
1451                 if (m_detached_inventories.count(loc.name) == 0)
1452                         return NULL;
1453                 return m_detached_inventories[loc.name];
1454         }
1455         break;
1456         default:
1457                 FATAL_ERROR("Invalid inventory location type.");
1458                 break;
1459         }
1460         return NULL;
1461 }
1462
1463 void Client::inventoryAction(InventoryAction *a)
1464 {
1465         /*
1466                 Send it to the server
1467         */
1468         sendInventoryAction(a);
1469
1470         /*
1471                 Predict some local inventory changes
1472         */
1473         a->clientApply(this, this);
1474
1475         // Remove it
1476         delete a;
1477 }
1478
1479 float Client::getAnimationTime()
1480 {
1481         return m_animation_time;
1482 }
1483
1484 int Client::getCrackLevel()
1485 {
1486         return m_crack_level;
1487 }
1488
1489 v3s16 Client::getCrackPos()
1490 {
1491         return m_crack_pos;
1492 }
1493
1494 void Client::setCrack(int level, v3s16 pos)
1495 {
1496         int old_crack_level = m_crack_level;
1497         v3s16 old_crack_pos = m_crack_pos;
1498
1499         m_crack_level = level;
1500         m_crack_pos = pos;
1501
1502         if(old_crack_level >= 0 && (level < 0 || pos != old_crack_pos))
1503         {
1504                 // remove old crack
1505                 addUpdateMeshTaskForNode(old_crack_pos, false, true);
1506         }
1507         if(level >= 0 && (old_crack_level < 0 || pos != old_crack_pos))
1508         {
1509                 // add new crack
1510                 addUpdateMeshTaskForNode(pos, false, true);
1511         }
1512 }
1513
1514 u16 Client::getHP()
1515 {
1516         LocalPlayer *player = m_env.getLocalPlayer();
1517         assert(player);
1518         return player->hp;
1519 }
1520
1521 bool Client::getChatMessage(std::wstring &res)
1522 {
1523         if (m_chat_queue.empty())
1524                 return false;
1525
1526         ChatMessage *chatMessage = m_chat_queue.front();
1527         m_chat_queue.pop();
1528
1529         res = L"";
1530
1531         switch (chatMessage->type) {
1532                 case CHATMESSAGE_TYPE_RAW:
1533                 case CHATMESSAGE_TYPE_ANNOUNCE:
1534                 case CHATMESSAGE_TYPE_SYSTEM:
1535                         res = chatMessage->message;
1536                         break;
1537                 case CHATMESSAGE_TYPE_NORMAL: {
1538                         if (!chatMessage->sender.empty())
1539                                 res = L"<" + chatMessage->sender + L"> " + chatMessage->message;
1540                         else
1541                                 res = chatMessage->message;
1542                         break;
1543                 }
1544                 default:
1545                         break;
1546         }
1547
1548         delete chatMessage;
1549         return true;
1550 }
1551
1552 void Client::typeChatMessage(const std::wstring &message)
1553 {
1554         // Discard empty line
1555         if (message.empty())
1556                 return;
1557
1558         // If message was consumed by script API, don't send it to server
1559         if (m_mods_loaded && m_script->on_sending_message(wide_to_utf8(message)))
1560                 return;
1561
1562         // Send to others
1563         sendChatMessage(message);
1564 }
1565
1566 void Client::addUpdateMeshTask(v3s16 p, bool ack_to_server, bool urgent)
1567 {
1568         // Check if the block exists to begin with. In the case when a non-existing
1569         // neighbor is automatically added, it may not. In that case we don't want
1570         // to tell the mesh update thread about it.
1571         MapBlock *b = m_env.getMap().getBlockNoCreateNoEx(p);
1572         if (b == NULL)
1573                 return;
1574
1575         m_mesh_update_thread.updateBlock(&m_env.getMap(), p, ack_to_server, urgent);
1576 }
1577
1578 void Client::addUpdateMeshTaskWithEdge(v3s16 blockpos, bool ack_to_server, bool urgent)
1579 {
1580         try{
1581                 addUpdateMeshTask(blockpos, ack_to_server, urgent);
1582         }
1583         catch(InvalidPositionException &e){}
1584
1585         // Leading edge
1586         for (int i=0;i<6;i++)
1587         {
1588                 try{
1589                         v3s16 p = blockpos + g_6dirs[i];
1590                         addUpdateMeshTask(p, false, urgent);
1591                 }
1592                 catch(InvalidPositionException &e){}
1593         }
1594 }
1595
1596 void Client::addUpdateMeshTaskForNode(v3s16 nodepos, bool ack_to_server, bool urgent)
1597 {
1598         {
1599                 v3s16 p = nodepos;
1600                 infostream<<"Client::addUpdateMeshTaskForNode(): "
1601                                 <<"("<<p.X<<","<<p.Y<<","<<p.Z<<")"
1602                                 <<std::endl;
1603         }
1604
1605         v3s16 blockpos          = getNodeBlockPos(nodepos);
1606         v3s16 blockpos_relative = blockpos * MAP_BLOCKSIZE;
1607
1608         try{
1609                 addUpdateMeshTask(blockpos, ack_to_server, urgent);
1610         }
1611         catch(InvalidPositionException &e) {}
1612
1613         // Leading edge
1614         if(nodepos.X == blockpos_relative.X){
1615                 try{
1616                         v3s16 p = blockpos + v3s16(-1,0,0);
1617                         addUpdateMeshTask(p, false, urgent);
1618                 }
1619                 catch(InvalidPositionException &e){}
1620         }
1621
1622         if(nodepos.Y == blockpos_relative.Y){
1623                 try{
1624                         v3s16 p = blockpos + v3s16(0,-1,0);
1625                         addUpdateMeshTask(p, false, urgent);
1626                 }
1627                 catch(InvalidPositionException &e){}
1628         }
1629
1630         if(nodepos.Z == blockpos_relative.Z){
1631                 try{
1632                         v3s16 p = blockpos + v3s16(0,0,-1);
1633                         addUpdateMeshTask(p, false, urgent);
1634                 }
1635                 catch(InvalidPositionException &e){}
1636         }
1637 }
1638
1639 ClientEvent *Client::getClientEvent()
1640 {
1641         FATAL_ERROR_IF(m_client_event_queue.empty(),
1642                         "Cannot getClientEvent, queue is empty.");
1643
1644         ClientEvent *event = m_client_event_queue.front();
1645         m_client_event_queue.pop();
1646         return event;
1647 }
1648
1649 const Address Client::getServerAddress()
1650 {
1651         return m_con->GetPeerAddress(PEER_ID_SERVER);
1652 }
1653
1654 float Client::mediaReceiveProgress()
1655 {
1656         if (m_media_downloader)
1657                 return m_media_downloader->getProgress();
1658
1659         return 1.0; // downloader only exists when not yet done
1660 }
1661
1662 typedef struct TextureUpdateArgs {
1663         gui::IGUIEnvironment *guienv;
1664         u64 last_time_ms;
1665         u16 last_percent;
1666         const wchar_t* text_base;
1667         ITextureSource *tsrc;
1668 } TextureUpdateArgs;
1669
1670 void texture_update_progress(void *args, u32 progress, u32 max_progress)
1671 {
1672                 TextureUpdateArgs* targs = (TextureUpdateArgs*) args;
1673                 u16 cur_percent = ceil(progress / (double) max_progress * 100.);
1674
1675                 // update the loading menu -- if neccessary
1676                 bool do_draw = false;
1677                 u64 time_ms = targs->last_time_ms;
1678                 if (cur_percent != targs->last_percent) {
1679                         targs->last_percent = cur_percent;
1680                         time_ms = porting::getTimeMs();
1681                         // only draw when the user will notice something:
1682                         do_draw = (time_ms - targs->last_time_ms > 100);
1683                 }
1684
1685                 if (do_draw) {
1686                         targs->last_time_ms = time_ms;
1687                         std::basic_stringstream<wchar_t> strm;
1688                         strm << targs->text_base << " " << targs->last_percent << "%...";
1689                         RenderingEngine::draw_load_screen(strm.str(), targs->guienv, targs->tsrc, 0,
1690                                 72 + (u16) ((18. / 100.) * (double) targs->last_percent), true);
1691                 }
1692 }
1693
1694 void Client::afterContentReceived()
1695 {
1696         infostream<<"Client::afterContentReceived() started"<<std::endl;
1697         assert(m_itemdef_received); // pre-condition
1698         assert(m_nodedef_received); // pre-condition
1699         assert(mediaReceived()); // pre-condition
1700
1701         const wchar_t* text = wgettext("Loading textures...");
1702
1703         // Clear cached pre-scaled 2D GUI images, as this cache
1704         // might have images with the same name but different
1705         // content from previous sessions.
1706         guiScalingCacheClear();
1707
1708         // Rebuild inherited images and recreate textures
1709         infostream<<"- Rebuilding images and textures"<<std::endl;
1710         RenderingEngine::draw_load_screen(text, guienv, m_tsrc, 0, 70);
1711         m_tsrc->rebuildImagesAndTextures();
1712         delete[] text;
1713
1714         // Rebuild shaders
1715         infostream<<"- Rebuilding shaders"<<std::endl;
1716         text = wgettext("Rebuilding shaders...");
1717         RenderingEngine::draw_load_screen(text, guienv, m_tsrc, 0, 71);
1718         m_shsrc->rebuildShaders();
1719         delete[] text;
1720
1721         // Update node aliases
1722         infostream<<"- Updating node aliases"<<std::endl;
1723         text = wgettext("Initializing nodes...");
1724         RenderingEngine::draw_load_screen(text, guienv, m_tsrc, 0, 72);
1725         m_nodedef->updateAliases(m_itemdef);
1726         for (const auto &path : getTextureDirs()) {
1727                 TextureOverrideSource override_source(path + DIR_DELIM + "override.txt");
1728                 m_nodedef->applyTextureOverrides(override_source.getNodeTileOverrides());
1729                 m_itemdef->applyTextureOverrides(override_source.getItemTextureOverrides());
1730         }
1731         m_nodedef->setNodeRegistrationStatus(true);
1732         m_nodedef->runNodeResolveCallbacks();
1733         delete[] text;
1734
1735         // Update node textures and assign shaders to each tile
1736         infostream<<"- Updating node textures"<<std::endl;
1737         TextureUpdateArgs tu_args;
1738         tu_args.guienv = guienv;
1739         tu_args.last_time_ms = porting::getTimeMs();
1740         tu_args.last_percent = 0;
1741         tu_args.text_base =  wgettext("Initializing nodes");
1742         tu_args.tsrc = m_tsrc;
1743         m_nodedef->updateTextures(this, texture_update_progress, &tu_args);
1744         delete[] tu_args.text_base;
1745
1746         // Start mesh update thread after setting up content definitions
1747         infostream<<"- Starting mesh update thread"<<std::endl;
1748         m_mesh_update_thread.start();
1749
1750         m_state = LC_Ready;
1751         sendReady();
1752
1753         if (m_mods_loaded)
1754                 m_script->on_client_ready(m_env.getLocalPlayer());
1755
1756         text = wgettext("Done!");
1757         RenderingEngine::draw_load_screen(text, guienv, m_tsrc, 0, 100);
1758         infostream<<"Client::afterContentReceived() done"<<std::endl;
1759         delete[] text;
1760 }
1761
1762 float Client::getRTT()
1763 {
1764         return m_con->getPeerStat(PEER_ID_SERVER,con::AVG_RTT);
1765 }
1766
1767 float Client::getCurRate()
1768 {
1769         return (m_con->getLocalStat(con::CUR_INC_RATE) +
1770                         m_con->getLocalStat(con::CUR_DL_RATE));
1771 }
1772
1773 void Client::makeScreenshot()
1774 {
1775         irr::video::IVideoDriver *driver = RenderingEngine::get_video_driver();
1776         irr::video::IImage* const raw_image = driver->createScreenShot();
1777
1778         if (!raw_image)
1779                 return;
1780
1781         time_t t = time(NULL);
1782         struct tm *tm = localtime(&t);
1783
1784         char timetstamp_c[64];
1785         strftime(timetstamp_c, sizeof(timetstamp_c), "%Y%m%d_%H%M%S", tm);
1786
1787         std::string screenshot_dir;
1788
1789         if (fs::IsPathAbsolute(g_settings->get("screenshot_path")))
1790                 screenshot_dir = g_settings->get("screenshot_path");
1791         else
1792                 screenshot_dir = porting::path_user + DIR_DELIM + g_settings->get("screenshot_path");
1793
1794         std::string filename_base = screenshot_dir
1795                         + DIR_DELIM
1796                         + std::string("screenshot_")
1797                         + std::string(timetstamp_c);
1798         std::string filename_ext = "." + g_settings->get("screenshot_format");
1799         std::string filename;
1800
1801         // Create the directory if it doesn't already exist.
1802         // Otherwise, saving the screenshot would fail.
1803         fs::CreateDir(screenshot_dir);
1804
1805         u32 quality = (u32)g_settings->getS32("screenshot_quality");
1806         quality = MYMIN(MYMAX(quality, 0), 100) / 100.0 * 255;
1807
1808         // Try to find a unique filename
1809         unsigned serial = 0;
1810
1811         while (serial < SCREENSHOT_MAX_SERIAL_TRIES) {
1812                 filename = filename_base + (serial > 0 ? ("_" + itos(serial)) : "") + filename_ext;
1813                 std::ifstream tmp(filename.c_str());
1814                 if (!tmp.good())
1815                         break;  // File did not apparently exist, we'll go with it
1816                 serial++;
1817         }
1818
1819         if (serial == SCREENSHOT_MAX_SERIAL_TRIES) {
1820                 infostream << "Could not find suitable filename for screenshot" << std::endl;
1821         } else {
1822                 irr::video::IImage* const image =
1823                                 driver->createImage(video::ECF_R8G8B8, raw_image->getDimension());
1824
1825                 if (image) {
1826                         raw_image->copyTo(image);
1827
1828                         std::ostringstream sstr;
1829                         if (driver->writeImageToFile(image, filename.c_str(), quality)) {
1830                                 sstr << "Saved screenshot to '" << filename << "'";
1831                         } else {
1832                                 sstr << "Failed to save screenshot '" << filename << "'";
1833                         }
1834                         pushToChatQueue(new ChatMessage(CHATMESSAGE_TYPE_SYSTEM,
1835                                         utf8_to_wide(sstr.str())));
1836                         infostream << sstr.str() << std::endl;
1837                         image->drop();
1838                 }
1839         }
1840
1841         raw_image->drop();
1842 }
1843
1844 bool Client::shouldShowMinimap() const
1845 {
1846         return !m_minimap_disabled_by_server;
1847 }
1848
1849 void Client::pushToEventQueue(ClientEvent *event)
1850 {
1851         m_client_event_queue.push(event);
1852 }
1853
1854 void Client::showMinimap(const bool show)
1855 {
1856         m_game_ui->showMinimap(show);
1857 }
1858
1859 // IGameDef interface
1860 // Under envlock
1861 IItemDefManager* Client::getItemDefManager()
1862 {
1863         return m_itemdef;
1864 }
1865 const NodeDefManager* Client::getNodeDefManager()
1866 {
1867         return m_nodedef;
1868 }
1869 ICraftDefManager* Client::getCraftDefManager()
1870 {
1871         return NULL;
1872         //return m_craftdef;
1873 }
1874 ITextureSource* Client::getTextureSource()
1875 {
1876         return m_tsrc;
1877 }
1878 IWritableShaderSource* Client::getShaderSource()
1879 {
1880         return m_shsrc;
1881 }
1882
1883 u16 Client::allocateUnknownNodeId(const std::string &name)
1884 {
1885         errorstream << "Client::allocateUnknownNodeId(): "
1886                         << "Client cannot allocate node IDs" << std::endl;
1887         FATAL_ERROR("Client allocated unknown node");
1888
1889         return CONTENT_IGNORE;
1890 }
1891 ISoundManager* Client::getSoundManager()
1892 {
1893         return m_sound;
1894 }
1895 MtEventManager* Client::getEventManager()
1896 {
1897         return m_event;
1898 }
1899
1900 ParticleManager* Client::getParticleManager()
1901 {
1902         return &m_particle_manager;
1903 }
1904
1905 scene::IAnimatedMesh* Client::getMesh(const std::string &filename, bool cache)
1906 {
1907         StringMap::const_iterator it = m_mesh_data.find(filename);
1908         if (it == m_mesh_data.end()) {
1909                 errorstream << "Client::getMesh(): Mesh not found: \"" << filename
1910                         << "\"" << std::endl;
1911                 return NULL;
1912         }
1913         const std::string &data    = it->second;
1914
1915         // Create the mesh, remove it from cache and return it
1916         // This allows unique vertex colors and other properties for each instance
1917         Buffer<char> data_rw(data.c_str(), data.size()); // Const-incorrect Irrlicht
1918         io::IReadFile *rfile   = RenderingEngine::get_filesystem()->createMemoryReadFile(
1919                         *data_rw, data_rw.getSize(), filename.c_str());
1920         FATAL_ERROR_IF(!rfile, "Could not create/open RAM file");
1921
1922         scene::IAnimatedMesh *mesh = RenderingEngine::get_scene_manager()->getMesh(rfile);
1923         rfile->drop();
1924         if (!mesh)
1925                 return nullptr;
1926         mesh->grab();
1927         if (!cache)
1928                 RenderingEngine::get_mesh_cache()->removeMesh(mesh);
1929         return mesh;
1930 }
1931
1932 const std::string* Client::getModFile(std::string filename)
1933 {
1934         // strip dir delimiter from beginning of path
1935         auto pos = filename.find_first_of(':');
1936         if (pos == std::string::npos)
1937                 return nullptr;
1938         pos++;
1939         auto pos2 = filename.find_first_not_of('/', pos);
1940         if (pos2 > pos)
1941                 filename.erase(pos, pos2 - pos);
1942
1943         StringMap::const_iterator it = m_mod_vfs.find(filename);
1944         if (it == m_mod_vfs.end())
1945                 return nullptr;
1946         return &it->second;
1947 }
1948
1949 bool Client::registerModStorage(ModMetadata *storage)
1950 {
1951         if (m_mod_storages.find(storage->getModName()) != m_mod_storages.end()) {
1952                 errorstream << "Unable to register same mod storage twice. Storage name: "
1953                                 << storage->getModName() << std::endl;
1954                 return false;
1955         }
1956
1957         m_mod_storages[storage->getModName()] = storage;
1958         return true;
1959 }
1960
1961 void Client::unregisterModStorage(const std::string &name)
1962 {
1963         std::unordered_map<std::string, ModMetadata *>::const_iterator it =
1964                 m_mod_storages.find(name);
1965         if (it != m_mod_storages.end()) {
1966                 // Save unconditionaly on unregistration
1967                 it->second->save(getModStoragePath());
1968                 m_mod_storages.erase(name);
1969         }
1970 }
1971
1972 std::string Client::getModStoragePath() const
1973 {
1974         return porting::path_user + DIR_DELIM + "client" + DIR_DELIM + "mod_storage";
1975 }
1976
1977 /*
1978  * Mod channels
1979  */
1980
1981 bool Client::joinModChannel(const std::string &channel)
1982 {
1983         if (m_modchannel_mgr->channelRegistered(channel))
1984                 return false;
1985
1986         NetworkPacket pkt(TOSERVER_MODCHANNEL_JOIN, 2 + channel.size());
1987         pkt << channel;
1988         Send(&pkt);
1989
1990         m_modchannel_mgr->joinChannel(channel, 0);
1991         return true;
1992 }
1993
1994 bool Client::leaveModChannel(const std::string &channel)
1995 {
1996         if (!m_modchannel_mgr->channelRegistered(channel))
1997                 return false;
1998
1999         NetworkPacket pkt(TOSERVER_MODCHANNEL_LEAVE, 2 + channel.size());
2000         pkt << channel;
2001         Send(&pkt);
2002
2003         m_modchannel_mgr->leaveChannel(channel, 0);
2004         return true;
2005 }
2006
2007 bool Client::sendModChannelMessage(const std::string &channel, const std::string &message)
2008 {
2009         if (!m_modchannel_mgr->canWriteOnChannel(channel))
2010                 return false;
2011
2012         if (message.size() > STRING_MAX_LEN) {
2013                 warningstream << "ModChannel message too long, dropping before sending "
2014                                 << " (" << message.size() << " > " << STRING_MAX_LEN << ", channel: "
2015                                 << channel << ")" << std::endl;
2016                 return false;
2017         }
2018
2019         // @TODO: do some client rate limiting
2020         NetworkPacket pkt(TOSERVER_MODCHANNEL_MSG, 2 + channel.size() + 2 + message.size());
2021         pkt << channel << message;
2022         Send(&pkt);
2023         return true;
2024 }
2025
2026 ModChannel* Client::getModChannel(const std::string &channel)
2027 {
2028         return m_modchannel_mgr->getModChannel(channel);
2029 }