pub const PROTOCOL_VERSION: u32 = 3;
use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
pub struct NetworkId(pub u64);
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct LocalId(pub u64);
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
pub struct ClientId(pub u64);
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
pub struct ComponentKind(pub u16);
pub const INPUT_COMMAND_KIND: ComponentKind = ComponentKind(128);
pub const ROOM_DEFINITION_KIND: ComponentKind = ComponentKind(129);
pub const ROOM_BOUNDS_KIND: ComponentKind = ComponentKind(130);
pub const ROOM_MEMBERSHIP_KIND: ComponentKind = ComponentKind(131);
pub const MINING_BEAM_KIND: ComponentKind = ComponentKind(1024);
pub const CARGO_HOLD_KIND: ComponentKind = ComponentKind(1025);
pub const ASTEROID_KIND: ComponentKind = ComponentKind(1026);
#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
#[repr(C)]
pub struct Transform {
pub x: f32,
pub y: f32,
pub z: f32,
pub rotation: f32,
pub entity_type: u16,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[repr(u8)]
pub enum ShipClass {
Interceptor = 0,
Dreadnought = 1,
Hauler = 2,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
pub struct WeaponId(pub u8);
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
pub struct SectorId(pub u64);
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[repr(u8)]
pub enum OreType {
RawOre = 0,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[repr(u8)]
pub enum ProjectileType {
PulseLaser = 0,
SeekerMissile = 1,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[repr(u8)]
pub enum AIState {
Patrol = 0,
Aggro = 1,
Combat = 2,
Return = 3,
}
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
pub enum RespawnLocation {
NearestSafeZone,
Station(u64),
Coordinate(f32, f32),
}
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq)]
pub enum PlayerInputKind {
Move { x: f32, y: f32 },
ToggleMining { target: NetworkId },
FirePrimary,
}
pub const MAX_ACTIONS: usize = 128;
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct InputCommand {
pub tick: u64,
pub actions: Vec<PlayerInputKind>,
pub last_seen_input_tick: Option<u64>,
}
impl InputCommand {
#[must_use]
pub fn clamped(mut self) -> Self {
for action in &mut self.actions {
if let PlayerInputKind::Move { x, y } = action {
*x = x.clamp(-1.0, 1.0);
*y = y.clamp(-1.0, 1.0);
}
}
self
}
pub fn validate(&self) -> Result<(), &'static str> {
if self.actions.len() > MAX_ACTIONS {
return Err("Too many actions in InputCommand");
}
Ok(())
}
}
#[derive(Debug, Clone, Copy, Serialize, Deserialize, Default)]
pub struct MiningBeam {
pub active: bool,
pub target: Option<NetworkId>,
}
#[derive(Debug, Clone, Copy, Serialize, Deserialize, Default)]
pub struct CargoHold {
pub ore_count: u16,
pub capacity: u16,
}
#[derive(Debug, Clone, Copy, Serialize, Deserialize, Default)]
pub struct Asteroid {
pub ore_remaining: u16,
pub total_capacity: u16,
}
#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
pub struct ShipStats {
pub hp: u16,
pub max_hp: u16,
pub shield: u16,
pub max_shield: u16,
pub energy: u16,
pub max_energy: u16,
pub shield_regen_per_s: u16,
pub energy_regen_per_s: u16,
}
impl Default for ShipStats {
fn default() -> Self {
Self {
hp: 100,
max_hp: 100,
shield: 100,
max_shield: 100,
energy: 100,
max_energy: 100,
shield_regen_per_s: 0,
energy_regen_per_s: 0,
}
}
}
pub const MAX_ROOM_STRING_BYTES: usize = 64;
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[error("string too long: {len} bytes exceeds the maximum of {max} bytes")]
pub struct RoomStringError {
pub len: usize,
pub max: usize,
}
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[serde(try_from = "String", into = "String")]
pub struct RoomName(String);
impl RoomName {
#[must_use = "the validated RoomName must be used"]
pub fn new(s: impl Into<String>) -> Result<Self, RoomStringError> {
let s = s.into();
if s.len() > MAX_ROOM_STRING_BYTES {
return Err(RoomStringError {
len: s.len(),
max: MAX_ROOM_STRING_BYTES,
});
}
Ok(Self(s))
}
#[must_use]
pub fn as_str(&self) -> &str {
&self.0
}
}
impl TryFrom<String> for RoomName {
type Error = RoomStringError;
fn try_from(s: String) -> Result<Self, Self::Error> {
Self::new(s)
}
}
impl From<RoomName> for String {
fn from(n: RoomName) -> String {
n.0
}
}
impl std::fmt::Display for RoomName {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
self.0.fmt(f)
}
}
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[serde(try_from = "String", into = "String")]
pub struct PermissionString(String);
impl PermissionString {
#[must_use = "the validated PermissionString must be used"]
pub fn new(s: impl Into<String>) -> Result<Self, RoomStringError> {
let s = s.into();
if s.len() > MAX_ROOM_STRING_BYTES {
return Err(RoomStringError {
len: s.len(),
max: MAX_ROOM_STRING_BYTES,
});
}
Ok(Self(s))
}
#[must_use]
pub fn as_str(&self) -> &str {
&self.0
}
}
impl TryFrom<String> for PermissionString {
type Error = RoomStringError;
fn try_from(s: String) -> Result<Self, Self::Error> {
Self::new(s)
}
}
impl From<PermissionString> for String {
fn from(p: PermissionString) -> String {
p.0
}
}
impl std::fmt::Display for PermissionString {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
self.0.fmt(f)
}
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub enum RoomAccessPolicy {
Open,
Permission(PermissionString),
InviteOnly,
Locked,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RoomDefinition {
pub name: RoomName,
pub capacity: u32,
pub access: RoomAccessPolicy,
pub is_template: bool,
}
#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
pub struct RoomBounds {
pub min_x: f32,
pub min_y: f32,
pub max_x: f32,
pub max_y: f32,
}
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Hash)]
pub struct RoomMembership(pub NetworkId);
use std::sync::atomic::{AtomicU64, Ordering};
use thiserror::Error;
#[derive(Debug, Error, PartialEq, Eq)]
pub enum AllocatorError {
#[error("NetworkId overflow (reached u64::MAX)")]
Overflow,
#[error("NetworkId allocator exhausted (reached limit)")]
Exhausted,
}
#[derive(Debug)]
pub struct NetworkIdAllocator {
start_id: u64,
next: AtomicU64,
}
impl Default for NetworkIdAllocator {
fn default() -> Self {
Self::new(1)
}
}
impl NetworkIdAllocator {
#[must_use]
pub fn new(start_id: u64) -> Self {
Self {
start_id,
next: AtomicU64::new(start_id),
}
}
pub fn allocate(&self) -> Result<NetworkId, AllocatorError> {
let val = self
.next
.fetch_update(Ordering::Relaxed, Ordering::Relaxed, |curr| {
if curr == u64::MAX {
None
} else {
Some(curr + 1)
}
})
.map_err(|_| AllocatorError::Overflow)?;
if val == 0 {
return Err(AllocatorError::Exhausted);
}
Ok(NetworkId(val))
}
pub fn reset(&self) {
self.next.store(self.start_id, Ordering::Relaxed);
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_primitive_derives() {
let nid1 = NetworkId(42);
let nid2 = nid1;
assert_eq!(nid1, nid2);
let lid1 = LocalId(42);
let lid2 = LocalId(42);
assert_eq!(lid1, lid2);
let cid = ClientId(99);
assert_eq!(format!("{cid:?}"), "ClientId(99)");
let kind = ComponentKind(1);
assert_eq!(kind.0, 1);
}
#[test]
fn test_input_command_clamping() {
let cmd = InputCommand {
tick: 1,
actions: vec![PlayerInputKind::Move { x: 2.0, y: -5.0 }],
last_seen_input_tick: None,
};
let clamped = cmd.clamped();
if let PlayerInputKind::Move { x, y } = clamped.actions[0] {
assert!((x - 1.0).abs() < f32::EPSILON);
assert!((y - -1.0).abs() < f32::EPSILON);
} else {
panic!("Expected Move action");
}
let valid = InputCommand {
tick: 1,
actions: vec![PlayerInputKind::Move { x: 0.5, y: -0.2 }],
last_seen_input_tick: None,
};
let clamped = valid.clamped();
if let PlayerInputKind::Move { x, y } = clamped.actions[0] {
assert!((x - 0.5).abs() < f32::EPSILON);
assert!((y - -0.2).abs() < f32::EPSILON);
} else {
panic!("Expected Move action");
}
}
#[test]
fn test_ship_stats_non_zero_default() {
let stats = ShipStats::default();
assert!(stats.max_hp > 0);
assert!(stats.max_shield > 0);
assert!(stats.max_energy > 0);
assert_eq!(stats.hp, stats.max_hp);
}
}