diff --git a/Cargo.lock b/Cargo.lock index a70b004..ff5f783 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -121,6 +121,12 @@ version = "2.10.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "812e12b5285cc515a9c72a5c1d3b6d46a19dac5acfef5265968c166106e31dd3" +[[package]] +name = "bumpalo" +version = "3.19.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "46c5e41b57b8bba42a04676d81cb89e9ee8e859a1a66f80a5a72e1cb76b34d43" + [[package]] name = "cfg-if" version = "1.0.4" @@ -271,6 +277,18 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "getrandom" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd" +dependencies = [ + "cfg-if", + "libc", + "r-efi", + "wasip2", +] + [[package]] name = "gimli" version = "0.32.3" @@ -325,6 +343,16 @@ dependencies = [ "syn", ] +[[package]] +name = "js-sys" +version = "0.3.83" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "464a3709c7f55f1f721e5389aa6ea4e3bc6aba669353300af094b29ffbdde1d8" +dependencies = [ + "once_cell", + "wasm-bindgen", +] + [[package]] name = "lib_efo" version = "0.1.0" @@ -338,6 +366,7 @@ dependencies = [ "serde", "serde_json", "thiserror", + "uuid", ] [[package]] @@ -412,6 +441,12 @@ dependencies = [ "memchr", ] +[[package]] +name = "once_cell" +version = "1.21.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "42f5e15c9953c5e4ccceeb2e7382a716482c34515315f7b03532b8b4e8393d2d" + [[package]] name = "once_cell_polyfill" version = "1.70.2" @@ -457,6 +492,12 @@ dependencies = [ "proc-macro2", ] +[[package]] +name = "r-efi" +version = "5.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f" + [[package]] name = "regex" version = "1.12.2" @@ -505,6 +546,12 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "rustversion" +version = "1.0.22" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b39cdef0fa800fc44525c84ccb54a029961a8215f9619753635a9c0d2538d46d" + [[package]] name = "ryu" version = "1.0.20" @@ -677,6 +724,72 @@ version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821" +[[package]] +name = "uuid" +version = "1.18.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2f87b8aa10b915a06587d0dec516c282ff295b475d94abf425d62b57710070a2" +dependencies = [ + "getrandom", + "js-sys", + "serde", + "wasm-bindgen", +] + +[[package]] +name = "wasip2" +version = "1.0.1+wasi-0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0562428422c63773dad2c345a1882263bbf4d65cf3f42e90921f787ef5ad58e7" +dependencies = [ + "wit-bindgen", +] + +[[package]] +name = "wasm-bindgen" +version = "0.2.106" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d759f433fa64a2d763d1340820e46e111a7a5ab75f993d1852d70b03dbb80fd" +dependencies = [ + "cfg-if", + "once_cell", + "rustversion", + "wasm-bindgen-macro", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-macro" +version = "0.2.106" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "48cb0d2638f8baedbc542ed444afc0644a29166f1595371af4fecf8ce1e7eeb3" +dependencies = [ + "quote", + "wasm-bindgen-macro-support", +] + +[[package]] +name = "wasm-bindgen-macro-support" +version = "0.2.106" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cefb59d5cd5f92d9dcf80e4683949f15ca4b511f4ac0a6e14d4e1ac60c6ecd40" +dependencies = [ + "bumpalo", + "proc-macro2", + "quote", + "syn", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-shared" +version = "0.2.106" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cbc538057e648b67f72a982e708d485b2efa771e1ac05fec311f9f63e5800db4" +dependencies = [ + "unicode-ident", +] + [[package]] name = "winapi-util" version = "0.1.11" @@ -774,3 +887,9 @@ name = "windows_x86_64_msvc" version = "0.53.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d6bbff5f0aada427a1e5a6da5f1f98158182f26556f345ac9e04d36d0ebed650" + +[[package]] +name = "wit-bindgen" +version = "0.46.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f17a85883d4e6d00e8a97c586de764dabcc06133f7f1d55dce5cdc070ad7fe59" diff --git a/bin_efo/src/commands/epoch.rs b/bin_efo/src/commands/epoch.rs index a860281..2a567d2 100644 --- a/bin_efo/src/commands/epoch.rs +++ b/bin_efo/src/commands/epoch.rs @@ -9,8 +9,7 @@ use crate::{ success::{SuccessMessages, display_success}, }; use lib_efo::{ - epoch_struct::{EpochConfig, EpochId}, - epoch_traits::ConfigWritable, + epoch::{EpochConfig, EpochId, epoch_traits::ConfigWritable}, error::EpochError, }; use log::{debug, info}; @@ -73,10 +72,7 @@ fn handle_summary(args: cli_epoch::Summary, main_epoch: &mut EpochConfig) -> Res #[allow(clippy::unwrap_used)] // The epoch_id must exists at this point if let Some(epoch) = main_epoch.list_existing_epochs.get_mut(&epoch_id).unwrap() { epoch.summary = args.summary.clone(); - epoch.save_with_context( - "Saving new summary", - &lib_efo::epoch_struct::SaveMode::Erase, - )?; + epoch.save_with_context("Saving new summary", &lib_efo::epoch::SaveMode::Erase)?; display_success(&SuccessMessages::ChangedSummary(epoch_id, args.summary)); } @@ -133,7 +129,7 @@ fn handle_switch(args: cli_epoch::Switch, main_epoch: &mut EpochConfig) -> Resul main_epoch.save_with_context( "Saving modified epoch config", - &lib_efo::epoch_struct::SaveMode::Erase, + &lib_efo::epoch::SaveMode::Erase, )?; display_success(&SuccessMessages::EpochSwitchSuccess(target)); Ok(()) @@ -166,9 +162,11 @@ fn handle_next(_args: cli_epoch::Next, main_epoch: &mut EpochConfig) -> Result<( Err(AppError::Epoch(EpochError::FutureEpochExist)) } else { let new_epoch = main_epoch.compute_next()?; + let new_id = new_epoch.epoch_id; // Insert new epoch - main_epoch.insert_and_save(new_epoch, &lib_efo::epoch_struct::SaveMode::DoNotErase)?; + main_epoch.insert_and_save(new_epoch, &lib_efo::epoch::SaveMode::DoNotErase)?; + display_success(&SuccessMessages::EpochNextSuccess(current_id, new_id)); Ok(()) } } @@ -239,16 +237,14 @@ fn handle_taging(args: cli_epoch::Tag, main_epoch: &mut EpochConfig) -> Result<( .unwrap() { current_epoch_info.tags.push(args.tag.clone()); - current_epoch_info.save_with_context( - "Saving modified epoch", - &lib_efo::epoch_struct::SaveMode::Erase, - )?; + current_epoch_info + .save_with_context("Saving modified epoch", &lib_efo::epoch::SaveMode::Erase)?; main_epoch .tags .insert(args.tag.clone(), main_epoch.epoch_id); main_epoch.save_with_context( "Saving modified main config", - &lib_efo::epoch_struct::SaveMode::Erase, + &lib_efo::epoch::SaveMode::Erase, )?; Ok(()) } else { diff --git a/bin_efo/src/commands/epoch/cli_epoch.rs b/bin_efo/src/commands/epoch/cli_epoch.rs index f768f86..de436e6 100644 --- a/bin_efo/src/commands/epoch/cli_epoch.rs +++ b/bin_efo/src/commands/epoch/cli_epoch.rs @@ -16,7 +16,7 @@ #![warn(missing_docs, clippy::missing_docs_in_private_items)] use clap::{Args, Subcommand}; -use lib_efo::epoch_struct::EpochIdentifier; +use lib_efo::epoch::EpochIdentifier; /// Top‑level sub‑command for the `efo epoch` command. /// diff --git a/bin_efo/src/commands/init.rs b/bin_efo/src/commands/init.rs index e7b7379..fdb6bc2 100644 --- a/bin_efo/src/commands/init.rs +++ b/bin_efo/src/commands/init.rs @@ -13,8 +13,7 @@ use clap::Args; use lib_efo::{ - epoch_struct::{EpochConfig, EpochInfo}, - epoch_traits::ConfigWritable, + epoch::{EpochConfig, EpochInfo, epoch_traits::ConfigWritable}, error::EpochError, }; use std::fs::read_dir; @@ -55,7 +54,7 @@ pub fn init(args: &InitCmd) -> Result<(), AppError> { epoch_config .save_with_context( "Creatig initial config", - &lib_efo::epoch_struct::SaveMode::DoNotErase, + &lib_efo::epoch::SaveMode::DoNotErase, ) .map_err(|_| EpochError::AlreadyInitialized { advice: Some( @@ -77,7 +76,7 @@ fn init_epoch(_args: &InitCmd) -> Result<(), AppError> { _ = empty.create_subfolders(); empty.save_with_context( "Creating empty epoch file 0", - &lib_efo::epoch_struct::SaveMode::DoNotErase, + &lib_efo::epoch::SaveMode::DoNotErase, )?; Ok(()) } diff --git a/bin_efo/src/success.rs b/bin_efo/src/success.rs index cb1e53b..440e218 100644 --- a/bin_efo/src/success.rs +++ b/bin_efo/src/success.rs @@ -1,22 +1,25 @@ //! List of all success messages possible use derive_more::Display; -use lib_efo::epoch_struct::EpochId; +use lib_efo::epoch::EpochId; #[derive(Display, Clone, Debug)] #[allow(missing_docs, clippy::missing_docs_in_private_items)] pub enum SuccessMessages { #[display("Switched to epoch {_0}")] - EpochSwitchSuccess(lib_efo::epoch_struct::EpochId), + EpochSwitchSuccess(lib_efo::epoch::EpochId), #[display("All future events deleted – back to epoch {_0}")] - DeletedAllFutureEvents(lib_efo::epoch_struct::EpochId), + DeletedAllFutureEvents(lib_efo::epoch::EpochId), #[display("The folder was initialized as an epoch folder")] FolderInitializedSuccessfully(&'static str), #[display("Changed the summary of epoch {_0} with: '{_1}'")] ChangedSummary(EpochId, String), + + #[display("Successfully computed the new epoch. The current epoch is now {_1} (was {_0})")] + EpochNextSuccess(EpochId, EpochId), } /// Display the success message to stdout diff --git a/lib_efo/Cargo.toml b/lib_efo/Cargo.toml index d9e38e8..291afa5 100644 --- a/lib_efo/Cargo.toml +++ b/lib_efo/Cargo.toml @@ -13,3 +13,4 @@ env_logger = {workspace = true} log = {workspace = true} derive_more = {workspace = true} cli-table = "0.5.0" +uuid = { version = "1.18.1", features = ["serde", "v4"] } diff --git a/lib_efo/src/epoch_struct.rs b/lib_efo/src/epoch.rs similarity index 99% rename from lib_efo/src/epoch_struct.rs rename to lib_efo/src/epoch.rs index d197a85..7cc3713 100644 --- a/lib_efo/src/epoch_struct.rs +++ b/lib_efo/src/epoch.rs @@ -33,6 +33,7 @@ pub use epoch_config::EpochConfig; pub mod epoch_info; pub use epoch_info::EpochInfo; +pub mod epoch_traits; // TODO[5]: Try to load from a config and have it inserted as a backup /// The subfolder naming convention diff --git a/lib_efo/src/epoch_struct/epoch_config.rs b/lib_efo/src/epoch/epoch_config.rs similarity index 97% rename from lib_efo/src/epoch_struct/epoch_config.rs rename to lib_efo/src/epoch/epoch_config.rs index 217941c..27117a0 100644 --- a/lib_efo/src/epoch_struct/epoch_config.rs +++ b/lib_efo/src/epoch/epoch_config.rs @@ -10,7 +10,10 @@ //! The world data and all event logs belong to the individual epoch //! directories and are **not** part of this file. -use crate::epoch_traits::ConfigWritable; +use crate::epoch::{ + EpochId, EpochIdentifier, EpochInfo, MAIN_NAME, SUBFOLDER_NAMING, SaveMode, + epoch_traits::ConfigWritable, +}; use std::{ collections::HashMap, fs::{read_to_string, remove_dir_all}, @@ -20,14 +23,7 @@ use std::{ use log::{info, warn}; use serde::{Deserialize, Serialize}; -use crate::{ - epoch_struct::{ - EpochId, EpochIdentifier, MAIN_NAME, SUBFOLDER_NAMING, SaveMode, epoch_info::EpochInfo, - }, - epoch_traits::Prettiable, - error::EpochError, - io_err_with_help, -}; +use crate::{epoch::epoch_traits::Prettiable, error::EpochError, io_err_with_help}; /// The file written to *.epochconfig* that tells the CLI which /// epoch folder is the “current” one. diff --git a/lib_efo/src/epoch_struct/epoch_info.rs b/lib_efo/src/epoch/epoch_info.rs similarity index 94% rename from lib_efo/src/epoch_struct/epoch_info.rs rename to lib_efo/src/epoch/epoch_info.rs index 7d28e9c..b7fb7f1 100644 --- a/lib_efo/src/epoch_struct/epoch_info.rs +++ b/lib_efo/src/epoch/epoch_info.rs @@ -12,8 +12,10 @@ use serde::{Deserialize, Serialize}; use std::fs::create_dir_all; use crate::{ - epoch_struct::{self, EpochId, SUB_NAME, SUBFOLDER_NAMING, TagList}, - epoch_traits::{ConfigWritable, Prettiable}, + epoch::{ + EpochId, SUB_NAME, SUBFOLDER_NAMING, TagList, + epoch_traits::{ConfigWritable, Prettiable}, + }, error::EpochError, io_err_with_help, }; @@ -58,7 +60,7 @@ impl Prettiable for EpochInfo {} impl Default for EpochInfo { fn default() -> Self { Self { - epoch_id: epoch_struct::EpochId::new(0), + epoch_id: EpochId::new(0), rng_seed: 0, tags: TagList::new(), summary: String::new(), diff --git a/lib_efo/src/epoch_traits.rs b/lib_efo/src/epoch/epoch_traits.rs similarity index 98% rename from lib_efo/src/epoch_traits.rs rename to lib_efo/src/epoch/epoch_traits.rs index 85e16d9..ac7ec34 100644 --- a/lib_efo/src/epoch_traits.rs +++ b/lib_efo/src/epoch/epoch_traits.rs @@ -9,7 +9,7 @@ use cli_table::{Style, Table, WithTitle}; use serde::Serialize; use std::{fmt::Display, fs::File, io::Write}; -use crate::{epoch_struct::SaveMode, error::EpochError}; +use crate::{epoch::SaveMode, error::EpochError}; /// Elements that can be compared with another instance to produce a diff. pub trait Diffable {} diff --git a/lib_efo/src/error.rs b/lib_efo/src/error.rs index dd660b4..d0ad190 100644 --- a/lib_efo/src/error.rs +++ b/lib_efo/src/error.rs @@ -14,7 +14,7 @@ use std::{num::ParseIntError, path::PathBuf}; use thiserror::Error; -use crate::epoch_struct::EpochId; +use crate::epoch::EpochId; use miette::Diagnostic; /// Errors that can be returned by the storage layer. @@ -229,12 +229,6 @@ pub enum UserErrors { /// Helper macro to convert a `std::io::Error` into an `EpochError::Io` /// with an attached help message. /// -/// ```rust -/// # use lib_efo::error::io_err_with_help; -/// let result: Result<(), std::io::Error> = std::fs::read_to_string("does_not_exist").map(|_| ()); -/// let err = io_err_with_help!(result, "Make sure the file exists"); -/// ``` -/// /// The macro captures the current line number for debugging purposes. #[macro_export] macro_rules! io_err_with_help { diff --git a/lib_efo/src/lib.rs b/lib_efo/src/lib.rs index 5c0ffe5..a9a8e92 100644 --- a/lib_efo/src/lib.rs +++ b/lib_efo/src/lib.rs @@ -20,8 +20,9 @@ #![warn(missing_docs, clippy::missing_docs_in_private_items)] #![deny(clippy::unwrap_used)] -pub mod epoch_struct; -pub mod epoch_traits; +pub mod epoch; +pub mod stats; +pub mod town; #[macro_use] pub mod error; pub mod utils; diff --git a/lib_efo/src/stats.rs b/lib_efo/src/stats.rs new file mode 100644 index 0000000..0cd8903 --- /dev/null +++ b/lib_efo/src/stats.rs @@ -0,0 +1,485 @@ +//! Module holing all stats and methods to use them + +#![allow(dead_code)] + +use uuid::Uuid; +mod implementations; + +/// Statistics that describe the population of a city and its social climate. +/// +/// The struct is split into four logical groups: +/// * **Core metrics** – values that change every turn and drive the city’s behaviour. +/// * **Derived metrics** – calculated from the core metrics and other game data. +/// * **Hidden metrics** – internal state that influences derived values but is not exposed directly to the player. +/// * **Resource & skill metrics** – affect production and the city’s efficiency. +/// +/// All statistics are represented by custom wrappers (`PrimaryStat`, `InferredStat`, …) to keep +/// type‑safety and to indicate how they are normally updated. +struct Demographics { + // ──────────────────────────────────────────────────────────────────────────────── + // 1. Core metrics – the “raw” population data + // ──────────────────────────────────────────────────────────────────────────────── + /// Population count + /// + /// *Effect*: Drives resource consumption and output capacity. + /// *Source*: Updated by the growth/decay formulas each turn. + population: PrimaryStat, + + /// Growth rate of the population (per‑turn change). + /// + /// *Effect*: Forecasts future needs and indicates potential unrest. + /// *Source*: Derivative of `population`, `happiness`, and `stability`. + growth_rate: PrimaryStat, + + /// Crime level of the city. + /// + /// *Effect*: Can trigger riots and lower stability. + /// *Source*: Result of the crime function (often influenced by class disparity and law enforcement). + crime: PrimaryStat, + + /// Overall health of the population. + /// + /// *Effect*: Affects population size and can generate unrest. + /// *Source*: Output of the health function (influenced by sanitation, disease spread, etc.). + health: PrimaryStat, + + /// Base skill of the populace (e.g., general craftsmanship). + /// + /// *Effect*: Determines how efficiently the city can produce goods. + /// *Source*: Global slider set by the player; may be modified by education or tech bonuses. + skill: PrimaryStat, + + // ──────────────────────────────────────────────────────────────────────────────── + // 2. Derived metrics – calculated from the core data + // ──────────────────────────────────────────────────────────────────────────────── + /// Overall “demographics” score. + /// + /// *Effect*: Used as a weighting factor for major random events (e.g., disasters, hero visits). + /// *Source*: Inferred from the primary metrics, with a heavy emphasis on `population` and `unrest`. + demographics: InferredStat, + + /// Expected consumption of resources. + /// + /// *Effect*: Drives the city’s production targets and food/water needs. + /// *Source*: `consumption = f(population, class distribution, technology level)`. + consumption: InferredStat, + + /// Level of social unrest. + /// + /// *Effect*: Predicts riots, rebellions, tax evasion, and other disruptive behaviour. + /// *Source*: `unrest = f(happiness, crime, war, stability)`. + unrest: InferredStat, + + // ──────────────────────────────────────────────────────────────────────────────── + // 3. Hidden metrics – internal state not directly exposed + // ──────────────────────────────────────────────────────────────────────────────── + /// Base happiness of the population (internal scale). + /// + /// *Effect*: Influences productivity, tax compliance, and the calculation of `unrest`. + /// *Source*: Output of the happiness function (affected by class, war, and infrastructure). + happiness: HiddenStat, + + /// Base level of fear among citizens (internal scale). + /// + /// *Effect*: Contributes to `unrest`, crime, and population growth rate. + /// *Source*: Result of monster encounters, external threats, and environmental hazards. + fear: HiddenStat, +} +/// Statistics that describe the city’s economic health and its impact on the empire. +/// +/// The fields are divided into three groups: +/// * **Core metrics** – the raw values that the player can control or that the engine updates. +/// * **Derived metrics** – numbers calculated from the core metrics (often the ones displayed to the player). +/// * **Hidden metrics** – internal helpers that drive the derived values but are not exposed to the UI. +struct Economics { + // ──────────────────────────────────────── + // 1. Core metrics – raw, player‑controlled values + // ──────────────────────────────────────── + /// Amount of food produced by the city. + /// + /// *Effect*: Food is required to keep the population alive and productive. + /// *Source*: `food = farm_yield + tech_level`. + food: PrimaryStat, + + /// Strength of the city’s industry. + /// + /// *Effect*: Drives tax revenue and the ability to produce units. + /// *Source*: `industry = factory_output + tech_level`. + industry: PrimaryStat, + + /// Scientific output of the city. + /// + /// *Effect*: Determines how fast research is completed. + /// *Source*: `science = research_center_output + tech_level`. + science: PrimaryStat, + + /// Revenue collected through taxation. + /// + /// *Effect*: Funds city upkeep and projects. + /// *Source*: `tax = tax_rate × wealth × (1 – evasion)`. + tax: PrimaryStat, + + /// Debt / budget deficit of the city. + /// + /// *Effect*: Affects stability and population growth. + /// *Source*: Result of budget calculations; naturally decays if `eco_power` stays high. + debt: PrimaryStat, + + /// Trade volume / exports generated by the city. + /// + /// *Effect*: Influences influence and wealth. + /// *Source*: `trade = trade_network_output`. + trade: PrimaryStat, + + // ──────────────────────────────────────── + // 2. Derived metrics – calculated from core data + // ──────────────────────────────────────── + /// Overall economic power of the city. + /// + /// *Effect*: Used to rank the city’s importance within the empire. + /// *Source*: `eco_power = wealth × stability × influence`. + eco_power: InferredStat, + + /// Net monetary output – the city’s “wealth” or GDP. + /// + /// *Effect*: Determines the city’s overall financial health. + /// *Source*: `wealth = tax + trade + industry_profits`. + wealth: InferredStat, + + // ──────────────────────────────────────── + // 3. Hidden metrics – internal helpers + // ──────────────────────────────────────── + /// Cost of maintaining the city’s infrastructure. + /// + /// *Effect*: Drain on the budget (reduces available funds for projects). + /// *Source*: `infra_cost = cost_of_wonders + cost_of_roads + ...`. + infra_cost: InferredStat, +} +/// Statistics that govern the city’s cultural life and its influence on the empire. +/// +/// The fields are grouped into: +/// * **Core metrics** – the raw outputs that the player can build into. +/// * **Derived metrics** – values calculated from the core metrics (often the ones displayed to the player). +/// * **Hidden metrics** – internal helpers that help derive the derived values (none in this struct, but the pattern is kept for consistency). +struct Social { + // ───────────────────────────────────────────────────────────── + // 1. Core metrics – directly produced by the city + // ───────────────────────────────────────────────────────────── + /// Cultural output from arts, theatres, museums, etc. + /// + /// *Effect*: Drives tourism, prestige, and overall happiness. + /// *Source*: `culture = Σ(cultural_building_output)`. + culture: PrimaryStat, + + /// Religious influence from temples, churches, etc. + /// + /// *Effect*: Affects stability and political influence. + /// *Source*: `religion = Σ(religious_building_output)`. + religion: PrimaryStat, + + /// Level of education/literacy in the city. + /// + /// *Effect*: Improves productivity, science output, and reduces unrest. + /// *Source*: `education = Σ(education_building_output)`. + education: PrimaryStat, + + // ───────────────────────────────────────────────────────────── + // 2. Derived metrics – calculated from core data + // ───────────────────────────────────────────────────────────── + /// Tourism revenue generated by the city’s attractions. + /// + /// *Effect*: Provides an additional income stream. + /// *Source*: `tourism = number_of_tourists × price_per_tourist`. + tourism: PrimaryStat, + + /// Overall social prestige of the city. + /// + /// *Effect*: Determines the city’s standing in the empire and in diplomatic relations. + /// *Source*: `social = f(culture, religion, education, influence)` (the exact formula is hidden but inferred from the other values). + social: InferredStat, + + /// Cultural influence over the surrounding region. + /// + /// *Effect*: Increases the city’s sway in the empire and can grant diplomatic bonuses. + /// *Source*: `influence = culture × population`. + influence: InferredStat, +} + +/// Statistics that describe a city’s armed forces and its battlefield posture. +/// +/// The fields are split into two logical groups: +/// * **Core metrics** – raw numbers that the player can influence with units, training, or infrastructure. +/// * **Derived metrics** – values calculated each turn from the core metrics (the ones most players will see). +/// +/// All stats use wrapper types (`PrimaryStat`, `InferredStat`) so that the compiler can enforce +/// that only the correct kinds of values are combined in formulas. +struct Military { + // ───────────────────────────────────────────────── + // 1. Core metrics – the raw, game‑state numbers + // ───────────────────────────────────────────────── + /// Number of battle‑ready units (size, type, equipment, etc.). + /// + /// *Effect*: Determines the city’s direct defensive and offensive capability. + /// *Source*: Sum of all units in the army list that are trained and equipped. + army: PrimaryStat, + + /// Composite strength of the army (tech, training, equipment). + /// + /// *Effect*: Adds to combat power in battles and determines the required force to defeat the enemy. + /// *Source*: `strength = Σ(unit_strength) × tech_bonus × training_bonus`. + strength: PrimaryStat, + + /// Readiness/morale of the forces. + /// + /// *Effect*: Modifies the actual combat effectiveness in battles. + /// *Source*: Output of the morale function, which may depend on recent victories, supply levels, etc. + readiness: PrimaryStat, + + /// Defensive bonus from fortifications (walls, towers, etc.). + /// + /// *Effect*: Adds a defensive multiplier to the city’s overall defense rating. + /// *Source*: `fortification = Σ(fortification_building_bonus)`. + fortification: PrimaryStat, + + /// Strategic importance of the city’s location. + /// + /// *Effect*: Influences enemy targeting decisions and the city’s priority for defense upgrades. + /// *Source*: `strategic_value = f(proximity_to_borders, resource_nodes, transport_hubs)`. + strategic_value: PrimaryStat, + + // ───────────────────────────────────────────────── + // 2. Derived metrics – calculated from the core data + // ───────────────────────────────────────────────── + /// Overall threat level facing the city. + /// + /// *Effect*: Predicts the likelihood of being attacked and can trigger early warning alerts. + /// *Source*: `threat = (enemy_proximity + enemy_strength) / defense`. + threat: InferredStat, + + // ───────────────────────────────────────────────── + // 3. Main combined metric – the city’s total military power + // ───────────────────────────────────────────────── + /// Combined military power used for empire‑wide rankings and event weighting. + /// + /// *Effect*: The “size” of the city’s armed forces in the eyes of the empire. + /// *Source*: `military = f(army, strength, readiness, fortification, strategic_value)`. + military: InferredStat, +} +/// Statistics that describe a city’s built environment and its ability to support the population. +/// +/// The fields are separated into two logical groups: +/// * **Core infrastructure** – the raw assets the player builds and upgrades. +/// * **Derived infrastructure** – numbers calculated each turn from the core assets (the ones you’ll see in the UI). +/// +/// All stats use the wrapper types (`PrimaryStat`, `InferredStat`) so that the compiler can +/// keep the formulas type‑safe and easy to reason about. +struct Infrastructure { + // ─────────────────────────────────────────────────────────── + // 1. Core infrastructure – the raw, player‑controlled values + // ─────────────────────────────────────────────────────── + /// Communication network strength. + /// + /// *Effect*: Enables espionage, real‑time resource monitoring, and can unlock advanced building upgrades. + /// *Source*: `communications = Σ(communication_building_bonus)`. + communications: PrimaryStat, + + /// Total water and electricity supply capacity. + /// + /// *Effect*: Required for industry output and maintaining population health. + /// *Source*: `needs = Σ(supply_unit_output)`. + needs: PrimaryStat, + + /// Total amount of waste / pollution produced by the city. + /// + /// *Effect*: Reduces health and happiness, can trigger unrest if too high. + /// *Source*: `pollution = Σ(building_pollution)`. + pollution: PrimaryStat, + + /// Available building slots (housing, industry, etc.). + /// + /// *Effect*: Caps how many new structures can be added until more slots are built. + /// *Source*: `space = Σ(slot_building_capacity)`. + space: PrimaryStat, + + // ─────────────────────────────────────────────────────────── + // 2. Derived infrastructure – calculated from core data + // ─────────────────────────────────────────────────────── + /// Overall connectivity of the city (roads, rails, ports, etc.). + /// + /// *Effect*: Drives trade volume, military supply lines, and logistics efficiency. + /// *Source*: `connectivity = Σ(link_strength)`. + connectivity: InferredStat, + + /// Total infrastructure power of the city. + /// + /// *Effect*: Used to rank the city’s importance within the empire and to calculate event weights. + /// *Source*: `infrastructure = f(connectivity, communications, needs, pollution, space)`. + infrastructure: InferredStat, +} + +/// Strategic context and meta‑data for a city. +/// +/// The struct is divided into three logical parts: +/// * **Location & spatial data** – hidden values that feed map‑based calculations. +/// * **Strategic positioning** – meta‑information that determines specialization, trade, and defense. +/// * **Political & relational data** – things that influence diplomacy, governance, and inter‑city links. +/// +/// All fields use the wrapper types (`HiddenStat`, `PrimaryStat`, `InferredStat`) so the compiler +/// can enforce that only the correct kinds of values are combined in formulas. +struct Strategics { + // ──────────────────────────────────────── + // 1. Location & spatial data (hidden) + // ──────────────────────────────────────── + /// Cartesian coordinates of the city on the world map. + /// + /// *Effect*: Used for distance calculations, visibility, and map‑based event logic. + /// *Source*: Raw coordinates supplied by the map generator. + position: HiddenStat, + + /// Euclidean distance to the empire’s capital. + /// + /// *Effect*: Influences trade costs, supply line strength, and early warning range. + /// *Source*: `distance_to_capital = dist(position, capital_position)`. + distance_to_capital: HiddenStat, + + /// List of nearby resource nodes (mines, forests, farms, etc.). + /// + /// *Effect*: Drives the city’s specialization and determines the default output mix. + /// *Source*: `ressources = filter(resource_list, distance ≤ detection_radius)`. + ressources: HiddenStat, + + /// The city’s chosen specialization tag (e.g., “Agricultural Hub”, “Industrial Center”). + /// + /// *Effect*: Sets the default output multipliers for production. + /// *Source*: `specialisation = tag_assigned_by_player_or_ai`. + specialisation: HiddenStat, + + // ──────────────────────────────────────── + // 2. Strategic positioning (hidden + public) + // ──────────────────────────────────────── + /// Current governor or leader assigned to the city. + /// + /// *Effect*: Adds personal bonuses and can modify policies or diplomatic stance. + /// *Source*: `governor = selected_leader_uuid`. + governor: Uuid, + + /// The city’s classification (capital, trade hub, frontier post, etc.). + /// + /// *Effect*: Alters base production, tax rates, and certain event probabilities. + /// *Source*: `category = tag_assigned_by_player_or_ai`. + category: PrimaryStat, + + /// The faction or empire to which the city currently belongs. + /// + /// *Effect*: Determines diplomatic relations, war status, and access to empire‑wide bonuses. + /// *Source*: `faction = current_faction_uuid`. + faction: Uuid, + + // ──────────────────────────────────────── + // 3. Links & relational data + // ──────────────────────────────────────── + /// UIDs of all entities the city is linked to (roads, trade routes, alliances, war declarations, etc.). + /// + /// *Effect*: Influences economic, military, and diplomatic interactions. + /// *Source*: `links = Vec` collected from the city’s network manager. + links: Vec, + + // ──────────────────────────────────────── + // 4. Meta‑statistics (derived) + // ──────────────────────────────────────── + /// Prestige / reputation of the city in the eyes of the empire and foreign powers. + /// + /// *Effect*: Affects foreign relations, diplomatic offers, and event weighting. + /// *Source*: `prestige = f(culture, trade, military)`. + prestige: InferredStat, +} + +// --- STAT TYPES --------------------------------------------------------------- +// The game distinguishes four kinds of statistics. +// The *visibility* of a stat determines whether it is shown to the player +// (Primary / Inferred) and whether the player can change it manually +// (Primary / Hidden). +// +// All four stat structs simply wrap a signed integer, but they all +// implement the same behaviour via the `GameStat` trait below. + +/// A stat that is shown to the player *and* can be modified manually. +#[allow(missing_docs)] +pub struct PrimaryStat { + pub value: isize, +} + +/// A stat that is hidden from the recap UI, but still user‑editable. +#[allow(missing_docs)] +pub struct HiddenStat { + pub value: isize, +} + +/// A stat that is calculated from other data, shown to the player, +/// but not directly editable. +#[allow(missing_docs)] +pub struct InferredStat { + pub value: isize, +} + +/// A stat that is calculated from other data and hidden from the UI. +#[allow(missing_docs)] +pub struct HiddenInferredStat { + pub value: isize, +} + +// --- VISIBILITY ENUM ------------------------------------------------------------ + +/// The underlying visibility level for a stat. +/// The enum is used by `GameStat::visibility` to let the UI decide +/// whether to display a particular stat or not. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum VisibilityLevel { + /// Primary stat – shown & editable. + Primary, + /// Hidden stat – not shown, editable. + Hidden, + /// Inferred stat – shown, calculated. + Inferred, + /// Hidden inferred stat – not shown, calculated. + HiddenInferred, +} + +/// --- 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. +pub trait GameStat { + /// Convert the raw integer to a 50‑point scale. + fn to_50(&self) -> isize { + (self.get_value().clamp(0, 70) - 10).min(50) + } + + /// Convert the raw integer to a 10‑point scale. + fn to_10(&self) -> isize { + self.to_50() / 5 + } + + /// Return the raw integer value, always bound to 0-70 + fn get_value(&self) -> isize; + + /// Return the stat’s visibility level. + fn visibility(&self) -> VisibilityLevel; + + /// Return the raw integer value, always bound to 0-70 + fn change_value(&mut self, value: isize); + + /// Create a Gamestat from it's underlying value + fn from_value(value: isize) -> Self + where + Self: Sized; +} +/// Trait for objects that can expose a stat via a string key. +/// The trait returns a *boxed* trait object so callers do not need to know +/// the concrete type that was stored. +pub trait Accessible { + /// Return the requested stat as a `Box`. + /// `None` if the key does not exist. + fn get_val(&self, key: &str) -> Option>; +} diff --git a/lib_efo/src/stats/implementations.rs b/lib_efo/src/stats/implementations.rs new file mode 100644 index 0000000..156d3e3 --- /dev/null +++ b/lib_efo/src/stats/implementations.rs @@ -0,0 +1,159 @@ +//! All traits implementatition for the main structs are deffered here + +use crate::stats::VisibilityLevel; +use crate::stats::{ + Demographics, Economics, GameStat, HiddenInferredStat, HiddenStat, InferredStat, + Infrastructure, Military, PrimaryStat, Social, +}; + +/// Generates an `impl GameStat for ` where the only difference between +/// multiple implementations is the visibility level. +/// +/// # Parameters +/// * `$type`: the concrete type that implements `GameStat` +/// * `$vis`: the enum variant of `VisibilityLevel` to return +macro_rules! impl_game_stat { + ($type:ident, $vis:ident) => { + impl GameStat for $type { + fn get_value(&self) -> isize { + self.value + } + + fn visibility(&self) -> VisibilityLevel { + VisibilityLevel::$vis + } + + fn change_value(&mut self, value: isize) { + self.value = value; + } + + fn from_value(value: isize) -> Self + where + Self: Sized, + { + Self { value } + } + } + }; +} + +impl_game_stat!(PrimaryStat, Primary); +impl_game_stat!(HiddenStat, Hidden); +impl_game_stat!(InferredStat, Inferred); +impl_game_stat!(HiddenInferredStat, HiddenInferred); + +/// A field accessor to be able to modify fields on the fly +macro_rules! field_accessor { + ($name:ident { $($field:ident),* }) => { + impl $name { + fn get_field(&self, key: &str) -> Option<&dyn GameStat> { + match key { + $( + stringify!($field) => Some(&self.$field), + )* + _ => None, + } + } + + fn get_field_mut(&mut self, key: &str) -> Option<&mut dyn GameStat> { + match key { + $( + stringify!($field) => Some(&mut self.$field), + )* + _ => None, + } + } + } + }; +} + +field_accessor!(Demographics { + population, + growth_rate, + crime, + health, + skill, + demographics, + consumption, + unrest, + happiness, + fear +}); +field_accessor!(Economics { + food, + industry, + science, + tax, + debt, + trade, + eco_power, + wealth, + infra_cost +}); +field_accessor!(Social { + culture, + religion, + education, + tourism, + social, + influence +}); + +field_accessor!(Military { + army, + strength, + readiness, + fortification, + strategic_value, + threat, + military +}); +field_accessor!(Infrastructure { + communications, + needs, + pollution, + space, + connectivity, + infrastructure +}); +// field_accessor!(Strategics { +// position, +// distance_to_capital, +// ressources, +// specialisation, +// governor, +// category, +// faction, +// links, +// prestige +// }); + +#[cfg(test)] +pub(crate) mod test { + #![allow(clippy::unwrap_used)] + use crate::stats::GameStat; + use crate::stats::PrimaryStat; + + struct Person { + name: PrimaryStat, + age: PrimaryStat, + email: PrimaryStat, + } + + field_accessor!(Person { name, age, email }); + + #[test] + fn bob() { + let person = Person { + name: PrimaryStat { value: 10 }, + age: PrimaryStat { value: 20 }, + email: PrimaryStat { value: 70 }, + }; + let name = person.get_field("name").unwrap(); + let email = person.get_field("email").unwrap(); + let age = person.get_field("age").unwrap(); + assert_eq!(name.to_50(), 0); + assert_eq!(age.to_50(), 10); + assert_eq!(email.to_50(), 50); + } +} diff --git a/lib_efo/src/town.rs b/lib_efo/src/town.rs new file mode 100644 index 0000000..30d2a85 --- /dev/null +++ b/lib_efo/src/town.rs @@ -0,0 +1 @@ +//! All the structs and logic surrounding towns