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