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