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