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