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