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