27#include <SDL3/SDL_stdinc.h>
29#include <SDL3_net/SDL_net.h>
34#include <entt/entt.hpp>
74 const std::uint8_t* bytes,
77 std::uint32_t& ackedTick)>;
111 const std::optional<net::UdpSessionTransport::RelayConfig>& relay = std::nullopt,
112 const std::optional<net::UdpSessionTransport::PunchAssist>& punch = std::nullopt);
124 bool send(
const void* data, uint32_t size);
157 bool sendVoiceFrame(std::uint16_t sequence, std::uint8_t frameMs, std::span<const std::uint8_t> opus);
428 std::optional<MatchStatePacket>
681 bool applySnapshot(std::uint32_t snapshotTick,
const std::uint8_t* bytes, Uint32 size, Uint32 wireSize);
PR-27 — per-entity animation state snapshot, decoupled from CharacterAnimator.
Bounded text-chat packet helpers shared by client, server, and tests.
ConnectError
Definition Client.hpp:57
@ ResolveFailed
Definition Client.hpp:59
@ ResolveTimedOut
Definition Client.hpp:60
@ ConnectFailed
Definition Client.hpp:63
@ LobbyFull
Definition Client.hpp:64
@ ConnectTimedOut
Definition Client.hpp:62
@ CreateClientFailed
Definition Client.hpp:61
@ None
Definition Client.hpp:58
Runtime host-controlled discovery advertisement settings.
Per-connection assembly buffer for fragmented UDP packets.
Shared lobby data types exchanged between server and clients.
Shared definitions for match status and state synchronization between server and clients.
Length-prefixed message framing layer over a TCP stream socket.
Structure of kill event broadcasted from server to clients.
Network configuration loaded from config.toml at startup.
Per-client outbound message queue with replace-on-stale semantics.
Serialize and deserialize the entt ECS registry for network replication.
Shared ECS registry type alias for the game engine.
entt::registry Registry
Shared ECS registry type alias.
Definition Registry.hpp:11
Wire-format types for the PR-20 lag-comp shot debug visualizer.
Wire-format particle effect event broadcast from server to all clients.
Thin wrapper over SDL3_net's NET_DatagramSocket.
UDP-first session transport with handshake, reliability, and relay routing.
Bounded Opus voice-frame packet helpers.
TCP stream client — sends input to the server and receives state updates.
Definition Client.hpp:69
std::deque< DelayedInbound > simLatInbound_
Definition Client.hpp:658
size_t inputRingHead_
Next write index, wraps mod k_inputRedundancy.
Definition Client.hpp:475
static constexpr size_t k_inputRedundancy
Number of recent inputs included in each INPUT packet for redundancy.
Definition Client.hpp:355
VoiceFrameCallback voiceFrameFn_
Called for proximity-routed Opus voice frames.
Definition Client.hpp:422
net::UdpSessionTransport session_
Definition Client.hpp:572
void onSnapshotApply(SnapshotApplyCallback fn)
Register the snapshot-apply callback; must be set before the first poll().
Definition Client.hpp:187
net::UdpEndpoint udpEndpoint_
Definition Client.hpp:573
Uint64 snapshotIntervalEmaNs_
Definition Client.hpp:552
std::vector< std::vector< uint8_t > > udpRecvQueue_
UDP-received payloads waiting for the game thread to dispatch.
Definition Client.hpp:584
void sendPing()
Send a PING packet to the server for RTT measurement.
Definition Client.cpp:329
std::function< bool(std::uint32_t snapshotTick, const std::uint8_t *bytes, Uint32 size, Uint64 captureNs, std::uint32_t &ackedTick)> SnapshotApplyCallback
Called by Client to apply a raw snapshot; the registry-owning caller performs the actual load.
Definition Client.hpp:73
std::function< void(const std::vector< LobbyPlayer > &players, ClientId localId)> LobbyStateCallback
Fired once on join with the full lobby snapshot and this client's assigned ID.
Definition Client.hpp:96
std::deque< DelayedOutbound > simLatOutbound_
Definition Client.hpp:650
bool consumeSnapshotApplied() noexcept
Whether a snapshot was applied since the last call to consumeSnapshotApplied().
Definition Client.hpp:252
std::optional< ClientId > latestLobbyLocalId_
This client's ID as reported in the LOBBY_STATE packet.
Definition Client.hpp:432
std::mutex stateMutex_
Definition Client.hpp:488
bool shouldDropPacketLocked()
Roll the loss RNG.
Definition Client.cpp:883
NET_Address * serverAddr
Resolved server address.
Definition Client.hpp:415
std::function< void(const LobbyUpdateEvent &update)> LobbyUpdateCallback
Fired for each incremental lobby roster update broadcast from the server.
Definition Client.hpp:94
MatchConfigCallback matchConfigFn_
Called whenever a MATCH_CONFIG packet is received.
Definition Client.hpp:426
bool sendVoiceFrame(std::uint16_t sequence, std::uint8_t frameMs, std::span< const std::uint8_t > opus)
Send one Opus-encoded voice frame. Voice rides unreliable sequenced UDP.
Definition Client.cpp:580
std::uint64_t connectionId_
Definition Client.hpp:575
void onMatchConfig(MatchConfigCallback fn)
Register the match-config update callback.
Definition Client.hpp:213
uint64_t bytesSentWindow
Definition Client.hpp:464
std::thread networkThread_
Definition Client.hpp:489
void onLobbyUpdate(LobbyUpdateCallback fn)
Register the incremental lobby-update callback.
Definition Client.hpp:205
std::optional< MatchConfig > getLatestMatchConfig() const
Return the latest match configuration received from the server, if any.
Definition Client.hpp:229
uint16_t udpInputSequence_
Per-channel sequence for INPUT datagrams.
Definition Client.hpp:576
uint32_t registryUpdatesWindow
Definition Client.hpp:468
bool snapshotAppliedFlag_
Definition Client.hpp:560
bool sendChatMessage(std::string_view message)
Send an all-chat message to the authoritative server.
Definition Client.cpp:563
KillEventCallback killEventFn_
Called for each replicated kill event from server.
Definition Client.hpp:419
std::function< void(const MatchConfig &config)> MatchConfigCallback
Definition Client.hpp:97
LobbyUpdateCallback lobbyUpdateFn_
Called for each lobby update received from server.
Definition Client.hpp:424
std::uint16_t chatClientSeq_
Definition Client.hpp:577
void shutdown()
Close the socket and release the resolved address.
Definition Client.cpp:250
std::optional< entt::entity > getServerLocalPlayerEntity() const
Server-assigned local-player entity before continuous_loader mapping.
Definition Client.hpp:283
void updateStats(float dt)
Update bandwidth stats. Call once per frame with the frame delta time.
Definition Client.cpp:375
bool usingUdpSession_
Definition Client.hpp:571
bool poll()
Receive and process one pending message.
Definition Client.cpp:1524
std::optional< std::vector< LobbyPlayer > > latestLobbyPlayers_
Most-recent lobby roster received from the server.
Definition Client.hpp:431
int interpDelaySnapshots_
Definition Client.hpp:551
std::array< InputSnapshot, k_inputRedundancy > inputRing_
Definition Client.hpp:474
void recvUdpDelayed(std::vector< uint8_t > &&payload)
Enqueue an assembled UDP message into udpRecvQueue_ immediately if the simulator is off,...
Definition Client.cpp:930
std::function< void(const net::shotdebug::ShotDebugCapture &)> ShotDebugCallback
PR-20: callback for SHOT_DEBUG_REPORT.
Definition Client.hpp:91
const NetworkStats & getNetStats() const
Access current network statistics.
Definition Client.hpp:223
bool sendServerShutdown()
Request server shutdown. The server accepts this only from the current host.
Definition Client.cpp:629
std::uint32_t keyframeTick_
Definition Client.hpp:459
void setSimulatedLossPercent(int percent) noexcept
Phase 6 testing: simulate UDP packet loss.
Definition Client.cpp:874
uint64_t reliableSeenBitmask_
Definition Client.hpp:601
void resetInputHistory()
Clear redundant input history at the start of a new local match instance.
Definition Client.cpp:506
bool sendShotIntent(std::uint32_t shotInputTick, std::uint16_t targetClientId, const AnimSnapshot &targetAnim)
PR-27 (netsync): send a SHOT_INTENT packet describing the client's view of the target's animation sta...
Definition Client.cpp:513
net::UdpEndpointAddr serverUdpAddr_
Definition Client.hpp:574
net::FragmentReassembler unreliableReassembler_
Phase 3d-4: reassembly buffer for fragmented snapshot datagrams on the Unreliable channel.
Definition Client.hpp:591
float getSnapshotAlpha() const
Render-time interpolation alpha based on snapshot timing.
Definition Client.cpp:683
Uint64 getInterpolationRenderTimeNs() const
Render time the renderer should display non-local entities at.
Definition Client.cpp:839
void recordInterpolationSamples(Registry ®istry, Uint64 captureNs)
Record interpolation samples after the caller has applied a snapshot.
Definition Client.cpp:799
void onLobbyState(LobbyStateCallback fn)
Register the full lobby-snapshot callback, fired once on join.
Definition Client.hpp:209
Uint64 prevSnapshotApplyNs_
Definition Client.hpp:505
void onMatchStateUpdate(MatchStateUpdateFn fn)
Register the match-state update callback, fired on every MATCH_STATE packet.
Definition Client.hpp:196
RosterEventCallback rosterEventFn_
Called for mid-match player join/leave updates.
Definition Client.hpp:421
void onShotDebugReport(ShotDebugCallback fn)
Register the shot-debug callback (PR-20); fired for each SHOT_DEBUG_REPORT.
Definition Client.hpp:204
void networkLoop()
Network-thread main loop body.
Definition Client.cpp:948
bool sendMatchConfig(const MatchConfig &config)
Send an updated match configuration to the server (host-only).
Definition Client.cpp:611
void onRosterEvent(RosterEventCallback fn)
Register the roster-event callback, fired for each mid-match join/leave.
Definition Client.hpp:201
float statsAccumulator
Definition Client.hpp:469
std::optional< std::string > latestServerName_
Server display name reported by the latest LOBBY_STATE packet.
Definition Client.hpp:433
bool sendInputSnapshot(const InputSnapshot &snap)
Push the latest input into the redundant ring and send to the server.
Definition Client.cpp:389
TransportConfig transportConfig_
Definition Client.hpp:570
void onTextChat(TextChatCallback fn)
Definition Client.hpp:199
std::uint32_t reliableHighestSeen_
Phase 3d-5: sliding-window bitset for ReliableOrdered channel dedup.
Definition Client.hpp:600
std::function< void(const PlayerRosterEvent &)> RosterEventCallback
Fired for server-authored mid-match join/leave notifications.
Definition Client.hpp:84
bool sendCancelStartMatch()
Send a CANCEL_START_MATCH packet to the server (host-only).
Definition Client.cpp:605
std::function< void(const NetKillEvent &)> KillEventCallback
Definition Client.hpp:81
std::function< void(const net::voice::ServerVoiceFrame &)> VoiceFrameCallback
Definition Client.hpp:85
ShotDebugCallback shotDebugFn_
PR-20: called for each SHOT_DEBUG_REPORT from server.
Definition Client.hpp:423
uint32_t serverAckedClientTick_
Definition Client.hpp:559
std::atomic< int > simulatedLossPercent_
Per-direction independent UDP-drop probability (slider value, 0–100).
Definition Client.hpp:629
void dispatchMessage(const uint8_t *data, Uint32 size)
Decode and dispatch a single complete framed message.
Definition Client.cpp:1156
bool sendPhysicsDiagRecording(bool enabled)
Ask the server to start/stop authoritative physics CSV recording.
Definition Client.cpp:571
bool applySnapshot(std::uint32_t snapshotTick, const std::uint8_t *bytes, Uint32 size, Uint32 wireSize)
Invoke snapshotApplyFn_ with raw snapshot bytes; updates delta-decode state on success.
Definition Client.cpp:1129
Uint64 lastSnapshotApplyNs_
Definition Client.hpp:504
std::vector< uint8_t > keyframePayload_
Definition Client.hpp:458
bool isConnected()
True while a server connection is currently owned by this client.
Definition Client.cpp:286
uint64_t bytesRecvWindow
Definition Client.hpp:465
void onKillEvent(KillEventCallback fn)
Register the kill-event callback, fired for each replicated kill from the server.
Definition Client.hpp:198
bool sendStartMatch()
Send a START_MATCH packet to the server (host-only).
Definition Client.cpp:599
std::function< void(const NetParticleEvent &evt)> RawParticleEventCallback
Called for each replicated particle event before entity mapping; caller is responsible for mapping.
Definition Client.hpp:79
uint32_t getServerAckedClientTick() const noexcept
Latest server-acked client predict tick.
Definition Client.hpp:245
std::atomic< bool > socketDead_
Latched-true once the network thread observes a socket error.
Definition Client.hpp:495
static constexpr Uint64 k_defaultSnapshotIntervalNs
Definition Client.hpp:529
int getSimulatedLatencyMs() const noexcept
Get the currently-effective simulated total RTT.
Definition Client.hpp:380
size_t inputRingCount_
Valid entries in ring; saturates at k_inputRedundancy.
Definition Client.hpp:476
uint64_t udpSessionLastBytesSent_
Definition Client.hpp:466
RawParticleEventCallback rawParticleEventFn_
Called for unmapped replicated particle events.
Definition Client.hpp:417
void onVoiceFrame(VoiceFrameCallback fn)
Definition Client.hpp:202
uint64_t udpSessionLastBytesRecv_
Definition Client.hpp:467
bool send(const void *data, uint32_t size)
Send a raw message to the server.
Definition Client.cpp:305
int getSimulatedLossPercent() const noexcept
Get the currently-effective simulated packet loss %.
Definition Client.hpp:406
std::atomic< int > simulatedLatencyMs_
Total simulated RTT in ms (slider value, 0–200).
Definition Client.hpp:624
MatchStateUpdateFn matchStateUpdateFn_
Called whenever a MATCH_STATE packet is received.
Definition Client.hpp:418
void onRawParticleEvent(RawParticleEventCallback fn)
Register the raw particle-event callback.
Definition Client.hpp:191
bool acceptReliableSequence(std::uint32_t seq)
Sliding-window dedup helper.
Definition Client.cpp:643
std::optional< MatchStatePacket > latestMatchState_
Most-recent MATCH_STATE packet; populated by dispatchMessage.
Definition Client.hpp:429
void applyInterpolatedTransforms(Registry ®istry)
PR-19: overwrite Position.value (and InputSnapshot.yaw) for every non-local entity with an Interpolat...
Definition Client.cpp:713
SnapshotApplyCallback snapshotApplyFn_
Applies snapshot bytes in the registry-owning caller.
Definition Client.hpp:416
MessageStream msgStream
Framed message stream for server communication.
Definition Client.hpp:414
NetworkStats stats
Live network metrics.
Definition Client.hpp:461
std::optional< std::pair< std::vector< LobbyPlayer >, ClientId > > getLatestLobbyState() const
Return the latest lobby roster received from the server, if any.
Definition Client.cpp:635
std::function< void(const MatchStatePacket &)> MatchStateUpdateFn
Definition Client.hpp:80
ConnectError init(const char *addr, Uint16 port, const TransportConfig &transport={}, int timeoutMs=-1, const std::optional< net::UdpSessionTransport::RelayConfig > &relay=std::nullopt, const std::optional< net::UdpSessionTransport::PunchAssist > &punch=std::nullopt)
Create the TCP socket and connect to the server.
Definition Client.cpp:46
std::atomic< bool > shouldStop_
Definition Client.hpp:490
std::optional< MatchConfig > latestMatchConfig_
Most-recent MATCH_CONFIG packet; populated by dispatchMessage.
Definition Client.hpp:430
std::optional< MatchStatePacket > getLatestMatchState() const
Return the latest match state packet received from the server, if any.
Definition Client.hpp:226
TextChatCallback textChatFn_
Called for server-broadcast all-chat messages.
Definition Client.hpp:420
bool sendUdpDelayed(net::PacketHeader hdr, const void *data, int len)
Send a UDP datagram immediately if the latency simulator is off, otherwise queue it for delayed send.
Definition Client.cpp:896
bool reliableHasAny_
False until the first reliable event arrives.
Definition Client.hpp:602
bool sendGameplayReady()
Definition Client.cpp:1577
std::optional< entt::entity > localPlayerEntity
The local player's entity, once assigned by the server.
Definition Client.hpp:427
void setSimulatedLatencyMs(int totalMs) noexcept
Phase 6 testing: simulate added round-trip latency.
Definition Client.cpp:861
std::function< void(const net::chat::ServerTextChat &)> TextChatCallback
Definition Client.hpp:82
OutboundQueue outbound_
Definition Client.hpp:487
LobbyStateCallback lobbyStateFn_
Called once on join with the full lobby snapshot.
Definition Client.hpp:425
bool sendPlayerReady(bool ready)
Send a PLAYER_READY or PLAYER_UNREADY packet to the server.
Definition Client.cpp:593
std::optional< std::string > getLatestServerName() const
Return the latest server display name received from the server, if any.
Definition Client.hpp:235
std::mt19937 simLossRng_
PRNG for the loss simulator.
Definition Client.hpp:636
Uint64 getSnapshotIntervalNs() const
Approximate snapshot interval in nanoseconds.
Definition Client.cpp:708
bool sendDiscoverySettings(const DiscoverySettings &settings)
Send updated discovery advertisement settings to the server.
Definition Client.cpp:619
Length-prefixed framing layer over a TCP stream socket.
Definition MessageStream.hpp:29
Per-connection outbound message queue.
Definition OutboundQueue.hpp:85
Definition FragmentReassembler.hpp:33
Wraps a NET_DatagramSocket with header-prefixed I/O.
Definition UdpEndpoint.hpp:109
Definition UdpSessionTransport.hpp:26
Snapshot of an entity's full animation state at one instant.
Definition AnimSnapshot.hpp:73
Associates an entity with a connected network client.
Definition ClientId.hpp:10
One inbound payload queued for delayed dispatch.
Definition Client.hpp:654
Uint64 deliverAtCounter
Performance counter at which to enqueue.
Definition Client.hpp:655
std::vector< uint8_t > payload
Already-assembled message ([PacketType][rest]).
Definition Client.hpp:656
One outbound UDP datagram queued for delayed send.
Definition Client.hpp:644
std::vector< uint8_t > payload
Datagram payload bytes.
Definition Client.hpp:647
Uint64 sendAtCounter
Performance counter at which to send.
Definition Client.hpp:645
net::PacketHeader header
Caller-supplied header (passed through verbatim).
Definition Client.hpp:646
std::size_t totalBytes
For deferred bandwidth accounting.
Definition Client.hpp:648
Host-managed discovery visibility flags.
Definition DiscoverySettings.hpp:11
Incremental lobby change event broadcast to all connected clients.
Definition LobbyStatus.hpp:34
Definition MatchConfig.hpp:4
Definition MatchStatus.hpp:17
Event representing a player kill, sent from server to client for kill feed updates.
Definition NetKillEvent.hpp:12
Wire-format particle event broadcast from server to all clients.
Definition ShotEvent.hpp:28
Live network statistics updated each frame.
Definition Client.hpp:45
float registryUpdatesPerSec
Registry updates received per second.
Definition Client.hpp:53
float avgRttMs
Exponential moving average RTT (ms).
Definition Client.hpp:47
uint32_t registryUpdateSize
Last registry update payload size (bytes).
Definition Client.hpp:52
float rttMs
Latest round-trip time (ms).
Definition Client.hpp:46
uint64_t bytesSentTotal
Total bytes sent since connection.
Definition Client.hpp:49
float recvBytesPerSec
Receive bandwidth (bytes/sec, smoothed).
Definition Client.hpp:50
float sendBytesPerSec
Send bandwidth (bytes/sec, smoothed).
Definition Client.hpp:51
uint64_t bytesRecvTotal
Total bytes received since connection.
Definition Client.hpp:48
Server-authored join/leave notification for in-progress matches.
Definition RosterEvent.hpp:20
Phase 3d: per-feature toggles for the UDP transport rollout.
Definition NetworkConfig.hpp:63
A UDP datagram address (server's view of a remote peer).
Definition UdpEndpoint.hpp:49
Definition ChatProtocol.hpp:27
Server-side runtime capture of one shot's debug data, produced by WeaponSystem::handleFire and consum...
Definition ShotDebugReport.hpp:111
Definition VoiceProtocol.hpp:36