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