use std::io;
use std::ops::Range;
use crate::navmesh::bytes::Reader;
use crate::navmesh::num::i32_to_f32;
pub const PROTOCOL_VERSION: u32 = 10;
pub const DEFAULT_PORT: u16 = 36533;
const WORLD_BLOCK_LEN: usize = 84;
const CELL_CLASS_LEN: usize = 16;
const LINK_CLASS_LEN: usize = 52;
const PART_LEN: usize = 16;
const VERTEX_LEN: usize = 12;
const MIN_GROUP_LEN: usize = 12;
const MAX_CELL_CLASSES: usize = 64;
const MAX_LINK_CLASSES: usize = 256;
const MAX_TILES: i64 = 1 << 28;
const MAX_CELLS: i32 = 2048;
const MAX_GROUPS: usize = 65536;
const MAX_PARTS: usize = 1_048_576;
const MAX_VERTICES: i32 = 1 << 26;
#[derive(Debug, Clone, Default)]
#[non_exhaustive]
pub struct WorldBlock {
pub world_size_x: f32,
pub world_size_z: f32,
pub tile_width: f32,
pub tile_height: f32,
pub tiles_x: i32,
pub tiles_z: i32,
pub deep_sea_height: f32,
pub deep_water_depth: f32,
pub contour_max_error: f32,
pub obstacles: bool,
pub block_size: i32,
pub filter_isolated_islands: bool,
pub seed_position: [f32; 3],
pub stand_height: f32,
pub crouch_height: f32,
pub prone_height: f32,
pub diameter: f32,
pub max_step_height: f32,
pub max_slope: f32,
pub obstacles_raw: [u8; 4],
pub filter_raw: [u8; 4],
}
impl PartialEq for WorldBlock {
fn eq(&self, other: &Self) -> bool {
self.world_size_x == other.world_size_x
&& self.world_size_z == other.world_size_z
&& self.tile_width == other.tile_width
&& self.tile_height == other.tile_height
&& self.tiles_x == other.tiles_x
&& self.tiles_z == other.tiles_z
&& self.deep_sea_height == other.deep_sea_height
&& self.deep_water_depth == other.deep_water_depth
&& self.contour_max_error == other.contour_max_error
&& flag_bytes(self.obstacles, self.obstacles_raw)
== flag_bytes(other.obstacles, other.obstacles_raw)
&& self.block_size == other.block_size
&& flag_bytes(self.filter_isolated_islands, self.filter_raw)
== flag_bytes(other.filter_isolated_islands, other.filter_raw)
&& self.seed_position == other.seed_position
&& self.stand_height == other.stand_height
&& self.crouch_height == other.crouch_height
&& self.prone_height == other.prone_height
&& self.diameter == other.diameter
&& self.max_step_height == other.max_step_height
&& self.max_slope == other.max_slope
}
}
impl WorldBlock {
fn read(r: &mut Reader<'_>) -> io::Result<Self> {
let world_size_x = r.f32()?;
let world_size_z = r.f32()?;
let tile_width = r.f32()?;
let tile_height = r.f32()?;
let tiles_x = r.i32()?;
let tiles_z = r.i32()?;
let deep_sea_height = r.f32()?;
let deep_water_depth = r.f32()?;
let contour_max_error = r.f32()?;
let obstacles_raw = r.array::<4>()?;
let block_size = r.i32()?;
let filter_raw = r.array::<4>()?;
Ok(Self {
world_size_x,
world_size_z,
tile_width,
tile_height,
tiles_x,
tiles_z,
deep_sea_height,
deep_water_depth,
contour_max_error,
obstacles: obstacles_raw[0] != 0,
block_size,
filter_isolated_islands: filter_raw[0] != 0,
seed_position: r.f32x3()?,
stand_height: r.f32()?,
crouch_height: r.f32()?,
prone_height: r.f32()?,
diameter: r.f32()?,
max_step_height: r.f32()?,
max_slope: r.f32()?,
obstacles_raw,
filter_raw,
})
}
fn write(&self, out: &mut Vec<u8>) {
for v in [
self.world_size_x,
self.world_size_z,
self.tile_width,
self.tile_height,
] {
out.extend_from_slice(&v.to_le_bytes());
}
out.extend_from_slice(&self.tiles_x.to_le_bytes());
out.extend_from_slice(&self.tiles_z.to_le_bytes());
for v in [
self.deep_sea_height,
self.deep_water_depth,
self.contour_max_error,
] {
out.extend_from_slice(&v.to_le_bytes());
}
out.extend_from_slice(&flag_bytes(self.obstacles, self.obstacles_raw));
out.extend_from_slice(&self.block_size.to_le_bytes());
out.extend_from_slice(&flag_bytes(self.filter_isolated_islands, self.filter_raw));
for v in self.seed_position {
out.extend_from_slice(&v.to_le_bytes());
}
for v in [
self.stand_height,
self.crouch_height,
self.prone_height,
self.diameter,
self.max_step_height,
self.max_slope,
] {
out.extend_from_slice(&v.to_le_bytes());
}
}
}
fn flag_bytes(flag: bool, mut raw: [u8; 4]) -> [u8; 4] {
if (raw[0] != 0) != flag {
raw[0] = u8::from(flag);
}
raw
}
#[derive(Debug, Clone, PartialEq, Default)]
#[non_exhaustive]
pub struct CellClass {
pub cells: i32,
pub cells2: u32,
pub width: f32,
pub unused: u32,
}
impl CellClass {
#[must_use]
pub fn cell_size(&self) -> f32 {
self.width / i32_to_f32(self.cells)
}
}
#[derive(Debug, Clone, PartialEq, Default)]
#[non_exhaustive]
pub struct LinkClass {
pub index: u32,
pub name_hash: u32,
pub type_id: i32,
pub jump_height: f32,
pub jump_length: f32,
pub jump_dropdown_min: f32,
pub jump_dropdown_max: f32,
pub min_center_height: f32,
pub agent_height: f32,
pub max_step_height: f32,
pub agent_radius: f32,
pub flags: u16,
pub area: u8,
pub pad: u8,
pub color: i32,
}
#[derive(Debug, Clone, PartialEq, Default)]
#[non_exhaustive]
pub struct WorldParams {
pub world: WorldBlock,
pub cell_classes: Vec<CellClass>,
pub link_classes: Vec<LinkClass>,
}
impl WorldParams {
pub fn parse_message(payload: &[u8]) -> io::Result<Self> {
let mut r = Reader::new(payload);
let version = r.u32().map_err(|_| error!("world params truncated"))?;
if version != PROTOCOL_VERSION {
return Err(error!(
"server protocol version {version}, expected {PROTOCOL_VERSION}"
));
}
Self::parse(r.rest())
}
pub fn parse(payload: &[u8]) -> io::Result<Self> {
let mut r = Reader::new(payload);
let world = WorldBlock::read(&mut r)?;
let n = r.count("cell class count", MAX_CELL_CLASSES, CELL_CLASS_LEN)?;
let mut cell_classes = Vec::with_capacity(n);
for _ in 0..n {
cell_classes.push(CellClass {
cells: r.i32()?,
cells2: r.u32()?,
width: r.f32()?,
unused: r.u32()?,
});
}
let m = r.count("link count", MAX_LINK_CLASSES, LINK_CLASS_LEN)?;
let mut link_classes = Vec::with_capacity(m);
for _ in 0..m {
link_classes.push(LinkClass {
index: r.u32()?,
name_hash: r.u32()?,
type_id: r.i32()?,
jump_height: r.f32()?,
jump_length: r.f32()?,
jump_dropdown_min: r.f32()?,
jump_dropdown_max: r.f32()?,
min_center_height: r.f32()?,
agent_height: r.f32()?,
max_step_height: r.f32()?,
agent_radius: r.f32()?,
flags: r.u16()?,
area: r.u8()?,
pad: r.u8()?,
color: r.i32()?,
});
}
if r.remaining() != 0 {
return Err(error!("unexpected bytes after world params"));
}
let tiles = i64::from(world.tiles_x) * i64::from(world.tiles_z);
if world.tiles_x <= 0 || world.tiles_z <= 0 || tiles > MAX_TILES {
return Err(error!(
"invalid tile grid {} x {}",
world.tiles_x, world.tiles_z
));
}
#[expect(
clippy::neg_cmp_op_on_partial_ord,
reason = "NaN must fail the check, as in the spec"
)]
if !(world.tile_width > 0.0) || !(world.tile_height > 0.0) {
return Err(error!(
"invalid tile size {} x {}",
world.tile_width, world.tile_height
));
}
for (i, class) in cell_classes.iter().enumerate() {
#[expect(
clippy::neg_cmp_op_on_partial_ord,
reason = "NaN must fail the check, as in the spec"
)]
if class.cells <= 0 || !(class.width > 0.0) {
return Err(error!("invalid cell class {i}"));
}
if class.cells > MAX_CELLS {
return Err(error!(
"implausible cell count {} in cell class {i}",
class.cells
));
}
}
Ok(Self {
world,
cell_classes,
link_classes,
})
}
#[must_use]
pub fn encode(&self) -> Vec<u8> {
let mut out = Vec::with_capacity(
WORLD_BLOCK_LEN
+ 8
+ self.cell_classes.len() * CELL_CLASS_LEN
+ self.link_classes.len() * LINK_CLASS_LEN,
);
self.world.write(&mut out);
out.extend_from_slice(&len_u32(self.cell_classes.len()).to_le_bytes());
for c in &self.cell_classes {
out.extend_from_slice(&c.cells.to_le_bytes());
out.extend_from_slice(&c.cells2.to_le_bytes());
out.extend_from_slice(&c.width.to_le_bytes());
out.extend_from_slice(&c.unused.to_le_bytes());
}
out.extend_from_slice(&len_u32(self.link_classes.len()).to_le_bytes());
for l in &self.link_classes {
out.extend_from_slice(&l.index.to_le_bytes());
out.extend_from_slice(&l.name_hash.to_le_bytes());
out.extend_from_slice(&l.type_id.to_le_bytes());
for v in [
l.jump_height,
l.jump_length,
l.jump_dropdown_min,
l.jump_dropdown_max,
l.min_center_height,
l.agent_height,
l.max_step_height,
l.agent_radius,
] {
out.extend_from_slice(&v.to_le_bytes());
}
out.extend_from_slice(&l.flags.to_le_bytes());
out.push(l.area);
out.push(l.pad);
out.extend_from_slice(&l.color.to_le_bytes());
}
out
}
}
fn len_u32(n: usize) -> u32 {
u32::try_from(n).unwrap_or(u32::MAX)
}
#[derive(Debug, Clone, PartialEq, Default)]
#[non_exhaustive]
pub struct TilePart {
pub part_index: u32,
pub object_id: u64,
pub first_vertex: u32,
}
#[derive(Debug, Clone, PartialEq, Default)]
#[non_exhaustive]
pub struct TileGroup {
pub area: u32,
pub parts: Vec<TilePart>,
pub verts: Vec<[f32; 3]>,
}
#[derive(Debug, Clone, PartialEq, Default)]
#[non_exhaustive]
pub struct TileInput {
pub x: i32,
pub z: i32,
pub cell_class: u32,
pub bmin: [f32; 3],
pub bmax: [f32; 3],
pub groups: Vec<TileGroup>,
}
impl TileInput {
pub fn parse(payload: &[u8]) -> io::Result<Self> {
let mut r = Reader::new(payload);
let x = r.i32()?;
let z = r.i32()?;
let cell_class = r.u32()?;
let group_count = r.count("group count", MAX_GROUPS, MIN_GROUP_LEN)?;
let bmin = r.f32x3()?;
let bmax = r.f32x3()?;
let mut groups = Vec::with_capacity(group_count);
for _ in 0..group_count {
groups.push(read_group(&mut r)?);
}
if r.remaining() != 0 {
return Err(error!("unexpected bytes after tile record"));
}
Ok(Self {
x,
z,
cell_class,
bmin,
bmax,
groups,
})
}
#[must_use]
pub fn encode(&self) -> Vec<u8> {
let mut out = Vec::new();
out.extend_from_slice(&self.x.to_le_bytes());
out.extend_from_slice(&self.z.to_le_bytes());
out.extend_from_slice(&self.cell_class.to_le_bytes());
out.extend_from_slice(&len_u32(self.groups.len()).to_le_bytes());
for v in self.bmin.iter().chain(&self.bmax) {
out.extend_from_slice(&v.to_le_bytes());
}
for g in &self.groups {
out.extend_from_slice(&g.area.to_le_bytes());
out.extend_from_slice(&len_u32(g.parts.len()).to_le_bytes());
for p in &g.parts {
out.extend_from_slice(&p.part_index.to_le_bytes());
out.extend_from_slice(&p.object_id.to_le_bytes());
out.extend_from_slice(&p.first_vertex.to_le_bytes());
}
let count = i32::try_from(g.verts.len()).unwrap_or(i32::MAX);
out.extend_from_slice(&count.to_le_bytes());
for v in g.verts.iter().flatten() {
out.extend_from_slice(&v.to_le_bytes());
}
}
out
}
#[must_use]
pub fn part_vertex_range(&self, group: usize, part: usize) -> Option<Range<usize>> {
let g = self.groups.get(group)?;
let start = usize::try_from(g.parts.get(part)?.first_vertex).ok()?;
let end = match g.parts.get(part.checked_add(1)?) {
Some(next) => usize::try_from(next.first_vertex).ok()?,
None => g.verts.len(),
};
(start <= end && end <= g.verts.len()).then_some(start..end)
}
}
fn read_group(r: &mut Reader<'_>) -> io::Result<TileGroup> {
let area = r.u32()?;
let part_count = r.count("part count", MAX_PARTS, PART_LEN)?;
let mut parts = Vec::with_capacity(part_count);
for _ in 0..part_count {
parts.push(TilePart {
part_index: r.u32()?,
object_id: r.u64()?,
first_vertex: r.u32()?,
});
}
let vertex_count = r.i32()?;
if !(0..=MAX_VERTICES).contains(&vertex_count) {
return Err(error!("implausible vertex count {vertex_count}"));
}
let vertex_count = usize::try_from(vertex_count)
.map_err(|_| error!("implausible vertex count {vertex_count}"))?;
r.check_available(vertex_count, VERTEX_LEN)?;
let mut previous = 0usize;
for part in &parts {
let first = usize::try_from(part.first_vertex)
.map_err(|_| error!("part vertex range out of bounds"))?;
if first < previous || first > vertex_count {
return Err(error!("part vertex range out of bounds"));
}
previous = first;
}
let mut verts = Vec::with_capacity(vertex_count);
for _ in 0..vertex_count {
let v = r.f32x3()?;
if !v.iter().all(|c| c.is_finite()) {
return Err(error!("non-finite vertex"));
}
verts.push(v);
}
Ok(TileGroup { area, parts, verts })
}
#[must_use]
pub fn encode_tile_request(x: i32, z: i32, world: &WorldBlock) -> [u8; 24] {
let mut out = [0u8; 24];
let fields = [
x.to_le_bytes(),
z.to_le_bytes(),
(i32_to_f32(x) * world.tile_width).to_le_bytes(),
(i32_to_f32(z) * world.tile_height).to_le_bytes(),
(i32_to_f32(x.saturating_add(1)) * world.tile_width).to_le_bytes(),
(i32_to_f32(z.saturating_add(1)) * world.tile_height).to_le_bytes(),
];
for (chunk, field) in out.as_chunks_mut::<4>().0.iter_mut().zip(fields) {
*chunk = field;
}
out
}