Files
stoneheart_at_home/app/lan_session.hpp

80 lines
2.7 KiB
C++

#pragma once
#include "settlement/core/world.hpp"
#include <cstdint>
#include <functional>
#include <memory>
#include <optional>
#include <string>
namespace settlement { class SimulationRuntime; }
namespace settlement::viewer {
enum class LanState { Offline, Hosting, HostConnected, Connecting, GuestConnected, GuestDisconnected };
inline constexpr std::uint16_t colony_lan_port = 41727;
struct LanRejection {
CommandStatus status;
CommandKind kind;
GridPosition cell;
std::uint8_t value;
GridPosition destination;
};
struct LanCommandResult {
CommandStatus status;
CommandKind kind;
GridPosition cell;
std::uint8_t value;
GridPosition destination;
AgentId resident;
};
struct LanSessionOptions {
// Runs on the polling thread after a guest command's snapshot checks and
// before owner admission. May block or throw for diagnostics/tests.
std::function<void()> before_command_admission;
};
class LanSession {
public:
LanSession();
explicit LanSession(LanSessionOptions options);
~LanSession();
LanSession(const LanSession&) = delete;
LanSession& operator=(const LanSession&) = delete;
void host(std::uint16_t port = colony_lan_port, bool loopback_only = false);
void join(std::string address, std::string code, std::uint16_t port = colony_lan_port);
void reconnect();
void leave() noexcept;
[[nodiscard]] LanState state() const noexcept;
[[nodiscard]] bool is_guest() const noexcept;
[[nodiscard]] std::string join_code() const;
[[nodiscard]] std::uint16_t port() const noexcept;
[[nodiscard]] const std::string& detail() const noexcept;
[[nodiscard]] bool submit(CommandKind kind, GridPosition cell, std::uint8_t value,
GridPosition destination = {}, AgentId resident = 0);
[[nodiscard]] std::optional<LanRejection> take_rejection() noexcept;
// poll_guest pauses further sends until this one retained result is drained.
[[nodiscard]] std::optional<LanCommandResult> take_result() noexcept;
[[nodiscard]] std::unique_ptr<World> poll(World& world);
// Protocol 11 accepts the compiled default rules and a representable 32x32
// active colony. Incompatible state drops the peer, including queued bytes,
// while the listener and authoritative owner remain available.
// Calls never wait for the owner. An admitted guest operation survives peer
// turnover, so poll_host must continue with the same owner until it settles.
void poll_host(SimulationRuntime& runtime);
[[nodiscard]] std::unique_ptr<World> poll_guest();
private:
struct Impl;
std::unique_ptr<Impl> impl_;
};
[[nodiscard]] std::string local_lan_addresses();
} // namespace settlement::viewer