123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111 |
- #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<uint32>(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<ToClientPacket>(type), in)) {
- LOG_WARNING(StringBuffer<100>("invalid packet of type ")
- .append(static_cast<uint32>(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();
- }
|