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