3 Copyright (C) 2010 celeron55, Perttu Ahola <celeron55@gmail.com>
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.
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.
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.
23 #include "clientserver.h"
24 #include "jmutexautolock.h"
29 void * ClientUpdateThread::Thread()
33 DSTACK(__FUNCTION_NAME);
35 BEGIN_DEBUG_EXCEPTION_HANDLER
39 m_client->asyncStep();
41 //m_client->updateSomeExpiredMeshes();
43 bool was = m_client->AsyncProcessData();
49 END_DEBUG_EXCEPTION_HANDLER
55 IrrlichtDevice *device,
56 const char *playername,
57 MapDrawControl &control):
59 m_env(new ClientMap(this, control,
60 device->getSceneManager()->getRootSceneNode(),
61 device->getSceneManager(), 666),
63 m_con(PROTOCOL_ID, 512, CONNECTION_TIMEOUT, this),
65 camera_position(0,0,0),
66 camera_direction(0,0,1),
67 m_server_ser_ver(SER_FMT_VER_INVALID),
69 m_inventory_updated(false),
72 m_packetcounter_timer = 0.0;
73 m_delete_unused_sectors_timer = 0.0;
74 m_connection_reinit_timer = 0.0;
75 m_avg_rtt_timer = 0.0;
76 m_playerpos_send_timer = 0.0;
78 //m_fetchblock_mutex.Init();
79 m_incoming_queue_mutex.Init();
82 m_step_dtime_mutex.Init();
87 JMutexAutoLock envlock(m_env_mutex);
88 //m_env.getMap().StartUpdater();
90 Player *player = new LocalPlayer();
92 player->updateName(playername);
94 /*f32 y = BS*2 + BS*20;
95 player->setPosition(v3f(0, y, 0));*/
96 //player->setPosition(v3f(0, y, 30900*BS)); // DEBUG
97 m_env.addPlayer(player);
104 JMutexAutoLock conlock(m_con_mutex);
108 m_thread.setRun(false);
109 while(m_thread.IsRunning())
113 void Client::connect(Address address)
115 DSTACK(__FUNCTION_NAME);
116 JMutexAutoLock lock(m_con_mutex);
117 m_con.setTimeoutMs(0);
118 m_con.Connect(address);
121 bool Client::connectedAndInitialized()
123 JMutexAutoLock lock(m_con_mutex);
125 if(m_con.Connected() == false)
128 if(m_server_ser_ver == SER_FMT_VER_INVALID)
134 void Client::step(float dtime)
136 DSTACK(__FUNCTION_NAME);
143 //dstream<<"Client steps "<<dtime<<std::endl;
146 //TimeTaker timer("ReceiveAll()", m_device);
152 //TimeTaker timer("m_con_mutex + m_con.RunTimeouts()", m_device);
154 JMutexAutoLock lock(m_con_mutex);
155 m_con.RunTimeouts(dtime);
162 float &counter = m_packetcounter_timer;
168 dout_client<<"Client packetcounter (20s):"<<std::endl;
169 m_packetcounter.print(dout_client);
170 m_packetcounter.clear();
176 Delete unused sectors
178 NOTE: This jams the game for a while because deleting sectors
182 float &counter = m_delete_unused_sectors_timer;
190 JMutexAutoLock lock(m_env_mutex);
192 core::list<v3s16> deleted_blocks;
194 float delete_unused_sectors_timeout =
195 g_settings.getFloat("client_delete_unused_sectors_timeout");
197 // Delete sector blocks
198 /*u32 num = m_env.getMap().deleteUnusedSectors
199 (delete_unused_sectors_timeout,
200 true, &deleted_blocks);*/
202 // Delete whole sectors
203 u32 num = m_env.getMap().deleteUnusedSectors
204 (delete_unused_sectors_timeout,
205 false, &deleted_blocks);
209 /*dstream<<DTIME<<"Client: Deleted blocks of "<<num
210 <<" unused sectors"<<std::endl;*/
211 dstream<<DTIME<<"Client: Deleted "<<num
212 <<" unused sectors"<<std::endl;
218 // Env is locked so con can be locked.
219 JMutexAutoLock lock(m_con_mutex);
221 core::list<v3s16>::Iterator i = deleted_blocks.begin();
222 core::list<v3s16> sendlist;
225 if(sendlist.size() == 255 || i == deleted_blocks.end())
227 if(sendlist.size() == 0)
236 u32 replysize = 2+1+6*sendlist.size();
237 SharedBuffer<u8> reply(replysize);
238 writeU16(&reply[0], TOSERVER_DELETEDBLOCKS);
239 reply[2] = sendlist.size();
241 for(core::list<v3s16>::Iterator
242 j = sendlist.begin();
243 j != sendlist.end(); j++)
245 writeV3S16(&reply[2+1+6*k], *j);
248 m_con.Send(PEER_ID_SERVER, 1, reply, true);
250 if(i == deleted_blocks.end())
256 sendlist.push_back(*i);
263 bool connected = connectedAndInitialized();
265 if(connected == false)
267 float &counter = m_connection_reinit_timer;
273 JMutexAutoLock envlock(m_env_mutex);
275 Player *myplayer = m_env.getLocalPlayer();
276 assert(myplayer != NULL);
278 // Send TOSERVER_INIT
279 // [0] u16 TOSERVER_INIT
280 // [2] u8 SER_FMT_VER_HIGHEST
281 // [3] u8[20] player_name
282 SharedBuffer<u8> data(2+1+20);
283 writeU16(&data[0], TOSERVER_INIT);
284 writeU8(&data[2], SER_FMT_VER_HIGHEST);
285 memcpy(&data[3], myplayer->getName(), 20);
286 // Send as unreliable
287 Send(0, data, false);
290 // Not connected, return
295 Do stuff if connected
300 JMutexAutoLock lock(m_env_mutex);
302 // Control local player (0ms)
303 LocalPlayer *player = m_env.getLocalPlayer();
304 assert(player != NULL);
305 player->applyControl(dtime);
307 //TimeTaker envtimer("env step", m_device);
311 // Step active blocks
312 for(core::map<v3s16, bool>::Iterator
313 i = m_active_blocks.getIterator();
314 i.atEnd() == false; i++)
316 v3s16 p = i.getNode()->getKey();
318 MapBlock *block = NULL;
321 block = m_env.getMap().getBlockNoCreate(p);
322 block->stepObjects(dtime, false, m_env.getDayNightRatio());
324 catch(InvalidPositionException &e)
331 float &counter = m_avg_rtt_timer;
336 JMutexAutoLock lock(m_con_mutex);
337 // connectedAndInitialized() is true, peer exists.
338 con::Peer *peer = m_con.GetPeer(PEER_ID_SERVER);
339 dstream<<DTIME<<"Client: avg_rtt="<<peer->avg_rtt<<std::endl;
343 float &counter = m_playerpos_send_timer;
353 JMutexAutoLock lock(m_step_dtime_mutex);
354 m_step_dtime += dtime;
358 float Client::asyncStep()
360 DSTACK(__FUNCTION_NAME);
361 //dstream<<"Client::asyncStep()"<<std::endl;
365 JMutexAutoLock lock1(m_step_dtime_mutex);
366 if(m_step_dtime < 0.001)
368 dtime = m_step_dtime;
376 // Virtual methods from con::PeerHandler
377 void Client::peerAdded(con::Peer *peer)
379 derr_client<<"Client::peerAdded(): peer->id="
380 <<peer->id<<std::endl;
382 void Client::deletingPeer(con::Peer *peer, bool timeout)
384 derr_client<<"Client::deletingPeer(): "
385 "Server Peer is getting deleted "
386 <<"(timeout="<<timeout<<")"<<std::endl;
389 void Client::ReceiveAll()
391 DSTACK(__FUNCTION_NAME);
397 catch(con::NoIncomingDataException &e)
401 catch(con::InvalidIncomingDataException &e)
403 dout_client<<DTIME<<"Client::ReceiveAll(): "
404 "InvalidIncomingDataException: what()="
405 <<e.what()<<std::endl;
410 void Client::Receive()
412 DSTACK(__FUNCTION_NAME);
413 u32 data_maxsize = 10000;
414 Buffer<u8> data(data_maxsize);
418 //TimeTaker t1("con mutex and receive", m_device);
419 JMutexAutoLock lock(m_con_mutex);
420 datasize = m_con.Receive(sender_peer_id, *data, data_maxsize);
422 //TimeTaker t1("ProcessData", m_device);
423 ProcessData(*data, datasize, sender_peer_id);
427 sender_peer_id given to this shall be quaranteed to be a valid peer
429 void Client::ProcessData(u8 *data, u32 datasize, u16 sender_peer_id)
431 DSTACK(__FUNCTION_NAME);
433 // Ignore packets that don't even fit a command
436 m_packetcounter.add(60000);
440 ToClientCommand command = (ToClientCommand)readU16(&data[0]);
442 //dstream<<"Client: received command="<<command<<std::endl;
443 m_packetcounter.add((u16)command);
446 If this check is removed, be sure to change the queue
447 system to know the ids
449 if(sender_peer_id != PEER_ID_SERVER)
451 dout_client<<DTIME<<"Client::ProcessData(): Discarding data not "
452 "coming from server: peer_id="<<sender_peer_id
459 JMutexAutoLock lock(m_con_mutex);
460 // All data is coming from the server
461 // PeerNotFoundException is handled by caller.
462 peer = m_con.GetPeer(PEER_ID_SERVER);
465 u8 ser_version = m_server_ser_ver;
467 //dstream<<"Client received command="<<(int)command<<std::endl;
469 // Execute fast commands straight away
471 if(command == TOCLIENT_INIT)
476 u8 deployed = data[2];
478 dout_client<<DTIME<<"Client: TOCLIENT_INIT received with "
479 "deployed="<<((int)deployed&0xff)<<std::endl;
481 if(deployed < SER_FMT_VER_LOWEST
482 || deployed > SER_FMT_VER_HIGHEST)
484 derr_client<<DTIME<<"Client: TOCLIENT_INIT: Server sent "
485 <<"unsupported ser_fmt_ver"<<std::endl;
489 m_server_ser_ver = deployed;
491 // Get player position
492 v3s16 playerpos_s16(0, BS*2+BS*20, 0);
493 if(datasize >= 2+1+6)
494 playerpos_s16 = readV3S16(&data[2+1]);
495 v3f playerpos_f = intToFloat(playerpos_s16) - v3f(0, BS/2, 0);
498 JMutexAutoLock envlock(m_env_mutex);
500 // Set player position
501 Player *player = m_env.getLocalPlayer();
502 assert(player != NULL);
503 player->setPosition(playerpos_f);
508 SharedBuffer<u8> reply(replysize);
509 writeU16(&reply[0], TOSERVER_INIT2);
511 m_con.Send(PEER_ID_SERVER, 1, reply, true);
516 if(ser_version == SER_FMT_VER_INVALID)
518 dout_client<<DTIME<<"WARNING: Client: Server serialization"
519 " format invalid or not initialized."
520 " Skipping incoming command="<<command<<std::endl;
524 // Just here to avoid putting the two if's together when
525 // making some copypasta
528 if(command == TOCLIENT_REMOVENODE)
533 p.X = readS16(&data[2]);
534 p.Y = readS16(&data[4]);
535 p.Z = readS16(&data[6]);
537 //TimeTaker t1("TOCLIENT_REMOVENODE", g_device);
539 // This will clear the cracking animation after digging
540 ((ClientMap&)m_env.getMap()).clearTempMod(p);
544 else if(command == TOCLIENT_ADDNODE)
546 if(datasize < 8 + MapNode::serializedLength(ser_version))
550 p.X = readS16(&data[2]);
551 p.Y = readS16(&data[4]);
552 p.Z = readS16(&data[6]);
554 //TimeTaker t1("TOCLIENT_ADDNODE", g_device);
557 n.deSerialize(&data[8], ser_version);
561 else if(command == TOCLIENT_PLAYERPOS)
563 dstream<<"WARNING: Received deprecated TOCLIENT_PLAYERPOS"
567 JMutexAutoLock lock(m_con_mutex);
568 our_peer_id = m_con.GetPeerID();
570 // Cancel if we don't have a peer id
571 if(our_peer_id == PEER_ID_NEW){
572 dout_client<<DTIME<<"TOCLIENT_PLAYERPOS cancelled: "
579 JMutexAutoLock envlock(m_env_mutex);
581 u32 player_size = 2+12+12+4+4;
583 u32 player_count = (datasize-2) / player_size;
585 for(u32 i=0; i<player_count; i++)
587 u16 peer_id = readU16(&data[start]);
589 Player *player = m_env.getPlayer(peer_id);
591 // Skip if player doesn't exist
594 start += player_size;
598 // Skip if player is local player
599 if(player->isLocal())
601 start += player_size;
605 v3s32 ps = readV3S32(&data[start+2]);
606 v3s32 ss = readV3S32(&data[start+2+12]);
607 s32 pitch_i = readS32(&data[start+2+12+12]);
608 s32 yaw_i = readS32(&data[start+2+12+12+4]);
609 /*dstream<<"Client: got "
610 <<"pitch_i="<<pitch_i
611 <<" yaw_i="<<yaw_i<<std::endl;*/
612 f32 pitch = (f32)pitch_i / 100.0;
613 f32 yaw = (f32)yaw_i / 100.0;
614 v3f position((f32)ps.X/100., (f32)ps.Y/100., (f32)ps.Z/100.);
615 v3f speed((f32)ss.X/100., (f32)ss.Y/100., (f32)ss.Z/100.);
616 player->setPosition(position);
617 player->setSpeed(speed);
618 player->setPitch(pitch);
621 /*dstream<<"Client: player "<<peer_id
623 <<" yaw="<<yaw<<std::endl;*/
625 start += player_size;
629 else if(command == TOCLIENT_PLAYERINFO)
633 JMutexAutoLock lock(m_con_mutex);
634 our_peer_id = m_con.GetPeerID();
636 // Cancel if we don't have a peer id
637 if(our_peer_id == PEER_ID_NEW){
638 dout_client<<DTIME<<"TOCLIENT_PLAYERINFO cancelled: "
644 //dstream<<DTIME<<"Client: Server reports players:"<<std::endl;
647 JMutexAutoLock envlock(m_env_mutex);
649 u32 item_size = 2+PLAYERNAME_SIZE;
650 u32 player_count = (datasize-2) / item_size;
653 core::list<u16> players_alive;
654 for(u32 i=0; i<player_count; i++)
656 // Make sure the name ends in '\0'
657 data[start+2+20-1] = 0;
659 u16 peer_id = readU16(&data[start]);
661 players_alive.push_back(peer_id);
663 /*dstream<<DTIME<<"peer_id="<<peer_id
664 <<" name="<<((char*)&data[start+2])<<std::endl;*/
666 // Don't update the info of the local player
667 if(peer_id == our_peer_id)
673 Player *player = m_env.getPlayer(peer_id);
675 // Create a player if it doesn't exist
678 player = new RemotePlayer(
679 m_device->getSceneManager()->getRootSceneNode(),
682 player->peer_id = peer_id;
683 m_env.addPlayer(player);
684 dout_client<<DTIME<<"Client: Adding new player "
685 <<peer_id<<std::endl;
688 player->updateName((char*)&data[start+2]);
694 Remove those players from the environment that
695 weren't listed by the server.
697 //dstream<<DTIME<<"Removing dead players"<<std::endl;
698 core::list<Player*> players = m_env.getPlayers();
699 core::list<Player*>::Iterator ip;
700 for(ip=players.begin(); ip!=players.end(); ip++)
702 // Ingore local player
706 // Warn about a special case
707 if((*ip)->peer_id == 0)
709 dstream<<DTIME<<"WARNING: Client: Removing "
710 "dead player with id=0"<<std::endl;
713 bool is_alive = false;
714 core::list<u16>::Iterator i;
715 for(i=players_alive.begin(); i!=players_alive.end(); i++)
717 if((*ip)->peer_id == *i)
723 /*dstream<<DTIME<<"peer_id="<<((*ip)->peer_id)
724 <<" is_alive="<<is_alive<<std::endl;*/
727 dstream<<DTIME<<"Removing dead player "<<(*ip)->peer_id
729 m_env.removePlayer((*ip)->peer_id);
733 else if(command == TOCLIENT_SECTORMETA)
738 [3...] v2s16 pos + sector metadata
743 //dstream<<"Client received TOCLIENT_SECTORMETA"<<std::endl;
746 JMutexAutoLock envlock(m_env_mutex);
748 std::string datastring((char*)&data[2], datasize-2);
749 std::istringstream is(datastring, std::ios_base::binary);
753 is.read((char*)buf, 1);
754 u16 sector_count = readU8(buf);
756 //dstream<<"sector_count="<<sector_count<<std::endl;
758 for(u16 i=0; i<sector_count; i++)
761 is.read((char*)buf, 4);
762 v2s16 pos = readV2S16(buf);
763 /*dstream<<"Client: deserializing sector at "
764 <<"("<<pos.X<<","<<pos.Y<<")"<<std::endl;*/
766 assert(m_env.getMap().mapType() == MAPTYPE_CLIENT);
767 ((ClientMap&)m_env.getMap()).deSerializeSector(pos, is);
771 else if(command == TOCLIENT_INVENTORY)
776 //TimeTaker t1("Parsing TOCLIENT_INVENTORY", m_device);
779 //TimeTaker t2("mutex locking", m_device);
780 JMutexAutoLock envlock(m_env_mutex);
783 //TimeTaker t3("istringstream init", m_device);
784 std::string datastring((char*)&data[2], datasize-2);
785 std::istringstream is(datastring, std::ios_base::binary);
788 //m_env.printPlayers(dstream);
790 //TimeTaker t4("player get", m_device);
791 Player *player = m_env.getLocalPlayer();
792 assert(player != NULL);
795 //TimeTaker t1("inventory.deSerialize()", m_device);
796 player->inventory.deSerialize(is);
799 m_inventory_updated = true;
801 //dstream<<"Client got player inventory:"<<std::endl;
802 //player->inventory.print(dstream);
806 else if(command == TOCLIENT_OBJECTDATA)
809 // Strip command word and create a stringstream
810 std::string datastring((char*)&data[2], datasize-2);
811 std::istringstream is(datastring, std::ios_base::binary);
815 JMutexAutoLock envlock(m_env_mutex);
823 is.read((char*)buf, 2);
824 u16 playercount = readU16(buf);
826 for(u16 i=0; i<playercount; i++)
828 is.read((char*)buf, 2);
829 u16 peer_id = readU16(buf);
830 is.read((char*)buf, 12);
831 v3s32 p_i = readV3S32(buf);
832 is.read((char*)buf, 12);
833 v3s32 s_i = readV3S32(buf);
834 is.read((char*)buf, 4);
835 s32 pitch_i = readS32(buf);
836 is.read((char*)buf, 4);
837 s32 yaw_i = readS32(buf);
839 Player *player = m_env.getPlayer(peer_id);
841 // Skip if player doesn't exist
847 // Skip if player is local player
848 if(player->isLocal())
853 f32 pitch = (f32)pitch_i / 100.0;
854 f32 yaw = (f32)yaw_i / 100.0;
855 v3f position((f32)p_i.X/100., (f32)p_i.Y/100., (f32)p_i.Z/100.);
856 v3f speed((f32)s_i.X/100., (f32)s_i.Y/100., (f32)s_i.Z/100.);
858 player->setPosition(position);
859 player->setSpeed(speed);
860 player->setPitch(pitch);
868 // Read active block count
869 is.read((char*)buf, 2);
870 u16 blockcount = readU16(buf);
872 // Initialize delete queue with all active blocks
873 core::map<v3s16, bool> abs_to_delete;
874 for(core::map<v3s16, bool>::Iterator
875 i = m_active_blocks.getIterator();
876 i.atEnd() == false; i++)
878 v3s16 p = i.getNode()->getKey();
880 <<"("<<p.x<<","<<p.y<<","<<p.z<<") "
881 <<" to abs_to_delete"
883 abs_to_delete.insert(p, true);
886 /*dstream<<"Initial delete queue size: "<<abs_to_delete.size()
889 for(u16 i=0; i<blockcount; i++)
892 is.read((char*)buf, 6);
893 v3s16 p = readV3S16(buf);
894 // Get block from somewhere
895 MapBlock *block = NULL;
897 block = m_env.getMap().getBlockNoCreate(p);
899 catch(InvalidPositionException &e)
901 //TODO: Create a dummy block?
906 <<"Could not get block at blockpos "
907 <<"("<<p.X<<","<<p.Y<<","<<p.Z<<") "
908 <<"in TOCLIENT_OBJECTDATA. Ignoring "
909 <<"following block object data."
914 /*dstream<<"Client updating objects for block "
915 <<"("<<p.X<<","<<p.Y<<","<<p.Z<<")"
918 // Insert to active block list
919 m_active_blocks.insert(p, true);
921 // Remove from deletion queue
922 if(abs_to_delete.find(p) != NULL)
923 abs_to_delete.remove(p);
926 Update objects of block
928 NOTE: Be sure this is done in the main thread.
930 block->updateObjects(is, m_server_ser_ver,
931 m_device->getSceneManager(), m_env.getDayNightRatio());
934 /*dstream<<"Final delete queue size: "<<abs_to_delete.size()
937 // Delete objects of blocks in delete queue
938 for(core::map<v3s16, bool>::Iterator
939 i = abs_to_delete.getIterator();
940 i.atEnd() == false; i++)
942 v3s16 p = i.getNode()->getKey();
945 MapBlock *block = m_env.getMap().getBlockNoCreate(p);
948 block->clearObjects();
949 // Remove from active blocks list
950 m_active_blocks.remove(p);
952 catch(InvalidPositionException &e)
954 dstream<<"WARNAING: Client: "
955 <<"Couldn't clear objects of active->inactive"
957 <<"("<<p.X<<","<<p.Y<<","<<p.Z<<")"
958 <<" because block was not found"
966 else if(command == TOCLIENT_TIME_OF_DAY)
971 u16 time = readU16(&data[2]);
973 m_time_of_day.set(time);
974 //dstream<<"Client: time="<<time<<std::endl;
984 const s32 daylength = 8;
985 const s32 nightlength = 2;
986 const s32 daytimelength = 4;
988 s32 t = (((m_time_of_day.get())%24000)/(24000/d));
990 if(t < nightlength/2 || t >= d - nightlength/2)
992 else if(t >= d/2 - daytimelength/2 && t < d/2 + daytimelength/2)
997 dstream<<"time_of_day="<<m_time_of_day.get()
1002 if(dr != m_env.getDayNightRatio())
1004 //dstream<<"dr="<<dr<<std::endl;
1005 dout_client<<DTIME<<"Client: changing day-night ratio"<<std::endl;
1006 m_env.setDayNightRatio(dr);
1007 m_env.expireMeshes(true);
1012 else if(command == TOCLIENT_CHAT_MESSAGE)
1020 std::string datastring((char*)&data[2], datasize-2);
1021 std::istringstream is(datastring, std::ios_base::binary);
1024 is.read((char*)buf, 2);
1025 u16 len = readU16(buf);
1027 std::wstring message;
1028 for(u16 i=0; i<len; i++)
1030 is.read((char*)buf, 2);
1031 message += (wchar_t)readU16(buf);
1034 /*dstream<<"Client received chat message: "
1035 <<wide_to_narrow(message)<<std::endl;*/
1037 m_chat_queue.push_back(message);
1039 // Default to queueing it (for slow commands)
1042 JMutexAutoLock lock(m_incoming_queue_mutex);
1044 IncomingPacket packet(data, datasize);
1045 m_incoming_queue.push_back(packet);
1050 Returns true if there was something in queue
1052 bool Client::AsyncProcessPacket()
1054 DSTACK(__FUNCTION_NAME);
1056 try //for catching con::PeerNotFoundException
1061 JMutexAutoLock lock(m_con_mutex);
1062 // All data is coming from the server
1063 peer = m_con.GetPeer(PEER_ID_SERVER);
1066 u8 ser_version = m_server_ser_ver;
1068 IncomingPacket packet = getPacket();
1069 u8 *data = packet.m_data;
1070 u32 datasize = packet.m_datalen;
1072 // An empty packet means queue is empty
1080 ToClientCommand command = (ToClientCommand)readU16(&data[0]);
1082 if(command == TOCLIENT_BLOCKDATA)
1084 // Ignore too small packet
1087 /*if(datasize < 8 + MapBlock::serializedLength(ser_version))
1091 p.X = readS16(&data[2]);
1092 p.Y = readS16(&data[4]);
1093 p.Z = readS16(&data[6]);
1095 /*dout_client<<DTIME<<"Client: Thread: BLOCKDATA for ("
1096 <<p.X<<","<<p.Y<<","<<p.Z<<")"<<std::endl;*/
1098 /*dstream<<DTIME<<"Client: Thread: BLOCKDATA for ("
1099 <<p.X<<","<<p.Y<<","<<p.Z<<")"<<std::endl;*/
1101 std::string datastring((char*)&data[8], datasize-8);
1102 std::istringstream istr(datastring, std::ios_base::binary);
1108 JMutexAutoLock envlock(m_env_mutex);
1110 v2s16 p2d(p.X, p.Z);
1111 sector = m_env.getMap().emergeSector(p2d);
1113 v2s16 sp = sector->getPos();
1116 dstream<<"ERROR: Got sector with getPos()="
1117 <<"("<<sp.X<<","<<sp.Y<<"), tried to get"
1118 <<"("<<p2d.X<<","<<p2d.Y<<")"<<std::endl;
1122 //assert(sector->getPos() == p2d);
1125 block = sector->getBlockNoCreate(p.Y);
1127 Update an existing block
1129 //dstream<<"Updating"<<std::endl;
1130 block->deSerialize(istr, ser_version);
1131 //block->setChangedFlag();
1133 catch(InvalidPositionException &e)
1138 //dstream<<"Creating new"<<std::endl;
1139 block = new MapBlock(&m_env.getMap(), p);
1140 block->deSerialize(istr, ser_version);
1141 sector->insertBlock(block);
1142 //block->setChangedFlag();
1146 mod.type = NODEMOD_CHANGECONTENT;
1147 mod.param = CONTENT_MESE;
1148 block->setTempMod(v3s16(8,10,8), mod);
1149 block->setTempMod(v3s16(8,9,8), mod);
1150 block->setTempMod(v3s16(8,8,8), mod);
1151 block->setTempMod(v3s16(8,7,8), mod);
1152 block->setTempMod(v3s16(8,6,8), mod);*/
1156 Well, this is a dumb way to do it, they should just
1157 be drawn as separate objects.
1162 mod.type = NODEMOD_CHANGECONTENT;
1163 mod.param = CONTENT_CLOUD;
1166 for(p2.X=3; p2.X<=13; p2.X++)
1167 for(p2.Z=3; p2.Z<=13; p2.Z++)
1169 block->setTempMod(p2, mod);
1185 u32 replysize = 2+1+6;
1186 SharedBuffer<u8> reply(replysize);
1187 writeU16(&reply[0], TOSERVER_GOTBLOCKS);
1189 writeV3S16(&reply[3], p);
1191 m_con.Send(PEER_ID_SERVER, 1, reply, true);
1194 Update Mesh of this block and blocks at x-, y- and z-.
1195 Environment should not be locked as it interlocks with the
1196 main thread, from which is will want to retrieve textures.
1199 m_env.getMap().updateMeshes(block->getPos(), getDayNightRatio());
1203 dout_client<<DTIME<<"WARNING: Client: Ignoring unknown command "
1204 <<command<<std::endl;
1210 catch(con::PeerNotFoundException &e)
1212 dout_client<<DTIME<<"Client::AsyncProcessData(): Cancelling: The server"
1213 " connection doesn't exist (a timeout or not yet connected?)"<<std::endl;
1218 bool Client::AsyncProcessData()
1222 bool r = AsyncProcessPacket();
1229 void Client::Send(u16 channelnum, SharedBuffer<u8> data, bool reliable)
1231 JMutexAutoLock lock(m_con_mutex);
1232 m_con.Send(PEER_ID_SERVER, channelnum, data, reliable);
1235 bool Client::isFetchingBlocks()
1237 JMutexAutoLock conlock(m_con_mutex);
1238 con::Peer *peer = m_con.GetPeerNoEx(PEER_ID_SERVER);
1239 // Not really fetching but can't fetch more.
1240 if(peer == NULL) return true;
1242 con::Channel *channel = &(peer->channels[1]);
1244 NOTE: Channel 0 should always be used for fetching blocks,
1245 and for nothing else.
1247 if(channel->incoming_reliables.size() > 0)
1249 if(channel->outgoing_reliables.size() > 0)
1254 IncomingPacket Client::getPacket()
1256 JMutexAutoLock lock(m_incoming_queue_mutex);
1258 core::list<IncomingPacket>::Iterator i;
1259 // Refer to first one
1260 i = m_incoming_queue.begin();
1262 // If queue is empty, return empty packet
1263 if(i == m_incoming_queue.end()){
1264 IncomingPacket packet;
1268 // Pop out first packet and return it
1269 IncomingPacket packet = *i;
1270 m_incoming_queue.erase(i);
1274 void Client::groundAction(u8 action, v3s16 nodepos_undersurface,
1275 v3s16 nodepos_oversurface, u16 item)
1277 if(connectedAndInitialized() == false){
1278 dout_client<<DTIME<<"Client::groundAction() "
1279 "cancelled (not connected)"
1288 [3] v3s16 nodepos_undersurface
1289 [9] v3s16 nodepos_abovesurface
1294 2: stop digging (all parameters ignored)
1296 u8 datasize = 2 + 1 + 6 + 6 + 2;
1297 SharedBuffer<u8> data(datasize);
1298 writeU16(&data[0], TOSERVER_GROUND_ACTION);
1299 writeU8(&data[2], action);
1300 writeV3S16(&data[3], nodepos_undersurface);
1301 writeV3S16(&data[9], nodepos_oversurface);
1302 writeU16(&data[15], item);
1303 Send(0, data, true);
1306 void Client::clickObject(u8 button, v3s16 blockpos, s16 id, u16 item)
1308 if(connectedAndInitialized() == false){
1309 dout_client<<DTIME<<"Client::clickObject() "
1310 "cancelled (not connected)"
1316 [0] u16 command=TOSERVER_CLICK_OBJECT
1317 [2] u8 button (0=left, 1=right)
1322 u8 datasize = 2 + 1 + 6 + 2 + 2;
1323 SharedBuffer<u8> data(datasize);
1324 writeU16(&data[0], TOSERVER_CLICK_OBJECT);
1325 writeU8(&data[2], button);
1326 writeV3S16(&data[3], blockpos);
1327 writeS16(&data[9], id);
1328 writeU16(&data[11], item);
1329 Send(0, data, true);
1332 void Client::sendSignText(v3s16 blockpos, s16 id, std::string text)
1341 std::ostringstream os(std::ios_base::binary);
1345 writeU16(buf, TOSERVER_SIGNTEXT);
1346 os.write((char*)buf, 2);
1349 writeV3S16(buf, blockpos);
1350 os.write((char*)buf, 6);
1354 os.write((char*)buf, 2);
1356 u16 textlen = text.size();
1357 // Write text length
1358 writeS16(buf, textlen);
1359 os.write((char*)buf, 2);
1362 os.write((char*)text.c_str(), textlen);
1365 std::string s = os.str();
1366 SharedBuffer<u8> data((u8*)s.c_str(), s.size());
1368 Send(0, data, true);
1371 void Client::sendInventoryAction(InventoryAction *a)
1373 std::ostringstream os(std::ios_base::binary);
1377 writeU16(buf, TOSERVER_INVENTORY_ACTION);
1378 os.write((char*)buf, 2);
1383 std::string s = os.str();
1384 SharedBuffer<u8> data((u8*)s.c_str(), s.size());
1386 Send(0, data, true);
1389 void Client::sendChatMessage(const std::wstring &message)
1391 std::ostringstream os(std::ios_base::binary);
1395 writeU16(buf, TOSERVER_CHAT_MESSAGE);
1396 os.write((char*)buf, 2);
1399 writeU16(buf, message.size());
1400 os.write((char*)buf, 2);
1403 for(u32 i=0; i<message.size(); i++)
1407 os.write((char*)buf, 2);
1411 std::string s = os.str();
1412 SharedBuffer<u8> data((u8*)s.c_str(), s.size());
1414 Send(0, data, true);
1417 void Client::sendPlayerPos()
1419 JMutexAutoLock envlock(m_env_mutex);
1421 Player *myplayer = m_env.getLocalPlayer();
1422 if(myplayer == NULL)
1427 JMutexAutoLock lock(m_con_mutex);
1428 our_peer_id = m_con.GetPeerID();
1431 // Set peer id if not set already
1432 if(myplayer->peer_id == PEER_ID_NEW)
1433 myplayer->peer_id = our_peer_id;
1434 // Check that an existing peer_id is the same as the connection's
1435 assert(myplayer->peer_id == our_peer_id);
1437 v3f pf = myplayer->getPosition();
1438 v3s32 position(pf.X*100, pf.Y*100, pf.Z*100);
1439 v3f sf = myplayer->getSpeed();
1440 v3s32 speed(sf.X*100, sf.Y*100, sf.Z*100);
1441 s32 pitch = myplayer->getPitch() * 100;
1442 s32 yaw = myplayer->getYaw() * 100;
1447 [2] v3s32 position*100
1448 [2+12] v3s32 speed*100
1449 [2+12+12] s32 pitch*100
1450 [2+12+12+4] s32 yaw*100
1453 SharedBuffer<u8> data(2+12+12+4+4);
1454 writeU16(&data[0], TOSERVER_PLAYERPOS);
1455 writeV3S32(&data[2], position);
1456 writeV3S32(&data[2+12], speed);
1457 writeS32(&data[2+12+12], pitch);
1458 writeS32(&data[2+12+12+4], yaw);
1460 // Send as unreliable
1461 Send(0, data, false);
1464 void Client::removeNode(v3s16 p)
1466 JMutexAutoLock envlock(m_env_mutex);
1468 core::map<v3s16, MapBlock*> modified_blocks;
1472 //TimeTaker t("removeNodeAndUpdate", m_device);
1473 m_env.getMap().removeNodeAndUpdate(p, modified_blocks);
1475 catch(InvalidPositionException &e)
1479 for(core::map<v3s16, MapBlock * >::Iterator
1480 i = modified_blocks.getIterator();
1481 i.atEnd() == false; i++)
1483 v3s16 p = i.getNode()->getKey();
1484 m_env.getMap().updateMeshes(p, m_env.getDayNightRatio());
1488 void Client::addNode(v3s16 p, MapNode n)
1490 JMutexAutoLock envlock(m_env_mutex);
1492 core::map<v3s16, MapBlock*> modified_blocks;
1496 m_env.getMap().addNodeAndUpdate(p, n, modified_blocks);
1498 catch(InvalidPositionException &e)
1501 for(core::map<v3s16, MapBlock * >::Iterator
1502 i = modified_blocks.getIterator();
1503 i.atEnd() == false; i++)
1505 v3s16 p = i.getNode()->getKey();
1506 m_env.getMap().updateMeshes(p, m_env.getDayNightRatio());
1510 void Client::updateCamera(v3f pos, v3f dir)
1512 m_env.getMap().updateCamera(pos, dir);
1513 camera_position = pos;
1514 camera_direction = dir;
1517 MapNode Client::getNode(v3s16 p)
1519 JMutexAutoLock envlock(m_env_mutex);
1520 return m_env.getMap().getNode(p);
1523 /*void Client::getNode(v3s16 p, MapNode n)
1525 JMutexAutoLock envlock(m_env_mutex);
1526 m_env.getMap().setNode(p, n);
1529 /*f32 Client::getGroundHeight(v2s16 p)
1531 JMutexAutoLock envlock(m_env_mutex);
1532 return m_env.getMap().getGroundHeight(p);
1535 /*bool Client::isNodeUnderground(v3s16 p)
1537 JMutexAutoLock envlock(m_env_mutex);
1538 return m_env.getMap().isNodeUnderground(p);
1541 /*Player * Client::getLocalPlayer()
1543 JMutexAutoLock envlock(m_env_mutex);
1544 return m_env.getLocalPlayer();
1547 /*core::list<Player*> Client::getPlayers()
1549 JMutexAutoLock envlock(m_env_mutex);
1550 return m_env.getPlayers();
1553 v3f Client::getPlayerPosition()
1555 JMutexAutoLock envlock(m_env_mutex);
1556 LocalPlayer *player = m_env.getLocalPlayer();
1557 assert(player != NULL);
1558 return player->getPosition();
1561 void Client::setPlayerControl(PlayerControl &control)
1563 JMutexAutoLock envlock(m_env_mutex);
1564 LocalPlayer *player = m_env.getLocalPlayer();
1565 assert(player != NULL);
1566 player->control = control;
1569 // Returns true if the inventory of the local player has been
1570 // updated from the server. If it is true, it is set to false.
1571 bool Client::getLocalInventoryUpdated()
1573 // m_inventory_updated is behind envlock
1574 JMutexAutoLock envlock(m_env_mutex);
1575 bool updated = m_inventory_updated;
1576 m_inventory_updated = false;
1580 // Copies the inventory of the local player to parameter
1581 void Client::getLocalInventory(Inventory &dst)
1583 JMutexAutoLock envlock(m_env_mutex);
1584 Player *player = m_env.getLocalPlayer();
1585 assert(player != NULL);
1586 dst = player->inventory;
1589 MapBlockObject * Client::getSelectedObject(
1591 v3f from_pos_f_on_map,
1592 core::line3d<f32> shootline_on_map
1595 JMutexAutoLock envlock(m_env_mutex);
1597 core::array<DistanceSortedObject> objects;
1599 for(core::map<v3s16, bool>::Iterator
1600 i = m_active_blocks.getIterator();
1601 i.atEnd() == false; i++)
1603 v3s16 p = i.getNode()->getKey();
1605 MapBlock *block = NULL;
1608 block = m_env.getMap().getBlockNoCreate(p);
1610 catch(InvalidPositionException &e)
1615 // Calculate from_pos relative to block
1616 v3s16 block_pos_i_on_map = block->getPosRelative();
1617 v3f block_pos_f_on_map = intToFloat(block_pos_i_on_map);
1618 v3f from_pos_f_on_block = from_pos_f_on_map - block_pos_f_on_map;
1620 block->getObjects(from_pos_f_on_block, max_d, objects);
1621 //block->getPseudoObjects(from_pos_f_on_block, max_d, objects);
1624 //dstream<<"Collected "<<objects.size()<<" nearby objects"<<std::endl;
1627 // After this, the closest object is the first in the array.
1630 for(u32 i=0; i<objects.size(); i++)
1632 MapBlockObject *obj = objects[i].obj;
1633 MapBlock *block = obj->getBlock();
1635 // Calculate shootline relative to block
1636 v3s16 block_pos_i_on_map = block->getPosRelative();
1637 v3f block_pos_f_on_map = intToFloat(block_pos_i_on_map);
1638 core::line3d<f32> shootline_on_block(
1639 shootline_on_map.start - block_pos_f_on_map,
1640 shootline_on_map.end - block_pos_f_on_map
1643 if(obj->isSelected(shootline_on_block))
1645 //dstream<<"Returning selected object"<<std::endl;
1650 //dstream<<"No object selected; returning NULL."<<std::endl;
1654 void Client::printDebugInfo(std::ostream &os)
1656 //JMutexAutoLock lock1(m_fetchblock_mutex);
1657 JMutexAutoLock lock2(m_incoming_queue_mutex);
1659 os<<"m_incoming_queue.getSize()="<<m_incoming_queue.getSize()
1660 //<<", m_fetchblock_history.size()="<<m_fetchblock_history.size()
1661 //<<", m_opt_not_found_history.size()="<<m_opt_not_found_history.size()
1665 /*s32 Client::getDayNightIndex()
1667 assert(m_daynight_i >= 0 && m_daynight_i < DAYNIGHT_CACHE_COUNT);
1668 return m_daynight_i;
1671 u32 Client::getDayNightRatio()
1673 JMutexAutoLock envlock(m_env_mutex);
1674 return m_env.getDayNightRatio();
1677 /*void Client::updateSomeExpiredMeshes()
1679 TimeTaker timer("updateSomeExpiredMeshes()", g_device);
1683 JMutexAutoLock envlock(m_env_mutex);
1684 player = m_env.getLocalPlayer();
1687 u32 daynight_ratio = getDayNightRatio();
1689 v3f playerpos = player->getPosition();
1690 v3f playerspeed = player->getSpeed();
1692 v3s16 center_nodepos = floatToInt(playerpos);
1693 v3s16 center = getNodeBlockPos(center_nodepos);
1699 for(s16 d = 0; d <= d_max; d++)
1701 core::list<v3s16> list;
1702 getFacePositions(list, d);
1704 core::list<v3s16>::Iterator li;
1705 for(li=list.begin(); li!=list.end(); li++)
1707 v3s16 p = *li + center;
1708 MapBlock *block = NULL;
1711 //JMutexAutoLock envlock(m_env_mutex);
1712 block = m_env.getMap().getBlockNoCreate(p);
1714 catch(InvalidPositionException &e)
1721 if(block->getMeshExpired() == false)
1724 block->updateMesh(daynight_ratio);