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_INEXISTENT){
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_INEXISTENT){
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 = 16;
985 const s32 nightlength = 6;
986 const s32 daytimelength = 8;
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 IncomingPacket Client::getPacket()
1237 JMutexAutoLock lock(m_incoming_queue_mutex);
1239 core::list<IncomingPacket>::Iterator i;
1240 // Refer to first one
1241 i = m_incoming_queue.begin();
1243 // If queue is empty, return empty packet
1244 if(i == m_incoming_queue.end()){
1245 IncomingPacket packet;
1249 // Pop out first packet and return it
1250 IncomingPacket packet = *i;
1251 m_incoming_queue.erase(i);
1255 void Client::groundAction(u8 action, v3s16 nodepos_undersurface,
1256 v3s16 nodepos_oversurface, u16 item)
1258 if(connectedAndInitialized() == false){
1259 dout_client<<DTIME<<"Client::groundAction() "
1260 "cancelled (not connected)"
1269 [3] v3s16 nodepos_undersurface
1270 [9] v3s16 nodepos_abovesurface
1275 2: stop digging (all parameters ignored)
1276 3: digging completed
1278 u8 datasize = 2 + 1 + 6 + 6 + 2;
1279 SharedBuffer<u8> data(datasize);
1280 writeU16(&data[0], TOSERVER_GROUND_ACTION);
1281 writeU8(&data[2], action);
1282 writeV3S16(&data[3], nodepos_undersurface);
1283 writeV3S16(&data[9], nodepos_oversurface);
1284 writeU16(&data[15], item);
1285 Send(0, data, true);
1288 void Client::clickObject(u8 button, v3s16 blockpos, s16 id, u16 item)
1290 if(connectedAndInitialized() == false){
1291 dout_client<<DTIME<<"Client::clickObject() "
1292 "cancelled (not connected)"
1298 [0] u16 command=TOSERVER_CLICK_OBJECT
1299 [2] u8 button (0=left, 1=right)
1304 u8 datasize = 2 + 1 + 6 + 2 + 2;
1305 SharedBuffer<u8> data(datasize);
1306 writeU16(&data[0], TOSERVER_CLICK_OBJECT);
1307 writeU8(&data[2], button);
1308 writeV3S16(&data[3], blockpos);
1309 writeS16(&data[9], id);
1310 writeU16(&data[11], item);
1311 Send(0, data, true);
1314 void Client::sendSignText(v3s16 blockpos, s16 id, std::string text)
1323 std::ostringstream os(std::ios_base::binary);
1327 writeU16(buf, TOSERVER_SIGNTEXT);
1328 os.write((char*)buf, 2);
1331 writeV3S16(buf, blockpos);
1332 os.write((char*)buf, 6);
1336 os.write((char*)buf, 2);
1338 u16 textlen = text.size();
1339 // Write text length
1340 writeS16(buf, textlen);
1341 os.write((char*)buf, 2);
1344 os.write((char*)text.c_str(), textlen);
1347 std::string s = os.str();
1348 SharedBuffer<u8> data((u8*)s.c_str(), s.size());
1350 Send(0, data, true);
1353 void Client::sendInventoryAction(InventoryAction *a)
1355 std::ostringstream os(std::ios_base::binary);
1359 writeU16(buf, TOSERVER_INVENTORY_ACTION);
1360 os.write((char*)buf, 2);
1365 std::string s = os.str();
1366 SharedBuffer<u8> data((u8*)s.c_str(), s.size());
1368 Send(0, data, true);
1371 void Client::sendChatMessage(const std::wstring &message)
1373 std::ostringstream os(std::ios_base::binary);
1377 writeU16(buf, TOSERVER_CHAT_MESSAGE);
1378 os.write((char*)buf, 2);
1381 writeU16(buf, message.size());
1382 os.write((char*)buf, 2);
1385 for(u32 i=0; i<message.size(); i++)
1389 os.write((char*)buf, 2);
1393 std::string s = os.str();
1394 SharedBuffer<u8> data((u8*)s.c_str(), s.size());
1396 Send(0, data, true);
1399 void Client::sendPlayerPos()
1401 JMutexAutoLock envlock(m_env_mutex);
1403 Player *myplayer = m_env.getLocalPlayer();
1404 if(myplayer == NULL)
1409 JMutexAutoLock lock(m_con_mutex);
1410 our_peer_id = m_con.GetPeerID();
1413 // Set peer id if not set already
1414 if(myplayer->peer_id == PEER_ID_INEXISTENT)
1415 myplayer->peer_id = our_peer_id;
1416 // Check that an existing peer_id is the same as the connection's
1417 assert(myplayer->peer_id == our_peer_id);
1419 v3f pf = myplayer->getPosition();
1420 v3s32 position(pf.X*100, pf.Y*100, pf.Z*100);
1421 v3f sf = myplayer->getSpeed();
1422 v3s32 speed(sf.X*100, sf.Y*100, sf.Z*100);
1423 s32 pitch = myplayer->getPitch() * 100;
1424 s32 yaw = myplayer->getYaw() * 100;
1429 [2] v3s32 position*100
1430 [2+12] v3s32 speed*100
1431 [2+12+12] s32 pitch*100
1432 [2+12+12+4] s32 yaw*100
1435 SharedBuffer<u8> data(2+12+12+4+4);
1436 writeU16(&data[0], TOSERVER_PLAYERPOS);
1437 writeV3S32(&data[2], position);
1438 writeV3S32(&data[2+12], speed);
1439 writeS32(&data[2+12+12], pitch);
1440 writeS32(&data[2+12+12+4], yaw);
1442 // Send as unreliable
1443 Send(0, data, false);
1446 void Client::removeNode(v3s16 p)
1448 JMutexAutoLock envlock(m_env_mutex);
1450 core::map<v3s16, MapBlock*> modified_blocks;
1454 //TimeTaker t("removeNodeAndUpdate", m_device);
1455 m_env.getMap().removeNodeAndUpdate(p, modified_blocks);
1457 catch(InvalidPositionException &e)
1461 for(core::map<v3s16, MapBlock * >::Iterator
1462 i = modified_blocks.getIterator();
1463 i.atEnd() == false; i++)
1465 v3s16 p = i.getNode()->getKey();
1466 m_env.getMap().updateMeshes(p, m_env.getDayNightRatio());
1470 void Client::addNode(v3s16 p, MapNode n)
1472 JMutexAutoLock envlock(m_env_mutex);
1474 core::map<v3s16, MapBlock*> modified_blocks;
1478 m_env.getMap().addNodeAndUpdate(p, n, modified_blocks);
1480 catch(InvalidPositionException &e)
1483 for(core::map<v3s16, MapBlock * >::Iterator
1484 i = modified_blocks.getIterator();
1485 i.atEnd() == false; i++)
1487 v3s16 p = i.getNode()->getKey();
1488 m_env.getMap().updateMeshes(p, m_env.getDayNightRatio());
1492 void Client::updateCamera(v3f pos, v3f dir)
1494 m_env.getMap().updateCamera(pos, dir);
1495 camera_position = pos;
1496 camera_direction = dir;
1499 MapNode Client::getNode(v3s16 p)
1501 JMutexAutoLock envlock(m_env_mutex);
1502 return m_env.getMap().getNode(p);
1505 /*void Client::getNode(v3s16 p, MapNode n)
1507 JMutexAutoLock envlock(m_env_mutex);
1508 m_env.getMap().setNode(p, n);
1511 /*f32 Client::getGroundHeight(v2s16 p)
1513 JMutexAutoLock envlock(m_env_mutex);
1514 return m_env.getMap().getGroundHeight(p);
1517 /*bool Client::isNodeUnderground(v3s16 p)
1519 JMutexAutoLock envlock(m_env_mutex);
1520 return m_env.getMap().isNodeUnderground(p);
1523 /*Player * Client::getLocalPlayer()
1525 JMutexAutoLock envlock(m_env_mutex);
1526 return m_env.getLocalPlayer();
1529 /*core::list<Player*> Client::getPlayers()
1531 JMutexAutoLock envlock(m_env_mutex);
1532 return m_env.getPlayers();
1535 v3f Client::getPlayerPosition()
1537 JMutexAutoLock envlock(m_env_mutex);
1538 LocalPlayer *player = m_env.getLocalPlayer();
1539 assert(player != NULL);
1540 return player->getPosition();
1543 void Client::setPlayerControl(PlayerControl &control)
1545 JMutexAutoLock envlock(m_env_mutex);
1546 LocalPlayer *player = m_env.getLocalPlayer();
1547 assert(player != NULL);
1548 player->control = control;
1551 // Returns true if the inventory of the local player has been
1552 // updated from the server. If it is true, it is set to false.
1553 bool Client::getLocalInventoryUpdated()
1555 // m_inventory_updated is behind envlock
1556 JMutexAutoLock envlock(m_env_mutex);
1557 bool updated = m_inventory_updated;
1558 m_inventory_updated = false;
1562 // Copies the inventory of the local player to parameter
1563 void Client::getLocalInventory(Inventory &dst)
1565 JMutexAutoLock envlock(m_env_mutex);
1566 Player *player = m_env.getLocalPlayer();
1567 assert(player != NULL);
1568 dst = player->inventory;
1571 MapBlockObject * Client::getSelectedObject(
1573 v3f from_pos_f_on_map,
1574 core::line3d<f32> shootline_on_map
1577 JMutexAutoLock envlock(m_env_mutex);
1579 core::array<DistanceSortedObject> objects;
1581 for(core::map<v3s16, bool>::Iterator
1582 i = m_active_blocks.getIterator();
1583 i.atEnd() == false; i++)
1585 v3s16 p = i.getNode()->getKey();
1587 MapBlock *block = NULL;
1590 block = m_env.getMap().getBlockNoCreate(p);
1592 catch(InvalidPositionException &e)
1597 // Calculate from_pos relative to block
1598 v3s16 block_pos_i_on_map = block->getPosRelative();
1599 v3f block_pos_f_on_map = intToFloat(block_pos_i_on_map);
1600 v3f from_pos_f_on_block = from_pos_f_on_map - block_pos_f_on_map;
1602 block->getObjects(from_pos_f_on_block, max_d, objects);
1603 //block->getPseudoObjects(from_pos_f_on_block, max_d, objects);
1606 //dstream<<"Collected "<<objects.size()<<" nearby objects"<<std::endl;
1609 // After this, the closest object is the first in the array.
1612 for(u32 i=0; i<objects.size(); i++)
1614 MapBlockObject *obj = objects[i].obj;
1615 MapBlock *block = obj->getBlock();
1617 // Calculate shootline relative to block
1618 v3s16 block_pos_i_on_map = block->getPosRelative();
1619 v3f block_pos_f_on_map = intToFloat(block_pos_i_on_map);
1620 core::line3d<f32> shootline_on_block(
1621 shootline_on_map.start - block_pos_f_on_map,
1622 shootline_on_map.end - block_pos_f_on_map
1625 if(obj->isSelected(shootline_on_block))
1627 //dstream<<"Returning selected object"<<std::endl;
1632 //dstream<<"No object selected; returning NULL."<<std::endl;
1636 void Client::printDebugInfo(std::ostream &os)
1638 //JMutexAutoLock lock1(m_fetchblock_mutex);
1639 JMutexAutoLock lock2(m_incoming_queue_mutex);
1641 os<<"m_incoming_queue.getSize()="<<m_incoming_queue.getSize()
1642 //<<", m_fetchblock_history.size()="<<m_fetchblock_history.size()
1643 //<<", m_opt_not_found_history.size()="<<m_opt_not_found_history.size()
1647 /*s32 Client::getDayNightIndex()
1649 assert(m_daynight_i >= 0 && m_daynight_i < DAYNIGHT_CACHE_COUNT);
1650 return m_daynight_i;
1653 u32 Client::getDayNightRatio()
1655 JMutexAutoLock envlock(m_env_mutex);
1656 return m_env.getDayNightRatio();
1659 /*void Client::updateSomeExpiredMeshes()
1661 TimeTaker timer("updateSomeExpiredMeshes()", g_device);
1665 JMutexAutoLock envlock(m_env_mutex);
1666 player = m_env.getLocalPlayer();
1669 u32 daynight_ratio = getDayNightRatio();
1671 v3f playerpos = player->getPosition();
1672 v3f playerspeed = player->getSpeed();
1674 v3s16 center_nodepos = floatToInt(playerpos);
1675 v3s16 center = getNodeBlockPos(center_nodepos);
1681 for(s16 d = 0; d <= d_max; d++)
1683 core::list<v3s16> list;
1684 getFacePositions(list, d);
1686 core::list<v3s16>::Iterator li;
1687 for(li=list.begin(); li!=list.end(); li++)
1689 v3s16 p = *li + center;
1690 MapBlock *block = NULL;
1693 //JMutexAutoLock envlock(m_env_mutex);
1694 block = m_env.getMap().getBlockNoCreate(p);
1696 catch(InvalidPositionException &e)
1703 if(block->getMeshExpired() == false)
1706 block->updateMesh(daynight_ratio);