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