From 80f3c064999c9de9fec11804eec6c83d3fa586de Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Mon, 8 Dec 2025 23:27:44 +0100 Subject: [PATCH] Most of entities addentum --- bin_efo/src/commands.rs | 2 +- bin_efo/src/commands/chr.rs | 320 ++++++++++++++++++++++++++ bin_efo/src/commands/epoch.rs | 10 +- bin_efo/src/main.rs | 14 +- bin_efo/src/success.rs | 9 + lib_efo/src/entity.rs | 7 +- lib_efo/src/entity/implementations.rs | 24 +- lib_efo/src/epoch.rs | 7 + lib_efo/src/epoch/epoch_config.rs | 98 +++++++- lib_efo/src/epoch/epoch_info.rs | 18 +- lib_efo/src/error.rs | 32 ++- lib_efo/src/stats.rs | 37 ++- lib_efo/src/utils.rs | 52 +++-- 13 files changed, 600 insertions(+), 30 deletions(-) create mode 100644 bin_efo/src/commands/chr.rs diff --git a/bin_efo/src/commands.rs b/bin_efo/src/commands.rs index 83357b0..2786614 100644 --- a/bin_efo/src/commands.rs +++ b/bin_efo/src/commands.rs @@ -8,6 +8,7 @@ #![warn(missing_docs, clippy::missing_docs_in_private_items)] +pub mod chr; pub mod epoch; pub mod generate; pub mod init; @@ -16,4 +17,3 @@ pub mod show; // pub mod utils; // pub mod event; // pub mod town; -// pub mod chr; diff --git a/bin_efo/src/commands/chr.rs b/bin_efo/src/commands/chr.rs new file mode 100644 index 0000000..c408224 --- /dev/null +++ b/bin_efo/src/commands/chr.rs @@ -0,0 +1,320 @@ +//! Module handling the creation of characters + +use lib_efo::epoch::epoch_traits::{ConfigWritable, Diffable}; +use lib_efo::stats::Symbols; + +use clap::{Args, Subcommand}; +use lib_efo::Displayable; +use lib_efo::utils::RngLevel; +use lib_efo::{ + entity::Entity, + epoch::EpochConfig, + error::EpochError, + stats::{EntityType, StatPair}, +}; + +use crate::error::AppError; +use crate::success::display_success; + +/// Commands that operate on an entity. +/// +/// Each variant represents a different operation that can be performed on an +/// entity. The variant holds the arguments that are common to all operations. +#[derive(Subcommand, Debug)] +pub enum EntitySubCommands { + /// Add an entity + Add(EntityArgs), + /// Delete an entity + Del(EntityArgs), + /// Edit an existing entity + Edit(EntityArgs), + /// Find an entity by its identifier + Find(EntityArgs), + /// Show the details of an entity + Show(EntityArgs), + /// Show differences between two entities + Diff(EntityArgs), +} + +/// Arguments required for any entity operation. +/// +/// All fields are required. The `rng` field determines how unspecified stat +/// values are handled when an entity is created or edited. +#[derive(Args, Debug)] +pub struct EntityArgs { + /// Either an identifying tag or an Id + #[arg(long, group = "id")] + pub name: Option, + + /// An optional Uuid to either set or get + #[arg(long, group = "id")] + pub id: Option, + /// Non specified stat Repartition + #[arg(value_enum, default_value_t = RngLevel::Zero)] + pub rng: RngLevel, + /// All stats pairs involved + pub stats: Vec, +} + +/// Handles an entity subcommand. +/// +/// This function loads the main epoch configuration, then dispatches the +/// provided subcommand to the appropriate handler. It returns an +/// `AppError` if any operation fails. +/// +/// # Arguments +/// * `entity_sub_commands` - The subcommand chosen by the user. +/// * `e_type` - The type of entity to operate on. +/// +/// # Returns +/// A `Result` indicating success (`Ok(())`) or the encountered `AppError`. +pub fn handle_entity_creation( + entity_sub_commands: &EntitySubCommands, + e_type: &EntityType, +) -> Result<(), AppError> { + let mut main_epoch = EpochConfig::new_from_path(None)?; + match entity_sub_commands { + EntitySubCommands::Add(entity_args) => { + handle_create_entity(entity_args, e_type, &mut main_epoch) + } + EntitySubCommands::Del(entity_args) => { + handle_delete_entity(entity_args, e_type, &mut main_epoch) + } + EntitySubCommands::Edit(entity_args) => { + handle_edit_entity(entity_args, e_type, &mut main_epoch) + } + EntitySubCommands::Find(entity_args) => { + handle_find_entity(entity_args, e_type, &mut main_epoch) + } + EntitySubCommands::Show(entity_args) => { + handle_show_entity(entity_args, e_type, &mut main_epoch) + } + EntitySubCommands::Diff(entity_args) => { + handle_diff_entity(entity_args, e_type, &mut main_epoch) + } + }?; + Ok(()) +} + +/// Function handler for the diff subcommand +fn handle_diff_entity( + entity_args: &EntityArgs, + e_type: &EntityType, + main_epoch: &mut EpochConfig, +) -> Result<(), EpochError> { + // Load the epochs to diff + let id = main_epoch.epoch_id; + let id2 = main_epoch.epoch_id.add_to_epoch(-1); + main_epoch.try_load(&id)?; + main_epoch.try_load(&id2)?; + + // { + let epoch_current = unsafe { main_epoch.try_load_id(id) }?; + let epoch_past = unsafe { main_epoch.try_load_id(id2) }?; + let current_entity = find_entity(entity_args, e_type, epoch_current)?; + let past_entity = find_entity(entity_args, e_type, epoch_past)?; + + let diff = current_entity.delta(past_entity); + diff.print_full(); + + Ok(()) +} + +/// Function handler for the show subcommand +fn handle_show_entity( + entity_args: &EntityArgs, + e_type: &EntityType, + main_epoch: &mut EpochConfig, +) -> Result<(), EpochError> { + let epoch_info = main_epoch.try_load_current()?; + let e = find_entity(entity_args, e_type, epoch_info)?; + e.print_full(); + Ok(()) +} + +/// Function handler for the find subcommand +fn handle_find_entity( + entity_args: &EntityArgs, + e_type: &EntityType, + main_epoch: &mut EpochConfig, +) -> Result<(), EpochError> { + handle_show_entity(entity_args, e_type, main_epoch) +} + +/// Function handler for the edit subcommand +fn handle_edit_entity( + entity_args: &EntityArgs, + e_type: &EntityType, + main_epoch: &mut EpochConfig, +) -> Result<(), EpochError> { + let current_epoch = main_epoch.try_load_current_as_mut()?; + let vec_entities = vec_entities_mut(e_type, current_epoch); + let entity = vec_entities + .iter_mut() + .find(|e| find_by_args(e, entity_args)) + .ok_or(EpochError::EntityNotFound( + e_type.clone(), + entity_args.name.clone(), + entity_args.id.clone(), + ))?; + // TODO[new]: Modify all values + // + display_success(&crate::success::SuccessMessages::EditedEntity( + entity.name.clone(), + entity.entity_type.to_shortest(), + entity.id.to_string(), + )); + Ok(()) +} + +/// Function handler for the delete subcommand +fn handle_delete_entity( + entity_args: &EntityArgs, + e_type: &EntityType, + main_epoch: &mut EpochConfig, +) -> Result<(), EpochError> { + let epoch_info = main_epoch.try_load_current_as_mut()?; + + let vec_entities: &mut Vec = vec_entities_mut(e_type, epoch_info); + let index = vec_entities + .iter() + .position(|e| find_by_args(e, entity_args)) + .ok_or(EpochError::EntityNotFound( + e_type.clone(), + entity_args.name.clone(), + entity_args.id.clone(), + ))?; + + let e = vec_entities.swap_remove(index); + + display_success(&crate::success::SuccessMessages::DeletedEntity( + e.name, + e.entity_type.to_shortest(), + e.id.to_string(), + )); + Ok(()) +} + +/// Function handler for the create subcommand +fn handle_create_entity( + entity_args: &EntityArgs, + e_type: &EntityType, + main_epoch: &mut EpochConfig, +) -> Result<(), EpochError> { + let epoch_info = main_epoch.try_load_current_as_mut()?; + let vec_entities: &mut Vec = vec_entities_mut(e_type, epoch_info); + + // TODO: Create real entity + let _ = entity_args; + let e = Entity::default(); + + let message = &crate::success::SuccessMessages::CreatedEntity( + e.name.clone(), + e.entity_type.to_shortest(), + e.id.to_string(), + ); + vec_entities.push(e); + + // No need to change main epoch that didn't change a serialized field + epoch_info.save_with_context("Created entity", &lib_efo::epoch::SaveMode::Erase)?; + display_success(message); + + Ok(()) +} + +/// Looks up an entity inside the given `epoch_info` according to the +/// supplied arguments. +/// +/// The function returns a reference to the matching entity or an +/// `EpochError::EntityNotFound` if no entity matches. +/// +/// # Arguments +/// * `entity_args` – The arguments that identify the entity. +/// * `e_type` – The type of entity to look for. +/// * `epoch_info` – The epoch that contains all entities. +/// +/// # Returns +/// * `Ok(&Entity)` – The entity that matches the arguments. +/// * `Err(EpochError::EntityNotFound)` – No matching entity was found. +fn find_entity<'a>( + entity_args: &'a EntityArgs, + e_type: &'a EntityType, + epoch_info: &'a lib_efo::epoch::EpochInfo, +) -> Result<&'a Entity, EpochError> { + vec_entities(e_type, epoch_info) + .iter() + .find(|&e| find_by_args(e, entity_args)) + .ok_or(EpochError::EntityNotFound( + e_type.clone(), + entity_args.name.clone(), + entity_args.id.clone(), + )) +} + +/// Returns a slice over the entities of the requested type from the given `EpochInfo`. +/// +/// The function matches the supplied `e_type` to the appropriate collection +/// inside `epoch_info`. For unimplemented entity types the call will panic +/// because of the `todo!()` placeholder. +/// +/// # Arguments +/// * `e_type` – The type of entities to retrieve. +/// * `epoch_info` – The epoch information containing the collections. +/// +/// # Returns +/// A reference to the vector containing the requested entities. +/// The lifetime of the returned slice is tied to that of `epoch_info`. +#[inline] +fn vec_entities<'a>( + e_type: &'a EntityType, + epoch_info: &'a lib_efo::epoch::EpochInfo, +) -> &'a Vec { + match e_type { + EntityType::Character => &epoch_info.characters, + EntityType::Player => todo!(), + EntityType::Town => &epoch_info.towns, + EntityType::Monster => todo!(), + EntityType::Blocker => todo!(), + EntityType::Event => &epoch_info.events, + } +} + +#[inline] +/// Returns a mutable slice over the entities of the requested type from the given +/// `EpochInfo`. +/// +/// Like `vec_entities`, this function selects the appropriate collection +/// based on `e_type`. Unimplemented variants will panic due to the `todo!()`. +/// +/// # Arguments +/// * `e_type` – The type of entities to retrieve. +/// * `epoch_info` – The epoch information containing the collections. +/// +/// # Returns +/// A mutable reference to the vector containing the requested entities. +/// The lifetime of the returned slice is tied to that of `epoch_info`. +fn vec_entities_mut<'a>( + e_type: &'a EntityType, + epoch_info: &'a mut lib_efo::epoch::EpochInfo, +) -> &'a mut Vec { + match e_type { + EntityType::Character => &mut epoch_info.characters, + EntityType::Player => todo!(), + EntityType::Town => &mut epoch_info.towns, + EntityType::Monster => todo!(), + EntityType::Blocker => todo!(), + EntityType::Event => &mut epoch_info.events, + } +} + +/// Helper function finding by name, note that a lot more helpers could be done to find by other criterias +fn find_by_args(entity: &Entity, entity_args: &EntityArgs) -> bool { + if let Some(id) = &entity_args.id { + entity.id.hyphenated().to_string().starts_with(id) + } else if let Some(name) = &entity_args.name { + // TODO[9]: Consider a better method + entity.name.starts_with(name) + } else { + false + } +} diff --git a/bin_efo/src/commands/epoch.rs b/bin_efo/src/commands/epoch.rs index 930d1a7..b426aea 100644 --- a/bin_efo/src/commands/epoch.rs +++ b/bin_efo/src/commands/epoch.rs @@ -70,7 +70,11 @@ fn handle_summary(args: &cli_epoch::Summary, main_epoch: &mut EpochConfig) -> Re let epoch_id = main_epoch.epoch_id; main_epoch.try_load(&epoch_id)?; #[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() { + if let Some(epoch) = main_epoch + .list_existing_epochs + .get_mut(&epoch_id) + .ok_or(EpochError::EpochHashingImpossible(file!(), line!()))? + { epoch.summary = args.summary.clone(); epoch.save_with_context("Saving new summary", &lib_efo::epoch::SaveMode::Erase)?; display_success(&SuccessMessages::ChangedSummary( @@ -126,7 +130,7 @@ fn handle_log(args: &cli_epoch::Log, main_epoch: &mut EpochConfig) -> Result<(), /// /// This helper is internal to the `epoch` sub-command. fn handle_switch(args: &cli_epoch::Switch, main_epoch: &mut EpochConfig) -> Result<(), AppError> { - let target = main_epoch.get(&args.target)?; + let target = main_epoch.get_epoch_id(&args.target)?; main_epoch.try_load(&target)?; main_epoch.epoch_id = target; @@ -237,7 +241,7 @@ fn handle_taging(args: &cli_epoch::Tag, main_epoch: &mut EpochConfig) -> Result< if let Some(current_epoch_info) = main_epoch .list_existing_epochs .get_mut(&main_epoch.epoch_id) - .unwrap() + .ok_or(EpochError::EpochHashingImpossible(file!(), line!()))? { current_epoch_info.tags.push(args.tag.clone()); current_epoch_info diff --git a/bin_efo/src/main.rs b/bin_efo/src/main.rs index 1fdb4fe..8eeb561 100644 --- a/bin_efo/src/main.rs +++ b/bin_efo/src/main.rs @@ -28,7 +28,10 @@ use std::fmt::Debug; use clap::{ArgAction, Parser, Subcommand}; use crate::{ - commands::{epoch::cli_epoch::EpochCmd, generate::GenCmd, init::InitCmd, show::ShowCmd}, + commands::{ + chr::EntitySubCommands, epoch::cli_epoch::EpochCmd, generate::GenCmd, init::InitCmd, + show::ShowCmd, + }, error::AppError, }; mod commands; @@ -66,9 +69,11 @@ enum TopLevelCmd { /// Display some elements #[command(subcommand)] Show(ShowCmd), - // Event(commands::event::EventCmd), + /// Handle characters + #[command(subcommand)] + Chr(EntitySubCommands), + // Event(commands::event::EventCmd), // Org(commands::org::OrgCmd), - // Chr(commands::chr::ChrCmd), // Town(commands::town::TownCmd), // Link(commands::link::LinkCmd), /// Generate random structures and display them @@ -112,5 +117,8 @@ fn exec_dispatch(cli: Cli) -> Result<(), AppError> { TopLevelCmd::Epoch(cmd) => commands::epoch::handle_cmd(&cmd), TopLevelCmd::Show(cmd) => commands::show::handle_show_cmd(&cmd), TopLevelCmd::Gen(cmd) => commands::generate::gen_handler(&cmd), + TopLevelCmd::Chr(cmd) => { + commands::chr::handle_entity_creation(&cmd, &lib_efo::stats::EntityType::Character) + } } } diff --git a/bin_efo/src/success.rs b/bin_efo/src/success.rs index 60ffc71..811af3f 100644 --- a/bin_efo/src/success.rs +++ b/bin_efo/src/success.rs @@ -20,6 +20,15 @@ pub enum SuccessMessages { #[display("Successfully computed the new epoch. The current epoch is now {_1} (was {_0})")] EpochNextSuccess(EpochId, EpochId), + + #[display("Successfully deleted the entity {_0} ({_1} @ {_2})")] + DeletedEntity(String, String, String), + + #[display("Successfully created the entity {_0} ({_1} @ {_2})")] + CreatedEntity(String, String, String), + + #[display("Successfully edited the entity {_0} ({_1} @ {_2})")] + EditedEntity(String, String, String), } /// Display the success message to stdout diff --git a/lib_efo/src/entity.rs b/lib_efo/src/entity.rs index 8e34625..e92d35c 100644 --- a/lib_efo/src/entity.rs +++ b/lib_efo/src/entity.rs @@ -12,6 +12,7 @@ //! use derive_more::{Add, Sub}; use serde::{Deserialize, Serialize}; +use uuid::Uuid; use crate::stats::{EntityType, MetaStats, OverallStats}; pub mod implementations; @@ -24,6 +25,10 @@ pub mod implementations; pub struct Entity { /// The name of the entity pub name: String, + + /// The global identifier for the entity + pub id: Uuid, + /// Runtime statistics that determine the entity's behaviour. /// /// These values are updated by the game loop and reflect the @@ -48,7 +53,7 @@ pub struct Entity { /// Currently an enum that distinguishes creatures, items, /// terrain, etc. It will be phased out in favor of a trait-based /// system for greater type safety. - entity_type: EntityType, + pub entity_type: EntityType, /// The lifetime of the entity within the game world. /// diff --git a/lib_efo/src/entity/implementations.rs b/lib_efo/src/entity/implementations.rs index efaf362..94bd623 100644 --- a/lib_efo/src/entity/implementations.rs +++ b/lib_efo/src/entity/implementations.rs @@ -1,11 +1,14 @@ //! Implementation of all needed traits for the Entity struct use cli_table::{Style, WithTitle, print_stdout}; -use colored::*; // [3] - colored-rs examples +use colored::*; +use uuid::Uuid; // [3] - colored-rs examples use crate::Displayable; use crate::entity::Entity; use crate::epoch::epoch_traits::Diffable; -use crate::stats::{MetaStats, Symbols}; +use crate::error::EpochError; +use crate::stats::{EntityType, MetaStats, OverallStats, Symbols}; +use crate::utils::RngLevel; // ---------- Implementation ---------- impl Displayable for Entity { @@ -126,6 +129,22 @@ impl Entity { out } + + /// Create an entity using Special Rng Levels + pub fn create_rng(e_type: EntityType, rng: &RngLevel) -> Result { + let mut r = rand::rng(); + Ok(Self { + id: Uuid::new_v4(), + stats: OverallStats::create_rng(rng, &mut r)?, + temp_stats: OverallStats::default(), + metadata: MetaStats { + prestige: 12, + ..Default::default() + }, + entity_type: e_type, + ..Default::default() + }) + } } /// Compare a field on `self` with the same field on `other`. @@ -158,6 +177,7 @@ impl Diffable for Entity { duration: self.duration.clone(), effect_nature: self.effect_nature.clone(), effect_bounds: self.effect_bounds.clone() - other.effect_bounds.clone(), + id: Uuid::new_v4(), } } } diff --git a/lib_efo/src/epoch.rs b/lib_efo/src/epoch.rs index ad61733..b38d3c3 100644 --- a/lib_efo/src/epoch.rs +++ b/lib_efo/src/epoch.rs @@ -109,6 +109,13 @@ impl EpochId { pub fn next(&self) -> Self { Self { id: self.id + 1 } } + + /// Return a new epoch Id derived from this one + pub fn add_to_epoch(&self, other: i64) -> Self { + Self { + id: self.id.saturating_sub_signed(other), + } + } } impl std::ops::Deref for EpochId { diff --git a/lib_efo/src/epoch/epoch_config.rs b/lib_efo/src/epoch/epoch_config.rs index 9987432..7bf8ff9 100644 --- a/lib_efo/src/epoch/epoch_config.rs +++ b/lib_efo/src/epoch/epoch_config.rs @@ -86,7 +86,14 @@ impl EpochConfig { } } - /// Initialize the epoch more in depth + /// Initialize the epoch structure in depth. + /// + /// Scans the default configuration folder for sub‑directories that are + /// interpreted as epoch identifiers, logs each discovered epoch and + /// registers it in the in‑memory cache. + /// + /// This function may return an error if the configuration folder cannot + /// be read or if any directory name cannot be parsed as an `EpochId`. pub(crate) fn initialize(mut self) -> Result { let path = EpochConfig::default().save_subfolder(); let path = io_err_with_help!(Path::new(&path).read_dir(), "Reading initial folder {path}")?; @@ -138,6 +145,93 @@ impl EpochConfig { Ok(()) } + /// Load the currently active epoch. + /// + /// This helper first ensures that the current epoch’s metadata is cached + /// by delegating to `try_load`, then returns a reference to it. + /// + /// # Returns + /// * `Ok(&EpochInfo)` – Reference to the cached epoch. + /// * Propagates any error from `try_load`. + pub fn try_load_current(&mut self) -> Result<&EpochInfo, EpochError> { + self.try_load(&self.epoch_id.clone())?; + unsafe { self.try_load_id(self.epoch_id) } + } + + /// Load an epoch by its identifier. + /// + /// The caller must guarantee that the epoch has already been loaded into + /// the cache (e.g. by calling `try_load`). This function is marked `unsafe` + /// because it performs a raw reference conversion without performing that + /// check. + /// + /// # Safety + /// Calling this function when the requested epoch has not yet been + /// loaded results in undefined behaviour. + /// + /// # Arguments + /// * `epoch_id` – Identifier of the epoch to load. + /// + /// # Returns + /// * `Ok(&EpochInfo)` – Reference to the cached epoch. + /// * `Err(EpochError::EpochHashingImpossible(..))` – The identifier is + /// unknown. + /// * `Err(EpochError::LoadingEpochId(..))` – The epoch data is not yet + /// present in the cache. + pub unsafe fn try_load_id(&self, epoch_id: EpochId) -> Result<&EpochInfo, EpochError> { + let current = self + .list_existing_epochs + .get(&epoch_id) + .ok_or(EpochError::EpochHashingImpossible(file!(), line!()))? + .as_ref() + .ok_or(EpochError::LoadingEpochId(self.epoch_id))?; + Ok(current) + } + + /// Load the currently active epoch mutably. + /// + /// This is a convenience wrapper that forwards to `try_load_id_as_mut` + /// for the current epoch. + /// + /// # Returns + /// * `Ok(&mut EpochInfo)` – Mutable reference to the cached epoch. + /// * Propagates any error from the underlying load routine. + pub fn try_load_current_as_mut(&mut self) -> Result<&mut EpochInfo, EpochError> { + self.try_load_id_as_mut(self.epoch_id) + } + + /// Load an epoch’s metadata mutably. + /// + /// The function guarantees that the epoch data is present in the cache + /// by first invoking `try_load` on the current epoch ID. It then + /// retrieves a mutable reference to the requested epoch. + /// + /// # Arguments + /// * `epoch_id` – Identifier of the epoch to load. + /// + /// # Returns + /// * `Ok(&mut EpochInfo)` – Mutable reference to the cached epoch. + /// * `Err(EpochError::EpochHashingImpossible(..))` – The identifier is + /// unknown. + /// * `Err(EpochError::LoadingEpochId(..))` – The epoch data is not yet + /// present in the cache. + /// + /// # Notes + /// The call to `try_load` may incur a small performance penalty because + /// it ensures that the epoch metadata is read from disk even when the + /// caller already knows the epoch is cached. This function is *not* `unsafe`; + /// it performs all safety checks internally. + fn try_load_id_as_mut(&mut self, epoch_id: EpochId) -> Result<&mut EpochInfo, EpochError> { + self.try_load(&self.epoch_id.clone())?; + let current = self + .list_existing_epochs + .get_mut(&epoch_id) + .ok_or(EpochError::EpochHashingImpossible(file!(), line!()))? + .as_mut() + .ok_or(EpochError::LoadingEpochId(self.epoch_id))?; + Ok(current) + } + /// Retrieves the internal epoch ID for a given identifier. /// /// The identifier can be either a *tag* string (`EpochIdentifier::Tag`) or an @@ -152,7 +246,7 @@ impl EpochConfig { /// * `Err(EpochError::AmbiguousTag(tag))` if a supplied tag does not exist. /// * `Err(EpochError::EpochFolderMissing(id, path))` if an ID does not have an /// associated epoch folder. - pub fn get(&self, id: &EpochIdentifier) -> Result { + pub fn get_epoch_id(&self, id: &EpochIdentifier) -> Result { match id { EpochIdentifier::Tag(s) => self .tags diff --git a/lib_efo/src/epoch/epoch_info.rs b/lib_efo/src/epoch/epoch_info.rs index 1dceeec..ad6dd33 100644 --- a/lib_efo/src/epoch/epoch_info.rs +++ b/lib_efo/src/epoch/epoch_info.rs @@ -12,6 +12,7 @@ use serde::{Deserialize, Serialize}; use std::fs::create_dir_all; use crate::{ + entity::Entity, epoch::{ EpochId, SUB_NAME, SUBFOLDER_NAMING, TagList, epoch_traits::{ConfigWritable, Prettiable}, @@ -25,8 +26,8 @@ use crate::{ /// /// It contains only the information that is needed for the engine to /// reconstruct the state *of that particular epoch* (seed, selected -/// events, parent link, etc.). The full world data is kept in -/// separate storage (e.g. `world.json`). +/// events, parent link, etc.). The full world data will be kept in +/// separate storage (e.g. `world.json`) but is for stored here. #[derive(Debug, Clone, Serialize, Deserialize, Display, Table)] #[display( "Epoch ({epoch_id:>5}) | seed ({rng_seed:<10}) | tags ({tags:<10}) | summary ({summary:<20})" @@ -53,6 +54,16 @@ pub struct EpochInfo { /// Human-readable description or summary, useful for the `log` command. #[table(title = "Summary")] pub summary: String, + // TODO[9]: Store world separately + #[table(skip)] + /// The list of events currently in progress + pub events: Vec, + #[table(skip)] + /// The list of characters currently present + pub characters: Vec, + #[table(skip)] + /// The list of towns currently present + pub towns: Vec, } impl Prettiable for EpochInfo {} @@ -64,6 +75,9 @@ impl Default for EpochInfo { rng_seed: 0, tags: TagList::new(), summary: String::new(), + events: Vec::new(), + characters: Vec::new(), + towns: Vec::new(), } } } diff --git a/lib_efo/src/error.rs b/lib_efo/src/error.rs index b97ce4c..ba16da4 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::EpochId; +use crate::{epoch::EpochId, stats::EntityType}; use miette::Diagnostic; /// Errors that can be returned by the storage layer. @@ -198,6 +198,11 @@ pub enum EpochError { #[diagnostic(code(EpochError::ParsingEpochId))] ParsingEpochId(#[from] ParseIntError), + /// Impossible to load the given epoch + #[error("The id ({0}) couldn't be loaded")] + #[diagnostic(code(EpochError::LoadingEpochId))] + LoadingEpochId(EpochId), + /// Any other error that didn't fit into the above categories. #[error("An unknown error occurred: {0}")] #[diagnostic(code(EpochError::Unknown))] @@ -228,6 +233,31 @@ pub enum EpochError { /// Optionnal help help: Option, }, + + /// A non‑recoverable error while hashing an epoch identifier. + /// + /// This error should never happen in normal operation. It is surfaced only + /// when the hashing routine fails to produce a unique identifier for a + /// given epoch index. + #[error("Epoch hashing failed for `{0}` (index {1})")] + #[diagnostic(code(EpochError::EpochHashingImpossible))] + #[help("This is an internal error. Please file a bug report.")] + EpochHashingImpossible(&'static str, u32), + + /// The entity could not be found + #[error("Entity of type {0:?} with name {1:?} & id {2:?} not found")] + #[diagnostic(code(epoch::entity_not_found))] + #[help( + "Verify that the identifier is correct and that the entity exists in the current epoch." + )] + EntityNotFound(EntityType, Option, Option), + + /// The requested uniform RNG could not be created because the supplied + /// distribution parameters were invalid. + #[error("Failed to create uniform RNG: {0}")] + #[diagnostic(code(EpochError::UniformRngCreation))] + #[help("Ensure that the supplied range bounds satisfy `min < max`.")] + UniformRngCreation(#[from] rand::distr::uniform::Error), } /// A small enum of explicit user-facing error messages. diff --git a/lib_efo/src/stats.rs b/lib_efo/src/stats.rs index 90d731c..91feb40 100644 --- a/lib_efo/src/stats.rs +++ b/lib_efo/src/stats.rs @@ -12,13 +12,17 @@ #![allow(dead_code)] #![deny(clippy::missing_docs_in_private_items)] +use crate::error::EpochError; use crate::thin_newtype; +use crate::utils::RngLevel; use cli_table::Color; use cli_table::Table; use colored::Colorize; use derive_more::Add; use derive_more::Display; use derive_more::Sub; +use rand::distr::Distribution; +use rand::rngs::ThreadRng; use serde::{Deserialize, Serialize}; mod implementations; @@ -233,6 +237,37 @@ pub struct OverallStats { #[table(title = "HLT")] pub health: GenericStat, } +impl OverallStats { + /// Create Stats with a given rng distribution + pub(crate) fn create_rng( + rng: &RngLevel, + mut rng_t: &mut ThreadRng, + ) -> Result { + let r = rng.to_rng()?; + Ok(Self { + demographics: (r.sample(&mut rng_t) as isize).into(), + population: (r.sample(&mut rng_t) as isize).into(), + growth_rate: (r.sample(&mut rng_t) as isize).into(), + crime: (r.sample(&mut rng_t) as isize).into(), + happiness: (r.sample(&mut rng_t) as isize).into(), + economy: (r.sample(&mut rng_t) as isize).into(), + food: (r.sample(&mut rng_t) as isize).into(), + industry: (r.sample(&mut rng_t) as isize).into(), + science: (r.sample(&mut rng_t) as isize).into(), + trade: (r.sample(&mut rng_t) as isize).into(), + military: (r.sample(&mut rng_t) as isize).into(), + army: (r.sample(&mut rng_t) as isize).into(), + strength: (r.sample(&mut rng_t) as isize).into(), + fortification: (r.sample(&mut rng_t) as isize).into(), + threat: (r.sample(&mut rng_t) as isize).into(), + infrastructure: (r.sample(&mut rng_t) as isize).into(), + bureaucracy: (r.sample(&mut rng_t) as isize).into(), + transportation: (r.sample(&mut rng_t) as isize).into(), + sprawl: (r.sample(&mut rng_t) as isize).into(), + health: (r.sample(&mut rng_t) as isize).into(), + }) + } +} /// Strategic context and meta-data for an entity. /// @@ -316,7 +351,7 @@ pub struct MetaStats { /// Accepts two forms /// 1. "cri 10" (two separate tokens) /// 2. "cri:10" (one token with a separator) -#[derive(Debug, Serialize, Deserialize)] +#[derive(Debug, Serialize, Deserialize, Clone)] pub struct StatPair { /// The stat selected pub stat: ListStats, diff --git a/lib_efo/src/utils.rs b/lib_efo/src/utils.rs index 0f0ecbc..c7bcc69 100644 --- a/lib_efo/src/utils.rs +++ b/lib_efo/src/utils.rs @@ -6,25 +6,49 @@ #![warn(missing_docs, clippy::missing_docs_in_private_items)] -use std::path::Path; +use clap::ValueEnum; +use rand::distr::Uniform; use crate::error::EpochError; -/// Check whether `path` points to a valid Epoch directory. +/// How to fill in unspecified stat values. /// -/// A *valid* directory is one that satisfies the expectations of the `epoch` format. -pub fn is_a_epoch_directory(_path: &Path) -> Result<(), EpochError> { - todo!() +/// When an entity is created or edited, any stat that is not explicitly +/// provided will be assigned a value according to the chosen level. +#[derive(Debug, ValueEnum, Copy, Clone, PartialEq, Eq, PartialOrd, Ord)] +pub enum RngLevel { + /// All non specified values are zero + Zero, + /// All non specified values are low + Low, + /// All non specified values are medium + Med, + /// All non specified values are high + High, + /// All non specified values are very high + Legendary, + /// Stats are all over the place + Mixed, + /// All non specified are either high or low + Flawed, } -/// Validate that the configuration file at `path` is well-formed. -pub fn is_config_well_formated(_path: &Path) -> Result<(), EpochError> { - todo!() -} +impl RngLevel { + /// Turn into a range for rng generation + pub fn to_range(&self) -> std::ops::Range { + match self { + RngLevel::Zero => 0..0, + RngLevel::Low => 0..20, + RngLevel::Med => 10..40, + RngLevel::High => 20..50, + RngLevel::Legendary => 40..70, + RngLevel::Mixed => 0..70, + RngLevel::Flawed => 0..100, + } + } -#[cfg(test)] -mod test { - #![allow(dead_code)] - fn test_directory() {} - fn test_config() {} + /// Turn into a rng generator + pub fn to_rng(&self) -> Result, EpochError> { + Ok(Uniform::try_from(self.to_range())?) + } }