A third try on terrain generation. No trees yet.
[oweals/minetest.git] / src / client.cpp
1 /*
2 Minetest-c55
3 Copyright (C) 2010 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 General Public License as published by
7 the Free Software Foundation; either version 2 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 General Public License for more details.
14
15 You should have received a copy of the GNU 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 "client.h"
21 #include "utility.h"
22 #include <iostream>
23 #include "clientserver.h"
24 #include "jmutexautolock.h"
25 #include "main.h"
26 #include <sstream>
27 #include "porting.h"
28
29 void * ClientUpdateThread::Thread()
30 {
31         ThreadStarted();
32
33         DSTACK(__FUNCTION_NAME);
34         
35         BEGIN_DEBUG_EXCEPTION_HANDLER
36         
37         while(getRun())
38         {
39                 m_client->asyncStep();
40
41                 //m_client->updateSomeExpiredMeshes();
42
43                 bool was = m_client->AsyncProcessData();
44
45                 if(was == false)
46                         sleep_ms(10);
47         }
48
49         END_DEBUG_EXCEPTION_HANDLER
50
51         return NULL;
52 }
53
54 Client::Client(
55                 IrrlichtDevice *device,
56                 const char *playername,
57                 MapDrawControl &control):
58         m_thread(this),
59         m_env(
60                 new ClientMap(this, control,
61                         device->getSceneManager()->getRootSceneNode(),
62                         device->getSceneManager(), 666),
63                 device->getSceneManager()
64         ),
65         m_con(PROTOCOL_ID, 512, CONNECTION_TIMEOUT, this),
66         m_device(device),
67         camera_position(0,0,0),
68         camera_direction(0,0,1),
69         m_server_ser_ver(SER_FMT_VER_INVALID),
70         m_step_dtime(0.0),
71         m_inventory_updated(false),
72         m_time_of_day(0)
73 {
74         m_packetcounter_timer = 0.0;
75         m_delete_unused_sectors_timer = 0.0;
76         m_connection_reinit_timer = 0.0;
77         m_avg_rtt_timer = 0.0;
78         m_playerpos_send_timer = 0.0;
79
80         //m_fetchblock_mutex.Init();
81         m_incoming_queue_mutex.Init();
82         m_env_mutex.Init();
83         m_con_mutex.Init();
84         m_step_dtime_mutex.Init();
85
86         m_thread.Start();
87
88         /*
89                 Add local player
90         */
91         {
92                 JMutexAutoLock envlock(m_env_mutex);
93
94                 Player *player = new LocalPlayer();
95
96                 player->updateName(playername);
97
98                 m_env.addPlayer(player);
99         }
100
101         // Add some active objects for testing
102         /*{
103                 ClientActiveObject *obj = new TestCAO(0, v3f(0, 10*BS, 0));
104                 m_env.addActiveObject(obj);
105         }*/
106 }
107
108 Client::~Client()
109 {
110         {
111                 JMutexAutoLock conlock(m_con_mutex);
112                 m_con.Disconnect();
113         }
114
115         m_thread.setRun(false);
116         while(m_thread.IsRunning())
117                 sleep_ms(100);
118 }
119
120 void Client::connect(Address address)
121 {
122         DSTACK(__FUNCTION_NAME);
123         JMutexAutoLock lock(m_con_mutex);
124         m_con.setTimeoutMs(0);
125         m_con.Connect(address);
126 }
127
128 bool Client::connectedAndInitialized()
129 {
130         JMutexAutoLock lock(m_con_mutex);
131
132         if(m_con.Connected() == false)
133                 return false;
134         
135         if(m_server_ser_ver == SER_FMT_VER_INVALID)
136                 return false;
137         
138         return true;
139 }
140
141 void Client::step(float dtime)
142 {
143         DSTACK(__FUNCTION_NAME);
144         
145         // Limit a bit
146         if(dtime > 2.0)
147                 dtime = 2.0;
148         
149         
150         //dstream<<"Client steps "<<dtime<<std::endl;
151
152         {
153                 //TimeTaker timer("ReceiveAll()", m_device);
154                 // 0ms
155                 ReceiveAll();
156         }
157         
158         {
159                 //TimeTaker timer("m_con_mutex + m_con.RunTimeouts()", m_device);
160                 // 0ms
161                 JMutexAutoLock lock(m_con_mutex);
162                 m_con.RunTimeouts(dtime);
163         }
164
165         /*
166                 Packet counter
167         */
168         {
169                 float &counter = m_packetcounter_timer;
170                 counter -= dtime;
171                 if(counter <= 0.0)
172                 {
173                         counter = 20.0;
174                         
175                         dout_client<<"Client packetcounter (20s):"<<std::endl;
176                         m_packetcounter.print(dout_client);
177                         m_packetcounter.clear();
178                 }
179         }
180
181         {
182                 /*
183                         Delete unused sectors
184
185                         NOTE: This jams the game for a while because deleting sectors
186                               clear caches
187                 */
188                 
189                 float &counter = m_delete_unused_sectors_timer;
190                 counter -= dtime;
191                 if(counter <= 0.0)
192                 {
193                         // 3 minute interval
194                         //counter = 180.0;
195                         counter = 60.0;
196
197                         JMutexAutoLock lock(m_env_mutex);
198
199                         core::list<v3s16> deleted_blocks;
200
201                         float delete_unused_sectors_timeout = 
202                                 g_settings.getFloat("client_delete_unused_sectors_timeout");
203         
204                         // Delete sector blocks
205                         /*u32 num = m_env.getMap().deleteUnusedSectors
206                                         (delete_unused_sectors_timeout,
207                                         true, &deleted_blocks);*/
208                         
209                         // Delete whole sectors
210                         u32 num = m_env.getMap().deleteUnusedSectors
211                                         (delete_unused_sectors_timeout,
212                                         false, &deleted_blocks);
213
214                         if(num > 0)
215                         {
216                                 /*dstream<<DTIME<<"Client: Deleted blocks of "<<num
217                                                 <<" unused sectors"<<std::endl;*/
218                                 dstream<<DTIME<<"Client: Deleted "<<num
219                                                 <<" unused sectors"<<std::endl;
220                                 
221                                 /*
222                                         Send info to server
223                                 */
224
225                                 // Env is locked so con can be locked.
226                                 JMutexAutoLock lock(m_con_mutex);
227                                 
228                                 core::list<v3s16>::Iterator i = deleted_blocks.begin();
229                                 core::list<v3s16> sendlist;
230                                 for(;;)
231                                 {
232                                         if(sendlist.size() == 255 || i == deleted_blocks.end())
233                                         {
234                                                 if(sendlist.size() == 0)
235                                                         break;
236                                                 /*
237                                                         [0] u16 command
238                                                         [2] u8 count
239                                                         [3] v3s16 pos_0
240                                                         [3+6] v3s16 pos_1
241                                                         ...
242                                                 */
243                                                 u32 replysize = 2+1+6*sendlist.size();
244                                                 SharedBuffer<u8> reply(replysize);
245                                                 writeU16(&reply[0], TOSERVER_DELETEDBLOCKS);
246                                                 reply[2] = sendlist.size();
247                                                 u32 k = 0;
248                                                 for(core::list<v3s16>::Iterator
249                                                                 j = sendlist.begin();
250                                                                 j != sendlist.end(); j++)
251                                                 {
252                                                         writeV3S16(&reply[2+1+6*k], *j);
253                                                         k++;
254                                                 }
255                                                 m_con.Send(PEER_ID_SERVER, 1, reply, true);
256
257                                                 if(i == deleted_blocks.end())
258                                                         break;
259
260                                                 sendlist.clear();
261                                         }
262
263                                         sendlist.push_back(*i);
264                                         i++;
265                                 }
266                         }
267                 }
268         }
269
270         bool connected = connectedAndInitialized();
271
272         if(connected == false)
273         {
274                 float &counter = m_connection_reinit_timer;
275                 counter -= dtime;
276                 if(counter <= 0.0)
277                 {
278                         counter = 2.0;
279
280                         JMutexAutoLock envlock(m_env_mutex);
281                         
282                         Player *myplayer = m_env.getLocalPlayer();
283                         assert(myplayer != NULL);
284         
285                         // Send TOSERVER_INIT
286                         // [0] u16 TOSERVER_INIT
287                         // [2] u8 SER_FMT_VER_HIGHEST
288                         // [3] u8[20] player_name
289                         SharedBuffer<u8> data(2+1+PLAYERNAME_SIZE);
290                         writeU16(&data[0], TOSERVER_INIT);
291                         writeU8(&data[2], SER_FMT_VER_HIGHEST);
292                         memset((char*)&data[3], 0, PLAYERNAME_SIZE);
293                         snprintf((char*)&data[3], PLAYERNAME_SIZE, "%s", myplayer->getName());
294                         // Send as unreliable
295                         Send(0, data, false);
296                 }
297
298                 // Not connected, return
299                 return;
300         }
301
302         /*
303                 Do stuff if connected
304         */
305         
306         {
307                 // 0ms
308                 JMutexAutoLock lock(m_env_mutex);
309
310                 // Control local player (0ms)
311                 LocalPlayer *player = m_env.getLocalPlayer();
312                 assert(player != NULL);
313                 player->applyControl(dtime);
314
315                 //TimeTaker envtimer("env step", m_device);
316                 // Step environment
317                 m_env.step(dtime);
318
319                 // Step active blocks
320                 for(core::map<v3s16, bool>::Iterator
321                                 i = m_active_blocks.getIterator();
322                                 i.atEnd() == false; i++)
323                 {
324                         v3s16 p = i.getNode()->getKey();
325
326                         MapBlock *block = NULL;
327                         try
328                         {
329                                 block = m_env.getMap().getBlockNoCreate(p);
330                                 block->stepObjects(dtime, false, m_env.getDayNightRatio());
331                         }
332                         catch(InvalidPositionException &e)
333                         {
334                         }
335                 }
336         }
337
338         {
339                 float &counter = m_avg_rtt_timer;
340                 counter += dtime;
341                 if(counter >= 10)
342                 {
343                         counter = 0.0;
344                         JMutexAutoLock lock(m_con_mutex);
345                         // connectedAndInitialized() is true, peer exists.
346                         con::Peer *peer = m_con.GetPeer(PEER_ID_SERVER);
347                         dstream<<DTIME<<"Client: avg_rtt="<<peer->avg_rtt<<std::endl;
348                 }
349         }
350         {
351                 float &counter = m_playerpos_send_timer;
352                 counter += dtime;
353                 if(counter >= 0.2)
354                 {
355                         counter = 0.0;
356                         sendPlayerPos();
357                 }
358         }
359
360         /*{
361                 JMutexAutoLock lock(m_step_dtime_mutex);
362                 m_step_dtime += dtime;
363         }*/
364 }
365
366 float Client::asyncStep()
367 {
368         DSTACK(__FUNCTION_NAME);
369         //dstream<<"Client::asyncStep()"<<std::endl;
370         
371         /*float dtime;
372         {
373                 JMutexAutoLock lock1(m_step_dtime_mutex);
374                 if(m_step_dtime < 0.001)
375                         return 0.0;
376                 dtime = m_step_dtime;
377                 m_step_dtime = 0.0;
378         }
379
380         return dtime;*/
381         return 0.0;
382 }
383
384 // Virtual methods from con::PeerHandler
385 void Client::peerAdded(con::Peer *peer)
386 {
387         derr_client<<"Client::peerAdded(): peer->id="
388                         <<peer->id<<std::endl;
389 }
390 void Client::deletingPeer(con::Peer *peer, bool timeout)
391 {
392         derr_client<<"Client::deletingPeer(): "
393                         "Server Peer is getting deleted "
394                         <<"(timeout="<<timeout<<")"<<std::endl;
395 }
396
397 void Client::ReceiveAll()
398 {
399         DSTACK(__FUNCTION_NAME);
400         for(;;)
401         {
402                 try{
403                         Receive();
404                 }
405                 catch(con::NoIncomingDataException &e)
406                 {
407                         break;
408                 }
409                 catch(con::InvalidIncomingDataException &e)
410                 {
411                         dout_client<<DTIME<<"Client::ReceiveAll(): "
412                                         "InvalidIncomingDataException: what()="
413                                         <<e.what()<<std::endl;
414                 }
415         }
416 }
417
418 void Client::Receive()
419 {
420         DSTACK(__FUNCTION_NAME);
421         u32 data_maxsize = 10000;
422         Buffer<u8> data(data_maxsize);
423         u16 sender_peer_id;
424         u32 datasize;
425         {
426                 //TimeTaker t1("con mutex and receive", m_device);
427                 JMutexAutoLock lock(m_con_mutex);
428                 datasize = m_con.Receive(sender_peer_id, *data, data_maxsize);
429         }
430         //TimeTaker t1("ProcessData", m_device);
431         ProcessData(*data, datasize, sender_peer_id);
432 }
433
434 /*
435         sender_peer_id given to this shall be quaranteed to be a valid peer
436 */
437 void Client::ProcessData(u8 *data, u32 datasize, u16 sender_peer_id)
438 {
439         DSTACK(__FUNCTION_NAME);
440
441         // Ignore packets that don't even fit a command
442         if(datasize < 2)
443         {
444                 m_packetcounter.add(60000);
445                 return;
446         }
447
448         ToClientCommand command = (ToClientCommand)readU16(&data[0]);
449
450         //dstream<<"Client: received command="<<command<<std::endl;
451         m_packetcounter.add((u16)command);
452         
453         /*
454                 If this check is removed, be sure to change the queue
455                 system to know the ids
456         */
457         if(sender_peer_id != PEER_ID_SERVER)
458         {
459                 dout_client<<DTIME<<"Client::ProcessData(): Discarding data not "
460                                 "coming from server: peer_id="<<sender_peer_id
461                                 <<std::endl;
462                 return;
463         }
464
465         con::Peer *peer;
466         {
467                 JMutexAutoLock lock(m_con_mutex);
468                 // All data is coming from the server
469                 // PeerNotFoundException is handled by caller.
470                 peer = m_con.GetPeer(PEER_ID_SERVER);
471         }
472
473         u8 ser_version = m_server_ser_ver;
474
475         //dstream<<"Client received command="<<(int)command<<std::endl;
476
477         // Execute fast commands straight away
478
479         if(command == TOCLIENT_INIT)
480         {
481                 if(datasize < 3)
482                         return;
483
484                 u8 deployed = data[2];
485
486                 dout_client<<DTIME<<"Client: TOCLIENT_INIT received with "
487                                 "deployed="<<((int)deployed&0xff)<<std::endl;
488
489                 if(deployed < SER_FMT_VER_LOWEST
490                                 || deployed > SER_FMT_VER_HIGHEST)
491                 {
492                         derr_client<<DTIME<<"Client: TOCLIENT_INIT: Server sent "
493                                         <<"unsupported ser_fmt_ver"<<std::endl;
494                         return;
495                 }
496                 
497                 m_server_ser_ver = deployed;
498
499                 // Get player position
500                 v3s16 playerpos_s16(0, BS*2+BS*20, 0);
501                 if(datasize >= 2+1+6)
502                         playerpos_s16 = readV3S16(&data[2+1]);
503                 v3f playerpos_f = intToFloat(playerpos_s16, BS) - v3f(0, BS/2, 0);
504
505                 { //envlock
506                         JMutexAutoLock envlock(m_env_mutex);
507                         
508                         // Set player position
509                         Player *player = m_env.getLocalPlayer();
510                         assert(player != NULL);
511                         player->setPosition(playerpos_f);
512                 }
513
514                 // Get map seed
515                 m_map_seed = readU64(&data[2+1+6]);
516                 dstream<<"Client: received map seed: "<<m_map_seed<<std::endl;
517                 
518                 // Reply to server
519                 u32 replysize = 2;
520                 SharedBuffer<u8> reply(replysize);
521                 writeU16(&reply[0], TOSERVER_INIT2);
522                 // Send as reliable
523                 m_con.Send(PEER_ID_SERVER, 1, reply, true);
524
525                 return;
526         }
527         
528         if(ser_version == SER_FMT_VER_INVALID)
529         {
530                 dout_client<<DTIME<<"WARNING: Client: Server serialization"
531                                 " format invalid or not initialized."
532                                 " Skipping incoming command="<<command<<std::endl;
533                 return;
534         }
535         
536         // Just here to avoid putting the two if's together when
537         // making some copypasta
538         {}
539
540         if(command == TOCLIENT_REMOVENODE)
541         {
542                 if(datasize < 8)
543                         return;
544                 v3s16 p;
545                 p.X = readS16(&data[2]);
546                 p.Y = readS16(&data[4]);
547                 p.Z = readS16(&data[6]);
548                 
549                 //TimeTaker t1("TOCLIENT_REMOVENODE", g_device);
550                 
551                 // This will clear the cracking animation after digging
552                 ((ClientMap&)m_env.getMap()).clearTempMod(p);
553
554                 removeNode(p);
555         }
556         else if(command == TOCLIENT_ADDNODE)
557         {
558                 if(datasize < 8 + MapNode::serializedLength(ser_version))
559                         return;
560
561                 v3s16 p;
562                 p.X = readS16(&data[2]);
563                 p.Y = readS16(&data[4]);
564                 p.Z = readS16(&data[6]);
565                 
566                 //TimeTaker t1("TOCLIENT_ADDNODE", g_device);
567
568                 MapNode n;
569                 n.deSerialize(&data[8], ser_version);
570                 
571                 addNode(p, n);
572         }
573         else if(command == TOCLIENT_PLAYERPOS)
574         {
575                 dstream<<"WARNING: Received deprecated TOCLIENT_PLAYERPOS"
576                                 <<std::endl;
577                 /*u16 our_peer_id;
578                 {
579                         JMutexAutoLock lock(m_con_mutex);
580                         our_peer_id = m_con.GetPeerID();
581                 }
582                 // Cancel if we don't have a peer id
583                 if(our_peer_id == PEER_ID_INEXISTENT){
584                         dout_client<<DTIME<<"TOCLIENT_PLAYERPOS cancelled: "
585                                         "we have no peer id"
586                                         <<std::endl;
587                         return;
588                 }*/
589
590                 { //envlock
591                         JMutexAutoLock envlock(m_env_mutex);
592                         
593                         u32 player_size = 2+12+12+4+4;
594                                 
595                         u32 player_count = (datasize-2) / player_size;
596                         u32 start = 2;
597                         for(u32 i=0; i<player_count; i++)
598                         {
599                                 u16 peer_id = readU16(&data[start]);
600
601                                 Player *player = m_env.getPlayer(peer_id);
602
603                                 // Skip if player doesn't exist
604                                 if(player == NULL)
605                                 {
606                                         start += player_size;
607                                         continue;
608                                 }
609
610                                 // Skip if player is local player
611                                 if(player->isLocal())
612                                 {
613                                         start += player_size;
614                                         continue;
615                                 }
616
617                                 v3s32 ps = readV3S32(&data[start+2]);
618                                 v3s32 ss = readV3S32(&data[start+2+12]);
619                                 s32 pitch_i = readS32(&data[start+2+12+12]);
620                                 s32 yaw_i = readS32(&data[start+2+12+12+4]);
621                                 /*dstream<<"Client: got "
622                                                 <<"pitch_i="<<pitch_i
623                                                 <<" yaw_i="<<yaw_i<<std::endl;*/
624                                 f32 pitch = (f32)pitch_i / 100.0;
625                                 f32 yaw = (f32)yaw_i / 100.0;
626                                 v3f position((f32)ps.X/100., (f32)ps.Y/100., (f32)ps.Z/100.);
627                                 v3f speed((f32)ss.X/100., (f32)ss.Y/100., (f32)ss.Z/100.);
628                                 player->setPosition(position);
629                                 player->setSpeed(speed);
630                                 player->setPitch(pitch);
631                                 player->setYaw(yaw);
632
633                                 /*dstream<<"Client: player "<<peer_id
634                                                 <<" pitch="<<pitch
635                                                 <<" yaw="<<yaw<<std::endl;*/
636
637                                 start += player_size;
638                         }
639                 } //envlock
640         }
641         else if(command == TOCLIENT_PLAYERINFO)
642         {
643                 u16 our_peer_id;
644                 {
645                         JMutexAutoLock lock(m_con_mutex);
646                         our_peer_id = m_con.GetPeerID();
647                 }
648                 // Cancel if we don't have a peer id
649                 if(our_peer_id == PEER_ID_INEXISTENT){
650                         dout_client<<DTIME<<"TOCLIENT_PLAYERINFO cancelled: "
651                                         "we have no peer id"
652                                         <<std::endl;
653                         return;
654                 }
655                 
656                 //dstream<<DTIME<<"Client: Server reports players:"<<std::endl;
657
658                 { //envlock
659                         JMutexAutoLock envlock(m_env_mutex);
660                         
661                         u32 item_size = 2+PLAYERNAME_SIZE;
662                         u32 player_count = (datasize-2) / item_size;
663                         u32 start = 2;
664                         // peer_ids
665                         core::list<u16> players_alive;
666                         for(u32 i=0; i<player_count; i++)
667                         {
668                                 // Make sure the name ends in '\0'
669                                 data[start+2+20-1] = 0;
670
671                                 u16 peer_id = readU16(&data[start]);
672
673                                 players_alive.push_back(peer_id);
674                                 
675                                 /*dstream<<DTIME<<"peer_id="<<peer_id
676                                                 <<" name="<<((char*)&data[start+2])<<std::endl;*/
677
678                                 // Don't update the info of the local player
679                                 if(peer_id == our_peer_id)
680                                 {
681                                         start += item_size;
682                                         continue;
683                                 }
684
685                                 Player *player = m_env.getPlayer(peer_id);
686
687                                 // Create a player if it doesn't exist
688                                 if(player == NULL)
689                                 {
690                                         player = new RemotePlayer(
691                                                         m_device->getSceneManager()->getRootSceneNode(),
692                                                         m_device,
693                                                         -1);
694                                         player->peer_id = peer_id;
695                                         m_env.addPlayer(player);
696                                         dout_client<<DTIME<<"Client: Adding new player "
697                                                         <<peer_id<<std::endl;
698                                 }
699                                 
700                                 player->updateName((char*)&data[start+2]);
701
702                                 start += item_size;
703                         }
704                         
705                         /*
706                                 Remove those players from the environment that
707                                 weren't listed by the server.
708                         */
709                         //dstream<<DTIME<<"Removing dead players"<<std::endl;
710                         core::list<Player*> players = m_env.getPlayers();
711                         core::list<Player*>::Iterator ip;
712                         for(ip=players.begin(); ip!=players.end(); ip++)
713                         {
714                                 // Ingore local player
715                                 if((*ip)->isLocal())
716                                         continue;
717                                 
718                                 // Warn about a special case
719                                 if((*ip)->peer_id == 0)
720                                 {
721                                         dstream<<DTIME<<"WARNING: Client: Removing "
722                                                         "dead player with id=0"<<std::endl;
723                                 }
724
725                                 bool is_alive = false;
726                                 core::list<u16>::Iterator i;
727                                 for(i=players_alive.begin(); i!=players_alive.end(); i++)
728                                 {
729                                         if((*ip)->peer_id == *i)
730                                         {
731                                                 is_alive = true;
732                                                 break;
733                                         }
734                                 }
735                                 /*dstream<<DTIME<<"peer_id="<<((*ip)->peer_id)
736                                                 <<" is_alive="<<is_alive<<std::endl;*/
737                                 if(is_alive)
738                                         continue;
739                                 dstream<<DTIME<<"Removing dead player "<<(*ip)->peer_id
740                                                 <<std::endl;
741                                 m_env.removePlayer((*ip)->peer_id);
742                         }
743                 } //envlock
744         }
745         else if(command == TOCLIENT_SECTORMETA)
746         {
747                 /*
748                         [0] u16 command
749                         [2] u8 sector count
750                         [3...] v2s16 pos + sector metadata
751                 */
752                 if(datasize < 3)
753                         return;
754
755                 //dstream<<"Client received TOCLIENT_SECTORMETA"<<std::endl;
756
757                 { //envlock
758                         JMutexAutoLock envlock(m_env_mutex);
759                         
760                         std::string datastring((char*)&data[2], datasize-2);
761                         std::istringstream is(datastring, std::ios_base::binary);
762
763                         u8 buf[4];
764
765                         is.read((char*)buf, 1);
766                         u16 sector_count = readU8(buf);
767                         
768                         //dstream<<"sector_count="<<sector_count<<std::endl;
769
770                         for(u16 i=0; i<sector_count; i++)
771                         {
772                                 // Read position
773                                 is.read((char*)buf, 4);
774                                 v2s16 pos = readV2S16(buf);
775                                 /*dstream<<"Client: deserializing sector at "
776                                                 <<"("<<pos.X<<","<<pos.Y<<")"<<std::endl;*/
777                                 // Create sector
778                                 assert(m_env.getMap().mapType() == MAPTYPE_CLIENT);
779                                 ((ClientMap&)m_env.getMap()).deSerializeSector(pos, is);
780                         }
781                 } //envlock
782         }
783         else if(command == TOCLIENT_INVENTORY)
784         {
785                 if(datasize < 3)
786                         return;
787
788                 //TimeTaker t1("Parsing TOCLIENT_INVENTORY", m_device);
789
790                 { //envlock
791                         //TimeTaker t2("mutex locking", m_device);
792                         JMutexAutoLock envlock(m_env_mutex);
793                         //t2.stop();
794                         
795                         //TimeTaker t3("istringstream init", m_device);
796                         std::string datastring((char*)&data[2], datasize-2);
797                         std::istringstream is(datastring, std::ios_base::binary);
798                         //t3.stop();
799                         
800                         //m_env.printPlayers(dstream);
801
802                         //TimeTaker t4("player get", m_device);
803                         Player *player = m_env.getLocalPlayer();
804                         assert(player != NULL);
805                         //t4.stop();
806
807                         //TimeTaker t1("inventory.deSerialize()", m_device);
808                         player->inventory.deSerialize(is);
809                         //t1.stop();
810
811                         m_inventory_updated = true;
812
813                         //dstream<<"Client got player inventory:"<<std::endl;
814                         //player->inventory.print(dstream);
815                 }
816         }
817         //DEBUG
818         else if(command == TOCLIENT_OBJECTDATA)
819         //else if(0)
820         {
821                 // Strip command word and create a stringstream
822                 std::string datastring((char*)&data[2], datasize-2);
823                 std::istringstream is(datastring, std::ios_base::binary);
824                 
825                 { //envlock
826                 
827                 JMutexAutoLock envlock(m_env_mutex);
828
829                 u8 buf[12];
830
831                 /*
832                         Read players
833                 */
834
835                 is.read((char*)buf, 2);
836                 u16 playercount = readU16(buf);
837                 
838                 for(u16 i=0; i<playercount; i++)
839                 {
840                         is.read((char*)buf, 2);
841                         u16 peer_id = readU16(buf);
842                         is.read((char*)buf, 12);
843                         v3s32 p_i = readV3S32(buf);
844                         is.read((char*)buf, 12);
845                         v3s32 s_i = readV3S32(buf);
846                         is.read((char*)buf, 4);
847                         s32 pitch_i = readS32(buf);
848                         is.read((char*)buf, 4);
849                         s32 yaw_i = readS32(buf);
850                         
851                         Player *player = m_env.getPlayer(peer_id);
852
853                         // Skip if player doesn't exist
854                         if(player == NULL)
855                         {
856                                 continue;
857                         }
858
859                         // Skip if player is local player
860                         if(player->isLocal())
861                         {
862                                 continue;
863                         }
864         
865                         f32 pitch = (f32)pitch_i / 100.0;
866                         f32 yaw = (f32)yaw_i / 100.0;
867                         v3f position((f32)p_i.X/100., (f32)p_i.Y/100., (f32)p_i.Z/100.);
868                         v3f speed((f32)s_i.X/100., (f32)s_i.Y/100., (f32)s_i.Z/100.);
869                         
870                         player->setPosition(position);
871                         player->setSpeed(speed);
872                         player->setPitch(pitch);
873                         player->setYaw(yaw);
874                 }
875
876                 /*
877                         Read block objects
878                 */
879
880                 // Read active block count
881                 is.read((char*)buf, 2);
882                 u16 blockcount = readU16(buf);
883                 
884                 // Initialize delete queue with all active blocks
885                 core::map<v3s16, bool> abs_to_delete;
886                 for(core::map<v3s16, bool>::Iterator
887                                 i = m_active_blocks.getIterator();
888                                 i.atEnd() == false; i++)
889                 {
890                         v3s16 p = i.getNode()->getKey();
891                         /*dstream<<"adding "
892                                         <<"("<<p.x<<","<<p.y<<","<<p.z<<") "
893                                         <<" to abs_to_delete"
894                                         <<std::endl;*/
895                         abs_to_delete.insert(p, true);
896                 }
897
898                 /*dstream<<"Initial delete queue size: "<<abs_to_delete.size()
899                                 <<std::endl;*/
900                 
901                 for(u16 i=0; i<blockcount; i++)
902                 {
903                         // Read blockpos
904                         is.read((char*)buf, 6);
905                         v3s16 p = readV3S16(buf);
906                         // Get block from somewhere
907                         MapBlock *block = NULL;
908                         try{
909                                 block = m_env.getMap().getBlockNoCreate(p);
910                         }
911                         catch(InvalidPositionException &e)
912                         {
913                                 //TODO: Create a dummy block?
914                         }
915                         if(block == NULL)
916                         {
917                                 dstream<<"WARNING: "
918                                                 <<"Could not get block at blockpos "
919                                                 <<"("<<p.X<<","<<p.Y<<","<<p.Z<<") "
920                                                 <<"in TOCLIENT_OBJECTDATA. Ignoring "
921                                                 <<"following block object data."
922                                                 <<std::endl;
923                                 return;
924                         }
925
926                         /*dstream<<"Client updating objects for block "
927                                         <<"("<<p.X<<","<<p.Y<<","<<p.Z<<")"
928                                         <<std::endl;*/
929
930                         // Insert to active block list
931                         m_active_blocks.insert(p, true);
932
933                         // Remove from deletion queue
934                         if(abs_to_delete.find(p) != NULL)
935                                 abs_to_delete.remove(p);
936
937                         /*
938                                 Update objects of block
939                                 
940                                 NOTE: Be sure this is done in the main thread.
941                         */
942                         block->updateObjects(is, m_server_ser_ver,
943                                         m_device->getSceneManager(), m_env.getDayNightRatio());
944                 }
945                 
946                 /*dstream<<"Final delete queue size: "<<abs_to_delete.size()
947                                 <<std::endl;*/
948                 
949                 // Delete objects of blocks in delete queue
950                 for(core::map<v3s16, bool>::Iterator
951                                 i = abs_to_delete.getIterator();
952                                 i.atEnd() == false; i++)
953                 {
954                         v3s16 p = i.getNode()->getKey();
955                         try
956                         {
957                                 MapBlock *block = m_env.getMap().getBlockNoCreate(p);
958                                 
959                                 // Clear objects
960                                 block->clearObjects();
961                                 // Remove from active blocks list
962                                 m_active_blocks.remove(p);
963                         }
964                         catch(InvalidPositionException &e)
965                         {
966                                 dstream<<"WARNAING: Client: "
967                                                 <<"Couldn't clear objects of active->inactive"
968                                                 <<" block "
969                                                 <<"("<<p.X<<","<<p.Y<<","<<p.Z<<")"
970                                                 <<" because block was not found"
971                                                 <<std::endl;
972                                 // Ignore
973                         }
974                 }
975
976                 } //envlock
977         }
978         else if(command == TOCLIENT_TIME_OF_DAY)
979         {
980                 if(datasize < 4)
981                         return;
982                 
983                 u16 time = readU16(&data[2]);
984                 time = time % 24000;
985                 m_time_of_day.set(time);
986                 //dstream<<"Client: time="<<time<<std::endl;
987                 
988                 /*
989                         Day/night
990
991                         time_of_day:
992                         0 = midnight
993                         12000 = midday
994                 */
995                 {
996                         u32 dr = time_to_daynight_ratio(m_time_of_day.get());
997
998                         dstream<<"Client: time_of_day="<<m_time_of_day.get()
999                                         <<", dr="<<dr
1000                                         <<std::endl;
1001                         
1002                         if(dr != m_env.getDayNightRatio())
1003                         {
1004                                 dout_client<<DTIME<<"Client: changing day-night ratio"<<std::endl;
1005                                 m_env.setDayNightRatio(dr);
1006                                 m_env.expireMeshes(true);
1007                         }
1008                 }
1009
1010         }
1011         else if(command == TOCLIENT_CHAT_MESSAGE)
1012         {
1013                 /*
1014                         u16 command
1015                         u16 length
1016                         wstring message
1017                 */
1018                 u8 buf[6];
1019                 std::string datastring((char*)&data[2], datasize-2);
1020                 std::istringstream is(datastring, std::ios_base::binary);
1021                 
1022                 // Read stuff
1023                 is.read((char*)buf, 2);
1024                 u16 len = readU16(buf);
1025                 
1026                 std::wstring message;
1027                 for(u16 i=0; i<len; i++)
1028                 {
1029                         is.read((char*)buf, 2);
1030                         message += (wchar_t)readU16(buf);
1031                 }
1032
1033                 /*dstream<<"Client received chat message: "
1034                                 <<wide_to_narrow(message)<<std::endl;*/
1035                 
1036                 m_chat_queue.push_back(message);
1037         }
1038         else if(command == TOCLIENT_ACTIVE_OBJECT_REMOVE_ADD)
1039         {
1040                 /*
1041                         u16 command
1042                         u16 count of removed objects
1043                         for all removed objects {
1044                                 u16 id
1045                         }
1046                         u16 count of added objects
1047                         for all added objects {
1048                                 u16 id
1049                                 u8 type
1050                                 u16 initialization data length
1051                                 string initialization data
1052                         }
1053                 */
1054
1055                 char buf[6];
1056                 // Get all data except the command number
1057                 std::string datastring((char*)&data[2], datasize-2);
1058                 // Throw them in an istringstream
1059                 std::istringstream is(datastring, std::ios_base::binary);
1060
1061                 // Read stuff
1062                 
1063                 // Read removed objects
1064                 is.read(buf, 2);
1065                 u16 removed_count = readU16((u8*)buf);
1066                 for(u16 i=0; i<removed_count; i++)
1067                 {
1068                         is.read(buf, 2);
1069                         u16 id = readU16((u8*)buf);
1070                         // Remove it
1071                         {
1072                                 JMutexAutoLock envlock(m_env_mutex);
1073                                 m_env.removeActiveObject(id);
1074                         }
1075                 }
1076                 
1077                 // Read added objects
1078                 is.read(buf, 2);
1079                 u16 added_count = readU16((u8*)buf);
1080                 for(u16 i=0; i<added_count; i++)
1081                 {
1082                         is.read(buf, 2);
1083                         u16 id = readU16((u8*)buf);
1084                         is.read(buf, 1);
1085                         u8 type = readU8((u8*)buf);
1086                         std::string data = deSerializeLongString(is);
1087                         // Add it
1088                         {
1089                                 JMutexAutoLock envlock(m_env_mutex);
1090                                 m_env.addActiveObject(id, type, data);
1091                         }
1092                 }
1093         }
1094         else if(command == TOCLIENT_ACTIVE_OBJECT_MESSAGES)
1095         {
1096                 /*
1097                         u16 command
1098                         for all objects
1099                         {
1100                                 u16 id
1101                                 u16 message length
1102                                 string message
1103                         }
1104                 */
1105                 char buf[6];
1106                 // Get all data except the command number
1107                 std::string datastring((char*)&data[2], datasize-2);
1108                 // Throw them in an istringstream
1109                 std::istringstream is(datastring, std::ios_base::binary);
1110                 
1111                 while(is.eof() == false)
1112                 {
1113                         // Read stuff
1114                         is.read(buf, 2);
1115                         u16 id = readU16((u8*)buf);
1116                         if(is.eof())
1117                                 break;
1118                         is.read(buf, 2);
1119                         u16 message_size = readU16((u8*)buf);
1120                         std::string message;
1121                         message.reserve(message_size);
1122                         for(u16 i=0; i<message_size; i++)
1123                         {
1124                                 is.read(buf, 1);
1125                                 message.append(buf, 1);
1126                         }
1127                         // Pass on to the environment
1128                         {
1129                                 JMutexAutoLock envlock(m_env_mutex);
1130                                 m_env.processActiveObjectMessage(id, message);
1131                         }
1132                 }
1133         }
1134         // Default to queueing it (for slow commands)
1135         else
1136         {
1137                 JMutexAutoLock lock(m_incoming_queue_mutex);
1138                 
1139                 IncomingPacket packet(data, datasize);
1140                 m_incoming_queue.push_back(packet);
1141         }
1142 }
1143
1144 /*
1145         Returns true if there was something in queue
1146 */
1147 bool Client::AsyncProcessPacket()
1148 {
1149         DSTACK(__FUNCTION_NAME);
1150         
1151         try //for catching con::PeerNotFoundException
1152         {
1153
1154         con::Peer *peer;
1155         {
1156                 JMutexAutoLock lock(m_con_mutex);
1157                 // All data is coming from the server
1158                 peer = m_con.GetPeer(PEER_ID_SERVER);
1159         }
1160         
1161         u8 ser_version = m_server_ser_ver;
1162
1163         IncomingPacket packet = getPacket();
1164         u8 *data = packet.m_data;
1165         u32 datasize = packet.m_datalen;
1166         
1167         // An empty packet means queue is empty
1168         if(data == NULL){
1169                 return false;
1170         }
1171         
1172         if(datasize < 2)
1173                 return true;
1174         
1175         ToClientCommand command = (ToClientCommand)readU16(&data[0]);
1176
1177         if(command == TOCLIENT_BLOCKDATA)
1178         {
1179                 // Ignore too small packet
1180                 if(datasize < 8)
1181                         return true;
1182                 /*if(datasize < 8 + MapBlock::serializedLength(ser_version))
1183                         goto getdata;*/
1184                         
1185                 v3s16 p;
1186                 p.X = readS16(&data[2]);
1187                 p.Y = readS16(&data[4]);
1188                 p.Z = readS16(&data[6]);
1189                 
1190                 /*dout_client<<DTIME<<"Client: Thread: BLOCKDATA for ("
1191                                 <<p.X<<","<<p.Y<<","<<p.Z<<")"<<std::endl;*/
1192
1193                 /*dstream<<DTIME<<"Client: Thread: BLOCKDATA for ("
1194                                 <<p.X<<","<<p.Y<<","<<p.Z<<")"<<std::endl;*/
1195                 
1196                 std::string datastring((char*)&data[8], datasize-8);
1197                 std::istringstream istr(datastring, std::ios_base::binary);
1198                 
1199                 MapSector *sector;
1200                 MapBlock *block;
1201                 
1202                 { //envlock
1203                         JMutexAutoLock envlock(m_env_mutex);
1204                         
1205                         v2s16 p2d(p.X, p.Z);
1206                         sector = m_env.getMap().emergeSector(p2d);
1207                         
1208                         v2s16 sp = sector->getPos();
1209                         if(sp != p2d)
1210                         {
1211                                 dstream<<"ERROR: Got sector with getPos()="
1212                                                 <<"("<<sp.X<<","<<sp.Y<<"), tried to get"
1213                                                 <<"("<<p2d.X<<","<<p2d.Y<<")"<<std::endl;
1214                         }
1215
1216                         assert(sp == p2d);
1217                         //assert(sector->getPos() == p2d);
1218                         
1219                         try{
1220                                 block = sector->getBlockNoCreate(p.Y);
1221                                 /*
1222                                         Update an existing block
1223                                 */
1224                                 //dstream<<"Updating"<<std::endl;
1225                                 block->deSerialize(istr, ser_version);
1226                                 //block->setChangedFlag();
1227                         }
1228                         catch(InvalidPositionException &e)
1229                         {
1230                                 /*
1231                                         Create a new block
1232                                 */
1233                                 //dstream<<"Creating new"<<std::endl;
1234                                 block = new MapBlock(&m_env.getMap(), p);
1235                                 block->deSerialize(istr, ser_version);
1236                                 sector->insertBlock(block);
1237                                 //block->setChangedFlag();
1238
1239                                 //DEBUG
1240                                 /*NodeMod mod;
1241                                 mod.type = NODEMOD_CHANGECONTENT;
1242                                 mod.param = CONTENT_MESE;
1243                                 block->setTempMod(v3s16(8,10,8), mod);
1244                                 block->setTempMod(v3s16(8,9,8), mod);
1245                                 block->setTempMod(v3s16(8,8,8), mod);
1246                                 block->setTempMod(v3s16(8,7,8), mod);
1247                                 block->setTempMod(v3s16(8,6,8), mod);*/
1248                                 
1249                                 /*
1250                                         Add some coulds
1251                                         Well, this is a dumb way to do it, they should just
1252                                         be drawn as separate objects.
1253                                 */
1254                                 /*if(p.Y == 3)
1255                                 {
1256                                         NodeMod mod;
1257                                         mod.type = NODEMOD_CHANGECONTENT;
1258                                         mod.param = CONTENT_CLOUD;
1259                                         v3s16 p2;
1260                                         p2.Y = 8;
1261                                         for(p2.X=3; p2.X<=13; p2.X++)
1262                                         for(p2.Z=3; p2.Z<=13; p2.Z++)
1263                                         {
1264                                                 block->setTempMod(p2, mod);
1265                                         }
1266                                 }*/
1267                         }
1268                 } //envlock
1269                 
1270                 /*
1271                         Acknowledge block.
1272                 */
1273                 /*
1274                         [0] u16 command
1275                         [2] u8 count
1276                         [3] v3s16 pos_0
1277                         [3+6] v3s16 pos_1
1278                         ...
1279                 */
1280                 u32 replysize = 2+1+6;
1281                 SharedBuffer<u8> reply(replysize);
1282                 writeU16(&reply[0], TOSERVER_GOTBLOCKS);
1283                 reply[2] = 1;
1284                 writeV3S16(&reply[3], p);
1285                 // Send as reliable
1286                 m_con.Send(PEER_ID_SERVER, 1, reply, true);
1287
1288                 /*
1289                         Update Mesh of this block and blocks at x-, y- and z-.
1290                         Environment should not be locked as it interlocks with the
1291                         main thread, from which is will want to retrieve textures.
1292                 */
1293
1294                 m_env.getClientMap().updateMeshes(block->getPos(), getDayNightRatio());
1295         }
1296         else
1297         {
1298                 dout_client<<DTIME<<"WARNING: Client: Ignoring unknown command "
1299                                 <<command<<std::endl;
1300         }
1301
1302         return true;
1303
1304         } //try
1305         catch(con::PeerNotFoundException &e)
1306         {
1307                 /*dout_client<<DTIME<<"Client::AsyncProcessData(): Cancelling: The server"
1308                                 " connection doesn't exist (a timeout or not yet connected?)"<<std::endl;*/
1309                 return false;
1310         }
1311 }
1312
1313 bool Client::AsyncProcessData()
1314 {
1315         for(;;)
1316         {
1317                 bool r = AsyncProcessPacket();
1318                 if(r == false)
1319                         break;
1320         }
1321         return false;
1322 }
1323
1324 void Client::Send(u16 channelnum, SharedBuffer<u8> data, bool reliable)
1325 {
1326         JMutexAutoLock lock(m_con_mutex);
1327         m_con.Send(PEER_ID_SERVER, channelnum, data, reliable);
1328 }
1329
1330 IncomingPacket Client::getPacket()
1331 {
1332         JMutexAutoLock lock(m_incoming_queue_mutex);
1333         
1334         core::list<IncomingPacket>::Iterator i;
1335         // Refer to first one
1336         i = m_incoming_queue.begin();
1337
1338         // If queue is empty, return empty packet
1339         if(i == m_incoming_queue.end()){
1340                 IncomingPacket packet;
1341                 return packet;
1342         }
1343         
1344         // Pop out first packet and return it
1345         IncomingPacket packet = *i;
1346         m_incoming_queue.erase(i);
1347         return packet;
1348 }
1349
1350 void Client::groundAction(u8 action, v3s16 nodepos_undersurface,
1351                 v3s16 nodepos_oversurface, u16 item)
1352 {
1353         if(connectedAndInitialized() == false){
1354                 dout_client<<DTIME<<"Client::groundAction() "
1355                                 "cancelled (not connected)"
1356                                 <<std::endl;
1357                 return;
1358         }
1359         
1360         /*
1361                 length: 17
1362                 [0] u16 command
1363                 [2] u8 action
1364                 [3] v3s16 nodepos_undersurface
1365                 [9] v3s16 nodepos_abovesurface
1366                 [15] u16 item
1367                 actions:
1368                 0: start digging
1369                 1: place block
1370                 2: stop digging (all parameters ignored)
1371                 3: digging completed
1372         */
1373         u8 datasize = 2 + 1 + 6 + 6 + 2;
1374         SharedBuffer<u8> data(datasize);
1375         writeU16(&data[0], TOSERVER_GROUND_ACTION);
1376         writeU8(&data[2], action);
1377         writeV3S16(&data[3], nodepos_undersurface);
1378         writeV3S16(&data[9], nodepos_oversurface);
1379         writeU16(&data[15], item);
1380         Send(0, data, true);
1381 }
1382
1383 void Client::clickObject(u8 button, v3s16 blockpos, s16 id, u16 item)
1384 {
1385         if(connectedAndInitialized() == false){
1386                 dout_client<<DTIME<<"Client::clickObject() "
1387                                 "cancelled (not connected)"
1388                                 <<std::endl;
1389                 return;
1390         }
1391         
1392         /*
1393                 [0] u16 command=TOSERVER_CLICK_OBJECT
1394                 [2] u8 button (0=left, 1=right)
1395                 [3] v3s16 block
1396                 [9] s16 id
1397                 [11] u16 item
1398         */
1399         u8 datasize = 2 + 1 + 6 + 2 + 2;
1400         SharedBuffer<u8> data(datasize);
1401         writeU16(&data[0], TOSERVER_CLICK_OBJECT);
1402         writeU8(&data[2], button);
1403         writeV3S16(&data[3], blockpos);
1404         writeS16(&data[9], id);
1405         writeU16(&data[11], item);
1406         Send(0, data, true);
1407 }
1408
1409 void Client::sendSignText(v3s16 blockpos, s16 id, std::string text)
1410 {
1411         /*
1412                 u16 command
1413                 v3s16 blockpos
1414                 s16 id
1415                 u16 textlen
1416                 textdata
1417         */
1418         std::ostringstream os(std::ios_base::binary);
1419         u8 buf[12];
1420         
1421         // Write command
1422         writeU16(buf, TOSERVER_SIGNTEXT);
1423         os.write((char*)buf, 2);
1424         
1425         // Write blockpos
1426         writeV3S16(buf, blockpos);
1427         os.write((char*)buf, 6);
1428
1429         // Write id
1430         writeS16(buf, id);
1431         os.write((char*)buf, 2);
1432
1433         u16 textlen = text.size();
1434         // Write text length
1435         writeS16(buf, textlen);
1436         os.write((char*)buf, 2);
1437
1438         // Write text
1439         os.write((char*)text.c_str(), textlen);
1440         
1441         // Make data buffer
1442         std::string s = os.str();
1443         SharedBuffer<u8> data((u8*)s.c_str(), s.size());
1444         // Send as reliable
1445         Send(0, data, true);
1446 }
1447         
1448 void Client::sendInventoryAction(InventoryAction *a)
1449 {
1450         std::ostringstream os(std::ios_base::binary);
1451         u8 buf[12];
1452         
1453         // Write command
1454         writeU16(buf, TOSERVER_INVENTORY_ACTION);
1455         os.write((char*)buf, 2);
1456
1457         a->serialize(os);
1458         
1459         // Make data buffer
1460         std::string s = os.str();
1461         SharedBuffer<u8> data((u8*)s.c_str(), s.size());
1462         // Send as reliable
1463         Send(0, data, true);
1464 }
1465
1466 void Client::sendChatMessage(const std::wstring &message)
1467 {
1468         std::ostringstream os(std::ios_base::binary);
1469         u8 buf[12];
1470         
1471         // Write command
1472         writeU16(buf, TOSERVER_CHAT_MESSAGE);
1473         os.write((char*)buf, 2);
1474         
1475         // Write length
1476         writeU16(buf, message.size());
1477         os.write((char*)buf, 2);
1478         
1479         // Write string
1480         for(u32 i=0; i<message.size(); i++)
1481         {
1482                 u16 w = message[i];
1483                 writeU16(buf, w);
1484                 os.write((char*)buf, 2);
1485         }
1486         
1487         // Make data buffer
1488         std::string s = os.str();
1489         SharedBuffer<u8> data((u8*)s.c_str(), s.size());
1490         // Send as reliable
1491         Send(0, data, true);
1492 }
1493
1494 void Client::sendPlayerPos()
1495 {
1496         JMutexAutoLock envlock(m_env_mutex);
1497         
1498         Player *myplayer = m_env.getLocalPlayer();
1499         if(myplayer == NULL)
1500                 return;
1501         
1502         u16 our_peer_id;
1503         {
1504                 JMutexAutoLock lock(m_con_mutex);
1505                 our_peer_id = m_con.GetPeerID();
1506         }
1507         
1508         // Set peer id if not set already
1509         if(myplayer->peer_id == PEER_ID_INEXISTENT)
1510                 myplayer->peer_id = our_peer_id;
1511         // Check that an existing peer_id is the same as the connection's
1512         assert(myplayer->peer_id == our_peer_id);
1513         
1514         v3f pf = myplayer->getPosition();
1515         v3s32 position(pf.X*100, pf.Y*100, pf.Z*100);
1516         v3f sf = myplayer->getSpeed();
1517         v3s32 speed(sf.X*100, sf.Y*100, sf.Z*100);
1518         s32 pitch = myplayer->getPitch() * 100;
1519         s32 yaw = myplayer->getYaw() * 100;
1520
1521         /*
1522                 Format:
1523                 [0] u16 command
1524                 [2] v3s32 position*100
1525                 [2+12] v3s32 speed*100
1526                 [2+12+12] s32 pitch*100
1527                 [2+12+12+4] s32 yaw*100
1528         */
1529
1530         SharedBuffer<u8> data(2+12+12+4+4);
1531         writeU16(&data[0], TOSERVER_PLAYERPOS);
1532         writeV3S32(&data[2], position);
1533         writeV3S32(&data[2+12], speed);
1534         writeS32(&data[2+12+12], pitch);
1535         writeS32(&data[2+12+12+4], yaw);
1536
1537         // Send as unreliable
1538         Send(0, data, false);
1539 }
1540
1541 void Client::removeNode(v3s16 p)
1542 {
1543         JMutexAutoLock envlock(m_env_mutex);
1544         
1545         core::map<v3s16, MapBlock*> modified_blocks;
1546
1547         try
1548         {
1549                 //TimeTaker t("removeNodeAndUpdate", m_device);
1550                 m_env.getMap().removeNodeAndUpdate(p, modified_blocks);
1551         }
1552         catch(InvalidPositionException &e)
1553         {
1554         }
1555         
1556         for(core::map<v3s16, MapBlock * >::Iterator
1557                         i = modified_blocks.getIterator();
1558                         i.atEnd() == false; i++)
1559         {
1560                 v3s16 p = i.getNode()->getKey();
1561                 m_env.getClientMap().updateMeshes(p, m_env.getDayNightRatio());
1562         }
1563 }
1564
1565 void Client::addNode(v3s16 p, MapNode n)
1566 {
1567         JMutexAutoLock envlock(m_env_mutex);
1568
1569         TimeTaker timer1("Client::addNode()");
1570
1571         core::map<v3s16, MapBlock*> modified_blocks;
1572
1573         try
1574         {
1575                 TimeTaker timer3("Client::addNode(): addNodeAndUpdate");
1576                 m_env.getMap().addNodeAndUpdate(p, n, modified_blocks);
1577         }
1578         catch(InvalidPositionException &e)
1579         {}
1580         
1581         TimeTaker timer2("Client::addNode(): updateMeshes");
1582
1583         for(core::map<v3s16, MapBlock * >::Iterator
1584                         i = modified_blocks.getIterator();
1585                         i.atEnd() == false; i++)
1586         {
1587                 v3s16 p = i.getNode()->getKey();
1588                 m_env.getClientMap().updateMeshes(p, m_env.getDayNightRatio());
1589         }
1590 }
1591         
1592 void Client::updateCamera(v3f pos, v3f dir)
1593 {
1594         m_env.getClientMap().updateCamera(pos, dir);
1595         camera_position = pos;
1596         camera_direction = dir;
1597 }
1598
1599 MapNode Client::getNode(v3s16 p)
1600 {
1601         JMutexAutoLock envlock(m_env_mutex);
1602         return m_env.getMap().getNode(p);
1603 }
1604
1605 v3f Client::getPlayerPosition()
1606 {
1607         JMutexAutoLock envlock(m_env_mutex);
1608         LocalPlayer *player = m_env.getLocalPlayer();
1609         assert(player != NULL);
1610         return player->getPosition();
1611 }
1612
1613 void Client::setPlayerControl(PlayerControl &control)
1614 {
1615         JMutexAutoLock envlock(m_env_mutex);
1616         LocalPlayer *player = m_env.getLocalPlayer();
1617         assert(player != NULL);
1618         player->control = control;
1619 }
1620
1621 // Returns true if the inventory of the local player has been
1622 // updated from the server. If it is true, it is set to false.
1623 bool Client::getLocalInventoryUpdated()
1624 {
1625         // m_inventory_updated is behind envlock
1626         JMutexAutoLock envlock(m_env_mutex);
1627         bool updated = m_inventory_updated;
1628         m_inventory_updated = false;
1629         return updated;
1630 }
1631
1632 // Copies the inventory of the local player to parameter
1633 void Client::getLocalInventory(Inventory &dst)
1634 {
1635         JMutexAutoLock envlock(m_env_mutex);
1636         Player *player = m_env.getLocalPlayer();
1637         assert(player != NULL);
1638         dst = player->inventory;
1639 }
1640
1641 MapBlockObject * Client::getSelectedObject(
1642                 f32 max_d,
1643                 v3f from_pos_f_on_map,
1644                 core::line3d<f32> shootline_on_map
1645         )
1646 {
1647         JMutexAutoLock envlock(m_env_mutex);
1648
1649         core::array<DistanceSortedObject> objects;
1650
1651         for(core::map<v3s16, bool>::Iterator
1652                         i = m_active_blocks.getIterator();
1653                         i.atEnd() == false; i++)
1654         {
1655                 v3s16 p = i.getNode()->getKey();
1656
1657                 MapBlock *block = NULL;
1658                 try
1659                 {
1660                         block = m_env.getMap().getBlockNoCreate(p);
1661                 }
1662                 catch(InvalidPositionException &e)
1663                 {
1664                         continue;
1665                 }
1666
1667                 // Calculate from_pos relative to block
1668                 v3s16 block_pos_i_on_map = block->getPosRelative();
1669                 v3f block_pos_f_on_map = intToFloat(block_pos_i_on_map, BS);
1670                 v3f from_pos_f_on_block = from_pos_f_on_map - block_pos_f_on_map;
1671
1672                 block->getObjects(from_pos_f_on_block, max_d, objects);
1673                 //block->getPseudoObjects(from_pos_f_on_block, max_d, objects);
1674         }
1675
1676         //dstream<<"Collected "<<objects.size()<<" nearby objects"<<std::endl;
1677         
1678         // Sort them.
1679         // After this, the closest object is the first in the array.
1680         objects.sort();
1681
1682         for(u32 i=0; i<objects.size(); i++)
1683         {
1684                 MapBlockObject *obj = objects[i].obj;
1685                 MapBlock *block = obj->getBlock();
1686
1687                 // Calculate shootline relative to block
1688                 v3s16 block_pos_i_on_map = block->getPosRelative();
1689                 v3f block_pos_f_on_map = intToFloat(block_pos_i_on_map, BS);
1690                 core::line3d<f32> shootline_on_block(
1691                                 shootline_on_map.start - block_pos_f_on_map,
1692                                 shootline_on_map.end - block_pos_f_on_map
1693                 );
1694
1695                 if(obj->isSelected(shootline_on_block))
1696                 {
1697                         //dstream<<"Returning selected object"<<std::endl;
1698                         return obj;
1699                 }
1700         }
1701
1702         //dstream<<"No object selected; returning NULL."<<std::endl;
1703         return NULL;
1704 }
1705
1706 void Client::printDebugInfo(std::ostream &os)
1707 {
1708         //JMutexAutoLock lock1(m_fetchblock_mutex);
1709         JMutexAutoLock lock2(m_incoming_queue_mutex);
1710
1711         os<<"m_incoming_queue.getSize()="<<m_incoming_queue.getSize()
1712                 //<<", m_fetchblock_history.size()="<<m_fetchblock_history.size()
1713                 //<<", m_opt_not_found_history.size()="<<m_opt_not_found_history.size()
1714                 <<std::endl;
1715 }
1716         
1717 /*s32 Client::getDayNightIndex()
1718 {
1719         assert(m_daynight_i >= 0 && m_daynight_i < DAYNIGHT_CACHE_COUNT);
1720         return m_daynight_i;
1721 }*/
1722
1723 u32 Client::getDayNightRatio()
1724 {
1725         JMutexAutoLock envlock(m_env_mutex);
1726         return m_env.getDayNightRatio();
1727 }
1728
1729 /*void Client::updateSomeExpiredMeshes()
1730 {
1731         TimeTaker timer("updateSomeExpiredMeshes()", g_device);
1732         
1733         Player *player;
1734         {
1735                 JMutexAutoLock envlock(m_env_mutex);
1736                 player = m_env.getLocalPlayer();
1737         }
1738
1739         u32 daynight_ratio = getDayNightRatio();
1740
1741         v3f playerpos = player->getPosition();
1742         v3f playerspeed = player->getSpeed();
1743
1744         v3s16 center_nodepos = floatToInt(playerpos, BS);
1745         v3s16 center = getNodeBlockPos(center_nodepos);
1746
1747         u32 counter = 0;
1748
1749         s16 d_max = 5;
1750         
1751         for(s16 d = 0; d <= d_max; d++)
1752         {
1753                 core::list<v3s16> list;
1754                 getFacePositions(list, d);
1755                 
1756                 core::list<v3s16>::Iterator li;
1757                 for(li=list.begin(); li!=list.end(); li++)
1758                 {
1759                         v3s16 p = *li + center;
1760                         MapBlock *block = NULL;
1761                         try
1762                         {
1763                                 //JMutexAutoLock envlock(m_env_mutex);
1764                                 block = m_env.getMap().getBlockNoCreate(p);
1765                         }
1766                         catch(InvalidPositionException &e)
1767                         {
1768                         }
1769
1770                         if(block == NULL)
1771                                 continue;
1772
1773                         if(block->getMeshExpired() == false)
1774                                 continue;
1775
1776                         block->updateMesh(daynight_ratio);
1777
1778                         counter++;
1779                         if(counter >= 5)
1780                                 return;
1781                 }
1782         }
1783 }*/
1784