ferravex_net/
lib.rs

1//! Bounded, versioned network protocol shared by native and browser game clients.
2//!
3//! The protocol never accepts client positions or client-selected time steps.
4//! Native UDP is intentionally a thin primitive:
5//! accounts/encryption and NAT traversal remain outside this prototype. The
6//! first-party WebSocket gateway carries browser datagrams to the same authority.
7pub mod baselines;
8pub mod clock;
9pub mod delta;
10pub mod history;
11pub mod local_link;
12pub mod reliable;
13pub mod time;
14#[cfg(not(target_arch = "wasm32"))]
15pub mod websocket;
16mod wire_v4;
17pub use wire_v4::{Client as ClientExtension, Server as ServerExtension, TimedInput};
18
19use std::collections::VecDeque;
20use std::fmt;
21
22pub const MAX_PACKET_BYTES: usize = 1200;
23pub const MAX_PLAYERS: usize = 16;
24pub const MAX_INPUTS_PER_PACKET: usize = 6;
25pub const MAX_QUEUED_INPUTS: usize = 64;
26pub const BUTTON_JUMP: u8 = 1;
27pub const BUTTON_FIRE: u8 = 2;
28pub const BUTTON_RELOAD: u8 = 4;
29pub const MAX_PITCH: f32 = 1.55;
30const MAGIC: &[u8; 4] = b"FVRX";
31/// Version 4 adds timed inputs, clock exchanges, snapshot ACK/deltas and commands.
32// Version 5 preserves the v4 payloads and gates the retuned prediction rules.
33pub const PROTOCOL_VERSION: u8 = 5;
34
35#[derive(Clone, Copy, Debug, Default, PartialEq)]
36pub struct InputFrame {
37    pub sequence: u32,
38    /// Strafe right in [-1, 1].
39    pub move_x: f32,
40    /// Move forward in [-1, 1]; yaw zero faces negative Z.
41    pub move_z: f32,
42    pub yaw: f32,
43    /// Positive pitch looks up.
44    pub pitch: f32,
45    pub buttons: u8,
46}
47impl InputFrame {
48    pub fn sanitized(mut self) -> Self {
49        let finite = |v: f32| if v.is_finite() { v } else { 0.0 };
50        self.move_x = finite(self.move_x).clamp(-1.0, 1.0);
51        self.move_z = finite(self.move_z).clamp(-1.0, 1.0);
52        self.yaw = (finite(self.yaw) + std::f32::consts::PI).rem_euclid(std::f32::consts::TAU)
53            - std::f32::consts::PI;
54        self.pitch = finite(self.pitch).clamp(-MAX_PITCH, MAX_PITCH);
55        self.buttons &= BUTTON_JUMP | BUTTON_FIRE | BUTTON_RELOAD;
56        self
57    }
58    pub fn is_valid(self) -> bool {
59        self.move_x.is_finite()
60            && self.move_x.abs() <= 1.0
61            && self.move_z.is_finite()
62            && self.move_z.abs() <= 1.0
63            && self.yaw.is_finite()
64            && self.yaw.abs() <= std::f32::consts::PI
65            && self.pitch.is_finite()
66            && self.pitch.abs() <= MAX_PITCH
67            && self.buttons & !(BUTTON_JUMP | BUTTON_FIRE | BUTTON_RELOAD) == 0
68    }
69}
70
71#[derive(Clone, Debug, PartialEq)]
72pub enum ClientPacket {
73    Extension(ClientExtension),
74    EventAck {
75        session: u64,
76        sequence: u64,
77    },
78    Hello {
79        nonce: u64,
80    },
81    Input {
82        session: u64,
83        inputs: Vec<InputFrame>,
84    },
85}
86#[derive(Clone, Debug, PartialEq)]
87pub enum ServerPacket {
88    Extension(ServerExtension),
89    ReliableEvent {
90        session: u64,
91        event: reliable::EventPacket,
92    },
93    Welcome {
94        nonce: u64,
95        session: u64,
96        player_id: u8,
97        tick: u32,
98    },
99    Snapshot(Snapshot),
100}
101#[derive(Clone, Debug, Default, PartialEq)]
102pub struct Snapshot {
103    /// Session cookie prevents delayed packets from a prior connection being accepted.
104    pub session: u64,
105    pub tick: u32,
106    pub ack_sequence: u32,
107    pub ack_valid: bool,
108    /// Low 32 bits of the authority life generation for each player slot.
109    pub epochs: [u32; MAX_PLAYERS],
110    pub players: Vec<PlayerSnapshot>,
111}
112#[derive(Clone, Copy, Debug, Default, PartialEq)]
113pub struct PlayerSnapshot {
114    pub id: u8,
115    pub position: [f32; 3],
116    pub velocity: [f32; 3],
117    pub yaw: f32,
118    pub pitch: f32,
119    pub health: u8,
120    pub ammo: u8,
121    pub grounded: bool,
122    pub jump_coyote: f32,
123    pub jump_buffer: f32,
124    pub jump_held: bool,
125    pub fire_cooldown: u16,
126    pub reload_ticks: u16,
127    pub respawn_ticks: u16,
128}
129impl PlayerSnapshot {
130    fn is_valid(self) -> bool {
131        (self.id as usize) < MAX_PLAYERS
132            && self
133                .position
134                .into_iter()
135                .all(|v| v.is_finite() && v.abs() <= 4096.0)
136            && self
137                .velocity
138                .into_iter()
139                .all(|v| v.is_finite() && v.abs() <= 256.0)
140            && self.yaw.is_finite()
141            && self.yaw.abs() <= std::f32::consts::PI
142            && self.pitch.is_finite()
143            && self.pitch.abs() <= MAX_PITCH
144            && self.jump_coyote.is_finite()
145            && (0. ..=0.5).contains(&self.jump_coyote)
146            && self.jump_buffer.is_finite()
147            && (0. ..=0.5).contains(&self.jump_buffer)
148            && self.health <= 100
149            && self.ammo <= 30
150            && self.fire_cooldown <= 4096
151            && self.reload_ticks <= 4096
152            && self.respawn_ticks <= 4096
153    }
154}
155
156#[derive(Clone, Copy, Debug, PartialEq, Eq)]
157pub enum ProtocolError {
158    TooLarge,
159    Truncated,
160    Header,
161    Version,
162    Kind,
163    Invalid,
164    Trailing,
165}
166impl fmt::Display for ProtocolError {
167    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
168        write!(f, "invalid Ferravex packet: {self:?}")
169    }
170}
171impl std::error::Error for ProtocolError {}
172
173/// RFC-1982-style comparison. Exactly half a sequence space is ambiguous and rejected.
174pub fn sequence_newer(candidate: u32, previous: u32) -> bool {
175    let delta = candidate.wrapping_sub(previous);
176    delta != 0 && delta < (1 << 31)
177}
178
179/// Reason a checked input admission was rejected.
180///
181/// Validation precedes capacity, which precedes sequence ordering. A rejection
182/// changes only its metric, never pending controls or the sequence watermark.
183#[derive(Clone, Copy, Debug, PartialEq, Eq)]
184pub enum InputAdmissionError {
185    /// The embedded [`InputFrame`] fails [`InputFrame::is_valid`].
186    InvalidInput,
187    /// The queue already contains [`MAX_QUEUED_INPUTS`] entries.
188    Full,
189    /// The sequence equals the newest accepted sequence, even after removal.
190    DuplicateNewest,
191    /// The sequence is older, or exactly half a sequence space away.
192    /// Repeats of earlier accepted sequences also fall in this category.
193    OutOfOrder,
194}
195impl fmt::Display for InputAdmissionError {
196    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
197        write!(f, "input queue admission rejected: {self:?}")
198    }
199}
200impl std::error::Error for InputAdmissionError {}
201
202/// Queue-local activity since creation or the last [`InputQueue::reset_metrics`].
203///
204/// Every field saturates independently at [`u64::MAX`]. These count operations,
205/// not packets, ticks, simulated actions or remote delivery. Both legacy bool
206/// and checked admissions count exactly once. Admission never evicts an input.
207/// Coalesced and explicitly discarded entries are separate from rejections and
208/// from entries returned to the caller. Before saturation, absent a metrics
209/// reset with pending entries, accepted = pending + returned + coalesced + discarded.
210#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
211pub struct InputQueueMetrics {
212    /// Successfully appended inputs.
213    pub accepted_inputs: u64,
214    /// Admissions rejected for invalid embedded controls.
215    pub rejected_invalid: u64,
216    /// Admissions rejected for capacity, including stale sequences at capacity.
217    pub rejected_full: u64,
218    /// Admissions rejected for equality with the newest accepted sequence.
219    pub rejected_duplicate_newest: u64,
220    /// Admissions rejected for older or half-range ambiguous sequences.
221    pub rejected_out_of_order: u64,
222    /// Entries returned by pop operations; one per nonempty coalescing call.
223    /// Returning an entry does not establish that simulation consumed it.
224    pub returned_inputs: u64,
225    /// Older entries folded into a returned newest entry by coalescing.
226    /// Their action bits and the first recovered fire aim/time can survive.
227    pub coalesced_inputs: u64,
228    /// Pending entries dropped by clear_pending or reset_session, without return.
229    pub discarded_inputs: u64,
230}
231
232/// Deduplicates input redundancy and bounds per-client simulation backlog.
233///
234/// Checked admission preserves the legacy bool methods' ordering and bounds.
235/// All [`TimedInput::shot_tick`] values (including a tick without a fire bit)
236/// remain accepted when the embedded frame is valid; authority rewind policy
237/// belongs to the consumer, not this queue. No protocol bytes are changed.
238///
239/// Receive controls independently of rendering or local menus. Pop only for an
240/// actual authoritative tick; a local overlay must not suspend network/replay
241/// progression. Queue metrics describe removal, not executed simulation work.
242///
243/// This supplied-input recipe recovers an older fire press while using newest
244/// movement. Hand the returned command and shot time to the authority's fixed
245/// tick, then derive feedback from its accepted game events.
246///
247/// ```
248/// use ferravex_net::{
249///     BUTTON_FIRE, InputAdmissionError, InputFrame, InputQueue,
250///     InputQueueMetrics, TimedInput,
251/// };
252///
253/// let mut queue = InputQueue::default();
254/// queue.push_timed_checked(TimedInput {
255///     input: InputFrame {
256///         sequence: 40, yaw: 1.0, pitch: 0.25, buttons: BUTTON_FIRE,
257///         ..InputFrame::default()
258///     },
259///     shot_tick: Some(120),
260/// }).unwrap();
261/// let movement = InputFrame { sequence: 41, move_x: 1.0, ..InputFrame::default() };
262/// queue.push_checked(movement).unwrap();
263/// assert_eq!(queue.push_checked(movement), Err(InputAdmissionError::DuplicateNewest));
264/// // At the next actual authority tick:
265/// let command = queue.pop_latest_timed().unwrap();
266/// assert_eq!(command.input.sequence, 41);
267/// assert_eq!(command.input.move_x, 1.0);
268/// assert_eq!((command.input.yaw, command.input.pitch), (1.0, 0.25));
269/// assert_eq!(command.input.buttons, BUTTON_FIRE);
270/// assert_eq!(command.shot_tick, Some(120));
271/// let metrics = queue.metrics(); // Read-only copy for host diagnostics.
272/// assert_eq!(metrics.returned_inputs, 1);
273/// assert_eq!(metrics.coalesced_inputs, 1);
274/// assert_eq!(metrics.rejected_duplicate_newest, 1);
275///
276/// // A round reset discards pending controls but keeps replay protection.
277/// assert!(queue.push(InputFrame { sequence: 42, ..movement }));
278/// queue.clear_pending();
279/// assert_eq!(queue.metrics().discarded_inputs, 1);
280/// assert_eq!(queue.push_checked(movement), Err(InputAdmissionError::OutOfOrder));
281/// let previous_window = queue.reset_metrics();
282/// assert_eq!(previous_window.accepted_inputs, 3);
283/// assert_eq!(queue.metrics(), InputQueueMetrics::default());
284/// assert!(!queue.push(InputFrame { sequence: 42, ..movement }));
285/// // Only after the host establishes a new authenticated session:
286/// queue.reset_session(); // Clears pending and watermark; retains metrics/storage.
287/// assert!(queue.push(InputFrame::default()));
288/// ```
289#[derive(Debug, Default)]
290pub struct InputQueue {
291    queue: VecDeque<TimedInput>,
292    newest: Option<u32>,
293    metrics: InputQueueMetrics,
294}
295impl InputQueue {
296    /// Legacy admission; true exactly when [`Self::push_checked`] succeeds.
297    pub fn push(&mut self, input: InputFrame) -> bool {
298        self.push_checked(input).is_ok()
299    }
300    /// Legacy timed admission; counts once through [`Self::push_timed_checked`].
301    pub fn push_timed(&mut self, timed: TimedInput) -> bool {
302        self.push_timed_checked(timed).is_ok()
303    }
304    /// Append untimed controls or report the first rejection reason.
305    ///
306    /// Equivalent to [`Self::push_timed_checked`] with no shot tick. See the
307    /// [`InputQueue`] recipe for admission, coalescing and reset scopes.
308    pub fn push_checked(&mut self, input: InputFrame) -> Result<(), InputAdmissionError> {
309        self.push_timed_checked(TimedInput {
310            input,
311            shot_tick: None,
312        })
313    }
314    /// Append timed controls, validating input, capacity, then sequence ordering.
315    ///
316    /// Failure preserves all pending values and the watermark, and increments
317    /// exactly one saturating rejection counter. Only the embedded frame is
318    /// validated: shot_tick is opaque, as in the existing wire protocol.
319    /// Success appends without eviction and advances the accepted watermark.
320    pub fn push_timed_checked(&mut self, timed: TimedInput) -> Result<(), InputAdmissionError> {
321        let input = timed.input;
322        let rejection = if !input.is_valid() {
323            Some((
324                InputAdmissionError::InvalidInput,
325                &mut self.metrics.rejected_invalid,
326            ))
327        } else if self.queue.len() >= MAX_QUEUED_INPUTS {
328            Some((InputAdmissionError::Full, &mut self.metrics.rejected_full))
329        } else if self.newest == Some(input.sequence) {
330            Some((
331                InputAdmissionError::DuplicateNewest,
332                &mut self.metrics.rejected_duplicate_newest,
333            ))
334        } else if self
335            .newest
336            .is_some_and(|old| !sequence_newer(input.sequence, old))
337        {
338            Some((
339                InputAdmissionError::OutOfOrder,
340                &mut self.metrics.rejected_out_of_order,
341            ))
342        } else {
343            None
344        };
345        if let Some((reason, counter)) = rejection {
346            *counter = counter.saturating_add(1);
347            return Err(reason);
348        }
349        self.newest = Some(input.sequence);
350        self.queue.push_back(timed);
351        self.metrics.accepted_inputs = self.metrics.accepted_inputs.saturating_add(1);
352        Ok(())
353    }
354    /// Read a copy of queue-local counters without changing any state.
355    pub fn metrics(&self) -> InputQueueMetrics {
356        self.metrics
357    }
358    /// Begin a new metrics window and return the previous counters.
359    ///
360    /// Pending inputs, allocated storage and the accepted sequence watermark
361    /// are retained. Later removals can count inputs admitted before this reset.
362    pub fn reset_metrics(&mut self) -> InputQueueMetrics {
363        std::mem::take(&mut self.metrics)
364    }
365    /// Discard queued controls while retaining the sequence watermark and metrics.
366    ///
367    /// Increments discarded_inputs by the number removed; retains storage.
368    /// Suitable for an authority round reset, never a local menu pause.
369    pub fn clear_pending(&mut self) {
370        self.metrics.discarded_inputs = self
371            .metrics
372            .discarded_inputs
373            .saturating_add(self.queue.len() as u64);
374        self.queue.clear();
375    }
376    /// Discard pending controls and forget the accepted sequence watermark.
377    ///
378    /// Retains allocated storage and metrics (including these discards). Call
379    /// reset_metrics separately if a new reporting window is wanted. Use only
380    /// when the host establishes a new session; using this for a round/menu
381    /// would allow delayed controls from the same session to re-enter.
382    pub fn reset_session(&mut self) {
383        self.clear_pending();
384        self.newest = None;
385    }
386    /// Return the oldest input without its shot time, counting one returned entry.
387    pub fn pop(&mut self) -> Option<InputFrame> {
388        let timed = self.queue.pop_front()?;
389        self.metrics.returned_inputs = self.metrics.returned_inputs.saturating_add(1);
390        Some(timed.input)
391    }
392    /// Coalesce a burst to its newest movement/look sample without losing a
393    /// queued action press. The authority still simulates exactly one fixed step.
394    /// This prevents redundant commands recovered after loss from adding permanent
395    /// control latency. Previously consumed commands cannot re-enter the queue.
396    pub fn pop_latest(&mut self) -> Option<InputFrame> {
397        self.pop_latest_timed().map(|v| v.input)
398    }
399    /// A recovered older quick-fire press retains its original aim and shot time.
400    ///
401    /// Returns one entry and counts all older entries as coalesced. The newest
402    /// fire sample wins if present; otherwise the oldest queued fire sample wins.
403    /// Empty pops change no counters. Removal never resets the watermark.
404    pub fn pop_latest_timed(&mut self) -> Option<TimedInput> {
405        let mut latest = self.queue.pop_back()?;
406        self.metrics.returned_inputs = self.metrics.returned_inputs.saturating_add(1);
407        self.metrics.coalesced_inputs = self
408            .metrics
409            .coalesced_inputs
410            .saturating_add(self.queue.len() as u64);
411        for older in self.queue.drain(..) {
412            if latest.input.buttons & BUTTON_FIRE == 0 && older.input.buttons & BUTTON_FIRE != 0 {
413                latest.input.yaw = older.input.yaw;
414                latest.input.pitch = older.input.pitch;
415                latest.shot_tick = older.shot_tick;
416            }
417            latest.input.buttons |= older.input.buttons;
418        }
419        Some(latest)
420    }
421    pub fn len(&self) -> usize {
422        self.queue.len()
423    }
424    pub fn is_empty(&self) -> bool {
425        self.queue.is_empty()
426    }
427}
428
429#[cfg(test)]
430mod journey400_316_saturation_tests {
431    use super::*;
432
433    #[test]
434    fn every_counter_saturates_independently_without_affecting_queue_behavior() {
435        let near = u64::MAX - 1;
436        let mut queue = InputQueue {
437            metrics: InputQueueMetrics {
438                accepted_inputs: near,
439                rejected_invalid: near,
440                rejected_full: near,
441                rejected_duplicate_newest: near,
442                rejected_out_of_order: near,
443                returned_inputs: near,
444                coalesced_inputs: near,
445                discarded_inputs: near,
446            },
447            ..InputQueue::default()
448        };
449        for sequence in 0..3 {
450            assert!(queue.push(InputFrame {
451                sequence,
452                ..InputFrame::default()
453            }));
454        }
455        for _ in 0..2 {
456            assert!(!queue.push(InputFrame {
457                move_x: f32::NAN,
458                ..InputFrame::default()
459            }));
460            assert!(!queue.push(InputFrame {
461                sequence: 2,
462                ..InputFrame::default()
463            }));
464            assert!(!queue.push(InputFrame::default()));
465        }
466        assert_eq!(queue.pop_latest().unwrap().sequence, 2);
467        for sequence in 3..3 + MAX_QUEUED_INPUTS as u32 {
468            assert!(queue.push(InputFrame {
469                sequence,
470                ..InputFrame::default()
471            }));
472        }
473        for _ in 0..2 {
474            assert!(!queue.push(InputFrame {
475                sequence: 100,
476                ..InputFrame::default()
477            }));
478        }
479        assert_eq!(queue.pop().unwrap().sequence, 3);
480        queue.clear_pending();
481        assert!(queue.push(InputFrame {
482            sequence: 100,
483            ..InputFrame::default()
484        }));
485        queue.reset_session();
486        assert!(queue.is_empty());
487        assert_eq!(
488            queue.metrics(),
489            InputQueueMetrics {
490                accepted_inputs: u64::MAX,
491                rejected_invalid: u64::MAX,
492                rejected_full: u64::MAX,
493                rejected_duplicate_newest: u64::MAX,
494                rejected_out_of_order: u64::MAX,
495                returned_inputs: u64::MAX,
496                coalesced_inputs: u64::MAX,
497                discarded_inputs: u64::MAX,
498            }
499        );
500        assert_eq!(queue.reset_metrics().accepted_inputs, u64::MAX);
501        assert_eq!(queue.metrics(), InputQueueMetrics::default());
502        assert!(queue.push(InputFrame::default()));
503        assert_eq!(queue.metrics().accepted_inputs, 1);
504    }
505}
506
507/// Rejection from packet encoding. Field paths are stable diagnostic names;
508/// indices identify a zero-based input/player/epoch, never a byte offset.
509///
510/// All field validation precedes output capacity checking. Legacy allocating
511/// encoders map field/length errors to [`ProtocolError::Invalid`] and whole
512/// packet overflow to [`ProtocolError::TooLarge`]. They never return Capacity.
513/// See [`encode_client_into`] for a capacity/error example.
514#[derive(Clone, Copy, Debug, PartialEq, Eq)]
515#[non_exhaustive]
516pub enum EncodeError {
517    InvalidField {
518        field: &'static str,
519        index: Option<usize>,
520    },
521    Length {
522        field: &'static str,
523        len: usize,
524        min: usize,
525        max: usize,
526    },
527    TooLarge {
528        required: usize,
529        max: usize,
530    },
531    Capacity {
532        required: usize,
533        available: usize,
534    },
535}
536impl fmt::Display for EncodeError {
537    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
538        write!(f, "Ferravex packet encoding rejected: {self:?}")
539    }
540}
541impl std::error::Error for EncodeError {}
542impl EncodeError {
543    fn protocol(self) -> ProtocolError {
544        match self {
545            Self::TooLarge { .. } | Self::Capacity { .. } => ProtocolError::TooLarge,
546            Self::InvalidField { .. } | Self::Length { .. } => ProtocolError::Invalid,
547        }
548    }
549}
550
551// The same walker validates/counts with no destination, then writes to the
552// preflighted slice. Immutable packet borrows prevent changes between passes.
553// No unsafe aliases, allocation, stack packet copy or separate length formulas.
554struct Encoder<'a> {
555    destination: Option<&'a mut [u8]>,
556    len: usize,
557}
558impl Encoder<'_> {
559    fn extend_from_slice(&mut self, bytes: &[u8]) {
560        if let Some(destination) = &mut self.destination {
561            destination[self.len..self.len + bytes.len()].copy_from_slice(bytes);
562        }
563        self.len += bytes.len();
564    }
565    fn push(&mut self, byte: u8) {
566        self.extend_from_slice(&[byte]);
567    }
568    fn header(&mut self, kind: u8) {
569        self.extend_from_slice(MAGIC);
570        self.extend_from_slice(&[PROTOCOL_VERSION, kind]);
571    }
572}
573fn invalid(field: &'static str, index: Option<usize>) -> EncodeError {
574    EncodeError::InvalidField { field, index }
575}
576fn valid_field(ok: bool, field: &'static str, index: Option<usize>) -> Result<(), EncodeError> {
577    if ok {
578        Ok(())
579    } else {
580        Err(invalid(field, index))
581    }
582}
583fn valid_len(field: &'static str, len: usize, min: usize, max: usize) -> Result<(), EncodeError> {
584    if (min..=max).contains(&len) {
585        Ok(())
586    } else {
587        Err(EncodeError::Length {
588            field,
589            len,
590            min,
591            max,
592        })
593    }
594}
595fn valid_session(session: u64) -> Result<(), EncodeError> {
596    valid_field(session != 0, "session", None)
597}
598fn validate_input(input: &InputFrame, index: usize) -> Result<(), EncodeError> {
599    for (value, max, field) in [
600        (input.move_x, 1., "inputs.move_x"),
601        (input.move_z, 1., "inputs.move_z"),
602        (input.yaw, std::f32::consts::PI, "inputs.yaw"),
603        (input.pitch, MAX_PITCH, "inputs.pitch"),
604    ] {
605        valid_field(value.is_finite() && value.abs() <= max, field, Some(index))?;
606    }
607    valid_field(
608        input.buttons & !(BUTTON_JUMP | BUTTON_FIRE | BUTTON_RELOAD) == 0,
609        "inputs.buttons",
610        Some(index),
611    )
612}
613fn validate_player(p: &PlayerSnapshot, index: usize) -> Result<(), EncodeError> {
614    valid_field((p.id as usize) < MAX_PLAYERS, "players.id", Some(index))?;
615    for (values, max, fields) in [
616        (
617            p.position,
618            4096.,
619            [
620                "players.position.x",
621                "players.position.y",
622                "players.position.z",
623            ],
624        ),
625        (
626            p.velocity,
627            256.,
628            [
629                "players.velocity.x",
630                "players.velocity.y",
631                "players.velocity.z",
632            ],
633        ),
634    ] {
635        for (value, field) in values.into_iter().zip(fields) {
636            valid_field(value.is_finite() && value.abs() <= max, field, Some(index))?;
637        }
638    }
639    for (value, max, field) in [
640        (p.yaw, std::f32::consts::PI, "players.yaw"),
641        (p.pitch, MAX_PITCH, "players.pitch"),
642    ] {
643        valid_field(value.is_finite() && value.abs() <= max, field, Some(index))?;
644    }
645    for (value, field) in [
646        (p.jump_coyote, "players.jump_coyote"),
647        (p.jump_buffer, "players.jump_buffer"),
648    ] {
649        valid_field(
650            value.is_finite() && (0. ..=0.5).contains(&value),
651            field,
652            Some(index),
653        )?;
654    }
655    for (value, max, field) in [
656        (u16::from(p.health), 100, "players.health"),
657        (u16::from(p.ammo), 30, "players.ammo"),
658        (p.fire_cooldown, 4096, "players.fire_cooldown"),
659        (p.reload_ticks, 4096, "players.reload_ticks"),
660        (p.respawn_ticks, 4096, "players.respawn_ticks"),
661    ] {
662        valid_field(value <= max, field, Some(index))?;
663    }
664    Ok(())
665}
666fn planned_len(
667    write: impl FnOnce(&mut Encoder<'_>) -> Result<(), EncodeError>,
668) -> Result<usize, EncodeError> {
669    let mut out = Encoder {
670        destination: None,
671        len: 0,
672    };
673    write(&mut out)?;
674    if out.len > MAX_PACKET_BYTES {
675        return Err(EncodeError::TooLarge {
676            required: out.len,
677            max: MAX_PACKET_BYTES,
678        });
679    }
680    Ok(out.len)
681}
682fn encode_into(
683    destination: &mut [u8],
684    write: impl Fn(&mut Encoder<'_>) -> Result<(), EncodeError>,
685) -> Result<usize, EncodeError> {
686    let required = planned_len(&write)?;
687    if required > destination.len() {
688        return Err(EncodeError::Capacity {
689            required,
690            available: destination.len(),
691        });
692    }
693    let mut out = Encoder {
694        destination: Some(&mut destination[..required]),
695        len: 0,
696    };
697    // All validation already succeeded on these same immutable fields. Keep the
698    // second pass checked too; it cannot fail for a preflighted packet.
699    write(&mut out)?;
700    debug_assert_eq!(out.len, required);
701    Ok(required)
702}
703fn encode_allocated(
704    write: impl Fn(&mut Encoder<'_>) -> Result<(), EncodeError>,
705) -> Result<Vec<u8>, ProtocolError> {
706    let required = planned_len(&write).map_err(EncodeError::protocol)?;
707    let mut bytes = vec![0; required];
708    let mut out = Encoder {
709        destination: Some(&mut bytes),
710        len: 0,
711    };
712    write(&mut out).map_err(EncodeError::protocol)?;
713    debug_assert_eq!(out.len, required);
714    Ok(bytes)
715}
716fn put_u32(out: &mut Encoder<'_>, n: u32) {
717    out.extend_from_slice(&n.to_le_bytes());
718}
719fn put_u64(out: &mut Encoder<'_>, n: u64) {
720    out.extend_from_slice(&n.to_le_bytes());
721}
722fn put_f32(out: &mut Encoder<'_>, n: f32) {
723    put_u32(out, n.to_bits());
724}
725fn put_u16(out: &mut Encoder<'_>, n: u16) {
726    out.extend_from_slice(&n.to_le_bytes());
727}
728fn put_input(out: &mut Encoder<'_>, input: &InputFrame) {
729    put_u32(out, input.sequence);
730    for n in [input.move_x, input.move_z, input.yaw, input.pitch] {
731        put_f32(out, n);
732    }
733    out.push(input.buttons);
734}
735
736/// Exact v5 wire length after validating every client field; allocates nothing.
737/// Includes the six-byte header and session/envelope overhead. See
738/// [`encode_client_into`] for the shared validation/precedence contract.
739///
740/// ```
741/// use ferravex_net::{ClientPacket, encoded_client_len};
742/// assert_eq!(encoded_client_len(&ClientPacket::Hello { nonce: 7 }), Ok(14));
743/// ```
744pub fn encoded_client_len(packet: &ClientPacket) -> Result<usize, EncodeError> {
745    planned_len(|out| write_client(packet, out))
746}
747/// Exact validated v5 server wire length, without allocation. Inner delta bytes
748/// remain opaque: only outer tick ordering and byte length are checked, matching
749/// the legacy encoder/decoder. Does not authenticate/install/ACK a snapshot.
750///
751/// ```
752/// use ferravex_net::{ServerPacket, Snapshot, encoded_server_len};
753/// let packet = ServerPacket::Snapshot(Snapshot { session: 1, ..Snapshot::default() });
754/// assert_eq!(encoded_server_len(&packet), Ok(88));
755/// ```
756pub fn encoded_server_len(packet: &ServerPacket) -> Result<usize, EncodeError> {
757    planned_len(|out| write_server(packet, out))
758}
759/// Encode v5 into a disjoint caller slice without allocating. Success initializes
760/// exactly the returned prefix and leaves the tail untouched. Every error leaves
761/// the **entire** destination unchanged. Capacity means slice length, not any
762/// underlying Vec capacity; there is no internal scratch packet or retained state.
763///
764/// Error precedence: session first (Hello has none); collection length before
765/// its elements; elements in slice order, fields in InputFrame::is_valid /
766/// PlayerSnapshot::is_valid order; each player validity before duplicate ID;
767/// snapshot orphan epochs in slot order after all players. Extension fields are
768/// checked in wire order (delta tick order before byte length; pong client,
769/// receive, send bounds before send ordering then five-second span). Whole packet
770/// bound follows field validation; destination capacity is always last.
771/// Unrestricted sequence/nonce/tick/shot_tick values remain unrestricted.
772///
773/// ```
774/// use ferravex_net::{ClientPacket, EncodeError, encode_client_into};
775/// let packet = ClientPacket::Hello { nonce: 7 };
776/// let mut bytes = [99; 16];
777/// assert_eq!(encode_client_into(&packet, &mut bytes[..13]),
778///     Err(EncodeError::Capacity { required: 14, available: 13 }));
779/// assert_eq!(bytes, [99; 16]);
780/// let n = encode_client_into(&packet, &mut bytes).unwrap();
781/// assert_eq!(n, 14);
782/// assert_eq!(&bytes[n..], &[99; 2]);
783/// ```
784pub fn encode_client_into(
785    packet: &ClientPacket,
786    destination: &mut [u8],
787) -> Result<usize, EncodeError> {
788    encode_into(destination, |out| write_client(packet, out))
789}
790/// Server counterpart of [`encode_client_into`], with identical atomicity,
791/// tail, allocation and capacity guarantees. Preserves exact v5 float bits.
792///
793/// ```
794/// use ferravex_net::{ServerPacket, encode_server_into, decode_server, MAX_PACKET_BYTES};
795/// let packet = ServerPacket::Welcome { nonce: 0, session: 1, player_id: 0, tick: 4 };
796/// let mut bytes = [0; MAX_PACKET_BYTES];
797/// let n = encode_server_into(&packet, &mut bytes).unwrap();
798/// assert_eq!(decode_server(&bytes[..n]).unwrap(), packet);
799/// ```
800pub fn encode_server_into(
801    packet: &ServerPacket,
802    destination: &mut [u8],
803) -> Result<usize, EncodeError> {
804    encode_into(destination, |out| write_server(packet, out))
805}
806/// Allocating compatibility wrapper using the same validated v5 writer as
807/// [`encode_client_into`]. Accepted inputs, bytes and ProtocolError mapping are
808/// unchanged; returned Vec capacity is unspecified.
809pub fn encode_client(packet: &ClientPacket) -> Result<Vec<u8>, ProtocolError> {
810    encode_allocated(|out| write_client(packet, out))
811}
812/// Allocating compatibility wrapper for [`encode_server_into`].
813pub fn encode_server(packet: &ServerPacket) -> Result<Vec<u8>, ProtocolError> {
814    encode_allocated(|out| write_server(packet, out))
815}
816
817/// Borrowed v5 reliable/tactical envelope for an [`reliable::EventSender::send_due`]
818/// callback. Uses the owned packet codec, without cloning an EventPacket or its
819/// payload. Both wire families add **24 bytes** to the payload; reliable events
820/// accept empty payloads, commands require 1..=900 bytes. No sequence policy or
821/// application payload validation is added; validate the outer session and game
822/// payload before receiver admission. Safe Rust requires disjoint output/input.
823///
824/// Supplied-time recipe: local refusal, accepted loss, out-of-order receipt,
825/// individual wire ACKs, retry, and draining after downstream capacity reopens.
826/// Decode/admission and initial sender queueing may allocate; encoding does not.
827/// A real transport callback must return true only for a complete datagram or
828/// durable outbound queue acceptance. WouldBlock and short sends return false;
829/// retain fatal errors outside send_due and propagate them afterward. Local
830/// acceptance never manufactures a remote ACK.
831///
832/// ```
833/// use ferravex_net::{*, reliable::{EventSender, EventReceiver, EVENT_LIMIT}};
834/// let (mut sender, mut receiver) = (EventSender::default(), EventReceiver::default());
835/// sender.queue(b"first").unwrap();
836/// sender.queue(b"second").unwrap();
837/// let mut wire = [0; MAX_PACKET_BYTES];
838/// let refused = sender.send_due(1000, 2, 11, |event| {
839///     BorrowedEvent::ReliableEvent { session: 7, event }.encode_into(&mut wire).unwrap();
840///     false // e.g. WouldBlock; no retry timestamp is committed.
841/// });
842/// assert_eq!(refused.sent, 0);
843/// let mut ack_wire = [0; 22];
844/// let mut ack_len = 0;
845/// let report = sender.send_due(1001, 2, 11, |event| {
846///     let envelope = BorrowedEvent::ReliableEvent { session: 7, event };
847///     let n = envelope.encode_into(&mut wire).unwrap();
848///     assert_eq!(n, envelope.encoded_len().unwrap());
849///     if event.sequence == 0 { return true; } // Locally accepted, lost in transit.
850///     let ServerPacket::ReliableEvent { session: 7, event } = decode_server(&wire[..n]).unwrap()
851///         else { panic!("wrong session/family") };
852///     receiver.admit(&event, EVENT_LIMIT).unwrap(); // Application validation first in FPS.
853///     ack_len = encode_client_into(&ClientPacket::EventAck {
854///         session: 7, sequence: event.sequence,
855///     }, &mut ack_wire).unwrap();
856///     true
857/// });
858/// assert_eq!(report.sent, 2);
859/// let ClientPacket::EventAck { session: 7, sequence } = decode_client(&ack_wire[..ack_len]).unwrap()
860///     else { panic!("wrong session/family") };
861/// assert!(sender.acknowledge(sequence)); // Only the retained successor is ACKed.
862/// assert_eq!(receiver.drain_ready(2, 11, |_, _| true).delivered, 0);
863/// assert_eq!(sender.send_due(1100, 2, 11, |_| panic!("too early")).sent, 0);
864/// sender.send_due(1101, 1, 5, |event| {
865///     let n = BorrowedEvent::ReliableEvent { session: 7, event }.encode_into(&mut wire).unwrap();
866///     let ServerPacket::ReliableEvent { session: 7, event } = decode_server(&wire[..n]).unwrap()
867///         else { panic!("wrong session/family") };
868///     receiver.admit(&event, EVENT_LIMIT).unwrap();
869///     ack_len = encode_client_into(&ClientPacket::EventAck {
870///         session: 7, sequence: event.sequence,
871///     }, &mut ack_wire).unwrap();
872///     true
873/// });
874/// let ClientPacket::EventAck { session: 7, sequence } = decode_client(&ack_wire[..ack_len]).unwrap()
875///     else { panic!("wrong session/family") };
876/// assert!(sender.acknowledge(sequence));
877/// assert_eq!(sender.pending(), 0);
878/// assert_eq!(receiver.drain_ready(2, 11, |_, _| false).delivered, 0);
879/// // Later downstream capacity opens, without a new incoming packet.
880/// assert_eq!(receiver.drain_ready(1, 5, |seq, bytes| { assert_eq!((seq, bytes), (0, b"first".as_slice())); true }).delivered, 1);
881/// assert_eq!(receiver.drain_ready(1, 6, |seq, bytes| { assert_eq!((seq, bytes), (1, b"second".as_slice())); true }).delivered, 1);
882/// ```
883#[derive(Clone, Copy, Debug)]
884pub enum BorrowedEvent<'a> {
885    ReliableEvent {
886        session: u64,
887        event: &'a reliable::EventPacket,
888    },
889    Command {
890        session: u64,
891        event: &'a reliable::EventPacket,
892    },
893}
894impl BorrowedEvent<'_> {
895    /// Validated wire length, with the same precedence as [`encoded_client_len`].
896    /// See the complete supplied-time example on [`BorrowedEvent`].
897    pub fn encoded_len(self) -> Result<usize, EncodeError> {
898        planned_len(|out| self.write(out))
899    }
900    /// Checked caller-buffer encoding; shares [`encode_client_into`]'s full
901    /// failure atomicity and untouched-tail guarantees. No clone/allocation.
902    ///
903    /// ```
904    /// use ferravex_net::{BorrowedEvent, ClientExtension, ClientPacket, decode_client};
905    /// use ferravex_net::reliable::EventPacket;
906    /// let event = EventPacket { sequence: 3, payload: vec![1, 2] };
907    /// let envelope = BorrowedEvent::Command { session: 7, event: &event };
908    /// let mut wire = [99; 28];
909    /// let n = envelope.encode_into(&mut wire).unwrap();
910    /// assert_eq!(n, envelope.encoded_len().unwrap());
911    /// assert_eq!(&wire[n..], &[99; 2]);
912    /// assert_eq!(decode_client(&wire[..n]).unwrap(),
913    ///     ClientPacket::Extension(ClientExtension::Command { session: 7, event }));
914    /// ```
915    pub fn encode_into(self, destination: &mut [u8]) -> Result<usize, EncodeError> {
916        encode_into(destination, |out| self.write(out))
917    }
918    fn write(self, out: &mut Encoder<'_>) -> Result<(), EncodeError> {
919        let (kind, session, event, min) = match self {
920            Self::ReliableEvent { session, event } => (5, session, event, 0),
921            Self::Command { session, event } => (10, session, event, 1),
922        };
923        valid_session(session)?;
924        valid_len(
925            "event.payload",
926            event.payload.len(),
927            min,
928            reliable::EVENT_BYTES,
929        )?;
930        out.header(kind);
931        put_u64(out, session);
932        put_u64(out, event.sequence);
933        put_u16(out, event.payload.len() as u16);
934        out.extend_from_slice(&event.payload);
935        Ok(())
936    }
937}
938
939fn write_client(packet: &ClientPacket, out: &mut Encoder<'_>) -> Result<(), EncodeError> {
940    match packet {
941        ClientPacket::Extension(p) => return wire_v4::write_client(p, out),
942        ClientPacket::EventAck { session, sequence } => {
943            valid_session(*session)?;
944            out.header(6);
945            put_u64(out, *session);
946            put_u64(out, *sequence);
947        }
948        ClientPacket::Hello { nonce } => {
949            out.header(1);
950            put_u64(out, *nonce);
951        }
952        ClientPacket::Input { session, inputs } => {
953            valid_session(*session)?;
954            valid_len("inputs", inputs.len(), 1, MAX_INPUTS_PER_PACKET)?;
955            out.header(2);
956            put_u64(out, *session);
957            out.push(inputs.len() as u8);
958            for (index, input) in inputs.iter().enumerate() {
959                validate_input(input, index)?;
960                put_input(out, input);
961            }
962        }
963    }
964    Ok(())
965}
966fn write_server(packet: &ServerPacket, out: &mut Encoder<'_>) -> Result<(), EncodeError> {
967    match packet {
968        ServerPacket::Extension(p) => return wire_v4::write_server(p, out),
969        ServerPacket::ReliableEvent { session, event } => {
970            return BorrowedEvent::ReliableEvent {
971                session: *session,
972                event,
973            }
974            .write(out);
975        }
976        ServerPacket::Welcome {
977            nonce,
978            session,
979            player_id,
980            tick,
981        } => {
982            valid_session(*session)?;
983            valid_field((*player_id as usize) < MAX_PLAYERS, "player_id", None)?;
984            out.header(3);
985            put_u64(out, *nonce);
986            put_u64(out, *session);
987            out.push(*player_id);
988            put_u32(out, *tick);
989        }
990        ServerPacket::Snapshot(snapshot) => {
991            valid_session(snapshot.session)?;
992            valid_len("players", snapshot.players.len(), 0, MAX_PLAYERS)?;
993            let mut ids = 0u16;
994            for (index, p) in snapshot.players.iter().enumerate() {
995                validate_player(p, index)?;
996                valid_field(
997                    ids & (1u16 << p.id) == 0,
998                    "players.duplicate_id",
999                    Some(index),
1000                )?;
1001                ids |= 1u16 << p.id;
1002            }
1003            for (i, epoch) in snapshot.epochs.iter().enumerate() {
1004                valid_field(*epoch == 0 || ids & (1 << i) != 0, "epochs.orphan", Some(i))?;
1005            }
1006            out.header(4);
1007            put_u64(out, snapshot.session);
1008            put_u32(out, snapshot.tick);
1009            put_u32(out, snapshot.ack_sequence);
1010            out.push(snapshot.ack_valid as u8);
1011            for epoch in snapshot.epochs {
1012                put_u32(out, epoch);
1013            }
1014            out.push(snapshot.players.len() as u8);
1015            for p in &snapshot.players {
1016                out.push(p.id);
1017                for n in p
1018                    .position
1019                    .into_iter()
1020                    .chain(p.velocity)
1021                    .chain([p.yaw, p.pitch])
1022                {
1023                    put_f32(out, n);
1024                }
1025                out.extend_from_slice(&[p.health, p.ammo, p.grounded as u8]);
1026                put_f32(out, p.jump_coyote);
1027                put_f32(out, p.jump_buffer);
1028                out.push(p.jump_held as u8);
1029                put_u16(out, p.fire_cooldown);
1030                put_u16(out, p.reload_ticks);
1031                put_u16(out, p.respawn_ticks);
1032            }
1033        }
1034    }
1035    Ok(())
1036}
1037
1038struct Reader<'a> {
1039    data: &'a [u8],
1040    pos: usize,
1041}
1042impl<'a> Reader<'a> {
1043    fn new(data: &'a [u8]) -> Result<(Self, u8), ProtocolError> {
1044        if data.len() > MAX_PACKET_BYTES {
1045            return Err(ProtocolError::TooLarge);
1046        }
1047        if data.len() < 6 {
1048            return Err(ProtocolError::Truncated);
1049        }
1050        if &data[..4] != MAGIC {
1051            return Err(ProtocolError::Header);
1052        }
1053        if data[4] != PROTOCOL_VERSION {
1054            return Err(ProtocolError::Version);
1055        }
1056        Ok((Self { data, pos: 6 }, data[5]))
1057    }
1058    fn bytes<const N: usize>(&mut self) -> Result<[u8; N], ProtocolError> {
1059        let bytes = self
1060            .data
1061            .get(self.pos..self.pos + N)
1062            .ok_or(ProtocolError::Truncated)?;
1063        self.pos += N;
1064        Ok(bytes.try_into().expect("slice length checked"))
1065    }
1066    fn u8(&mut self) -> Result<u8, ProtocolError> {
1067        Ok(self.bytes::<1>()?[0])
1068    }
1069    fn u16(&mut self) -> Result<u16, ProtocolError> {
1070        Ok(u16::from_le_bytes(self.bytes()?))
1071    }
1072    fn u32(&mut self) -> Result<u32, ProtocolError> {
1073        Ok(u32::from_le_bytes(self.bytes()?))
1074    }
1075    fn u64(&mut self) -> Result<u64, ProtocolError> {
1076        Ok(u64::from_le_bytes(self.bytes()?))
1077    }
1078    fn f32(&mut self) -> Result<f32, ProtocolError> {
1079        Ok(f32::from_bits(self.u32()?))
1080    }
1081    fn boolean(&mut self) -> Result<bool, ProtocolError> {
1082        match self.u8()? {
1083            0 => Ok(false),
1084            1 => Ok(true),
1085            _ => Err(ProtocolError::Invalid),
1086        }
1087    }
1088    fn end(self) -> Result<(), ProtocolError> {
1089        if self.pos == self.data.len() {
1090            Ok(())
1091        } else {
1092            Err(ProtocolError::Trailing)
1093        }
1094    }
1095    fn input(&mut self) -> Result<InputFrame, ProtocolError> {
1096        let frame = InputFrame {
1097            sequence: self.u32()?,
1098            move_x: self.f32()?,
1099            move_z: self.f32()?,
1100            yaw: self.f32()?,
1101            pitch: self.f32()?,
1102            buttons: self.u8()?,
1103        };
1104        if !frame.is_valid() {
1105            return Err(ProtocolError::Invalid);
1106        }
1107        Ok(frame)
1108    }
1109}
1110pub fn decode_client(data: &[u8]) -> Result<ClientPacket, ProtocolError> {
1111    let (mut reader, kind) = Reader::new(data)?;
1112    let packet = match kind {
1113        7..=10 => ClientPacket::Extension(wire_v4::decode_client(&mut reader, kind)?),
1114        6 => {
1115            let session = reader.u64()?;
1116            let sequence = reader.u64()?;
1117            if session == 0 {
1118                return Err(ProtocolError::Invalid);
1119            }
1120            ClientPacket::EventAck { session, sequence }
1121        }
1122        1 => ClientPacket::Hello {
1123            nonce: reader.u64()?,
1124        },
1125        2 => {
1126            let session = reader.u64()?;
1127            let count = reader.u8()? as usize;
1128            if session == 0 || count == 0 || count > MAX_INPUTS_PER_PACKET {
1129                return Err(ProtocolError::Invalid);
1130            }
1131            let mut inputs = Vec::with_capacity(count);
1132            for _ in 0..count {
1133                inputs.push(reader.input()?);
1134            }
1135            ClientPacket::Input { session, inputs }
1136        }
1137        _ => return Err(ProtocolError::Kind),
1138    };
1139    reader.end()?;
1140    Ok(packet)
1141}
1142pub fn decode_server(data: &[u8]) -> Result<ServerPacket, ProtocolError> {
1143    let (mut r, kind) = Reader::new(data)?;
1144    let packet = match kind {
1145        11..=13 => ServerPacket::Extension(wire_v4::decode_server(&mut r, kind)?),
1146        5 => {
1147            let session = r.u64()?;
1148            let sequence = r.u64()?;
1149            let len = r.u16()? as usize;
1150            if session == 0 || len > reliable::EVENT_BYTES {
1151                return Err(ProtocolError::Invalid);
1152            }
1153            let payload = r
1154                .data
1155                .get(r.pos..r.pos + len)
1156                .ok_or(ProtocolError::Truncated)?
1157                .to_vec();
1158            r.pos += len;
1159            ServerPacket::ReliableEvent {
1160                session,
1161                event: reliable::EventPacket { sequence, payload },
1162            }
1163        }
1164        3 => {
1165            let nonce = r.u64()?;
1166            let session = r.u64()?;
1167            let player_id = r.u8()?;
1168            let tick = r.u32()?;
1169            if session == 0 || player_id as usize >= MAX_PLAYERS {
1170                return Err(ProtocolError::Invalid);
1171            }
1172            ServerPacket::Welcome {
1173                nonce,
1174                session,
1175                player_id,
1176                tick,
1177            }
1178        }
1179        4 => {
1180            let session = r.u64()?;
1181            if session == 0 {
1182                return Err(ProtocolError::Invalid);
1183            }
1184            let tick = r.u32()?;
1185            let ack_sequence = r.u32()?;
1186            let ack_valid = r.boolean()?;
1187            let mut epochs = [0; MAX_PLAYERS];
1188            for epoch in &mut epochs {
1189                *epoch = r.u32()?;
1190            }
1191            let count = r.u8()? as usize;
1192            if count > MAX_PLAYERS {
1193                return Err(ProtocolError::Invalid);
1194            }
1195            let mut players = Vec::with_capacity(count);
1196            let mut ids = 0u16;
1197            for _ in 0..count {
1198                let p = PlayerSnapshot {
1199                    id: r.u8()?,
1200                    position: [r.f32()?, r.f32()?, r.f32()?],
1201                    velocity: [r.f32()?, r.f32()?, r.f32()?],
1202                    yaw: r.f32()?,
1203                    pitch: r.f32()?,
1204                    health: r.u8()?,
1205                    ammo: r.u8()?,
1206                    grounded: r.boolean()?,
1207                    jump_coyote: r.f32()?,
1208                    jump_buffer: r.f32()?,
1209                    jump_held: r.boolean()?,
1210                    fire_cooldown: r.u16()?,
1211                    reload_ticks: r.u16()?,
1212                    respawn_ticks: r.u16()?,
1213                };
1214                if !p.is_valid() || ids & (1u16 << p.id) != 0 {
1215                    return Err(ProtocolError::Invalid);
1216                }
1217                ids |= 1u16 << p.id;
1218                players.push(p);
1219            }
1220            if epochs
1221                .iter()
1222                .enumerate()
1223                .any(|(i, e)| *e != 0 && ids & (1 << i) == 0)
1224            {
1225                return Err(ProtocolError::Invalid);
1226            }
1227            ServerPacket::Snapshot(Snapshot {
1228                session,
1229                tick,
1230                ack_sequence,
1231                ack_valid,
1232                epochs,
1233                players,
1234            })
1235        }
1236        _ => return Err(ProtocolError::Kind),
1237    };
1238    r.end()?;
1239    Ok(packet)
1240}
1241
1242/// Native sockets are optional by target; packet codecs remain available on wasm.
1243#[cfg(not(target_arch = "wasm32"))]
1244pub mod udp {
1245    use super::MAX_PACKET_BYTES;
1246    use std::{
1247        io,
1248        net::{SocketAddr, ToSocketAddrs, UdpSocket},
1249    };
1250    pub struct Socket {
1251        inner: UdpSocket,
1252    }
1253    impl Socket {
1254        pub fn bind(addr: impl ToSocketAddrs) -> io::Result<Self> {
1255            let inner = UdpSocket::bind(addr)?;
1256            inner.set_nonblocking(true)?;
1257            Ok(Self { inner })
1258        }
1259        pub fn connect(addr: impl ToSocketAddrs) -> io::Result<Self> {
1260            let remote = addr.to_socket_addrs()?.next().ok_or_else(|| {
1261                io::Error::new(io::ErrorKind::InvalidInput, "empty remote address")
1262            })?;
1263            let this = Self::bind(if remote.is_ipv4() {
1264                "0.0.0.0:0"
1265            } else {
1266                "[::]:0"
1267            })?;
1268            this.inner.connect(remote)?;
1269            Ok(this)
1270        }
1271        pub fn local_addr(&self) -> io::Result<SocketAddr> {
1272            self.inner.local_addr()
1273        }
1274        pub fn send(&self, bytes: &[u8]) -> io::Result<usize> {
1275            check_size(bytes)?;
1276            self.inner.send(bytes)
1277        }
1278        pub fn send_to(&self, bytes: &[u8], addr: SocketAddr) -> io::Result<usize> {
1279            check_size(bytes)?;
1280            self.inner.send_to(bytes, addr)
1281        }
1282        /// The extra byte detects oversized/truncated UDP datagrams. Pass the
1283        /// result to the codec, which rejects lengths above MAX_PACKET_BYTES.
1284        /// Windows discards oversized datagrams and returns InvalidData; callers
1285        /// should count those as rejected packets and continue their poll budget.
1286        /// Only an empty socket returns None.
1287        pub fn recv_from(
1288            &self,
1289            buffer: &mut [u8; MAX_PACKET_BYTES + 1],
1290        ) -> io::Result<Option<(usize, SocketAddr)>> {
1291            match self.inner.recv_from(buffer) {
1292                Ok(pair) => Ok(Some(pair)),
1293                Err(e) if e.kind() == io::ErrorKind::WouldBlock => Ok(None),
1294                #[cfg(windows)]
1295                Err(e) if e.raw_os_error() == Some(10040) => Err(io::Error::new(
1296                    io::ErrorKind::InvalidData,
1297                    "oversized UDP datagram discarded by Winsock",
1298                )),
1299                Err(e) => Err(e),
1300            }
1301        }
1302    }
1303    fn check_size(bytes: &[u8]) -> io::Result<()> {
1304        if bytes.len() > MAX_PACKET_BYTES {
1305            Err(io::Error::new(
1306                io::ErrorKind::InvalidInput,
1307                "packet exceeds MTU budget",
1308            ))
1309        } else {
1310            Ok(())
1311        }
1312    }
1313}
1314
1315#[cfg(test)]
1316mod tests {
1317    use super::*;
1318    #[test]
1319    fn codec_round_trip_and_budget() {
1320        let frame = InputFrame {
1321            sequence: u32::MAX,
1322            move_x: 0.5,
1323            move_z: -1.0,
1324            yaw: 2.0,
1325            pitch: 0.1,
1326            buttons: 7,
1327        };
1328        for packet in [
1329            ClientPacket::Hello { nonce: 123 },
1330            ClientPacket::Input {
1331                session: 99,
1332                inputs: vec![frame; MAX_INPUTS_PER_PACKET],
1333            },
1334        ] {
1335            assert_eq!(
1336                decode_client(&encode_client(&packet).unwrap()).unwrap(),
1337                packet
1338            );
1339        }
1340        let players = (0..MAX_PLAYERS)
1341            .map(|id| PlayerSnapshot {
1342                id: id as u8,
1343                health: 100,
1344                ammo: 30,
1345                jump_coyote: 0.1,
1346                jump_buffer: 0.12,
1347                jump_held: true,
1348                ..Default::default()
1349            })
1350            .collect();
1351        let packet = ServerPacket::Snapshot(Snapshot {
1352            epochs: [0; MAX_PLAYERS],
1353            session: 99,
1354            tick: 44,
1355            ack_valid: true,
1356            ack_sequence: 3,
1357            players,
1358        });
1359        let bytes = encode_server(&packet).unwrap();
1360        assert_eq!(bytes.len(), 904);
1361        assert!(bytes.len() < MAX_PACKET_BYTES);
1362        assert_eq!(decode_server(&bytes).unwrap(), packet);
1363        for length in 0..bytes.len() {
1364            assert!(decode_server(&bytes[..length]).is_err());
1365        }
1366    }
1367    #[test]
1368    fn jump_state_numeric_and_version_limits_fail_closed() {
1369        let player = PlayerSnapshot {
1370            health: 100,
1371            ammo: 30,
1372            ..Default::default()
1373        };
1374        let make = |p| {
1375            ServerPacket::Snapshot(Snapshot {
1376                epochs: [0; MAX_PLAYERS],
1377                session: 1,
1378                players: vec![p],
1379                ..Default::default()
1380            })
1381        };
1382        for bad in [f32::NAN, f32::INFINITY, -0.01, 0.51] {
1383            assert!(
1384                encode_server(&make(PlayerSnapshot {
1385                    jump_coyote: bad,
1386                    ..player
1387                }))
1388                .is_err()
1389            );
1390            assert!(
1391                encode_server(&make(PlayerSnapshot {
1392                    jump_buffer: bad,
1393                    ..player
1394                }))
1395                .is_err()
1396            );
1397        }
1398        let mut bytes = encode_server(&make(player)).unwrap();
1399        bytes[4] = 2;
1400        assert_eq!(decode_server(&bytes), Err(ProtocolError::Version));
1401    }
1402    #[test]
1403    fn reliable_event_wire_is_bounded_session_bound_and_versioned() {
1404        let ack = ClientPacket::EventAck {
1405            session: 77,
1406            sequence: 123,
1407        };
1408        assert_eq!(decode_client(&encode_client(&ack).unwrap()).unwrap(), ack);
1409        let packet = ServerPacket::ReliableEvent {
1410            session: 77,
1411            event: reliable::EventPacket {
1412                sequence: 123,
1413                payload: vec![4; reliable::EVENT_BYTES],
1414            },
1415        };
1416        let bytes = encode_server(&packet).unwrap();
1417        assert!(bytes.len() <= MAX_PACKET_BYTES);
1418        assert_eq!(decode_server(&bytes).unwrap(), packet);
1419        for n in 0..bytes.len() {
1420            assert!(decode_server(&bytes[..n]).is_err());
1421        }
1422        let mut old = bytes.clone();
1423        old[4] = 1;
1424        assert_eq!(decode_server(&old), Err(ProtocolError::Version));
1425        assert!(
1426            encode_client(&ClientPacket::EventAck {
1427                session: 0,
1428                sequence: 1
1429            })
1430            .is_err()
1431        );
1432        assert!(
1433            encode_server(&ServerPacket::ReliableEvent {
1434                session: 77,
1435                event: reliable::EventPacket {
1436                    sequence: 0,
1437                    payload: vec![0; reliable::EVENT_BYTES + 1]
1438                }
1439            })
1440            .is_err()
1441        );
1442    }
1443    #[test]
1444    fn reject_bad_numeric_and_trailing_data() {
1445        let p = ClientPacket::Input {
1446            session: 3,
1447            inputs: vec![InputFrame {
1448                move_x: f32::NAN,
1449                ..Default::default()
1450            }],
1451        };
1452        assert!(encode_client(&p).is_err());
1453        let mut bytes = encode_client(&ClientPacket::Hello { nonce: 5 }).unwrap();
1454        bytes.push(0);
1455        assert_eq!(decode_client(&bytes), Err(ProtocolError::Trailing));
1456        let frame = InputFrame {
1457            pitch: f32::INFINITY,
1458            ..Default::default()
1459        };
1460        assert!(frame.sanitized().is_valid());
1461    }
1462    #[test]
1463    fn queue_is_bounded_deduplicated_and_wrap_safe() {
1464        assert!(sequence_newer(0, u32::MAX));
1465        assert!(!sequence_newer(u32::MAX, 0));
1466        assert!(!sequence_newer(1 << 31, 0));
1467        let mut q = InputQueue::default();
1468        assert!(q.push(InputFrame {
1469            sequence: u32::MAX,
1470            ..Default::default()
1471        }));
1472        assert!(q.push(InputFrame::default()));
1473        assert!(!q.push(InputFrame::default()));
1474        for seq in 1..MAX_QUEUED_INPUTS as u32 {
1475            q.push(InputFrame {
1476                sequence: seq,
1477                ..Default::default()
1478            });
1479        }
1480        assert_eq!(q.len(), MAX_QUEUED_INPUTS);
1481        assert!(!q.push(InputFrame {
1482            sequence: 200,
1483            ..Default::default()
1484        }));
1485    }
1486    #[test]
1487    fn coalescing_keeps_latest_movement_and_recovers_action_press() {
1488        let mut queue = InputQueue::default();
1489        queue.push(InputFrame {
1490            sequence: 1,
1491            move_z: 1.,
1492            buttons: BUTTON_FIRE,
1493            ..Default::default()
1494        });
1495        queue.push(InputFrame {
1496            sequence: 2,
1497            move_x: 1.,
1498            ..Default::default()
1499        });
1500        let input = queue.pop_latest().unwrap();
1501        assert_eq!(input.sequence, 2);
1502        assert_eq!(input.move_z, 0.);
1503        assert_eq!(input.move_x, 1.);
1504        assert_eq!(input.buttons, BUTTON_FIRE);
1505        assert!(queue.is_empty());
1506        assert!(!queue.push(InputFrame {
1507            sequence: 1,
1508            buttons: BUTTON_FIRE,
1509            ..Default::default()
1510        }));
1511    }
1512    #[test]
1513    fn arbitrary_bytes_never_panic() {
1514        let mut state = 0x12345678u32;
1515        for len in 0..=MAX_PACKET_BYTES + 5 {
1516            let bytes: Vec<_> = (0..len)
1517                .map(|_| {
1518                    state ^= state << 13;
1519                    state ^= state >> 17;
1520                    state ^= state << 5;
1521                    state as u8
1522                })
1523                .collect();
1524            let _ = decode_client(&bytes);
1525            let _ = decode_server(&bytes);
1526        }
1527    }
1528    #[cfg(not(target_arch = "wasm32"))]
1529    #[test]
1530    fn native_udp_actual_socket_round_trip() {
1531        use std::{thread, time::Duration};
1532        let server = udp::Socket::bind("127.0.0.1:0").unwrap();
1533        let client = udp::Socket::connect(server.local_addr().unwrap()).unwrap();
1534        let bytes = encode_client(&ClientPacket::Hello { nonce: 88 }).unwrap();
1535        client.send(&bytes).unwrap();
1536        let mut buffer = [0; MAX_PACKET_BYTES + 1];
1537        for _ in 0..100 {
1538            if let Some((n, peer)) = server.recv_from(&mut buffer).unwrap() {
1539                assert_eq!(
1540                    decode_client(&buffer[..n]).unwrap(),
1541                    ClientPacket::Hello { nonce: 88 }
1542                );
1543                server.send_to(&buffer[..n], peer).unwrap();
1544                for _ in 0..100 {
1545                    if let Some((n, _)) = client.recv_from(&mut buffer).unwrap() {
1546                        assert_eq!(
1547                            decode_client(&buffer[..n]).unwrap(),
1548                            ClientPacket::Hello { nonce: 88 }
1549                        );
1550                        return;
1551                    }
1552                    thread::sleep(Duration::from_millis(1));
1553                }
1554                panic!("loopback UDP response not received");
1555            }
1556            thread::sleep(Duration::from_millis(1));
1557        }
1558        panic!("loopback UDP packet not received");
1559    }
1560}
1561
1562#[cfg(test)]
1563mod timed_queue_tests {
1564    use super::*;
1565    #[test]
1566    fn round_reset_rejects_delayed_controls_from_previous_round() {
1567        let mut q = InputQueue::default();
1568        assert!(q.push(InputFrame {
1569            sequence: 42,
1570            buttons: BUTTON_FIRE,
1571            ..Default::default()
1572        }));
1573        q.clear_pending();
1574        assert!(q.pop().is_none());
1575        assert!(!q.push(InputFrame {
1576            sequence: 42,
1577            buttons: BUTTON_FIRE,
1578            ..Default::default()
1579        }));
1580        assert!(!q.push(InputFrame {
1581            sequence: 41,
1582            ..Default::default()
1583        }));
1584        assert!(q.push(InputFrame {
1585            sequence: 43,
1586            ..Default::default()
1587        }));
1588        assert_eq!(q.pop_latest().unwrap().buttons, 0);
1589    }
1590    #[test]
1591    fn recovered_fire_keeps_old_aim_and_time_but_latest_movement() {
1592        let mut q = InputQueue::default();
1593        q.push_timed(TimedInput {
1594            input: InputFrame {
1595                sequence: 1,
1596                yaw: 1.,
1597                buttons: BUTTON_FIRE,
1598                ..Default::default()
1599            },
1600            shot_tick: Some(20),
1601        });
1602        q.push_timed(TimedInput {
1603            input: InputFrame {
1604                sequence: 2,
1605                yaw: 2.,
1606                move_x: 1.,
1607                ..Default::default()
1608            },
1609            shot_tick: None,
1610        });
1611        let v = q.pop_latest_timed().unwrap();
1612        assert_eq!(v.input.move_x, 1.);
1613        assert_eq!(v.input.yaw, 1.);
1614        assert_eq!(v.shot_tick, Some(20));
1615        assert_eq!(v.input.sequence, 2);
1616        assert_eq!(v.input.buttons, BUTTON_FIRE);
1617        assert!(q.is_empty());
1618    }
1619}