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