Skip to main content

dayzmake_core/navmesh/
wire.rs

1//! The wire format of the navmesh data server (messages 3, 4 and 5).
2//!
3//! All integers and floats are little-endian. This module parses and encodes message *payloads*; the
4//! frame (`u32 length`, `u32 messageId`) belongs to the transport. [`WorldParams::parse_message`]
5//! takes a payload that starts with the protocol version, [`WorldParams::parse`] one without it.
6//!
7//! The readers check every count against the bytes left before they allocate, so a hostile payload
8//! cannot make them allocate more than a small multiple of its own size.
9
10use std::io;
11use std::ops::Range;
12
13use crate::navmesh::bytes::Reader;
14use crate::navmesh::num::i32_to_f32;
15
16/// The protocol version of the world params message.
17pub const PROTOCOL_VERSION: u32 = 10;
18/// The default TCP port of the data server.
19pub const DEFAULT_PORT: u16 = 36533;
20
21const WORLD_BLOCK_LEN: usize = 84;
22const CELL_CLASS_LEN: usize = 16;
23const LINK_CLASS_LEN: usize = 52;
24const PART_LEN: usize = 16;
25const VERTEX_LEN: usize = 12;
26/// Smallest group: area, partCount, vertexCount.
27const MIN_GROUP_LEN: usize = 12;
28const MAX_CELL_CLASSES: usize = 64;
29const MAX_LINK_CLASSES: usize = 256;
30const MAX_TILES: i64 = 1 << 28;
31const MAX_CELLS: i32 = 2048;
32const MAX_GROUPS: usize = 65536;
33const MAX_PARTS: usize = 1_048_576;
34const MAX_VERTICES: i32 = 1 << 26;
35
36/// The 84-byte world block of the world params message (spec 3.4).
37///
38/// `obstacles` and `filter_isolated_islands` are one byte plus three pad bytes on the wire. The raw
39/// four bytes are kept in `obstacles_raw` and `filter_raw` so that parsing and encoding round-trips.
40/// Parsing sets the `bool` to `raw[0] != 0`. Encoding writes the raw bytes, but when the `bool`
41/// disagrees with `raw[0]` (a value built from [`Default`] with only the `bool` set), byte 0 is
42/// replaced by `u8::from(bool)`.
43///
44/// Equality follows the wire: two blocks are equal when every other field is equal and their
45/// effective flag bytes (the raw bytes with byte 0 forced to agree with the `bool`) are equal. So a
46/// block built from [`Default`] with only `obstacles = true` set equals the block parsed from its own
47/// encoding.
48#[derive(Debug, Clone, Default)]
49#[non_exhaustive]
50pub struct WorldBlock {
51    /// World size in x, metres.
52    pub world_size_x: f32,
53    /// World size in z, metres.
54    pub world_size_z: f32,
55    /// Tile width, metres.
56    pub tile_width: f32,
57    /// Tile height (extent in z), metres.
58    pub tile_height: f32,
59    /// Number of tiles in x.
60    pub tiles_x: i32,
61    /// Number of tiles in z.
62    pub tiles_z: i32,
63    /// Top of the sea box (a live tide value), metres.
64    pub deep_sea_height: f32,
65    /// Water deeper than this becomes deep water, metres.
66    pub deep_water_depth: f32,
67    /// Contour simplification error, metres.
68    pub contour_max_error: f32,
69    /// Extract tree parts as cylinder obstacles.
70    pub obstacles: bool,
71    /// Scheduler block edge length in tiles.
72    pub block_size: i32,
73    /// Run the island filter.
74    pub filter_isolated_islands: bool,
75    /// Seed position of the island filter.
76    pub seed_position: [f32; 3],
77    /// Agent stand height, metres.
78    pub stand_height: f32,
79    /// Agent crouch height, metres.
80    pub crouch_height: f32,
81    /// Agent prone height, metres.
82    pub prone_height: f32,
83    /// Agent diameter, metres.
84    pub diameter: f32,
85    /// Agent maximum step height, metres.
86    pub max_step_height: f32,
87    /// Agent maximum slope, degrees.
88    pub max_slope: f32,
89    /// The four wire bytes of `obstacles` (flag plus pad), kept for round-tripping.
90    pub obstacles_raw: [u8; 4],
91    /// The four wire bytes of `filter_isolated_islands` (flag plus pad), kept for round-tripping.
92    pub filter_raw: [u8; 4],
93}
94
95impl PartialEq for WorldBlock {
96    fn eq(&self, other: &Self) -> bool {
97        self.world_size_x == other.world_size_x
98            && self.world_size_z == other.world_size_z
99            && self.tile_width == other.tile_width
100            && self.tile_height == other.tile_height
101            && self.tiles_x == other.tiles_x
102            && self.tiles_z == other.tiles_z
103            && self.deep_sea_height == other.deep_sea_height
104            && self.deep_water_depth == other.deep_water_depth
105            && self.contour_max_error == other.contour_max_error
106            && flag_bytes(self.obstacles, self.obstacles_raw)
107                == flag_bytes(other.obstacles, other.obstacles_raw)
108            && self.block_size == other.block_size
109            && flag_bytes(self.filter_isolated_islands, self.filter_raw)
110                == flag_bytes(other.filter_isolated_islands, other.filter_raw)
111            && self.seed_position == other.seed_position
112            && self.stand_height == other.stand_height
113            && self.crouch_height == other.crouch_height
114            && self.prone_height == other.prone_height
115            && self.diameter == other.diameter
116            && self.max_step_height == other.max_step_height
117            && self.max_slope == other.max_slope
118    }
119}
120
121impl WorldBlock {
122    fn read(r: &mut Reader<'_>) -> io::Result<Self> {
123        let world_size_x = r.f32()?;
124        let world_size_z = r.f32()?;
125        let tile_width = r.f32()?;
126        let tile_height = r.f32()?;
127        let tiles_x = r.i32()?;
128        let tiles_z = r.i32()?;
129        let deep_sea_height = r.f32()?;
130        let deep_water_depth = r.f32()?;
131        let contour_max_error = r.f32()?;
132        let obstacles_raw = r.array::<4>()?;
133        let block_size = r.i32()?;
134        let filter_raw = r.array::<4>()?;
135        Ok(Self {
136            world_size_x,
137            world_size_z,
138            tile_width,
139            tile_height,
140            tiles_x,
141            tiles_z,
142            deep_sea_height,
143            deep_water_depth,
144            contour_max_error,
145            obstacles: obstacles_raw[0] != 0,
146            block_size,
147            filter_isolated_islands: filter_raw[0] != 0,
148            seed_position: r.f32x3()?,
149            stand_height: r.f32()?,
150            crouch_height: r.f32()?,
151            prone_height: r.f32()?,
152            diameter: r.f32()?,
153            max_step_height: r.f32()?,
154            max_slope: r.f32()?,
155            obstacles_raw,
156            filter_raw,
157        })
158    }
159
160    fn write(&self, out: &mut Vec<u8>) {
161        for v in [
162            self.world_size_x,
163            self.world_size_z,
164            self.tile_width,
165            self.tile_height,
166        ] {
167            out.extend_from_slice(&v.to_le_bytes());
168        }
169        out.extend_from_slice(&self.tiles_x.to_le_bytes());
170        out.extend_from_slice(&self.tiles_z.to_le_bytes());
171        for v in [
172            self.deep_sea_height,
173            self.deep_water_depth,
174            self.contour_max_error,
175        ] {
176            out.extend_from_slice(&v.to_le_bytes());
177        }
178        out.extend_from_slice(&flag_bytes(self.obstacles, self.obstacles_raw));
179        out.extend_from_slice(&self.block_size.to_le_bytes());
180        out.extend_from_slice(&flag_bytes(self.filter_isolated_islands, self.filter_raw));
181        for v in self.seed_position {
182            out.extend_from_slice(&v.to_le_bytes());
183        }
184        for v in [
185            self.stand_height,
186            self.crouch_height,
187            self.prone_height,
188            self.diameter,
189            self.max_step_height,
190            self.max_slope,
191        ] {
192            out.extend_from_slice(&v.to_le_bytes());
193        }
194    }
195}
196
197/// The raw flag bytes, with byte 0 forced to agree with `flag`.
198fn flag_bytes(flag: bool, mut raw: [u8; 4]) -> [u8; 4] {
199    if (raw[0] != 0) != flag {
200        raw[0] = u8::from(flag);
201    }
202    raw
203}
204
205/// One cell class: the voxel grid resolution of a tile (spec 3.4).
206#[derive(Debug, Clone, PartialEq, Default)]
207#[non_exhaustive]
208pub struct CellClass {
209    /// Number of cells across the tile width.
210    pub cells: i32,
211    /// Second cell count (observed equal to `cells`; unused).
212    pub cells2: u32,
213    /// Width in metres covered by `cells`.
214    pub width: f32,
215    /// Unused field (0 in test fixtures).
216    pub unused: u32,
217}
218
219impl CellClass {
220    /// The cell size in metres: `width / float(cells)`.
221    #[must_use]
222    pub fn cell_size(&self) -> f32 {
223        self.width / i32_to_f32(self.cells)
224    }
225}
226
227/// One link class: an off-mesh jump or climb link type (spec 3.4).
228#[derive(Debug, Clone, PartialEq, Default)]
229#[non_exhaustive]
230pub struct LinkClass {
231    /// Becomes the off-mesh connection `userId`.
232    pub index: u32,
233    /// Name hash (unused).
234    pub name_hash: u32,
235    /// Type id, -1 if unset (unused).
236    pub type_id: i32,
237    /// Jump height, metres.
238    pub jump_height: f32,
239    /// Jump length, metres.
240    pub jump_length: f32,
241    /// Minimum jump drop, metres.
242    pub jump_dropdown_min: f32,
243    /// Maximum jump drop, metres.
244    pub jump_dropdown_max: f32,
245    /// Minimum centre height (its sign selects the obstacle-height test).
246    pub min_center_height: f32,
247    /// Agent height, metres.
248    pub agent_height: f32,
249    /// Maximum step height, metres.
250    pub max_step_height: f32,
251    /// Agent radius, metres.
252    pub agent_radius: f32,
253    /// Poly flags assigned to the generated off-mesh polygons.
254    pub flags: u16,
255    /// Area id assigned to them (must fit 6 bits).
256    pub area: u8,
257    /// Padding byte.
258    pub pad: u8,
259    /// Debug colour (unused).
260    pub color: i32,
261}
262
263/// The world params message (id 4): world block, cell classes and link classes.
264#[derive(Debug, Clone, PartialEq, Default)]
265#[non_exhaustive]
266pub struct WorldParams {
267    /// The world block.
268    pub world: WorldBlock,
269    /// The cell classes, at most 64.
270    pub cell_classes: Vec<CellClass>,
271    /// The link classes, at most 256.
272    pub link_classes: Vec<LinkClass>,
273}
274
275impl WorldParams {
276    /// Parses a world params payload that starts with the protocol version.
277    ///
278    /// # Errors
279    ///
280    /// Fails when the payload is shorter than 4 bytes ("world params truncated"), when the version is
281    /// not [`PROTOCOL_VERSION`] ("server protocol version V, expected 10"), and for every error of
282    /// [`WorldParams::parse`].
283    pub fn parse_message(payload: &[u8]) -> io::Result<Self> {
284        let mut r = Reader::new(payload);
285        let version = r.u32().map_err(|_| error!("world params truncated"))?;
286        if version != PROTOCOL_VERSION {
287            return Err(error!(
288                "server protocol version {version}, expected {PROTOCOL_VERSION}"
289            ));
290        }
291        Self::parse(r.rest())
292    }
293
294    /// Parses a world params payload without the protocol version.
295    ///
296    /// # Errors
297    ///
298    /// Fails with the texts of spec 12.1: "message truncated", "unexpected bytes after world params",
299    /// "implausible cell class count N", "implausible link count N", "invalid tile grid", "invalid
300    /// tile size", "invalid cell class" and "implausible cell count" (more than 2048 cells).
301    pub fn parse(payload: &[u8]) -> io::Result<Self> {
302        let mut r = Reader::new(payload);
303        let world = WorldBlock::read(&mut r)?;
304        let n = r.count("cell class count", MAX_CELL_CLASSES, CELL_CLASS_LEN)?;
305        let mut cell_classes = Vec::with_capacity(n);
306        for _ in 0..n {
307            cell_classes.push(CellClass {
308                cells: r.i32()?,
309                cells2: r.u32()?,
310                width: r.f32()?,
311                unused: r.u32()?,
312            });
313        }
314        let m = r.count("link count", MAX_LINK_CLASSES, LINK_CLASS_LEN)?;
315        let mut link_classes = Vec::with_capacity(m);
316        for _ in 0..m {
317            link_classes.push(LinkClass {
318                index: r.u32()?,
319                name_hash: r.u32()?,
320                type_id: r.i32()?,
321                jump_height: r.f32()?,
322                jump_length: r.f32()?,
323                jump_dropdown_min: r.f32()?,
324                jump_dropdown_max: r.f32()?,
325                min_center_height: r.f32()?,
326                agent_height: r.f32()?,
327                max_step_height: r.f32()?,
328                agent_radius: r.f32()?,
329                flags: r.u16()?,
330                area: r.u8()?,
331                pad: r.u8()?,
332                color: r.i32()?,
333            });
334        }
335        if r.remaining() != 0 {
336            return Err(error!("unexpected bytes after world params"));
337        }
338        let tiles = i64::from(world.tiles_x) * i64::from(world.tiles_z);
339        if world.tiles_x <= 0 || world.tiles_z <= 0 || tiles > MAX_TILES {
340            return Err(error!(
341                "invalid tile grid {} x {}",
342                world.tiles_x, world.tiles_z
343            ));
344        }
345        // `!(x > 0.0)` is deliberate: NaN fails.
346        #[expect(
347            clippy::neg_cmp_op_on_partial_ord,
348            reason = "NaN must fail the check, as in the spec"
349        )]
350        if !(world.tile_width > 0.0) || !(world.tile_height > 0.0) {
351            return Err(error!(
352                "invalid tile size {} x {}",
353                world.tile_width, world.tile_height
354            ));
355        }
356        for (i, class) in cell_classes.iter().enumerate() {
357            #[expect(
358                clippy::neg_cmp_op_on_partial_ord,
359                reason = "NaN must fail the check, as in the spec"
360            )]
361            if class.cells <= 0 || !(class.width > 0.0) {
362                return Err(error!("invalid cell class {i}"));
363            }
364            if class.cells > MAX_CELLS {
365                return Err(error!(
366                    "implausible cell count {} in cell class {i}",
367                    class.cells
368                ));
369            }
370        }
371        Ok(Self {
372            world,
373            cell_classes,
374            link_classes,
375        })
376    }
377
378    /// Encodes the payload without the protocol version.
379    ///
380    /// Class counts above `u32::MAX` are not representable and are clamped; no real value comes
381    /// near that.
382    #[must_use]
383    pub fn encode(&self) -> Vec<u8> {
384        let mut out = Vec::with_capacity(
385            WORLD_BLOCK_LEN
386                + 8
387                + self.cell_classes.len() * CELL_CLASS_LEN
388                + self.link_classes.len() * LINK_CLASS_LEN,
389        );
390        self.world.write(&mut out);
391        out.extend_from_slice(&len_u32(self.cell_classes.len()).to_le_bytes());
392        for c in &self.cell_classes {
393            out.extend_from_slice(&c.cells.to_le_bytes());
394            out.extend_from_slice(&c.cells2.to_le_bytes());
395            out.extend_from_slice(&c.width.to_le_bytes());
396            out.extend_from_slice(&c.unused.to_le_bytes());
397        }
398        out.extend_from_slice(&len_u32(self.link_classes.len()).to_le_bytes());
399        for l in &self.link_classes {
400            out.extend_from_slice(&l.index.to_le_bytes());
401            out.extend_from_slice(&l.name_hash.to_le_bytes());
402            out.extend_from_slice(&l.type_id.to_le_bytes());
403            for v in [
404                l.jump_height,
405                l.jump_length,
406                l.jump_dropdown_min,
407                l.jump_dropdown_max,
408                l.min_center_height,
409                l.agent_height,
410                l.max_step_height,
411                l.agent_radius,
412            ] {
413                out.extend_from_slice(&v.to_le_bytes());
414            }
415            out.extend_from_slice(&l.flags.to_le_bytes());
416            out.push(l.area);
417            out.push(l.pad);
418            out.extend_from_slice(&l.color.to_le_bytes());
419        }
420        out
421    }
422}
423
424fn len_u32(n: usize) -> u32 {
425    u32::try_from(n).unwrap_or(u32::MAX)
426}
427
428/// One part of a tile group: an object (or a door state) and where its vertices start.
429#[derive(Debug, Clone, PartialEq, Default)]
430#[non_exhaustive]
431pub struct TilePart {
432    /// Part index, copied into the output's extra section.
433    pub part_index: u32,
434    /// Object id.
435    pub object_id: u64,
436    /// Index of the part's first vertex in the group's vertex list.
437    pub first_vertex: u32,
438}
439
440/// One geometry group of a tile: an area id, its parts and its vertices.
441#[derive(Debug, Clone, PartialEq, Default)]
442#[non_exhaustive]
443pub struct TileGroup {
444    /// Input area id (1 terrain, 2 water, 8 building, 10 tree, 12/13 door, 15 ladder, ...).
445    pub area: u32,
446    /// The parts, in vertex order.
447    pub parts: Vec<TilePart>,
448    /// The vertices (x, y up, z): a triangle soup, or vertex pairs for ladders.
449    pub verts: Vec<[f32; 3]>,
450}
451
452/// A tile input message (id 5): one tile's geometry.
453#[derive(Debug, Clone, PartialEq, Default)]
454#[non_exhaustive]
455pub struct TileInput {
456    /// Tile x.
457    pub x: i32,
458    /// Tile z.
459    pub z: i32,
460    /// Index into the cell-class list.
461    pub cell_class: u32,
462    /// Tile bounds minimum.
463    pub bmin: [f32; 3],
464    /// Tile bounds maximum.
465    pub bmax: [f32; 3],
466    /// The geometry groups.
467    pub groups: Vec<TileGroup>,
468}
469
470impl TileInput {
471    /// Parses a tile input payload.
472    ///
473    /// # Errors
474    ///
475    /// Fails with the texts of spec 12.1: "message truncated", "implausible group count N",
476    /// "implausible part count N", "implausible vertex count N", "part vertex range out of bounds",
477    /// "non-finite vertex" and "unexpected bytes after tile record".
478    pub fn parse(payload: &[u8]) -> io::Result<Self> {
479        let mut r = Reader::new(payload);
480        let x = r.i32()?;
481        let z = r.i32()?;
482        let cell_class = r.u32()?;
483        let group_count = r.count("group count", MAX_GROUPS, MIN_GROUP_LEN)?;
484        let bmin = r.f32x3()?;
485        let bmax = r.f32x3()?;
486        let mut groups = Vec::with_capacity(group_count);
487        for _ in 0..group_count {
488            groups.push(read_group(&mut r)?);
489        }
490        if r.remaining() != 0 {
491            return Err(error!("unexpected bytes after tile record"));
492        }
493        Ok(Self {
494            x,
495            z,
496            cell_class,
497            bmin,
498            bmax,
499            groups,
500        })
501    }
502
503    /// Encodes the payload.
504    ///
505    /// Counts above the wire's range are clamped; no real value comes near that.
506    #[must_use]
507    pub fn encode(&self) -> Vec<u8> {
508        let mut out = Vec::new();
509        out.extend_from_slice(&self.x.to_le_bytes());
510        out.extend_from_slice(&self.z.to_le_bytes());
511        out.extend_from_slice(&self.cell_class.to_le_bytes());
512        out.extend_from_slice(&len_u32(self.groups.len()).to_le_bytes());
513        for v in self.bmin.iter().chain(&self.bmax) {
514            out.extend_from_slice(&v.to_le_bytes());
515        }
516        for g in &self.groups {
517            out.extend_from_slice(&g.area.to_le_bytes());
518            out.extend_from_slice(&len_u32(g.parts.len()).to_le_bytes());
519            for p in &g.parts {
520                out.extend_from_slice(&p.part_index.to_le_bytes());
521                out.extend_from_slice(&p.object_id.to_le_bytes());
522                out.extend_from_slice(&p.first_vertex.to_le_bytes());
523            }
524            let count = i32::try_from(g.verts.len()).unwrap_or(i32::MAX);
525            out.extend_from_slice(&count.to_le_bytes());
526            for v in g.verts.iter().flatten() {
527                out.extend_from_slice(&v.to_le_bytes());
528            }
529        }
530        out
531    }
532
533    /// The vertex range of part `part` of group `group`: from its `first_vertex` to the next part's
534    /// (or the end of the group's vertices for the last part). `None` when the group or part does not
535    /// exist or the range is out of bounds.
536    #[must_use]
537    pub fn part_vertex_range(&self, group: usize, part: usize) -> Option<Range<usize>> {
538        let g = self.groups.get(group)?;
539        let start = usize::try_from(g.parts.get(part)?.first_vertex).ok()?;
540        let end = match g.parts.get(part.checked_add(1)?) {
541            Some(next) => usize::try_from(next.first_vertex).ok()?,
542            None => g.verts.len(),
543        };
544        (start <= end && end <= g.verts.len()).then_some(start..end)
545    }
546}
547
548fn read_group(r: &mut Reader<'_>) -> io::Result<TileGroup> {
549    let area = r.u32()?;
550    let part_count = r.count("part count", MAX_PARTS, PART_LEN)?;
551    let mut parts = Vec::with_capacity(part_count);
552    for _ in 0..part_count {
553        parts.push(TilePart {
554            part_index: r.u32()?,
555            object_id: r.u64()?,
556            first_vertex: r.u32()?,
557        });
558    }
559    let vertex_count = r.i32()?;
560    if !(0..=MAX_VERTICES).contains(&vertex_count) {
561        return Err(error!("implausible vertex count {vertex_count}"));
562    }
563    let vertex_count = usize::try_from(vertex_count)
564        .map_err(|_| error!("implausible vertex count {vertex_count}"))?;
565    r.check_available(vertex_count, VERTEX_LEN)?;
566    let mut previous = 0usize;
567    for part in &parts {
568        let first = usize::try_from(part.first_vertex)
569            .map_err(|_| error!("part vertex range out of bounds"))?;
570        if first < previous || first > vertex_count {
571            return Err(error!("part vertex range out of bounds"));
572        }
573        previous = first;
574    }
575    let mut verts = Vec::with_capacity(vertex_count);
576    for _ in 0..vertex_count {
577        let v = r.f32x3()?;
578        if !v.iter().all(|c| c.is_finite()) {
579            return Err(error!("non-finite vertex"));
580        }
581        verts.push(v);
582    }
583    Ok(TileGroup { area, parts, verts })
584}
585
586/// Encodes a tile request (message 3, spec 3.3): tile x and z, then the tile's min and max x and z
587/// as `float(x) * tileWidth`, `float(z) * tileHeight`, `float(x + 1) * tileWidth` and
588/// `float(z + 1) * tileHeight`.
589#[must_use]
590pub fn encode_tile_request(x: i32, z: i32, world: &WorldBlock) -> [u8; 24] {
591    let mut out = [0u8; 24];
592    let fields = [
593        x.to_le_bytes(),
594        z.to_le_bytes(),
595        (i32_to_f32(x) * world.tile_width).to_le_bytes(),
596        (i32_to_f32(z) * world.tile_height).to_le_bytes(),
597        (i32_to_f32(x.saturating_add(1)) * world.tile_width).to_le_bytes(),
598        (i32_to_f32(z.saturating_add(1)) * world.tile_height).to_le_bytes(),
599    ];
600    for (chunk, field) in out.as_chunks_mut::<4>().0.iter_mut().zip(fields) {
601        *chunk = field;
602    }
603    out
604}