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