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