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):
60 new ClientMap(this, control,
61 device->getSceneManager()->getRootSceneNode(),
62 device->getSceneManager(), 666),
63 device->getSceneManager()
65 m_con(PROTOCOL_ID, 512, CONNECTION_TIMEOUT, this),
67 camera_position(0,0,0),
68 camera_direction(0,0,1),
69 m_server_ser_ver(SER_FMT_VER_INVALID),
71 m_inventory_updated(false),
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;
80 //m_fetchblock_mutex.Init();
81 m_incoming_queue_mutex.Init();
84 m_step_dtime_mutex.Init();
92 JMutexAutoLock envlock(m_env_mutex);
94 Player *player = new LocalPlayer();
96 player->updateName(playername);
98 m_env.addPlayer(player);
101 // Add some active objects for testing
103 ClientActiveObject *obj = new TestCAO(0, v3f(0, 10*BS, 0));
104 m_env.addActiveObject(obj);
111 JMutexAutoLock conlock(m_con_mutex);
115 m_thread.setRun(false);
116 while(m_thread.IsRunning())
120 void Client::connect(Address address)
122 DSTACK(__FUNCTION_NAME);
123 JMutexAutoLock lock(m_con_mutex);
124 m_con.setTimeoutMs(0);
125 m_con.Connect(address);
128 bool Client::connectedAndInitialized()
130 JMutexAutoLock lock(m_con_mutex);
132 if(m_con.Connected() == false)
135 if(m_server_ser_ver == SER_FMT_VER_INVALID)
141 void Client::step(float dtime)
143 DSTACK(__FUNCTION_NAME);
150 //dstream<<"Client steps "<<dtime<<std::endl;
153 //TimeTaker timer("ReceiveAll()", m_device);
159 //TimeTaker timer("m_con_mutex + m_con.RunTimeouts()", m_device);
161 JMutexAutoLock lock(m_con_mutex);
162 m_con.RunTimeouts(dtime);
169 float &counter = m_packetcounter_timer;
175 dout_client<<"Client packetcounter (20s):"<<std::endl;
176 m_packetcounter.print(dout_client);
177 m_packetcounter.clear();
183 Delete unused sectors
185 NOTE: This jams the game for a while because deleting sectors
189 float &counter = m_delete_unused_sectors_timer;
197 JMutexAutoLock lock(m_env_mutex);
199 core::list<v3s16> deleted_blocks;
201 float delete_unused_sectors_timeout =
202 g_settings.getFloat("client_delete_unused_sectors_timeout");
204 // Delete sector blocks
205 /*u32 num = m_env.getMap().deleteUnusedSectors
206 (delete_unused_sectors_timeout,
207 true, &deleted_blocks);*/
209 // Delete whole sectors
210 u32 num = m_env.getMap().deleteUnusedSectors
211 (delete_unused_sectors_timeout,
212 false, &deleted_blocks);
216 /*dstream<<DTIME<<"Client: Deleted blocks of "<<num
217 <<" unused sectors"<<std::endl;*/
218 dstream<<DTIME<<"Client: Deleted "<<num
219 <<" unused sectors"<<std::endl;
225 // Env is locked so con can be locked.
226 JMutexAutoLock lock(m_con_mutex);
228 core::list<v3s16>::Iterator i = deleted_blocks.begin();
229 core::list<v3s16> sendlist;
232 if(sendlist.size() == 255 || i == deleted_blocks.end())
234 if(sendlist.size() == 0)
243 u32 replysize = 2+1+6*sendlist.size();
244 SharedBuffer<u8> reply(replysize);
245 writeU16(&reply[0], TOSERVER_DELETEDBLOCKS);
246 reply[2] = sendlist.size();
248 for(core::list<v3s16>::Iterator
249 j = sendlist.begin();
250 j != sendlist.end(); j++)
252 writeV3S16(&reply[2+1+6*k], *j);
255 m_con.Send(PEER_ID_SERVER, 1, reply, true);
257 if(i == deleted_blocks.end())
263 sendlist.push_back(*i);
270 bool connected = connectedAndInitialized();
272 if(connected == false)
274 float &counter = m_connection_reinit_timer;
280 JMutexAutoLock envlock(m_env_mutex);
282 Player *myplayer = m_env.getLocalPlayer();
283 assert(myplayer != NULL);
285 // Send TOSERVER_INIT
286 // [0] u16 TOSERVER_INIT
287 // [2] u8 SER_FMT_VER_HIGHEST
288 // [3] u8[20] player_name
289 SharedBuffer<u8> data(2+1+PLAYERNAME_SIZE);
290 writeU16(&data[0], TOSERVER_INIT);
291 writeU8(&data[2], SER_FMT_VER_HIGHEST);
292 memset((char*)&data[3], 0, PLAYERNAME_SIZE);
293 snprintf((char*)&data[3], PLAYERNAME_SIZE, "%s", myplayer->getName());
294 // Send as unreliable
295 Send(0, data, false);
298 // Not connected, return
303 Do stuff if connected
308 JMutexAutoLock lock(m_env_mutex);
310 // Control local player (0ms)
311 LocalPlayer *player = m_env.getLocalPlayer();
312 assert(player != NULL);
313 player->applyControl(dtime);
315 //TimeTaker envtimer("env step", m_device);
319 // Step active blocks
320 for(core::map<v3s16, bool>::Iterator
321 i = m_active_blocks.getIterator();
322 i.atEnd() == false; i++)
324 v3s16 p = i.getNode()->getKey();
326 MapBlock *block = NULL;
329 block = m_env.getMap().getBlockNoCreate(p);
330 block->stepObjects(dtime, false, m_env.getDayNightRatio());
332 catch(InvalidPositionException &e)
339 float &counter = m_avg_rtt_timer;
344 JMutexAutoLock lock(m_con_mutex);
345 // connectedAndInitialized() is true, peer exists.
346 con::Peer *peer = m_con.GetPeer(PEER_ID_SERVER);
347 dstream<<DTIME<<"Client: avg_rtt="<<peer->avg_rtt<<std::endl;
351 float &counter = m_playerpos_send_timer;
361 JMutexAutoLock lock(m_step_dtime_mutex);
362 m_step_dtime += dtime;
366 float Client::asyncStep()
368 DSTACK(__FUNCTION_NAME);
369 //dstream<<"Client::asyncStep()"<<std::endl;
373 JMutexAutoLock lock1(m_step_dtime_mutex);
374 if(m_step_dtime < 0.001)
376 dtime = m_step_dtime;
384 // Virtual methods from con::PeerHandler
385 void Client::peerAdded(con::Peer *peer)
387 derr_client<<"Client::peerAdded(): peer->id="
388 <<peer->id<<std::endl;
390 void Client::deletingPeer(con::Peer *peer, bool timeout)
392 derr_client<<"Client::deletingPeer(): "
393 "Server Peer is getting deleted "
394 <<"(timeout="<<timeout<<")"<<std::endl;
397 void Client::ReceiveAll()
399 DSTACK(__FUNCTION_NAME);
405 catch(con::NoIncomingDataException &e)
409 catch(con::InvalidIncomingDataException &e)
411 dout_client<<DTIME<<"Client::ReceiveAll(): "
412 "InvalidIncomingDataException: what()="
413 <<e.what()<<std::endl;
418 void Client::Receive()
420 DSTACK(__FUNCTION_NAME);
421 u32 data_maxsize = 10000;
422 Buffer<u8> data(data_maxsize);
426 //TimeTaker t1("con mutex and receive", m_device);
427 JMutexAutoLock lock(m_con_mutex);
428 datasize = m_con.Receive(sender_peer_id, *data, data_maxsize);
430 //TimeTaker t1("ProcessData", m_device);
431 ProcessData(*data, datasize, sender_peer_id);
435 sender_peer_id given to this shall be quaranteed to be a valid peer
437 void Client::ProcessData(u8 *data, u32 datasize, u16 sender_peer_id)
439 DSTACK(__FUNCTION_NAME);
441 // Ignore packets that don't even fit a command
444 m_packetcounter.add(60000);
448 ToClientCommand command = (ToClientCommand)readU16(&data[0]);
450 //dstream<<"Client: received command="<<command<<std::endl;
451 m_packetcounter.add((u16)command);
454 If this check is removed, be sure to change the queue
455 system to know the ids
457 if(sender_peer_id != PEER_ID_SERVER)
459 dout_client<<DTIME<<"Client::ProcessData(): Discarding data not "
460 "coming from server: peer_id="<<sender_peer_id
467 JMutexAutoLock lock(m_con_mutex);
468 // All data is coming from the server
469 // PeerNotFoundException is handled by caller.
470 peer = m_con.GetPeer(PEER_ID_SERVER);
473 u8 ser_version = m_server_ser_ver;
475 //dstream<<"Client received command="<<(int)command<<std::endl;
477 // Execute fast commands straight away
479 if(command == TOCLIENT_INIT)
484 u8 deployed = data[2];
486 dout_client<<DTIME<<"Client: TOCLIENT_INIT received with "
487 "deployed="<<((int)deployed&0xff)<<std::endl;
489 if(deployed < SER_FMT_VER_LOWEST
490 || deployed > SER_FMT_VER_HIGHEST)
492 derr_client<<DTIME<<"Client: TOCLIENT_INIT: Server sent "
493 <<"unsupported ser_fmt_ver"<<std::endl;
497 m_server_ser_ver = deployed;
499 // Get player position
500 v3s16 playerpos_s16(0, BS*2+BS*20, 0);
501 if(datasize >= 2+1+6)
502 playerpos_s16 = readV3S16(&data[2+1]);
503 v3f playerpos_f = intToFloat(playerpos_s16, BS) - v3f(0, BS/2, 0);
506 JMutexAutoLock envlock(m_env_mutex);
508 // Set player position
509 Player *player = m_env.getLocalPlayer();
510 assert(player != NULL);
511 player->setPosition(playerpos_f);
516 SharedBuffer<u8> reply(replysize);
517 writeU16(&reply[0], TOSERVER_INIT2);
519 m_con.Send(PEER_ID_SERVER, 1, reply, true);
524 if(ser_version == SER_FMT_VER_INVALID)
526 dout_client<<DTIME<<"WARNING: Client: Server serialization"
527 " format invalid or not initialized."
528 " Skipping incoming command="<<command<<std::endl;
532 // Just here to avoid putting the two if's together when
533 // making some copypasta
536 if(command == TOCLIENT_REMOVENODE)
541 p.X = readS16(&data[2]);
542 p.Y = readS16(&data[4]);
543 p.Z = readS16(&data[6]);
545 //TimeTaker t1("TOCLIENT_REMOVENODE", g_device);
547 // This will clear the cracking animation after digging
548 ((ClientMap&)m_env.getMap()).clearTempMod(p);
552 else if(command == TOCLIENT_ADDNODE)
554 if(datasize < 8 + MapNode::serializedLength(ser_version))
558 p.X = readS16(&data[2]);
559 p.Y = readS16(&data[4]);
560 p.Z = readS16(&data[6]);
562 //TimeTaker t1("TOCLIENT_ADDNODE", g_device);
565 n.deSerialize(&data[8], ser_version);
569 else if(command == TOCLIENT_PLAYERPOS)
571 dstream<<"WARNING: Received deprecated TOCLIENT_PLAYERPOS"
575 JMutexAutoLock lock(m_con_mutex);
576 our_peer_id = m_con.GetPeerID();
578 // Cancel if we don't have a peer id
579 if(our_peer_id == PEER_ID_INEXISTENT){
580 dout_client<<DTIME<<"TOCLIENT_PLAYERPOS cancelled: "
587 JMutexAutoLock envlock(m_env_mutex);
589 u32 player_size = 2+12+12+4+4;
591 u32 player_count = (datasize-2) / player_size;
593 for(u32 i=0; i<player_count; i++)
595 u16 peer_id = readU16(&data[start]);
597 Player *player = m_env.getPlayer(peer_id);
599 // Skip if player doesn't exist
602 start += player_size;
606 // Skip if player is local player
607 if(player->isLocal())
609 start += player_size;
613 v3s32 ps = readV3S32(&data[start+2]);
614 v3s32 ss = readV3S32(&data[start+2+12]);
615 s32 pitch_i = readS32(&data[start+2+12+12]);
616 s32 yaw_i = readS32(&data[start+2+12+12+4]);
617 /*dstream<<"Client: got "
618 <<"pitch_i="<<pitch_i
619 <<" yaw_i="<<yaw_i<<std::endl;*/
620 f32 pitch = (f32)pitch_i / 100.0;
621 f32 yaw = (f32)yaw_i / 100.0;
622 v3f position((f32)ps.X/100., (f32)ps.Y/100., (f32)ps.Z/100.);
623 v3f speed((f32)ss.X/100., (f32)ss.Y/100., (f32)ss.Z/100.);
624 player->setPosition(position);
625 player->setSpeed(speed);
626 player->setPitch(pitch);
629 /*dstream<<"Client: player "<<peer_id
631 <<" yaw="<<yaw<<std::endl;*/
633 start += player_size;
637 else if(command == TOCLIENT_PLAYERINFO)
641 JMutexAutoLock lock(m_con_mutex);
642 our_peer_id = m_con.GetPeerID();
644 // Cancel if we don't have a peer id
645 if(our_peer_id == PEER_ID_INEXISTENT){
646 dout_client<<DTIME<<"TOCLIENT_PLAYERINFO cancelled: "
652 //dstream<<DTIME<<"Client: Server reports players:"<<std::endl;
655 JMutexAutoLock envlock(m_env_mutex);
657 u32 item_size = 2+PLAYERNAME_SIZE;
658 u32 player_count = (datasize-2) / item_size;
661 core::list<u16> players_alive;
662 for(u32 i=0; i<player_count; i++)
664 // Make sure the name ends in '\0'
665 data[start+2+20-1] = 0;
667 u16 peer_id = readU16(&data[start]);
669 players_alive.push_back(peer_id);
671 /*dstream<<DTIME<<"peer_id="<<peer_id
672 <<" name="<<((char*)&data[start+2])<<std::endl;*/
674 // Don't update the info of the local player
675 if(peer_id == our_peer_id)
681 Player *player = m_env.getPlayer(peer_id);
683 // Create a player if it doesn't exist
686 player = new RemotePlayer(
687 m_device->getSceneManager()->getRootSceneNode(),
690 player->peer_id = peer_id;
691 m_env.addPlayer(player);
692 dout_client<<DTIME<<"Client: Adding new player "
693 <<peer_id<<std::endl;
696 player->updateName((char*)&data[start+2]);
702 Remove those players from the environment that
703 weren't listed by the server.
705 //dstream<<DTIME<<"Removing dead players"<<std::endl;
706 core::list<Player*> players = m_env.getPlayers();
707 core::list<Player*>::Iterator ip;
708 for(ip=players.begin(); ip!=players.end(); ip++)
710 // Ingore local player
714 // Warn about a special case
715 if((*ip)->peer_id == 0)
717 dstream<<DTIME<<"WARNING: Client: Removing "
718 "dead player with id=0"<<std::endl;
721 bool is_alive = false;
722 core::list<u16>::Iterator i;
723 for(i=players_alive.begin(); i!=players_alive.end(); i++)
725 if((*ip)->peer_id == *i)
731 /*dstream<<DTIME<<"peer_id="<<((*ip)->peer_id)
732 <<" is_alive="<<is_alive<<std::endl;*/
735 dstream<<DTIME<<"Removing dead player "<<(*ip)->peer_id
737 m_env.removePlayer((*ip)->peer_id);
741 else if(command == TOCLIENT_SECTORMETA)
746 [3...] v2s16 pos + sector metadata
751 //dstream<<"Client received TOCLIENT_SECTORMETA"<<std::endl;
754 JMutexAutoLock envlock(m_env_mutex);
756 std::string datastring((char*)&data[2], datasize-2);
757 std::istringstream is(datastring, std::ios_base::binary);
761 is.read((char*)buf, 1);
762 u16 sector_count = readU8(buf);
764 //dstream<<"sector_count="<<sector_count<<std::endl;
766 for(u16 i=0; i<sector_count; i++)
769 is.read((char*)buf, 4);
770 v2s16 pos = readV2S16(buf);
771 /*dstream<<"Client: deserializing sector at "
772 <<"("<<pos.X<<","<<pos.Y<<")"<<std::endl;*/
774 assert(m_env.getMap().mapType() == MAPTYPE_CLIENT);
775 ((ClientMap&)m_env.getMap()).deSerializeSector(pos, is);
779 else if(command == TOCLIENT_INVENTORY)
784 //TimeTaker t1("Parsing TOCLIENT_INVENTORY", m_device);
787 //TimeTaker t2("mutex locking", m_device);
788 JMutexAutoLock envlock(m_env_mutex);
791 //TimeTaker t3("istringstream init", m_device);
792 std::string datastring((char*)&data[2], datasize-2);
793 std::istringstream is(datastring, std::ios_base::binary);
796 //m_env.printPlayers(dstream);
798 //TimeTaker t4("player get", m_device);
799 Player *player = m_env.getLocalPlayer();
800 assert(player != NULL);
803 //TimeTaker t1("inventory.deSerialize()", m_device);
804 player->inventory.deSerialize(is);
807 m_inventory_updated = true;
809 //dstream<<"Client got player inventory:"<<std::endl;
810 //player->inventory.print(dstream);
814 else if(command == TOCLIENT_OBJECTDATA)
817 // Strip command word and create a stringstream
818 std::string datastring((char*)&data[2], datasize-2);
819 std::istringstream is(datastring, std::ios_base::binary);
823 JMutexAutoLock envlock(m_env_mutex);
831 is.read((char*)buf, 2);
832 u16 playercount = readU16(buf);
834 for(u16 i=0; i<playercount; i++)
836 is.read((char*)buf, 2);
837 u16 peer_id = readU16(buf);
838 is.read((char*)buf, 12);
839 v3s32 p_i = readV3S32(buf);
840 is.read((char*)buf, 12);
841 v3s32 s_i = readV3S32(buf);
842 is.read((char*)buf, 4);
843 s32 pitch_i = readS32(buf);
844 is.read((char*)buf, 4);
845 s32 yaw_i = readS32(buf);
847 Player *player = m_env.getPlayer(peer_id);
849 // Skip if player doesn't exist
855 // Skip if player is local player
856 if(player->isLocal())
861 f32 pitch = (f32)pitch_i / 100.0;
862 f32 yaw = (f32)yaw_i / 100.0;
863 v3f position((f32)p_i.X/100., (f32)p_i.Y/100., (f32)p_i.Z/100.);
864 v3f speed((f32)s_i.X/100., (f32)s_i.Y/100., (f32)s_i.Z/100.);
866 player->setPosition(position);
867 player->setSpeed(speed);
868 player->setPitch(pitch);
876 // Read active block count
877 is.read((char*)buf, 2);
878 u16 blockcount = readU16(buf);
880 // Initialize delete queue with all active blocks
881 core::map<v3s16, bool> abs_to_delete;
882 for(core::map<v3s16, bool>::Iterator
883 i = m_active_blocks.getIterator();
884 i.atEnd() == false; i++)
886 v3s16 p = i.getNode()->getKey();
888 <<"("<<p.x<<","<<p.y<<","<<p.z<<") "
889 <<" to abs_to_delete"
891 abs_to_delete.insert(p, true);
894 /*dstream<<"Initial delete queue size: "<<abs_to_delete.size()
897 for(u16 i=0; i<blockcount; i++)
900 is.read((char*)buf, 6);
901 v3s16 p = readV3S16(buf);
902 // Get block from somewhere
903 MapBlock *block = NULL;
905 block = m_env.getMap().getBlockNoCreate(p);
907 catch(InvalidPositionException &e)
909 //TODO: Create a dummy block?
914 <<"Could not get block at blockpos "
915 <<"("<<p.X<<","<<p.Y<<","<<p.Z<<") "
916 <<"in TOCLIENT_OBJECTDATA. Ignoring "
917 <<"following block object data."
922 /*dstream<<"Client updating objects for block "
923 <<"("<<p.X<<","<<p.Y<<","<<p.Z<<")"
926 // Insert to active block list
927 m_active_blocks.insert(p, true);
929 // Remove from deletion queue
930 if(abs_to_delete.find(p) != NULL)
931 abs_to_delete.remove(p);
934 Update objects of block
936 NOTE: Be sure this is done in the main thread.
938 block->updateObjects(is, m_server_ser_ver,
939 m_device->getSceneManager(), m_env.getDayNightRatio());
942 /*dstream<<"Final delete queue size: "<<abs_to_delete.size()
945 // Delete objects of blocks in delete queue
946 for(core::map<v3s16, bool>::Iterator
947 i = abs_to_delete.getIterator();
948 i.atEnd() == false; i++)
950 v3s16 p = i.getNode()->getKey();
953 MapBlock *block = m_env.getMap().getBlockNoCreate(p);
956 block->clearObjects();
957 // Remove from active blocks list
958 m_active_blocks.remove(p);
960 catch(InvalidPositionException &e)
962 dstream<<"WARNAING: Client: "
963 <<"Couldn't clear objects of active->inactive"
965 <<"("<<p.X<<","<<p.Y<<","<<p.Z<<")"
966 <<" because block was not found"
974 else if(command == TOCLIENT_TIME_OF_DAY)
979 u16 time = readU16(&data[2]);
981 m_time_of_day.set(time);
982 //dstream<<"Client: time="<<time<<std::endl;
992 u32 dr = time_to_daynight_ratio(m_time_of_day.get());
994 dstream<<"Client: time_of_day="<<m_time_of_day.get()
998 if(dr != m_env.getDayNightRatio())
1000 dout_client<<DTIME<<"Client: changing day-night ratio"<<std::endl;
1001 m_env.setDayNightRatio(dr);
1002 m_env.expireMeshes(true);
1007 else if(command == TOCLIENT_CHAT_MESSAGE)
1015 std::string datastring((char*)&data[2], datasize-2);
1016 std::istringstream is(datastring, std::ios_base::binary);
1019 is.read((char*)buf, 2);
1020 u16 len = readU16(buf);
1022 std::wstring message;
1023 for(u16 i=0; i<len; i++)
1025 is.read((char*)buf, 2);
1026 message += (wchar_t)readU16(buf);
1029 /*dstream<<"Client received chat message: "
1030 <<wide_to_narrow(message)<<std::endl;*/
1032 m_chat_queue.push_back(message);
1034 else if(command == TOCLIENT_ACTIVE_OBJECT_REMOVE_ADD)
1038 u16 count of removed objects
1039 for all removed objects {
1042 u16 count of added objects
1043 for all added objects {
1046 u16 initialization data length
1047 string initialization data
1052 // Get all data except the command number
1053 std::string datastring((char*)&data[2], datasize-2);
1054 // Throw them in an istringstream
1055 std::istringstream is(datastring, std::ios_base::binary);
1059 // Read removed objects
1061 u16 removed_count = readU16((u8*)buf);
1062 for(u16 i=0; i<removed_count; i++)
1065 u16 id = readU16((u8*)buf);
1068 JMutexAutoLock envlock(m_env_mutex);
1069 m_env.removeActiveObject(id);
1073 // Read added objects
1075 u16 added_count = readU16((u8*)buf);
1076 for(u16 i=0; i<added_count; i++)
1079 u16 id = readU16((u8*)buf);
1081 u8 type = readU8((u8*)buf);
1082 std::string data = deSerializeLongString(is);
1085 JMutexAutoLock envlock(m_env_mutex);
1086 m_env.addActiveObject(id, type, data);
1090 else if(command == TOCLIENT_ACTIVE_OBJECT_MESSAGES)
1102 // Get all data except the command number
1103 std::string datastring((char*)&data[2], datasize-2);
1104 // Throw them in an istringstream
1105 std::istringstream is(datastring, std::ios_base::binary);
1107 while(is.eof() == false)
1111 u16 id = readU16((u8*)buf);
1115 u16 message_size = readU16((u8*)buf);
1116 std::string message;
1117 message.reserve(message_size);
1118 for(u16 i=0; i<message_size; i++)
1121 message.append(buf, 1);
1123 // Pass on to the environment
1125 JMutexAutoLock envlock(m_env_mutex);
1126 m_env.processActiveObjectMessage(id, message);
1130 // Default to queueing it (for slow commands)
1133 JMutexAutoLock lock(m_incoming_queue_mutex);
1135 IncomingPacket packet(data, datasize);
1136 m_incoming_queue.push_back(packet);
1141 Returns true if there was something in queue
1143 bool Client::AsyncProcessPacket()
1145 DSTACK(__FUNCTION_NAME);
1147 try //for catching con::PeerNotFoundException
1152 JMutexAutoLock lock(m_con_mutex);
1153 // All data is coming from the server
1154 peer = m_con.GetPeer(PEER_ID_SERVER);
1157 u8 ser_version = m_server_ser_ver;
1159 IncomingPacket packet = getPacket();
1160 u8 *data = packet.m_data;
1161 u32 datasize = packet.m_datalen;
1163 // An empty packet means queue is empty
1171 ToClientCommand command = (ToClientCommand)readU16(&data[0]);
1173 if(command == TOCLIENT_BLOCKDATA)
1175 // Ignore too small packet
1178 /*if(datasize < 8 + MapBlock::serializedLength(ser_version))
1182 p.X = readS16(&data[2]);
1183 p.Y = readS16(&data[4]);
1184 p.Z = readS16(&data[6]);
1186 /*dout_client<<DTIME<<"Client: Thread: BLOCKDATA for ("
1187 <<p.X<<","<<p.Y<<","<<p.Z<<")"<<std::endl;*/
1189 /*dstream<<DTIME<<"Client: Thread: BLOCKDATA for ("
1190 <<p.X<<","<<p.Y<<","<<p.Z<<")"<<std::endl;*/
1192 std::string datastring((char*)&data[8], datasize-8);
1193 std::istringstream istr(datastring, std::ios_base::binary);
1199 JMutexAutoLock envlock(m_env_mutex);
1201 v2s16 p2d(p.X, p.Z);
1202 sector = m_env.getMap().emergeSector(p2d);
1204 v2s16 sp = sector->getPos();
1207 dstream<<"ERROR: Got sector with getPos()="
1208 <<"("<<sp.X<<","<<sp.Y<<"), tried to get"
1209 <<"("<<p2d.X<<","<<p2d.Y<<")"<<std::endl;
1213 //assert(sector->getPos() == p2d);
1216 block = sector->getBlockNoCreate(p.Y);
1218 Update an existing block
1220 //dstream<<"Updating"<<std::endl;
1221 block->deSerialize(istr, ser_version);
1222 //block->setChangedFlag();
1224 catch(InvalidPositionException &e)
1229 //dstream<<"Creating new"<<std::endl;
1230 block = new MapBlock(&m_env.getMap(), p);
1231 block->deSerialize(istr, ser_version);
1232 sector->insertBlock(block);
1233 //block->setChangedFlag();
1237 mod.type = NODEMOD_CHANGECONTENT;
1238 mod.param = CONTENT_MESE;
1239 block->setTempMod(v3s16(8,10,8), mod);
1240 block->setTempMod(v3s16(8,9,8), mod);
1241 block->setTempMod(v3s16(8,8,8), mod);
1242 block->setTempMod(v3s16(8,7,8), mod);
1243 block->setTempMod(v3s16(8,6,8), mod);*/
1247 Well, this is a dumb way to do it, they should just
1248 be drawn as separate objects.
1253 mod.type = NODEMOD_CHANGECONTENT;
1254 mod.param = CONTENT_CLOUD;
1257 for(p2.X=3; p2.X<=13; p2.X++)
1258 for(p2.Z=3; p2.Z<=13; p2.Z++)
1260 block->setTempMod(p2, mod);
1276 u32 replysize = 2+1+6;
1277 SharedBuffer<u8> reply(replysize);
1278 writeU16(&reply[0], TOSERVER_GOTBLOCKS);
1280 writeV3S16(&reply[3], p);
1282 m_con.Send(PEER_ID_SERVER, 1, reply, true);
1285 Update Mesh of this block and blocks at x-, y- and z-.
1286 Environment should not be locked as it interlocks with the
1287 main thread, from which is will want to retrieve textures.
1290 m_env.getClientMap().updateMeshes(block->getPos(), getDayNightRatio());
1294 dout_client<<DTIME<<"WARNING: Client: Ignoring unknown command "
1295 <<command<<std::endl;
1301 catch(con::PeerNotFoundException &e)
1303 /*dout_client<<DTIME<<"Client::AsyncProcessData(): Cancelling: The server"
1304 " connection doesn't exist (a timeout or not yet connected?)"<<std::endl;*/
1309 bool Client::AsyncProcessData()
1313 bool r = AsyncProcessPacket();
1320 void Client::Send(u16 channelnum, SharedBuffer<u8> data, bool reliable)
1322 JMutexAutoLock lock(m_con_mutex);
1323 m_con.Send(PEER_ID_SERVER, channelnum, data, reliable);
1326 IncomingPacket Client::getPacket()
1328 JMutexAutoLock lock(m_incoming_queue_mutex);
1330 core::list<IncomingPacket>::Iterator i;
1331 // Refer to first one
1332 i = m_incoming_queue.begin();
1334 // If queue is empty, return empty packet
1335 if(i == m_incoming_queue.end()){
1336 IncomingPacket packet;
1340 // Pop out first packet and return it
1341 IncomingPacket packet = *i;
1342 m_incoming_queue.erase(i);
1346 void Client::groundAction(u8 action, v3s16 nodepos_undersurface,
1347 v3s16 nodepos_oversurface, u16 item)
1349 if(connectedAndInitialized() == false){
1350 dout_client<<DTIME<<"Client::groundAction() "
1351 "cancelled (not connected)"
1360 [3] v3s16 nodepos_undersurface
1361 [9] v3s16 nodepos_abovesurface
1366 2: stop digging (all parameters ignored)
1367 3: digging completed
1369 u8 datasize = 2 + 1 + 6 + 6 + 2;
1370 SharedBuffer<u8> data(datasize);
1371 writeU16(&data[0], TOSERVER_GROUND_ACTION);
1372 writeU8(&data[2], action);
1373 writeV3S16(&data[3], nodepos_undersurface);
1374 writeV3S16(&data[9], nodepos_oversurface);
1375 writeU16(&data[15], item);
1376 Send(0, data, true);
1379 void Client::clickObject(u8 button, v3s16 blockpos, s16 id, u16 item)
1381 if(connectedAndInitialized() == false){
1382 dout_client<<DTIME<<"Client::clickObject() "
1383 "cancelled (not connected)"
1389 [0] u16 command=TOSERVER_CLICK_OBJECT
1390 [2] u8 button (0=left, 1=right)
1395 u8 datasize = 2 + 1 + 6 + 2 + 2;
1396 SharedBuffer<u8> data(datasize);
1397 writeU16(&data[0], TOSERVER_CLICK_OBJECT);
1398 writeU8(&data[2], button);
1399 writeV3S16(&data[3], blockpos);
1400 writeS16(&data[9], id);
1401 writeU16(&data[11], item);
1402 Send(0, data, true);
1405 void Client::sendSignText(v3s16 blockpos, s16 id, std::string text)
1414 std::ostringstream os(std::ios_base::binary);
1418 writeU16(buf, TOSERVER_SIGNTEXT);
1419 os.write((char*)buf, 2);
1422 writeV3S16(buf, blockpos);
1423 os.write((char*)buf, 6);
1427 os.write((char*)buf, 2);
1429 u16 textlen = text.size();
1430 // Write text length
1431 writeS16(buf, textlen);
1432 os.write((char*)buf, 2);
1435 os.write((char*)text.c_str(), textlen);
1438 std::string s = os.str();
1439 SharedBuffer<u8> data((u8*)s.c_str(), s.size());
1441 Send(0, data, true);
1444 void Client::sendInventoryAction(InventoryAction *a)
1446 std::ostringstream os(std::ios_base::binary);
1450 writeU16(buf, TOSERVER_INVENTORY_ACTION);
1451 os.write((char*)buf, 2);
1456 std::string s = os.str();
1457 SharedBuffer<u8> data((u8*)s.c_str(), s.size());
1459 Send(0, data, true);
1462 void Client::sendChatMessage(const std::wstring &message)
1464 std::ostringstream os(std::ios_base::binary);
1468 writeU16(buf, TOSERVER_CHAT_MESSAGE);
1469 os.write((char*)buf, 2);
1472 writeU16(buf, message.size());
1473 os.write((char*)buf, 2);
1476 for(u32 i=0; i<message.size(); i++)
1480 os.write((char*)buf, 2);
1484 std::string s = os.str();
1485 SharedBuffer<u8> data((u8*)s.c_str(), s.size());
1487 Send(0, data, true);
1490 void Client::sendPlayerPos()
1492 JMutexAutoLock envlock(m_env_mutex);
1494 Player *myplayer = m_env.getLocalPlayer();
1495 if(myplayer == NULL)
1500 JMutexAutoLock lock(m_con_mutex);
1501 our_peer_id = m_con.GetPeerID();
1504 // Set peer id if not set already
1505 if(myplayer->peer_id == PEER_ID_INEXISTENT)
1506 myplayer->peer_id = our_peer_id;
1507 // Check that an existing peer_id is the same as the connection's
1508 assert(myplayer->peer_id == our_peer_id);
1510 v3f pf = myplayer->getPosition();
1511 v3s32 position(pf.X*100, pf.Y*100, pf.Z*100);
1512 v3f sf = myplayer->getSpeed();
1513 v3s32 speed(sf.X*100, sf.Y*100, sf.Z*100);
1514 s32 pitch = myplayer->getPitch() * 100;
1515 s32 yaw = myplayer->getYaw() * 100;
1520 [2] v3s32 position*100
1521 [2+12] v3s32 speed*100
1522 [2+12+12] s32 pitch*100
1523 [2+12+12+4] s32 yaw*100
1526 SharedBuffer<u8> data(2+12+12+4+4);
1527 writeU16(&data[0], TOSERVER_PLAYERPOS);
1528 writeV3S32(&data[2], position);
1529 writeV3S32(&data[2+12], speed);
1530 writeS32(&data[2+12+12], pitch);
1531 writeS32(&data[2+12+12+4], yaw);
1533 // Send as unreliable
1534 Send(0, data, false);
1537 void Client::removeNode(v3s16 p)
1539 JMutexAutoLock envlock(m_env_mutex);
1541 core::map<v3s16, MapBlock*> modified_blocks;
1545 //TimeTaker t("removeNodeAndUpdate", m_device);
1546 m_env.getMap().removeNodeAndUpdate(p, modified_blocks);
1548 catch(InvalidPositionException &e)
1552 for(core::map<v3s16, MapBlock * >::Iterator
1553 i = modified_blocks.getIterator();
1554 i.atEnd() == false; i++)
1556 v3s16 p = i.getNode()->getKey();
1557 m_env.getClientMap().updateMeshes(p, m_env.getDayNightRatio());
1561 void Client::addNode(v3s16 p, MapNode n)
1563 JMutexAutoLock envlock(m_env_mutex);
1565 core::map<v3s16, MapBlock*> modified_blocks;
1569 m_env.getMap().addNodeAndUpdate(p, n, modified_blocks);
1571 catch(InvalidPositionException &e)
1574 for(core::map<v3s16, MapBlock * >::Iterator
1575 i = modified_blocks.getIterator();
1576 i.atEnd() == false; i++)
1578 v3s16 p = i.getNode()->getKey();
1579 m_env.getClientMap().updateMeshes(p, m_env.getDayNightRatio());
1583 void Client::updateCamera(v3f pos, v3f dir)
1585 m_env.getClientMap().updateCamera(pos, dir);
1586 camera_position = pos;
1587 camera_direction = dir;
1590 MapNode Client::getNode(v3s16 p)
1592 JMutexAutoLock envlock(m_env_mutex);
1593 return m_env.getMap().getNode(p);
1596 v3f Client::getPlayerPosition()
1598 JMutexAutoLock envlock(m_env_mutex);
1599 LocalPlayer *player = m_env.getLocalPlayer();
1600 assert(player != NULL);
1601 return player->getPosition();
1604 void Client::setPlayerControl(PlayerControl &control)
1606 JMutexAutoLock envlock(m_env_mutex);
1607 LocalPlayer *player = m_env.getLocalPlayer();
1608 assert(player != NULL);
1609 player->control = control;
1612 // Returns true if the inventory of the local player has been
1613 // updated from the server. If it is true, it is set to false.
1614 bool Client::getLocalInventoryUpdated()
1616 // m_inventory_updated is behind envlock
1617 JMutexAutoLock envlock(m_env_mutex);
1618 bool updated = m_inventory_updated;
1619 m_inventory_updated = false;
1623 // Copies the inventory of the local player to parameter
1624 void Client::getLocalInventory(Inventory &dst)
1626 JMutexAutoLock envlock(m_env_mutex);
1627 Player *player = m_env.getLocalPlayer();
1628 assert(player != NULL);
1629 dst = player->inventory;
1632 MapBlockObject * Client::getSelectedObject(
1634 v3f from_pos_f_on_map,
1635 core::line3d<f32> shootline_on_map
1638 JMutexAutoLock envlock(m_env_mutex);
1640 core::array<DistanceSortedObject> objects;
1642 for(core::map<v3s16, bool>::Iterator
1643 i = m_active_blocks.getIterator();
1644 i.atEnd() == false; i++)
1646 v3s16 p = i.getNode()->getKey();
1648 MapBlock *block = NULL;
1651 block = m_env.getMap().getBlockNoCreate(p);
1653 catch(InvalidPositionException &e)
1658 // Calculate from_pos relative to block
1659 v3s16 block_pos_i_on_map = block->getPosRelative();
1660 v3f block_pos_f_on_map = intToFloat(block_pos_i_on_map, BS);
1661 v3f from_pos_f_on_block = from_pos_f_on_map - block_pos_f_on_map;
1663 block->getObjects(from_pos_f_on_block, max_d, objects);
1664 //block->getPseudoObjects(from_pos_f_on_block, max_d, objects);
1667 //dstream<<"Collected "<<objects.size()<<" nearby objects"<<std::endl;
1670 // After this, the closest object is the first in the array.
1673 for(u32 i=0; i<objects.size(); i++)
1675 MapBlockObject *obj = objects[i].obj;
1676 MapBlock *block = obj->getBlock();
1678 // Calculate shootline relative to block
1679 v3s16 block_pos_i_on_map = block->getPosRelative();
1680 v3f block_pos_f_on_map = intToFloat(block_pos_i_on_map, BS);
1681 core::line3d<f32> shootline_on_block(
1682 shootline_on_map.start - block_pos_f_on_map,
1683 shootline_on_map.end - block_pos_f_on_map
1686 if(obj->isSelected(shootline_on_block))
1688 //dstream<<"Returning selected object"<<std::endl;
1693 //dstream<<"No object selected; returning NULL."<<std::endl;
1697 void Client::printDebugInfo(std::ostream &os)
1699 //JMutexAutoLock lock1(m_fetchblock_mutex);
1700 JMutexAutoLock lock2(m_incoming_queue_mutex);
1702 os<<"m_incoming_queue.getSize()="<<m_incoming_queue.getSize()
1703 //<<", m_fetchblock_history.size()="<<m_fetchblock_history.size()
1704 //<<", m_opt_not_found_history.size()="<<m_opt_not_found_history.size()
1708 /*s32 Client::getDayNightIndex()
1710 assert(m_daynight_i >= 0 && m_daynight_i < DAYNIGHT_CACHE_COUNT);
1711 return m_daynight_i;
1714 u32 Client::getDayNightRatio()
1716 JMutexAutoLock envlock(m_env_mutex);
1717 return m_env.getDayNightRatio();
1720 /*void Client::updateSomeExpiredMeshes()
1722 TimeTaker timer("updateSomeExpiredMeshes()", g_device);
1726 JMutexAutoLock envlock(m_env_mutex);
1727 player = m_env.getLocalPlayer();
1730 u32 daynight_ratio = getDayNightRatio();
1732 v3f playerpos = player->getPosition();
1733 v3f playerspeed = player->getSpeed();
1735 v3s16 center_nodepos = floatToInt(playerpos, BS);
1736 v3s16 center = getNodeBlockPos(center_nodepos);
1742 for(s16 d = 0; d <= d_max; d++)
1744 core::list<v3s16> list;
1745 getFacePositions(list, d);
1747 core::list<v3s16>::Iterator li;
1748 for(li=list.begin(); li!=list.end(); li++)
1750 v3s16 p = *li + center;
1751 MapBlock *block = NULL;
1754 //JMutexAutoLock envlock(m_env_mutex);
1755 block = m_env.getMap().getBlockNoCreate(p);
1757 catch(InvalidPositionException &e)
1764 if(block->getMeshExpired() == false)
1767 block->updateMesh(daynight_ratio);