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