Files
invoictoafpsgn/Net.h
T
2026-10-18 11:07:51 -04:00

67 lines
1.9 KiB
C++

#ifndef NET_CLASS
#define NET_CLASS
#include <cstdint>
#include <string>
#include <vector>
#include <glm/glm.hpp>
#include <glm/gtc/quaternion.hpp>
// Multiplayer UDP link for a LAN pit. One player hosts (UDP port 27015), everyone else joins by IP.
// Clients send their own transform to the host every frame; the host relays everyone's
// transform to everyone else. The host is player id 0, joiners get ids 1, 2, 3, ...
// All Winsock code lives in Net.cpp so windows.h never leaks into the rest of the engine.
struct NetState {
glm::vec3 position = glm::vec3(0.0f);
glm::quat rotation = glm::quat(1.0f, 0.0f, 0.0f, 0.0f);
bool sliding = false;
};
// A state received for some other player.
struct NetUpdate {
uint8_t id = 0;
NetState state;
};
class Lan {
public:
enum class Mode { Off, Host, Client };
// Total players in the pit, host included.
static constexpr int MaxPlayers = 8;
Lan();
~Lan();
// Opens the socket. For Client, hostIp is the host's IPv4 address. Returns false on failure.
bool Start(Mode mode, const std::string& hostIp);
void Stop();
Mode GetMode() const { return mode; }
bool IsActive() const { return active; }
// Call once per frame with our own state.
void Send(const NetState& state);
// Drains all waiting packets and appends the other players' newest states to 'out'.
void Receive(std::vector<NetUpdate>& out);
// Host: at least one player has joined. Client: the host has been heard from in the last 2 s.
bool IsConnected() const;
// Host only: number of joined players, not counting the host.
int PeerCount() const;
// This machine's IPv4 addresses (for the host to read out to the joiners).
static std::string LocalAddresses();
private:
struct Impl;
Impl* impl;
Mode mode = Mode::Off;
bool active = false;
};
inline Lan* lan = nullptr;
#endif