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