From 4e249fb3fbf75f0359758760d88e22aa5b14533c Mon Sep 17 00:00:00 2001 From: Perttu Ahola Date: Sat, 27 Nov 2010 01:02:21 +0200 Subject: Initial files --- src/client.cpp | 1639 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 1639 insertions(+) create mode 100644 src/client.cpp (limited to 'src/client.cpp') diff --git a/src/client.cpp b/src/client.cpp new file mode 100644 index 000000000..ee3269974 --- /dev/null +++ b/src/client.cpp @@ -0,0 +1,1639 @@ +#include "client.h" +#include "utility.h" +#include +#include "clientserver.h" +#include "jmutexautolock.h" +#include "main.h" +#include + +#ifdef _WIN32 + #include + #define sleep_ms(x) Sleep(x) +#else + #include + #define sleep_ms(x) usleep(x*1000) +#endif + +/* + FIXME: This thread can access the environment at any time +*/ + +void * ClientUpdateThread::Thread() +{ + ThreadStarted(); + + DSTACK(__FUNCTION_NAME); + +#if CATCH_UNHANDLED_EXCEPTIONS + try + { +#endif + while(getRun()) + { + m_client->asyncStep(); + + bool was = m_client->AsyncProcessData(); + + if(was == false) + sleep_ms(50); + } +#if CATCH_UNHANDLED_EXCEPTIONS + } + /* + This is what has to be done in threads to get suitable debug info + */ + catch(std::exception &e) + { + dstream<getSceneManager()->getRootSceneNode(), + device->getSceneManager(), 666), + dout_client), + m_con(PROTOCOL_ID, 512, CONNECTION_TIMEOUT, this), + m_device(device), + camera_position(0,0,0), + camera_direction(0,0,1), + m_server_ser_ver(SER_FMT_VER_INVALID), + m_step_dtime(0.0), + m_delete_unused_sectors_timeout(delete_unused_sectors_timeout), + m_inventory_updated(false) +{ + //m_fetchblock_mutex.Init(); + m_incoming_queue_mutex.Init(); + m_env_mutex.Init(); + m_con_mutex.Init(); + m_step_dtime_mutex.Init(); + + m_thread.Start(); + + { + JMutexAutoLock envlock(m_env_mutex); + //m_env.getMap().StartUpdater(); + + Player *player = new LocalPlayer(); + + player->updateName(playername); + + /*f32 y = BS*2 + BS*20; + player->setPosition(v3f(0, y, 0));*/ + //player->setPosition(v3f(0, y, 30900*BS)); // DEBUG + m_env.addPlayer(player); + } +} + +Client::~Client() +{ + m_thread.setRun(false); + while(m_thread.IsRunning()) + sleep_ms(100); +} + +void Client::connect(Address address) +{ + DSTACK(__FUNCTION_NAME); + JMutexAutoLock lock(m_con_mutex); + m_con.setTimeoutMs(0); + m_con.Connect(address); +} + +bool Client::connectedAndInitialized() +{ + JMutexAutoLock lock(m_con_mutex); + + if(m_con.Connected() == false) + return false; + + if(m_server_ser_ver == SER_FMT_VER_INVALID) + return false; + + return true; +} + +void Client::step(float dtime) +{ + DSTACK(__FUNCTION_NAME); + + // Limit a bit + if(dtime > 2.0) + dtime = 2.0; + + //dstream<<"Client steps "< deleted_blocks; + + // Delete sector blocks + /*u32 num = m_env.getMap().deleteUnusedSectors + (m_delete_unused_sectors_timeout, + true, &deleted_blocks);*/ + + // Delete whole sectors + u32 num = m_env.getMap().deleteUnusedSectors + (m_delete_unused_sectors_timeout, + false, &deleted_blocks); + + if(num > 0) + { + dstream<::Iterator i = deleted_blocks.begin(); + core::list sendlist; + for(;;) + { + if(sendlist.size() == 255 || i == deleted_blocks.end()) + { + if(sendlist.size() == 0) + break; + /* + [0] u16 command + [2] u8 count + [3] v3s16 pos_0 + [3+6] v3s16 pos_1 + ... + */ + u32 replysize = 2+1+6*sendlist.size(); + SharedBuffer reply(replysize); + writeU16(&reply[0], TOSERVER_DELETEDBLOCKS); + reply[2] = sendlist.size(); + u32 k = 0; + for(core::list::Iterator + j = sendlist.begin(); + j != sendlist.end(); j++) + { + writeV3S16(&reply[2+1+6*k], *j); + k++; + } + m_con.Send(PEER_ID_SERVER, 1, reply, true); + + if(i == deleted_blocks.end()) + break; + + sendlist.clear(); + } + + sendlist.push_back(*i); + i++; + } + } + } + } + + bool connected = connectedAndInitialized(); + + if(connected == false) + { + static float counter = -0.001; + counter -= dtime; + if(counter <= 0.0) + { + counter = 2.0; + + JMutexAutoLock envlock(m_env_mutex); + + Player *myplayer = m_env.getLocalPlayer(); + assert(myplayer != NULL); + + // Send TOSERVER_INIT + // [0] u16 TOSERVER_INIT + // [2] u8 SER_FMT_VER_HIGHEST + // [3] u8[20] player_name + SharedBuffer data(2+1+20); + writeU16(&data[0], TOSERVER_INIT); + writeU8(&data[2], SER_FMT_VER_HIGHEST); + memcpy(&data[3], myplayer->getName(), 20); + // Send as unreliable + Send(0, data, false); + } + + // Not connected, return + return; + } + + /* + Do stuff if connected + */ + + { + // 0ms + JMutexAutoLock lock(m_env_mutex); + + // Control local player (0ms) + LocalPlayer *player = m_env.getLocalPlayer(); + assert(player != NULL); + player->applyControl(dtime); + + //TimeTaker envtimer("env step", m_device); + // Step environment + m_env.step(dtime); + + // Step active blocks + for(core::map::Iterator + i = m_active_blocks.getIterator(); + i.atEnd() == false; i++) + { + v3s16 p = i.getNode()->getKey(); + + MapBlock *block = NULL; + try + { + block = m_env.getMap().getBlockNoCreate(p); + block->stepObjects(dtime, false); + } + catch(InvalidPositionException &e) + { + } + } + } + + { + // Fetch some nearby blocks + //fetchBlocks(); + } + + { + static float counter = 0.0; + counter += dtime; + if(counter >= 10) + { + counter = 0.0; + JMutexAutoLock lock(m_con_mutex); + // connectedAndInitialized() is true, peer exists. + con::Peer *peer = m_con.GetPeer(PEER_ID_SERVER); + dstream<id=" + <id<= 2+1+6) + playerpos_s16 = readV3S16(&data[2+1]); + v3f playerpos_f = intToFloat(playerpos_s16) - v3f(0, BS/2, 0); + + { //envlock + JMutexAutoLock envlock(m_env_mutex); + + // Set player position + Player *player = m_env.getLocalPlayer(); + assert(player != NULL); + player->setPosition(playerpos_f); + } + + // Reply to server + u32 replysize = 2; + SharedBuffer reply(replysize); + writeU16(&reply[0], TOSERVER_INIT2); + // Send as reliable + m_con.Send(PEER_ID_SERVER, 1, reply, true); + + return; + } + + if(ser_version == SER_FMT_VER_INVALID) + { + dout_client<isLocal()) + { + start += player_size; + continue; + } + + v3s32 ps = readV3S32(&data[start+2]); + v3s32 ss = readV3S32(&data[start+2+12]); + s32 pitch_i = readS32(&data[start+2+12+12]); + s32 yaw_i = readS32(&data[start+2+12+12+4]); + /*dstream<<"Client: got " + <<"pitch_i="< players_alive; + for(u32 i=0; iupdateName((char*)&data[start+2]); + + start += item_size; + } + + /* + Remove those players from the environment that + weren't listed by the server. + */ + //dstream< players = m_env.getPlayers(); + core::list::Iterator ip; + for(ip=players.begin(); ip!=players.end(); ip++) + { + // Ingore local player + if((*ip)->isLocal()) + continue; + + // Warn about a special case + if((*ip)->peer_id == 0) + { + dstream<::Iterator i; + for(i=players_alive.begin(); i!=players_alive.end(); i++) + { + if((*ip)->peer_id == *i) + { + is_alive = true; + break; + } + } + /*dstream<peer_id) + <<" is_alive="<peer_id + <peer_id); + } + } //envlock + } + else if(command == TOCLIENT_SECTORMETA) + { + /* + [0] u16 command + [2] u8 sector count + [3...] v2s16 pos + sector metadata + */ + if(datasize < 3) + return; + + //dstream<<"Client received TOCLIENT_SECTORMETA"<inventory.deSerialize(is); + //t1.stop(); + + m_inventory_updated = true; + + //dstream<<"Client got player inventory:"<inventory.print(dstream); + } + } + //DEBUG + else if(command == TOCLIENT_OBJECTDATA) + //else if(0) + { + // Strip command word and create a stringstream + std::string datastring((char*)&data[2], datasize-2); + std::istringstream is(datastring, std::ios_base::binary); + + { //envlock + + JMutexAutoLock envlock(m_env_mutex); + + u8 buf[12]; + + /* + Read players + */ + + is.read((char*)buf, 2); + u16 playercount = readU16(buf); + + for(u16 i=0; iisLocal()) + { + continue; + } + + f32 pitch = (f32)pitch_i / 100.0; + f32 yaw = (f32)yaw_i / 100.0; + v3f position((f32)p_i.X/100., (f32)p_i.Y/100., (f32)p_i.Z/100.); + v3f speed((f32)s_i.X/100., (f32)s_i.Y/100., (f32)s_i.Z/100.); + + player->setPosition(position); + player->setSpeed(speed); + player->setPitch(pitch); + player->setYaw(yaw); + } + + /* + Read block objects + */ + + // Read active block count + is.read((char*)buf, 2); + u16 blockcount = readU16(buf); + + // Initialize delete queue with all active blocks + core::map abs_to_delete; + for(core::map::Iterator + i = m_active_blocks.getIterator(); + i.atEnd() == false; i++) + { + v3s16 p = i.getNode()->getKey(); + /*dstream<<"adding " + <<"("<updateObjects(is, m_server_ser_ver, + m_device->getSceneManager()); + } + + /*dstream<<"Final delete queue size: "<::Iterator + i = abs_to_delete.getIterator(); + i.atEnd() == false; i++) + { + v3s16 p = i.getNode()->getKey(); + try + { + MapBlock *block = m_env.getMap().getBlockNoCreate(p); + + // Clear objects + block->clearObjects(); + // Remove from active blocks list + m_active_blocks.remove(p); + } + catch(InvalidPositionException &e) + { + dstream<<"WARNAING: Client: " + <<"Couldn't clear objects of active->inactive" + <<" block " + <<"("< modified_blocks; + + try + { + JMutexAutoLock envlock(m_env_mutex); + //TimeTaker t("removeNodeAndUpdate", m_device); + m_env.getMap().removeNodeAndUpdate(p, modified_blocks); + } + catch(InvalidPositionException &e) + { + } + + for(core::map::Iterator + i = modified_blocks.getIterator(); + i.atEnd() == false; i++) + { + v3s16 p = i.getNode()->getKey(); + //m_env.getMap().updateMeshes(p); + mesh_updater.add(p); + } + } + else if(command == TOCLIENT_ADDNODE) + { + if(datasize < 8 + MapNode::serializedLength(ser_version)) + return true; + + v3s16 p; + p.X = readS16(&data[2]); + p.Y = readS16(&data[4]); + p.Z = readS16(&data[6]); + + //TimeTaker t1("TOCLIENT_ADDNODE", g_device); + + MapNode n; + n.deSerialize(&data[8], ser_version); + + core::map modified_blocks; + + try + { + JMutexAutoLock envlock(m_env_mutex); + m_env.getMap().addNodeAndUpdate(p, n, modified_blocks); + } + catch(InvalidPositionException &e) + {} + + for(core::map::Iterator + i = modified_blocks.getIterator(); + i.atEnd() == false; i++) + { + v3s16 p = i.getNode()->getKey(); + //m_env.getMap().updateMeshes(p); + mesh_updater.add(p); + } + } + else if(command == TOCLIENT_BLOCKDATA) + { + // Ignore too small packet + if(datasize < 8) + return true; + /*if(datasize < 8 + MapBlock::serializedLength(ser_version)) + goto getdata;*/ + + v3s16 p; + p.X = readS16(&data[2]); + p.Y = readS16(&data[4]); + p.Z = readS16(&data[6]); + + /*dout_client<getPos(); + if(sp != p2d) + { + dstream<<"ERROR: Got sector with getPos()=" + <<"("<getPos() == p2d); + + try{ + block = sector->getBlockNoCreate(p.Y); + /* + Update an existing block + */ + //dstream<<"Updating"<deSerialize(istr, ser_version); + //block->setChangedFlag(); + } + catch(InvalidPositionException &e) + { + /* + Create a new block + */ + //dstream<<"Creating new"<deSerialize(istr, ser_version); + sector->insertBlock(block); + //block->setChangedFlag(); + } + } //envlock + + + // Old version has zero lighting, update it. + if(ser_version == 0 || ser_version == 1) + { + derr_client<<"Client: Block in old format: " + "Calculating lighting"< blocks_changed; + blocks_changed.insert(block->getPos(), block); + core::map modified_blocks; + m_env.getMap().updateLighting(blocks_changed, modified_blocks); + } + + /* + Update Mesh of this block and blocks at x-, y- and z- + */ + + //m_env.getMap().updateMeshes(block->getPos()); + mesh_updater.add(block->getPos()); + + /* + Acknowledge block. + */ + /* + [0] u16 command + [2] u8 count + [3] v3s16 pos_0 + [3+6] v3s16 pos_1 + ... + */ + u32 replysize = 2+1+6; + SharedBuffer reply(replysize); + writeU16(&reply[0], TOSERVER_GOTBLOCKS); + reply[2] = 1; + writeV3S16(&reply[3], p); + // Send as reliable + m_con.Send(PEER_ID_SERVER, 1, reply, true); + +#if 0 + /* + Remove from history + */ + { + JMutexAutoLock lock(m_fetchblock_mutex); + + if(m_fetchblock_history.find(p) != NULL) + { + m_fetchblock_history.remove(p); + } + else + { + /* + Acknowledge block. + */ + /* + [0] u16 command + [2] u8 count + [3] v3s16 pos_0 + [3+6] v3s16 pos_1 + ... + */ + u32 replysize = 2+1+6; + SharedBuffer reply(replysize); + writeU16(&reply[0], TOSERVER_GOTBLOCKS); + reply[2] = 1; + writeV3S16(&reply[3], p); + // Send as reliable + m_con.Send(PEER_ID_SERVER, 1, reply, true); + } + } +#endif + } + else + { + dout_client< data, bool reliable) +{ + JMutexAutoLock lock(m_con_mutex); + m_con.Send(PEER_ID_SERVER, channelnum, data, reliable); +} + +#if 0 +void Client::fetchBlock(v3s16 p, u8 flags) +{ + if(connectedAndInitialized() == false) + throw ClientNotReadyException + ("ClientNotReadyException: connectedAndInitialized() == false"); + + /*dstream<<"Client::fetchBlock(): Sending GETBLOCK for (" + < data(9); + writeU16(&data[0], TOSERVER_GETBLOCK); + writeS16(&data[2], p.X); + writeS16(&data[4], p.Y); + writeS16(&data[6], p.Z); + writeU8(&data[8], flags); + m_con.Send(PEER_ID_SERVER, 1, data, true); +} + +/* + Calls fetchBlock() on some nearby missing blocks. + + Returns when any of various network load indicators go over limit. + + Does nearly the same thing as the old updateChangedVisibleArea() +*/ +void Client::fetchBlocks() +{ + if(connectedAndInitialized() == false) + throw ClientNotReadyException + ("ClientNotReadyException: connectedAndInitialized() == false"); +} +#endif + +bool Client::isFetchingBlocks() +{ + JMutexAutoLock conlock(m_con_mutex); + con::Peer *peer = m_con.GetPeerNoEx(PEER_ID_SERVER); + // Not really fetching but can't fetch more. + if(peer == NULL) return true; + + con::Channel *channel = &(peer->channels[1]); + /* + NOTE: Channel 0 should always be used for fetching blocks, + and for nothing else. + */ + if(channel->incoming_reliables.size() > 0) + return true; + if(channel->outgoing_reliables.size() > 0) + return true; + return false; +} + +IncomingPacket Client::getPacket() +{ + JMutexAutoLock lock(m_incoming_queue_mutex); + + core::list::Iterator i; + // Refer to first one + i = m_incoming_queue.begin(); + + // If queue is empty, return empty packet + if(i == m_incoming_queue.end()){ + IncomingPacket packet; + return packet; + } + + // Pop out first packet and return it + IncomingPacket packet = *i; + m_incoming_queue.erase(i); + return packet; +} + +#if 0 +void Client::removeNode(v3s16 nodepos) +{ + if(connectedAndInitialized() == false){ + dout_client< data(8); + writeU16(&data[0], TOSERVER_REMOVENODE); + writeS16(&data[2], nodepos.X); + writeS16(&data[4], nodepos.Y); + writeS16(&data[6], nodepos.Z); + Send(0, data, true); +} + +void Client::addNodeFromInventory(v3s16 nodepos, u16 i) +{ + if(connectedAndInitialized() == false){ + dout_client< data(datasize); + writeU16(&data[0], TOSERVER_ADDNODE_FROM_INVENTORY); + writeS16(&data[2], nodepos.X); + writeS16(&data[4], nodepos.Y); + writeS16(&data[6], nodepos.Z); + writeU16(&data[8], i); + Send(0, data, true); +} +#endif + +void Client::clickGround(u8 button, v3s16 nodepos_undersurface, + v3s16 nodepos_oversurface, u16 item) +{ + if(connectedAndInitialized() == false){ + dout_client< data(datasize); + writeU16(&data[0], TOSERVER_CLICK_GROUND); + writeU8(&data[2], button); + writeV3S16(&data[3], nodepos_undersurface); + writeV3S16(&data[9], nodepos_oversurface); + writeU16(&data[15], item); + Send(0, data, true); +} + +void Client::clickObject(u8 button, v3s16 blockpos, s16 id, u16 item) +{ + if(connectedAndInitialized() == false){ + dout_client< data(datasize); + writeU16(&data[0], TOSERVER_CLICK_OBJECT); + writeU8(&data[2], button); + writeV3S16(&data[3], blockpos); + writeS16(&data[9], id); + writeU16(&data[11], item); + Send(0, data, true); +} + +void Client::release(u8 button) +{ + //TODO +} + +void Client::sendSignText(v3s16 blockpos, s16 id, std::string text) +{ + /* + u16 command + v3s16 blockpos + s16 id + u16 textlen + textdata + */ + std::ostringstream os(std::ios_base::binary); + u8 buf[12]; + + // Write command + writeU16(buf, TOSERVER_SIGNTEXT); + os.write((char*)buf, 2); + + // Write blockpos + writeV3S16(buf, blockpos); + os.write((char*)buf, 6); + + // Write id + writeS16(buf, id); + os.write((char*)buf, 2); + + u16 textlen = text.size(); + // Write text length + writeS16(buf, textlen); + os.write((char*)buf, 2); + + // Write text + os.write((char*)text.c_str(), textlen); + + // Make data buffer + std::string s = os.str(); + SharedBuffer data((u8*)s.c_str(), s.size()); + // Send as reliable + Send(0, data, true); +} + +void Client::sendPlayerPos() +{ + JMutexAutoLock envlock(m_env_mutex); + + Player *myplayer = m_env.getLocalPlayer(); + if(myplayer == NULL) + return; + + u16 our_peer_id; + { + JMutexAutoLock lock(m_con_mutex); + our_peer_id = m_con.GetPeerID(); + } + + // Set peer id if not set already + if(myplayer->peer_id == PEER_ID_NEW) + myplayer->peer_id = our_peer_id; + // Check that an existing peer_id is the same as the connection's + assert(myplayer->peer_id == our_peer_id); + + v3f pf = myplayer->getPosition(); + v3s32 position(pf.X*100, pf.Y*100, pf.Z*100); + v3f sf = myplayer->getSpeed(); + v3s32 speed(sf.X*100, sf.Y*100, sf.Z*100); + s32 pitch = myplayer->getPitch() * 100; + s32 yaw = myplayer->getYaw() * 100; + + /* + Format: + [0] u16 command + [2] v3s32 position*100 + [2+12] v3s32 speed*100 + [2+12+12] s32 pitch*100 + [2+12+12+4] s32 yaw*100 + */ + + SharedBuffer data(2+12+12+4+4); + writeU16(&data[0], TOSERVER_PLAYERPOS); + writeV3S32(&data[2], position); + writeV3S32(&data[2+12], speed); + writeS32(&data[2+12+12], pitch); + writeS32(&data[2+12+12+4], yaw); + + // Send as unreliable + Send(0, data, false); +} + + +void Client::updateCamera(v3f pos, v3f dir) +{ + m_env.getMap().updateCamera(pos, dir); + camera_position = pos; + camera_direction = dir; +} + +MapNode Client::getNode(v3s16 p) +{ + JMutexAutoLock envlock(m_env_mutex); + return m_env.getMap().getNode(p); +} + +/*f32 Client::getGroundHeight(v2s16 p) +{ + JMutexAutoLock envlock(m_env_mutex); + return m_env.getMap().getGroundHeight(p); +}*/ + +bool Client::isNodeUnderground(v3s16 p) +{ + JMutexAutoLock envlock(m_env_mutex); + return m_env.getMap().isNodeUnderground(p); +} + +/*Player * Client::getLocalPlayer() +{ + JMutexAutoLock envlock(m_env_mutex); + return m_env.getLocalPlayer(); +}*/ + +/*core::list Client::getPlayers() +{ + JMutexAutoLock envlock(m_env_mutex); + return m_env.getPlayers(); +}*/ + +v3f Client::getPlayerPosition() +{ + JMutexAutoLock envlock(m_env_mutex); + LocalPlayer *player = m_env.getLocalPlayer(); + assert(player != NULL); + return player->getPosition(); +} + +void Client::setPlayerControl(PlayerControl &control) +{ + JMutexAutoLock envlock(m_env_mutex); + LocalPlayer *player = m_env.getLocalPlayer(); + assert(player != NULL); + player->control = control; +} + +// Returns true if the inventory of the local player has been +// updated from the server. If it is true, it is set to false. +bool Client::getLocalInventoryUpdated() +{ + // m_inventory_updated is behind envlock + JMutexAutoLock envlock(m_env_mutex); + bool updated = m_inventory_updated; + m_inventory_updated = false; + return updated; +} + +// Copies the inventory of the local player to parameter +void Client::getLocalInventory(Inventory &dst) +{ + JMutexAutoLock envlock(m_env_mutex); + Player *player = m_env.getLocalPlayer(); + assert(player != NULL); + dst = player->inventory; +} + +MapBlockObject * Client::getSelectedObject( + f32 max_d, + v3f from_pos_f_on_map, + core::line3d shootline_on_map + ) +{ + JMutexAutoLock envlock(m_env_mutex); + + core::array objects; + + for(core::map::Iterator + i = m_active_blocks.getIterator(); + i.atEnd() == false; i++) + { + v3s16 p = i.getNode()->getKey(); + + MapBlock *block = NULL; + try + { + block = m_env.getMap().getBlockNoCreate(p); + } + catch(InvalidPositionException &e) + { + continue; + } + + // Calculate from_pos relative to block + v3s16 block_pos_i_on_map = block->getPosRelative(); + v3f block_pos_f_on_map = intToFloat(block_pos_i_on_map); + v3f from_pos_f_on_block = from_pos_f_on_map - block_pos_f_on_map; + + block->getObjects(from_pos_f_on_block, max_d, objects); + } + + //dstream<<"Collected "<getBlock(); + + // Calculate shootline relative to block + v3s16 block_pos_i_on_map = block->getPosRelative(); + v3f block_pos_f_on_map = intToFloat(block_pos_i_on_map); + core::line3d shootline_on_block( + shootline_on_map.start - block_pos_f_on_map, + shootline_on_map.end - block_pos_f_on_map + ); + + if(obj->isSelected(shootline_on_block)) + { + //dstream<<"Returning selected object"<