Use proper CMakeLists.txt for network and client directories
[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_back(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::list<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::list<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 }
960
961 void Client::interact(u8 action, const PointedThing& pointed)
962 {
963         if(m_state != LC_Ready) {
964                 errorstream << "Client::interact() "
965                                 "cancelled (not connected)"
966                                 << std::endl;
967                 return;
968         }
969
970         /*
971                 [0] u16 command
972                 [2] u8 action
973                 [3] u16 item
974                 [5] u32 length of the next item
975                 [9] serialized PointedThing
976                 actions:
977                 0: start digging (from undersurface) or use
978                 1: stop digging (all parameters ignored)
979                 2: digging completed
980                 3: place block or item (to abovesurface)
981                 4: use item
982         */
983
984         NetworkPacket* pkt = new NetworkPacket(TOSERVER_INTERACT, 1 + 2 + 0);
985
986         *pkt << action;
987         *pkt << (u16)getPlayerItem();
988
989         std::ostringstream tmp_os(std::ios::binary);
990         pointed.serialize(tmp_os);
991
992         pkt->putLongString(tmp_os.str());
993
994         Send(pkt);
995 }
996
997 void Client::sendNodemetaFields(v3s16 p, const std::string &formname,
998                 const std::map<std::string, std::string> &fields)
999 {
1000         size_t fields_size = fields.size();
1001         assert(fields_size <= 0xFFFF);
1002
1003         NetworkPacket* pkt = new NetworkPacket(TOSERVER_NODEMETA_FIELDS, 0);
1004
1005         *pkt << p << formname << (u16) (fields_size & 0xFFFF);
1006
1007         for(std::map<std::string, std::string>::const_iterator
1008                         i = fields.begin(); i != fields.end(); i++) {
1009                 const std::string &name = i->first;
1010                 const std::string &value = i->second;
1011                 *pkt << name;
1012                 pkt->putLongString(value);
1013         }
1014
1015         Send(pkt);
1016 }
1017
1018 void Client::sendInventoryFields(const std::string &formname,
1019                 const std::map<std::string, std::string> &fields)
1020 {
1021         size_t fields_size = fields.size();
1022         assert(fields_size <= 0xFFFF);
1023
1024         NetworkPacket* pkt = new NetworkPacket(TOSERVER_INVENTORY_FIELDS, 0);
1025         *pkt << formname << (u16) (fields_size & 0xFFFF);
1026
1027         for(std::map<std::string, std::string>::const_iterator
1028                         i = fields.begin(); i != fields.end(); i++) {
1029                 const std::string &name  = i->first;
1030                 const std::string &value = i->second;
1031                 *pkt << name;
1032                 pkt->putLongString(value);
1033         }
1034
1035         Send(pkt);
1036 }
1037
1038 void Client::sendInventoryAction(InventoryAction *a)
1039 {
1040         std::ostringstream os(std::ios_base::binary);
1041
1042         a->serialize(os);
1043
1044         // Make data buffer
1045         std::string s = os.str();
1046
1047         NetworkPacket* pkt = new NetworkPacket(TOSERVER_INVENTORY_ACTION, s.size());
1048         pkt->putRawString(s.c_str(),s.size());
1049
1050         Send(pkt);
1051 }
1052
1053 void Client::sendChatMessage(const std::wstring &message)
1054 {
1055         NetworkPacket* pkt = new NetworkPacket(TOSERVER_CHAT_MESSAGE, 2 + message.size() * sizeof(u16));
1056
1057         *pkt << message;
1058
1059         Send(pkt);
1060 }
1061
1062 void Client::sendChangePassword(const std::wstring &oldpassword,
1063         const std::wstring &newpassword)
1064 {
1065         Player *player = m_env.getLocalPlayer();
1066         if(player == NULL)
1067                 return;
1068
1069         std::string playername = player->getName();
1070         std::string oldpwd = translatePassword(playername, oldpassword);
1071         std::string newpwd = translatePassword(playername, newpassword);
1072
1073         NetworkPacket* pkt = new NetworkPacket(TOSERVER_PASSWORD, 2 * PASSWORD_SIZE);
1074
1075         for(u8 i = 0; i < PASSWORD_SIZE; i++) {
1076                 *pkt << (u8) (i < oldpwd.length() ? oldpwd[i] : 0);
1077         }
1078
1079         for(u8 i = 0; i < PASSWORD_SIZE; i++) {
1080                 *pkt << (u8) (i < newpwd.length() ? newpwd[i] : 0);
1081         }
1082
1083         Send(pkt);
1084 }
1085
1086
1087 void Client::sendDamage(u8 damage)
1088 {
1089         DSTACK(__FUNCTION_NAME);
1090
1091         NetworkPacket* pkt = new NetworkPacket(TOSERVER_DAMAGE, sizeof(u8));
1092         *pkt << damage;
1093         Send(pkt);
1094 }
1095
1096 void Client::sendBreath(u16 breath)
1097 {
1098         DSTACK(__FUNCTION_NAME);
1099
1100         NetworkPacket* pkt = new NetworkPacket(TOSERVER_BREATH, sizeof(u16));
1101         *pkt << breath;
1102         Send(pkt);
1103 }
1104
1105 void Client::sendRespawn()
1106 {
1107         DSTACK(__FUNCTION_NAME);
1108
1109         NetworkPacket* pkt = new NetworkPacket(TOSERVER_RESPAWN, 0);
1110         Send(pkt);
1111 }
1112
1113 void Client::sendReady()
1114 {
1115         DSTACK(__FUNCTION_NAME);
1116
1117         NetworkPacket* pkt = new NetworkPacket(TOSERVER_CLIENT_READY,
1118                         1 + 1 + 1 + 1 + 2 + sizeof(char) * strlen(minetest_version_hash));
1119
1120         *pkt << (u8) VERSION_MAJOR << (u8) VERSION_MINOR << (u8) VERSION_PATCH_ORIG
1121                 << (u8) 0 << (u16) strlen(minetest_version_hash);
1122
1123         pkt->putRawString(minetest_version_hash, (u16) strlen(minetest_version_hash));
1124         Send(pkt);
1125 }
1126
1127 void Client::sendPlayerPos()
1128 {
1129         LocalPlayer *myplayer = m_env.getLocalPlayer();
1130         if(myplayer == NULL)
1131                 return;
1132
1133         // Save bandwidth by only updating position when something changed
1134         if(myplayer->last_position        == myplayer->getPosition() &&
1135                         myplayer->last_speed      == myplayer->getSpeed()    &&
1136                         myplayer->last_pitch      == myplayer->getPitch()    &&
1137                         myplayer->last_yaw        == myplayer->getYaw()      &&
1138                         myplayer->last_keyPressed == myplayer->keyPressed)
1139                 return;
1140
1141         myplayer->last_position   = myplayer->getPosition();
1142         myplayer->last_speed      = myplayer->getSpeed();
1143         myplayer->last_pitch      = myplayer->getPitch();
1144         myplayer->last_yaw        = myplayer->getYaw();
1145         myplayer->last_keyPressed = myplayer->keyPressed;
1146
1147         u16 our_peer_id;
1148         {
1149                 //JMutexAutoLock lock(m_con_mutex); //bulk comment-out
1150                 our_peer_id = m_con.GetPeerID();
1151         }
1152
1153         // Set peer id if not set already
1154         if(myplayer->peer_id == PEER_ID_INEXISTENT)
1155                 myplayer->peer_id = our_peer_id;
1156         // Check that an existing peer_id is the same as the connection's
1157         assert(myplayer->peer_id == our_peer_id);
1158
1159         v3f pf         = myplayer->getPosition();
1160         v3f sf         = myplayer->getSpeed();
1161         s32 pitch      = myplayer->getPitch() * 100;
1162         s32 yaw        = myplayer->getYaw() * 100;
1163         u32 keyPressed = myplayer->keyPressed;
1164
1165         v3s32 position(pf.X*100, pf.Y*100, pf.Z*100);
1166         v3s32 speed(sf.X*100, sf.Y*100, sf.Z*100);
1167         /*
1168                 Format:
1169                 [0] v3s32 position*100
1170                 [12] v3s32 speed*100
1171                 [12+12] s32 pitch*100
1172                 [12+12+4] s32 yaw*100
1173                 [12+12+4+4] u32 keyPressed
1174         */
1175
1176         NetworkPacket* pkt = new NetworkPacket(TOSERVER_PLAYERPOS, 12 + 12 + 4 + 4 + 4);
1177
1178         *pkt << position << speed << pitch << yaw << keyPressed;
1179
1180         Send(pkt);
1181 }
1182
1183 void Client::sendPlayerItem(u16 item)
1184 {
1185         Player *myplayer = m_env.getLocalPlayer();
1186         if(myplayer == NULL)
1187                 return;
1188
1189         u16 our_peer_id = m_con.GetPeerID();
1190
1191         // Set peer id if not set already
1192         if(myplayer->peer_id == PEER_ID_INEXISTENT)
1193                 myplayer->peer_id = our_peer_id;
1194
1195         // Check that an existing peer_id is the same as the connection's
1196         assert(myplayer->peer_id == our_peer_id);
1197
1198         NetworkPacket* pkt = new NetworkPacket(TOSERVER_PLAYERITEM, 2);
1199
1200         *pkt << item;
1201
1202         Send(pkt);
1203 }
1204
1205 void Client::removeNode(v3s16 p)
1206 {
1207         std::map<v3s16, MapBlock*> modified_blocks;
1208
1209         try {
1210                 m_env.getMap().removeNodeAndUpdate(p, modified_blocks);
1211         }
1212         catch(InvalidPositionException &e) {
1213         }
1214
1215         for(std::map<v3s16, MapBlock *>::iterator
1216                         i = modified_blocks.begin();
1217                         i != modified_blocks.end(); ++i) {
1218                 addUpdateMeshTaskWithEdge(i->first, false, true);
1219         }
1220 }
1221
1222 void Client::addNode(v3s16 p, MapNode n, bool remove_metadata)
1223 {
1224         //TimeTaker timer1("Client::addNode()");
1225
1226         std::map<v3s16, MapBlock*> modified_blocks;
1227
1228         try {
1229                 //TimeTaker timer3("Client::addNode(): addNodeAndUpdate");
1230                 m_env.getMap().addNodeAndUpdate(p, n, modified_blocks, remove_metadata);
1231         }
1232         catch(InvalidPositionException &e) {
1233         }
1234
1235         for(std::map<v3s16, MapBlock *>::iterator
1236                         i = modified_blocks.begin();
1237                         i != modified_blocks.end(); ++i) {
1238                 addUpdateMeshTaskWithEdge(i->first, false, true);
1239         }
1240 }
1241
1242 void Client::setPlayerControl(PlayerControl &control)
1243 {
1244         LocalPlayer *player = m_env.getLocalPlayer();
1245         assert(player != NULL);
1246         player->control = control;
1247 }
1248
1249 void Client::selectPlayerItem(u16 item)
1250 {
1251         m_playeritem = item;
1252         m_inventory_updated = true;
1253         sendPlayerItem(item);
1254 }
1255
1256 // Returns true if the inventory of the local player has been
1257 // updated from the server. If it is true, it is set to false.
1258 bool Client::getLocalInventoryUpdated()
1259 {
1260         bool updated = m_inventory_updated;
1261         m_inventory_updated = false;
1262         return updated;
1263 }
1264
1265 // Copies the inventory of the local player to parameter
1266 void Client::getLocalInventory(Inventory &dst)
1267 {
1268         Player *player = m_env.getLocalPlayer();
1269         assert(player != NULL);
1270         dst = player->inventory;
1271 }
1272
1273 Inventory* Client::getInventory(const InventoryLocation &loc)
1274 {
1275         switch(loc.type){
1276         case InventoryLocation::UNDEFINED:
1277         {}
1278         break;
1279         case InventoryLocation::CURRENT_PLAYER:
1280         {
1281                 Player *player = m_env.getLocalPlayer();
1282                 assert(player != NULL);
1283                 return &player->inventory;
1284         }
1285         break;
1286         case InventoryLocation::PLAYER:
1287         {
1288                 Player *player = m_env.getPlayer(loc.name.c_str());
1289                 if(!player)
1290                         return NULL;
1291                 return &player->inventory;
1292         }
1293         break;
1294         case InventoryLocation::NODEMETA:
1295         {
1296                 NodeMetadata *meta = m_env.getMap().getNodeMetadata(loc.p);
1297                 if(!meta)
1298                         return NULL;
1299                 return meta->getInventory();
1300         }
1301         break;
1302         case InventoryLocation::DETACHED:
1303         {
1304                 if(m_detached_inventories.count(loc.name) == 0)
1305                         return NULL;
1306                 return m_detached_inventories[loc.name];
1307         }
1308         break;
1309         default:
1310                 assert(0);
1311         }
1312         return NULL;
1313 }
1314
1315 void Client::inventoryAction(InventoryAction *a)
1316 {
1317         /*
1318                 Send it to the server
1319         */
1320         sendInventoryAction(a);
1321
1322         /*
1323                 Predict some local inventory changes
1324         */
1325         a->clientApply(this, this);
1326
1327         // Remove it
1328         delete a;
1329 }
1330
1331 ClientActiveObject * Client::getSelectedActiveObject(
1332                 f32 max_d,
1333                 v3f from_pos_f_on_map,
1334                 core::line3d<f32> shootline_on_map
1335         )
1336 {
1337         std::vector<DistanceSortedActiveObject> objects;
1338
1339         m_env.getActiveObjects(from_pos_f_on_map, max_d, objects);
1340
1341         // Sort them.
1342         // After this, the closest object is the first in the array.
1343         std::sort(objects.begin(), objects.end());
1344
1345         for(unsigned int i=0; i<objects.size(); i++)
1346         {
1347                 ClientActiveObject *obj = objects[i].obj;
1348
1349                 core::aabbox3d<f32> *selection_box = obj->getSelectionBox();
1350                 if(selection_box == NULL)
1351                         continue;
1352
1353                 v3f pos = obj->getPosition();
1354
1355                 core::aabbox3d<f32> offsetted_box(
1356                                 selection_box->MinEdge + pos,
1357                                 selection_box->MaxEdge + pos
1358                 );
1359
1360                 if(offsetted_box.intersectsWithLine(shootline_on_map))
1361                 {
1362                         return obj;
1363                 }
1364         }
1365
1366         return NULL;
1367 }
1368
1369 std::list<std::string> Client::getConnectedPlayerNames()
1370 {
1371         return m_env.getPlayerNames();
1372 }
1373
1374 float Client::getAnimationTime()
1375 {
1376         return m_animation_time;
1377 }
1378
1379 int Client::getCrackLevel()
1380 {
1381         return m_crack_level;
1382 }
1383
1384 void Client::setHighlighted(v3s16 pos, bool show_highlighted)
1385 {
1386         m_show_highlighted = show_highlighted;
1387         v3s16 old_highlighted_pos = m_highlighted_pos;
1388         m_highlighted_pos = pos;
1389         addUpdateMeshTaskForNode(old_highlighted_pos, false, true);
1390         addUpdateMeshTaskForNode(m_highlighted_pos, false, true);
1391 }
1392
1393 void Client::setCrack(int level, v3s16 pos)
1394 {
1395         int old_crack_level = m_crack_level;
1396         v3s16 old_crack_pos = m_crack_pos;
1397
1398         m_crack_level = level;
1399         m_crack_pos = pos;
1400
1401         if(old_crack_level >= 0 && (level < 0 || pos != old_crack_pos))
1402         {
1403                 // remove old crack
1404                 addUpdateMeshTaskForNode(old_crack_pos, false, true);
1405         }
1406         if(level >= 0 && (old_crack_level < 0 || pos != old_crack_pos))
1407         {
1408                 // add new crack
1409                 addUpdateMeshTaskForNode(pos, false, true);
1410         }
1411 }
1412
1413 u16 Client::getHP()
1414 {
1415         Player *player = m_env.getLocalPlayer();
1416         assert(player != NULL);
1417         return player->hp;
1418 }
1419
1420 u16 Client::getBreath()
1421 {
1422         Player *player = m_env.getLocalPlayer();
1423         assert(player != NULL);
1424         return player->getBreath();
1425 }
1426
1427 bool Client::getChatMessage(std::wstring &message)
1428 {
1429         if(m_chat_queue.size() == 0)
1430                 return false;
1431         message = m_chat_queue.pop_front();
1432         return true;
1433 }
1434
1435 void Client::typeChatMessage(const std::wstring &message)
1436 {
1437         // Discard empty line
1438         if(message == L"")
1439                 return;
1440
1441         // Send to others
1442         sendChatMessage(message);
1443
1444         // Show locally
1445         if (message[0] == L'/')
1446         {
1447                 m_chat_queue.push_back((std::wstring)L"issued command: " + message);
1448         }
1449         else
1450         {
1451                 LocalPlayer *player = m_env.getLocalPlayer();
1452                 assert(player != NULL);
1453                 std::wstring name = narrow_to_wide(player->getName());
1454                 m_chat_queue.push_back((std::wstring)L"<" + name + L"> " + message);
1455         }
1456 }
1457
1458 void Client::addUpdateMeshTask(v3s16 p, bool ack_to_server, bool urgent)
1459 {
1460         MapBlock *b = m_env.getMap().getBlockNoCreateNoEx(p);
1461         if(b == NULL)
1462                 return;
1463
1464         /*
1465                 Create a task to update the mesh of the block
1466         */
1467
1468         MeshMakeData *data = new MeshMakeData(this, m_cache_enable_shaders);
1469
1470         {
1471                 //TimeTaker timer("data fill");
1472                 // Release: ~0ms
1473                 // Debug: 1-6ms, avg=2ms
1474                 data->fill(b);
1475                 data->setCrack(m_crack_level, m_crack_pos);
1476                 data->setHighlighted(m_highlighted_pos, m_show_highlighted);
1477                 data->setSmoothLighting(m_cache_smooth_lighting);
1478         }
1479
1480         // Add task to queue
1481         m_mesh_update_thread.m_queue_in.addBlock(p, data, ack_to_server, urgent);
1482 }
1483
1484 void Client::addUpdateMeshTaskWithEdge(v3s16 blockpos, bool ack_to_server, bool urgent)
1485 {
1486         try{
1487                 addUpdateMeshTask(blockpos, ack_to_server, urgent);
1488         }
1489         catch(InvalidPositionException &e){}
1490
1491         // Leading edge
1492         for (int i=0;i<6;i++)
1493         {
1494                 try{
1495                         v3s16 p = blockpos + g_6dirs[i];
1496                         addUpdateMeshTask(p, false, urgent);
1497                 }
1498                 catch(InvalidPositionException &e){}
1499         }
1500 }
1501
1502 void Client::addUpdateMeshTaskForNode(v3s16 nodepos, bool ack_to_server, bool urgent)
1503 {
1504         {
1505                 v3s16 p = nodepos;
1506                 infostream<<"Client::addUpdateMeshTaskForNode(): "
1507                                 <<"("<<p.X<<","<<p.Y<<","<<p.Z<<")"
1508                                 <<std::endl;
1509         }
1510
1511         v3s16 blockpos          = getNodeBlockPos(nodepos);
1512         v3s16 blockpos_relative = blockpos * MAP_BLOCKSIZE;
1513
1514         try{
1515                 addUpdateMeshTask(blockpos, ack_to_server, urgent);
1516         }
1517         catch(InvalidPositionException &e) {}
1518
1519         // Leading edge
1520         if(nodepos.X == blockpos_relative.X){
1521                 try{
1522                         v3s16 p = blockpos + v3s16(-1,0,0);
1523                         addUpdateMeshTask(p, false, urgent);
1524                 }
1525                 catch(InvalidPositionException &e){}
1526         }
1527
1528         if(nodepos.Y == blockpos_relative.Y){
1529                 try{
1530                         v3s16 p = blockpos + v3s16(0,-1,0);
1531                         addUpdateMeshTask(p, false, urgent);
1532                 }
1533                 catch(InvalidPositionException &e){}
1534         }
1535
1536         if(nodepos.Z == blockpos_relative.Z){
1537                 try{
1538                         v3s16 p = blockpos + v3s16(0,0,-1);
1539                         addUpdateMeshTask(p, false, urgent);
1540                 }
1541                 catch(InvalidPositionException &e){}
1542         }
1543 }
1544
1545 ClientEvent Client::getClientEvent()
1546 {
1547         if(m_client_event_queue.size() == 0)
1548         {
1549                 ClientEvent event;
1550                 event.type = CE_NONE;
1551                 return event;
1552         }
1553         return m_client_event_queue.pop_front();
1554 }
1555
1556 float Client::mediaReceiveProgress()
1557 {
1558         if (m_media_downloader)
1559                 return m_media_downloader->getProgress();
1560         else
1561                 return 1.0; // downloader only exists when not yet done
1562 }
1563
1564 void Client::afterContentReceived(IrrlichtDevice *device, gui::IGUIFont* font)
1565 {
1566         infostream<<"Client::afterContentReceived() started"<<std::endl;
1567         assert(m_itemdef_received);
1568         assert(m_nodedef_received);
1569         assert(mediaReceived());
1570
1571         const wchar_t* text = wgettext("Loading textures...");
1572
1573         // Rebuild inherited images and recreate textures
1574         infostream<<"- Rebuilding images and textures"<<std::endl;
1575         draw_load_screen(text,device, guienv, 0, 70);
1576         m_tsrc->rebuildImagesAndTextures();
1577         delete[] text;
1578
1579         // Rebuild shaders
1580         infostream<<"- Rebuilding shaders"<<std::endl;
1581         text = wgettext("Rebuilding shaders...");
1582         draw_load_screen(text, device, guienv, 0, 75);
1583         m_shsrc->rebuildShaders();
1584         delete[] text;
1585
1586         // Update node aliases
1587         infostream<<"- Updating node aliases"<<std::endl;
1588         text = wgettext("Initializing nodes...");
1589         draw_load_screen(text, device, guienv, 0, 80);
1590         m_nodedef->updateAliases(m_itemdef);
1591         m_nodedef->setNodeRegistrationStatus(true);
1592         m_nodedef->runNodeResolverCallbacks();
1593         delete[] text;
1594
1595         // Update node textures and assign shaders to each tile
1596         infostream<<"- Updating node textures"<<std::endl;
1597         m_nodedef->updateTextures(this);
1598
1599         // Preload item textures and meshes if configured to
1600         if(g_settings->getBool("preload_item_visuals"))
1601         {
1602                 verbosestream<<"Updating item textures and meshes"<<std::endl;
1603                 text = wgettext("Item textures...");
1604                 draw_load_screen(text, device, guienv, 0, 0);
1605                 std::set<std::string> names = m_itemdef->getAll();
1606                 size_t size = names.size();
1607                 size_t count = 0;
1608                 int percent = 0;
1609                 for(std::set<std::string>::const_iterator
1610                                 i = names.begin(); i != names.end(); ++i)
1611                 {
1612                         // Asking for these caches the result
1613                         m_itemdef->getInventoryTexture(*i, this);
1614                         m_itemdef->getWieldMesh(*i, this);
1615                         count++;
1616                         percent = (count * 100 / size * 0.2) + 80;
1617                         draw_load_screen(text, device, guienv, 0, percent);
1618                 }
1619                 delete[] text;
1620         }
1621
1622         // Start mesh update thread after setting up content definitions
1623         infostream<<"- Starting mesh update thread"<<std::endl;
1624         m_mesh_update_thread.Start();
1625
1626         m_state = LC_Ready;
1627         sendReady();
1628         text = wgettext("Done!");
1629         draw_load_screen(text, device, guienv, 0, 100);
1630         infostream<<"Client::afterContentReceived() done"<<std::endl;
1631         delete[] text;
1632 }
1633
1634 float Client::getRTT(void)
1635 {
1636         return m_con.getPeerStat(PEER_ID_SERVER,con::AVG_RTT);
1637 }
1638
1639 float Client::getCurRate(void)
1640 {
1641         return ( m_con.getLocalStat(con::CUR_INC_RATE) +
1642                         m_con.getLocalStat(con::CUR_DL_RATE));
1643 }
1644
1645 float Client::getAvgRate(void)
1646 {
1647         return ( m_con.getLocalStat(con::AVG_INC_RATE) +
1648                         m_con.getLocalStat(con::AVG_DL_RATE));
1649 }
1650
1651 void Client::makeScreenshot(IrrlichtDevice *device)
1652 {
1653         irr::video::IVideoDriver *driver = device->getVideoDriver();
1654         irr::video::IImage* const raw_image = driver->createScreenShot();
1655         if (raw_image) {
1656                 irr::video::IImage* const image = driver->createImage(video::ECF_R8G8B8,
1657                         raw_image->getDimension());
1658
1659                 if (image) {
1660                         raw_image->copyTo(image);
1661                         irr::c8 filename[256];
1662                         snprintf(filename, sizeof(filename), "%s" DIR_DELIM "screenshot_%u.png",
1663                                  g_settings->get("screenshot_path").c_str(),
1664                                  device->getTimer()->getRealTime());
1665                         std::ostringstream sstr;
1666                         if (driver->writeImageToFile(image, filename)) {
1667                                 sstr << "Saved screenshot to '" << filename << "'";
1668                         } else {
1669                                 sstr << "Failed to save screenshot '" << filename << "'";
1670                         }
1671                         m_chat_queue.push_back(narrow_to_wide(sstr.str()));
1672                         infostream << sstr.str() << std::endl;
1673                         image->drop();
1674                 }
1675                 raw_image->drop();
1676         }
1677 }
1678
1679 // IGameDef interface
1680 // Under envlock
1681 IItemDefManager* Client::getItemDefManager()
1682 {
1683         return m_itemdef;
1684 }
1685 INodeDefManager* Client::getNodeDefManager()
1686 {
1687         return m_nodedef;
1688 }
1689 ICraftDefManager* Client::getCraftDefManager()
1690 {
1691         return NULL;
1692         //return m_craftdef;
1693 }
1694 ITextureSource* Client::getTextureSource()
1695 {
1696         return m_tsrc;
1697 }
1698 IShaderSource* Client::getShaderSource()
1699 {
1700         return m_shsrc;
1701 }
1702 scene::ISceneManager* Client::getSceneManager()
1703 {
1704         return m_device->getSceneManager();
1705 }
1706 u16 Client::allocateUnknownNodeId(const std::string &name)
1707 {
1708         errorstream<<"Client::allocateUnknownNodeId(): "
1709                         <<"Client cannot allocate node IDs"<<std::endl;
1710         assert(0);
1711         return CONTENT_IGNORE;
1712 }
1713 ISoundManager* Client::getSoundManager()
1714 {
1715         return m_sound;
1716 }
1717 MtEventManager* Client::getEventManager()
1718 {
1719         return m_event;
1720 }
1721
1722 ParticleManager* Client::getParticleManager()
1723 {
1724         return &m_particle_manager;
1725 }
1726
1727 scene::IAnimatedMesh* Client::getMesh(const std::string &filename)
1728 {
1729         std::map<std::string, std::string>::const_iterator i =
1730                         m_mesh_data.find(filename);
1731         if(i == m_mesh_data.end()){
1732                 errorstream<<"Client::getMesh(): Mesh not found: \""<<filename<<"\""
1733                                 <<std::endl;
1734                 return NULL;
1735         }
1736         const std::string &data    = i->second;
1737         scene::ISceneManager *smgr = m_device->getSceneManager();
1738
1739         // Create the mesh, remove it from cache and return it
1740         // This allows unique vertex colors and other properties for each instance
1741         Buffer<char> data_rw(data.c_str(), data.size()); // Const-incorrect Irrlicht
1742         io::IFileSystem *irrfs = m_device->getFileSystem();
1743         io::IReadFile *rfile   = irrfs->createMemoryReadFile(
1744                         *data_rw, data_rw.getSize(), filename.c_str());
1745         assert(rfile);
1746
1747         scene::IAnimatedMesh *mesh = smgr->getMesh(rfile);
1748         rfile->drop();
1749         // NOTE: By playing with Irrlicht refcounts, maybe we could cache a bunch
1750         // of uniquely named instances and re-use them
1751         mesh->grab();
1752         smgr->getMeshCache()->removeMesh(mesh);
1753         return mesh;
1754 }