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