1use std::io;
11use std::ops::Range;
12
13use crate::navmesh::bytes::Reader;
14use crate::navmesh::num::i32_to_f32;
15
16pub const PROTOCOL_VERSION: u32 = 10;
18pub 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;
26const 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#[derive(Debug, Clone, Default)]
49#[non_exhaustive]
50pub struct WorldBlock {
51 pub world_size_x: f32,
53 pub world_size_z: f32,
55 pub tile_width: f32,
57 pub tile_height: f32,
59 pub tiles_x: i32,
61 pub tiles_z: i32,
63 pub deep_sea_height: f32,
65 pub deep_water_depth: f32,
67 pub contour_max_error: f32,
69 pub obstacles: bool,
71 pub block_size: i32,
73 pub filter_isolated_islands: bool,
75 pub seed_position: [f32; 3],
77 pub stand_height: f32,
79 pub crouch_height: f32,
81 pub prone_height: f32,
83 pub diameter: f32,
85 pub max_step_height: f32,
87 pub max_slope: f32,
89 pub obstacles_raw: [u8; 4],
91 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
197fn 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#[derive(Debug, Clone, PartialEq, Default)]
207#[non_exhaustive]
208pub struct CellClass {
209 pub cells: i32,
211 pub cells2: u32,
213 pub width: f32,
215 pub unused: u32,
217}
218
219impl CellClass {
220 #[must_use]
222 pub fn cell_size(&self) -> f32 {
223 self.width / i32_to_f32(self.cells)
224 }
225}
226
227#[derive(Debug, Clone, PartialEq, Default)]
229#[non_exhaustive]
230pub struct LinkClass {
231 pub index: u32,
233 pub name_hash: u32,
235 pub type_id: i32,
237 pub jump_height: f32,
239 pub jump_length: f32,
241 pub jump_dropdown_min: f32,
243 pub jump_dropdown_max: f32,
245 pub min_center_height: f32,
247 pub agent_height: f32,
249 pub max_step_height: f32,
251 pub agent_radius: f32,
253 pub flags: u16,
255 pub area: u8,
257 pub pad: u8,
259 pub color: i32,
261}
262
263#[derive(Debug, Clone, PartialEq, Default)]
265#[non_exhaustive]
266pub struct WorldParams {
267 pub world: WorldBlock,
269 pub cell_classes: Vec<CellClass>,
271 pub link_classes: Vec<LinkClass>,
273}
274
275impl WorldParams {
276 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 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 #[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 #[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#[derive(Debug, Clone, PartialEq, Default)]
430#[non_exhaustive]
431pub struct TilePart {
432 pub part_index: u32,
434 pub object_id: u64,
436 pub first_vertex: u32,
438}
439
440#[derive(Debug, Clone, PartialEq, Default)]
442#[non_exhaustive]
443pub struct TileGroup {
444 pub area: u32,
446 pub parts: Vec<TilePart>,
448 pub verts: Vec<[f32; 3]>,
450}
451
452#[derive(Debug, Clone, PartialEq, Default)]
454#[non_exhaustive]
455pub struct TileInput {
456 pub x: i32,
458 pub z: i32,
460 pub cell_class: u32,
462 pub bmin: [f32; 3],
464 pub bmax: [f32; 3],
466 pub groups: Vec<TileGroup>,
468}
469
470impl TileInput {
471 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 #[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 #[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#[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}