#include "client/Network.h" #include "client/Chat.h" #include "client/Main.h" #include "client/World.h" #include "common/NetworkPackets.h" #include "network/Client.h" #include "utils/Logger.h" static bool onWorldPacket(InPacket& in) { IntVector3 size = World::getSize(); for(int x = 0; x < size[0]; x++) { for(int y = 0; y < size[1]; y++) { for(int z = 0; z < size[2]; z++) { uint8 data = 0; if(in.read(data)) { return true; } World::set(x, y, z, data); } } } return false; } static bool onSetBlockPacket(InPacket& in) { IntVector3 pos; uint8 type; if(in.read(pos) || in.read(type)) { return true; } World::set(pos[0], pos[1], pos[2], type); return false; } static bool onPlayerPacket(InPacket& in) { Vector3 pos; int client; if(in.read(pos) || in.read(client)) { return true; } OtherPlayer* p = players.search(client); if(p != nullptr) { p->position = pos; } else { players.add(client, {pos}); } return false; } static bool onChatPacket(InPacket& in) { Chat::Message msg; uint32 u; while(!in.read(u)) { msg.appendUnicode(u); } Chat::add(msg); return false; } static bool handlePacket(ToClientPacket tcp, InPacket& in) { switch(tcp) { case ToClientPacket::WORLD: return onWorldPacket(in); case ToClientPacket::SET_BLOCK: return onSetBlockPacket(in); case ToClientPacket::PLAYER: return onPlayerPacket(in); case ToClientPacket::CHAT: return onChatPacket(in); } LOG_WARNING(StringBuffer<100>("unknown packet of type ") .append(static_cast(tcp))); return false; } static void onPacket(InPacket& in) { uint8 type = 0; if(in.read(type)) { LOG_WARNING("received packet without type"); return; } if(handlePacket(static_cast(type), in)) { LOG_WARNING(StringBuffer<100>("invalid packet of type ") .append(static_cast(type))); } } static void onDisconnect() { LOG_INFO("Disconnect"); } bool Network::start(const char* server) { Error e = Client::start(); if(e.has()) { LOG_ERROR(e.message); return true; } e = Client::connect(server, 11196, 40); if(e.has()) { LOG_ERROR(e.message); Client::stop(); return true; } Client::setPacketHandler(onPacket); Client::setDisconnectHandler(onDisconnect); return false; } void Network::stop() { Client::stop(); } void Network::tick() { Client::tick(); }