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