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