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