From 45d2cc495c5cfed4609a3bb78b3c1917790d53a2 Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Sun, 30 Nov 2025 14:56:10 +0100 Subject: [PATCH] Adds generic entities --- lib_efo/src/entity.rs | 19 +++++ lib_efo/src/lib.rs | 6 +- lib_efo/src/stats.rs | 108 ++++++++++++++++----------- lib_efo/src/stats/implementations.rs | 65 ++++++++++++++-- lib_efo/src/town.rs | 1 - 5 files changed, 144 insertions(+), 55 deletions(-) create mode 100644 lib_efo/src/entity.rs delete mode 100644 lib_efo/src/town.rs diff --git a/lib_efo/src/entity.rs b/lib_efo/src/entity.rs new file mode 100644 index 0000000..d841042 --- /dev/null +++ b/lib_efo/src/entity.rs @@ -0,0 +1,19 @@ +//! All the structs and logic surrounding entities +//! +//! + +use serde::{Deserialize, Serialize}; + +use crate::stats::{EntityType, MetaStats, OverallStats}; + +/// Fundamentaly everything is an entity, this can be error prone but the reduction of code duplication makes it worth it right now +/// Traits and thin structs could solve this but this will be added later and will be greatly simplified by the existence of the sub structs holding all the logic +#[derive(Serialize, Deserialize)] +pub struct Entity { + /// The stats of the entity, holding all the logic + stats: OverallStats, + /// Meta information + metadata: MetaStats, + /// Enum listing all entity types, this is bound to disapear in favor Typed Etities lateer + entity_type: EntityType, +} diff --git a/lib_efo/src/lib.rs b/lib_efo/src/lib.rs index a9a8e92..f18c370 100644 --- a/lib_efo/src/lib.rs +++ b/lib_efo/src/lib.rs @@ -20,11 +20,11 @@ #![warn(missing_docs, clippy::missing_docs_in_private_items)] #![deny(clippy::unwrap_used)] -pub mod epoch; -pub mod stats; -pub mod town; #[macro_use] pub mod error; +pub mod entity; +pub mod epoch; +pub mod stats; pub mod utils; use std::io::Result as IoResult; diff --git a/lib_efo/src/stats.rs b/lib_efo/src/stats.rs index 7e5ad13..dc73c6f 100644 --- a/lib_efo/src/stats.rs +++ b/lib_efo/src/stats.rs @@ -16,7 +16,8 @@ use cli_table::Table; use colored::Colorize; use derive_more::Display; use serde::{Deserialize, Serialize}; -use uuid::Uuid; + +use crate::thin_newtype; mod implementations; /// Aggregated statistics for a single entity. @@ -27,7 +28,7 @@ mod implementations; // Derive more #[derive(Table)] // #[derive(Add, Sub)] -struct OverallStats { +pub struct OverallStats { // ──────────────────────── Demographics ──────────────────────── /// Total economic health of the entity. /// @@ -211,8 +212,8 @@ struct OverallStats { /// /// All fields are intentionally simple – the logic that interprets them /// lives in separate modules (e.g. `map`, `network`, `governance`). -#[derive(Debug, Clone, Default)] -pub struct Strategics { +#[derive(Debug, Clone, Default, Serialize, Deserialize)] +pub struct MetaStats { // ──── Location & Spatial Data (hidden) ─────────────────────────────── /// Cartesian coordinates of the entity on the world map. /// @@ -220,31 +221,26 @@ pub struct Strategics { /// **Effect** – Used for distance calculations, visibility, and /// map‑based event logic. /// **Source** – Supplied by the map generator. - pub position: (usize, usize), + pub position: Position, - /// Euclidean distance to the empire’s capital (in tile units). - /// - /// **Purpose** – Metric of remoteness from the political centre. - /// **Effect** – Influences trade costs, supply‑line strength, - /// and the range of early‑warning signals. - /// **Source** – `distance_to_capital = dist(position, capital_position)`. - pub distance_to_capital: usize, + /// Identifier for the capital + pub capital: TownId, - /// List of nearby resource nodes (mines, forests, farms, etc.). - /// - /// **Purpose** – Resource map around the entity. - /// **Effect** – Drives the entity’s specialization and determines - /// the default output mix. - /// **Source** – `resources = filter(resource_list, distance ≤ detection_radius)`. - pub resources: Vec, + // /// List of nearby resource nodes (mines, forests, farms, etc.). + // /// + // /// **Purpose** – Resource map around the entity. + // /// **Effect** – Drives the entity’s specialization and determines + // /// the default output mix. + // /// **Source** – `resources = filter(resource_list, distance ≤ detection_radius)`. + // pub resources: Vec, - /// The entity’s chosen specialization tag - /// (e.g., “Agricultural Hub”, “Industrial Center”). - /// - /// **Purpose** – Identity that dictates default production multipliers. - /// **Effect** – Alters output curves and trade attractiveness. - /// **Source** – `specialization = tag_assigned_by_player_or_ai`. - pub specialization: String, + // /// The entity’s chosen specialization tag + // /// (e.g., “Agricultural Hub”, “Industrial Center”). + // /// + // /// **Purpose** – Identity that dictates default production multipliers. + // /// **Effect** – Alters output curves and trade attractiveness. + // /// **Source** – `specialization = tag_assigned_by_player_or_ai`. + // pub specialization: String, // ──── Strategic Positioning (hidden + public) ───────────────────── /// Current governor or leader assigned to the entity. @@ -253,23 +249,22 @@ pub struct Strategics { /// **Effect** – Adds personal bonuses and may modify policies /// or diplomatic stance. /// **Source** – `governor = selected_leader_uuid`. - pub governor: Uuid, - - /// The entity’s classification (capital, trade hub, frontier post, etc.). - /// - /// **Purpose** – Functional role within the empire. - /// **Effect** – Alters base production, tax rates, and - /// certain event probabilities. - /// **Source** – `role = tag_assigned_by_player_or_ai`. - pub role: String, + pub governor: CharacterId, + // /// The entity’s classification (capital, trade hub, frontier post, etc.). + // /// + // /// **Purpose** – Functional role within the empire. + // /// **Effect** – Alters base production, tax rates, and + // /// certain event probabilities. + // /// **Source** – `role = tag_assigned_by_player_or_ai`. + // pub role: String, /// The faction or empire to which the entity currently belongs. /// /// **Purpose** – Political affiliation. /// **Effect** – Determines diplomatic relations, war status, /// and access to empire‑wide bonuses. /// **Source** – `faction = current_faction_uuid`. - pub faction: Uuid, + pub faction: FactionId, /// UIDs of all entities the entity is linked to (roads, trade routes, /// alliances, war declarations, etc.). @@ -279,7 +274,7 @@ pub struct Strategics { /// interactions. /// **Source** – `links = Vec` collected from the entity’s /// network manager. - pub links: Vec, + pub links: Vec, /// Prestige / reputation of the entity in the eyes of the empire /// and foreign powers. @@ -291,6 +286,21 @@ pub struct Strategics { pub prestige: usize, } +/// Structure used to indicate position, possess nice helper methods to use as is in the program +#[derive(Debug, Default, Serialize, Deserialize, Clone)] +pub struct Position(isize, isize); + +impl Position { + /// The euclidian distance between two points + fn distance(&self, other: &Self) -> isize { + ((self.0 - other.0).pow(2) + (self.1 * other.1).pow(2)).isqrt() + } + + /// The position in grid coordinates + fn to_grid_distance(&self) -> (isize, isize) { + (self.0 / 200, self.1 / 200) + } +} /// A summary of the stats, only for display purposes #[allow(clippy::missing_docs_in_private_items)] #[derive(Table)] @@ -338,19 +348,31 @@ pub enum ListStats { Health, } -// fn print_generic_stat() -/// A stat that is shown to the player *and* can be modified manually. +/// The list of all types of entities #[allow(missing_docs)] -#[derive(Debug, Clone, Default, Serialize, Deserialize, Display)] -pub struct GenericStat { - pub value: isize, +#[derive(Serialize, Deserialize)] +pub enum EntityType { + Character, + Player, + Town, + Monster, + Blocker, + Event, } -/// --- TRAITS --------------------------------------------------------------- +// A stat that is shown to the player *and* can be modified manually. +thin_newtype!(GenericStat, isize); +thin_newtype!(TownId, usize); +thin_newtype!(CharacterId, usize); +thin_newtype!(FactionId, usize); + +// --- TRAITS --------------------------------------------------------------- /// A stat is a *game value* that can be converted to two different /// normalised ranges – a 50‑point range for “gaming” logic and a /// 10‑point range for “roll & UI” logic. The trait also exposes the /// underlying raw value and its visibility. +/// +// TODO[7]: Change this with Deref+From pub trait GameStat { /// Convert the raw integer to a 50‑point scale. fn to_50(&self) -> isize { diff --git a/lib_efo/src/stats/implementations.rs b/lib_efo/src/stats/implementations.rs index 508cfd2..091627e 100644 --- a/lib_efo/src/stats/implementations.rs +++ b/lib_efo/src/stats/implementations.rs @@ -9,6 +9,55 @@ use crate::stats::GenericStat; use crate::stats::ListStats; use crate::stats::OverallStats; +/// Creates a thin, deref‑able wrapper around an inner type. +#[macro_export] +macro_rules! thin_newtype { + ($name:ident, $inner:ty) => { + /// Thin wrapper that derefs to the inner type. + /// Ideal for zero‑overhead new‑type patterns. + #[repr(transparent)] + #[derive( + Debug, + Clone, + Default, + PartialEq, + Eq, + PartialOrd, + Ord, + Hash, + Serialize, + Deserialize, + Display, + )] + pub struct $name(pub $inner); + + impl std::ops::Deref for $name { + type Target = $inner; + fn deref(&self) -> &Self::Target { + &self.0 + } + } + + impl std::ops::DerefMut for $name { + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } + } + + impl From<$inner> for $name { + fn from(v: $inner) -> Self { + $name(v) + } + } + + impl From<$name> for $inner { + fn from(v: $name) -> Self { + v.0 + } + } + }; +} + /// Generates an `impl GameStat for ` where the only difference between /// multiple implementations is the visibility level. /// @@ -19,18 +68,18 @@ macro_rules! impl_game_stat { ($type:ident) => { impl GameStat for $type { fn get_value(&self) -> isize { - self.value + self.0 } fn change_value(&mut self, value: isize) { - self.value = value; + self.0 = value; } fn from_value(value: isize) -> Self where Self: Sized, { - Self { value } + Self(value) } } }; @@ -181,7 +230,7 @@ impl FromStr for StatPair { let value: isize = val_str .parse() .map_err(|_| EpochError::IllFormedStatQualifier(val_str.to_owned()))?; - Ok(StatPair(stat, stats::GenericStat { value })) + Ok(StatPair(stat, stats::GenericStat(value))) } } @@ -210,9 +259,9 @@ pub(crate) mod test { #[test] fn test_field_accessors() { let person = Person { - name: GenericStat { value: 10 }, - age: GenericStat { value: 20 }, - email: GenericStat { value: 70 }, + name: GenericStat(10), + age: GenericStat(20), + email: GenericStat(70), }; let name = person.get_field("name").unwrap(); let email = person.get_field("email").unwrap(); @@ -228,7 +277,7 @@ pub(crate) mod test { fn assert_pair_ok(input: &str, expected_stat: ListStats, expected_val: isize) { let pair = StatPair::from_str(input).expect("should parse"); assert_eq!(pair.0, expected_stat, "stat mismatch"); - assert_eq!(pair.1.value, expected_val, "value mismatch"); + assert_eq!(pair.1.0, expected_val, "value mismatch"); } #[test] fn test_stat_pair_parsing() { diff --git a/lib_efo/src/town.rs b/lib_efo/src/town.rs deleted file mode 100644 index 30d2a85..0000000 --- a/lib_efo/src/town.rs +++ /dev/null @@ -1 +0,0 @@ -//! All the structs and logic surrounding towns