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