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