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