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