From d4a88f402f8af5bb6e429682492d5a79331ca81d Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Mon, 15 Dec 2025 05:15:20 +0100 Subject: [PATCH] Adds double linking --- bin_efo/src/commands/entity_generic.rs | 18 ++--- .../entity_generic/helper_functions.rs | 25 +++++-- lib_efo/src/entity/implementations.rs | 31 +++++++-- ...entity__test__snapshot_entity_delta-2.snap | 7 +- ...ty__test__snapshot_meta_stats_delta-3.snap | 7 +- lib_efo/src/entity/test.rs | 18 ++--- lib_efo/src/epoch.rs | 2 +- lib_efo/src/epoch/epoch_info.rs | 69 ++++++++++++++++++- lib_efo/src/stats.rs | 53 ++++++++++++-- 9 files changed, 185 insertions(+), 45 deletions(-) diff --git a/bin_efo/src/commands/entity_generic.rs b/bin_efo/src/commands/entity_generic.rs index 41de79a..b389aef 100644 --- a/bin_efo/src/commands/entity_generic.rs +++ b/bin_efo/src/commands/entity_generic.rs @@ -239,17 +239,8 @@ pub struct CommonArgs { pub prestige: Option, /// Change the prestige by a delta - #[arg(long, group = "capital_group")] - pub add_prestige: Option, - // /// Add a link to another location - // /// This is currently unused and important for early testing - // #[arg(long, short = 'l')] - // pub add_link: Vec, - - // /// Add a link to another location - // /// This is currently unused and important for early testing - // #[arg(long)] - // pub del_link: Vec, + #[arg(long, group = "capital_group", allow_negative_numbers = true)] + pub prestige_add: Option, } /// Handles an entity subcommand. @@ -362,6 +353,11 @@ fn handle_delete_entity( ))?; let entity = vec_entities.swap_remove(index); + // TODO: Clean all the links from it's presence + // for l in entity.links(){ + // // Figure out what the link is + // // Delete either a governor or capital + // } epoch_info.save_with_context("Deleted entity", &lib_efo::epoch::SaveMode::Erase)?; display_success(&crate::success::SuccessMessages::DeletedEntity( diff --git a/bin_efo/src/commands/entity_generic/helper_functions.rs b/bin_efo/src/commands/entity_generic/helper_functions.rs index 8336721..6da9063 100644 --- a/bin_efo/src/commands/entity_generic/helper_functions.rs +++ b/bin_efo/src/commands/entity_generic/helper_functions.rs @@ -7,6 +7,7 @@ use lib_efo::{ naming::NAMING, stats::{self, EntityType, StatPair}, }; +use log::info; use crate::commands::entity_generic::{AddArgs, CommonArgs}; /// Update the given stats with the given argumenbts @@ -127,7 +128,7 @@ pub fn update_common_values( if let Some(prestige) = &entity_args.prestige { entity.modify_prestige(*prestige) } - if let Some(prestige) = &entity_args.add_prestige { + if let Some(prestige) = &entity_args.prestige_add { entity.modify_prestige_by_delta(*prestige) } } @@ -136,20 +137,32 @@ pub fn update_common_values( pub fn update_advanced_values( entity_args: &CommonArgs, entity: &mut Entity, - epoch_info: &EpochInfo, + epoch_info: &mut EpochInfo, ) -> Result<(), EpochError> { if let Some(governor) = &entity_args.governor { + info!("Adding {} to {}{}", governor, entity.id, entity.name); let governor = epoch_info.find_entity_of_type(&Some(governor.clone()), &EntityType::Character)?; entity.change_governor(stats::CharacterId(governor.id)); - } else if entity_args.no_governor { - entity.remove_governor(); + // Since I added a governor, I now need to add the link to the governor, + // note that if you add an entity to itself this will subtly break but the + // link usage being only for deletion, this breakage will not matter + // This double lookup is only done since the update is not done by the owning structure + epoch_info.add_to_links(governor.id, &EntityType::Character, entity.id)?; + } else if entity_args.no_governor + && let Some(g) = entity.remove_governor() + { + info!("Removing {}{} from {}", entity.id, entity.name, g); + epoch_info.del_from_links(*g, &EntityType::Character, entity.id)?; } if let Some(capital) = &entity_args.capital { let capital = epoch_info.find_entity_of_type(&Some(capital.clone()), &EntityType::Town)?; entity.change_capital(stats::TownId(capital.id)); - } else if entity_args.no_capital { - entity.remove_capital(); + epoch_info.add_to_links(capital.id, &EntityType::Town, entity.id)?; + } else if entity_args.no_capital + && let Some(c) = entity.remove_capital() + { + epoch_info.del_from_links(*c, &EntityType::Town, entity.id)?; } // Remove links if needed, updating two ways Ok(()) diff --git a/lib_efo/src/entity/implementations.rs b/lib_efo/src/entity/implementations.rs index 85488ab..e077d3c 100644 --- a/lib_efo/src/entity/implementations.rs +++ b/lib_efo/src/entity/implementations.rs @@ -17,7 +17,7 @@ use crate::epoch::epoch_traits::Diffable; use crate::error::EpochError; use crate::stats::{ self, EntityType, FactionId, GenericStat, ListStats, MetaStats, OverallStats, Position, - PositionGrid, StatPair, Symbols, + PositionGrid, StatPair, Symbols, TypedLink, }; use crate::utils::RngLevel; use crate::{Displayable, items_table}; @@ -39,14 +39,14 @@ impl Displayable for Entity { .metadata .capital .as_ref() - .map(|c| format!("Capital:  {} ", c.to_symbol()).green()) + .map(|c| format!("Capital:  {} ", c.to_symbol().blue())) .unwrap_or_default(); let governor = self .metadata .governor .as_ref() - .map(|g| format!("Governor:  {}", g.to_symbol()).blue()) + .map(|g| format!("Governor:  {}", g.to_symbol().blue())) .unwrap_or_default(); let prestige = if *self.metadata.prestige > 0 { @@ -103,6 +103,29 @@ impl Entity { self.stat_to_table(items) } + /// Adds a link (UUID) to the entity's metadata. + /// + /// If `id_to_add` is already present in the `links` vector, this method does + /// nothing – it silently ignores duplicates. The method is idempotent: calling + /// it repeatedly with the same UUID will not change the underlying state. + pub fn add_to_links(&mut self, id_to_add: stats::TypedLink) { + if !self.metadata.links.contains(&id_to_add) { + self.metadata.links.push(id_to_add); + } + } + + /// Removes a link (UUID) from the entity's metadata. + /// + /// If the supplied `id_to_remove` exists in `self.metadata.links`, it is + /// removed and returned wrapped in `Some`. If the UUID is not present, + /// the method returns `None` and leaves the link list unchanged. + pub fn del_from_links(&mut self, id_to_remove: stats::TypedLink) -> Option { + self.metadata + .links + .iter() + .position(|id| *id == id_to_remove) + .map(|pos| self.metadata.links.swap_remove(pos)) + } /// Display the entity's statistics in a pretty table (same format as /// `full_stats_to_table`). /// @@ -227,7 +250,7 @@ impl Entity { &format!( "{} {}\n", symbol, - uuid_to_symbol(**link, epoch_info, &EntityType::Town).yellow() + uuid_to_symbol(link.id, epoch_info, &EntityType::Town).yellow() ), )); } diff --git a/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_entity_delta-2.snap b/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_entity_delta-2.snap index a72ff83..8623121 100644 --- a/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_entity_delta-2.snap +++ b/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_entity_delta-2.snap @@ -145,9 +145,10 @@ Entity { ), ), links: [ - TownId( - 79000000-0000-0000-0000-000000000000, - ), + TypedLink { + id: 79000000-0000-0000-0000-000000000000, + role: Govern, + }, ], prestige: GenericStat( 0, diff --git a/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_meta_stats_delta-3.snap b/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_meta_stats_delta-3.snap index a592517..6a51e99 100644 --- a/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_meta_stats_delta-3.snap +++ b/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_meta_stats_delta-3.snap @@ -15,9 +15,10 @@ MetaStats { ), ), links: [ - TownId( - 02000000-0000-0000-0000-000000000000, - ), + TypedLink { + id: 02000000-0000-0000-0000-000000000000, + role: Govern, + }, ], prestige: GenericStat( 0, diff --git a/lib_efo/src/entity/test.rs b/lib_efo/src/entity/test.rs index b378536..053b02b 100644 --- a/lib_efo/src/entity/test.rs +++ b/lib_efo/src/entity/test.rs @@ -7,7 +7,7 @@ use crate::entity::{EffectApplication, EffectBounds, Entity, EntityDuration, Ent use crate::epoch::epoch_traits::Diffable; use crate::epoch::{EpochInfo, epoch_info}; use crate::error::EpochError; -use crate::stats::{self, EntityType, MetaStats, Position, StatPair, TownId}; +use crate::stats::{self, EntityType, MetaStats, Position, StatPair, TownId, TypedLink}; use std::io::Write; use super::*; @@ -239,9 +239,9 @@ fn full_entity() -> Entity { position: Position::from((2, 4)), faction: Some(crate::stats::FactionId(2)), links: vec![ - TownId(Uuid::from_u128_le(1212)), - TownId(Uuid::from_u128_le(121)), - TownId(Uuid::from_u128_le(121)), + stats::TypedLink::new(Uuid::from_u128_le(1212), stats::Role::Govern), + stats::TypedLink::new(Uuid::from_u128_le(121), stats::Role::Govern), + stats::TypedLink::new(Uuid::from_u128_le(121), stats::Role::Govern), ], reach: stats::Reach::Global, }, @@ -392,7 +392,7 @@ fn snapshot_entity_delta() { capital: Some(stats::TownId(Uuid::from_u128_le(124))), governor: Some(stats::CharacterId(Uuid::from_u128_le(12))), faction: Some(stats::FactionId(44)), - links: vec![TownId(Uuid::from_u128_le(141))], + links: vec![TypedLink::new(Uuid::from_u128_le(141), stats::Role::Govern)], prestige: stats::GenericStat(3), reach: stats::Reach::Local(12), }, @@ -413,7 +413,7 @@ fn snapshot_entity_delta() { capital: Some(stats::TownId(Uuid::from_u128_le(121))), governor: Some(stats::CharacterId(Uuid::from_u128_le(18))), faction: Some(stats::FactionId(5)), - links: vec![TownId(Uuid::from_u128_le(121))], + links: vec![TypedLink::new(Uuid::from_u128_le(121), stats::Role::Govern)], prestige: stats::GenericStat(5), reach: stats::Reach::Faction(stats::FactionId(2)), }, @@ -479,7 +479,7 @@ fn snapshot_meta_stats_delta() { capital: Some(stats::TownId(Uuid::from_u128_le(1000))), governor: Some(stats::CharacterId(Uuid::from_u128_le(522))), faction: Some(stats::FactionId(1)), - links: vec![TownId(Uuid::from_u128_le(12))], + links: vec![TypedLink::new(Uuid::from_u128_le(12), stats::Role::Govern)], prestige: stats::GenericStat(3), reach: stats::Reach::Global, }; @@ -489,7 +489,7 @@ fn snapshot_meta_stats_delta() { capital: Some(stats::TownId(Uuid::from_u128_le(12))), governor: Some(stats::CharacterId(Uuid::from_u128_le(882))), faction: Some(stats::FactionId(33)), - links: vec![TownId::from(Uuid::from_u128_le(42))], + links: vec![TypedLink::new(Uuid::from_u128_le(42), stats::Role::Govern)], prestige: stats::GenericStat(1), reach: stats::Reach::None, }; @@ -498,7 +498,7 @@ fn snapshot_meta_stats_delta() { capital: None, governor: Some(stats::CharacterId(Uuid::from_u128_le(1221))), faction: Some(stats::FactionId(33)), - links: vec![TownId::from(Uuid::from_u128_le(2))], + links: vec![TypedLink::new(Uuid::from_u128_le(2), stats::Role::Govern)], prestige: stats::GenericStat(1), reach: stats::Reach::Faction(stats::FactionId(12)), }; diff --git a/lib_efo/src/epoch.rs b/lib_efo/src/epoch.rs index b5a3f34..bf58b16 100644 --- a/lib_efo/src/epoch.rs +++ b/lib_efo/src/epoch.rs @@ -41,7 +41,7 @@ static SUBFOLDER_NAMING: &str = "epoch"; /// The main name of the epoch static MAIN_NAME: &str = ".epoch"; /// The subname of the epochinfo -static SUB_NAME: &str = ".epochinfo"; +static SUB_NAME: &str = "epochinfo.json"; /// A lightweight wrapper around a list of tags. /// diff --git a/lib_efo/src/epoch/epoch_info.rs b/lib_efo/src/epoch/epoch_info.rs index 808569e..4dbfa2b 100644 --- a/lib_efo/src/epoch/epoch_info.rs +++ b/lib_efo/src/epoch/epoch_info.rs @@ -19,7 +19,7 @@ use crate::{ epoch_traits::{ConfigWritable, Prettiable}, }, error::EpochError, - stats::{EntityType, Position, PositionIdentifier}, + stats::{EntityType, Position, PositionIdentifier, Role, TypedLink}, }; /// The metadata file stored inside each epoch directory @@ -146,6 +146,73 @@ impl EpochInfo { entity_to_find.clone(), )) } + + /// Adds a link between two entities inside the epoch. + /// + /// The link is added to the entity identified by `id_to_add_to`. If the + /// target entity is not found, an `EntityNotFoundById` error is returned. + /// + /// # Arguments + /// * `id_to_add_to` – The UUID of the entity that will receive the new link. + /// * `e_type` – The type of the entity that should receive the link. + /// * `id_to_add` – The UUID of the entity that should be linked. + pub fn add_to_links( + &mut self, + id_to_add_to: Uuid, + e_type: &EntityType, + id_to_add: Uuid, + ) -> Result<(), EpochError> { + let e = self + .vec_entities_mut(e_type) + .iter_mut() + .find(|entity| entity.id == id_to_add_to) + .ok_or(EpochError::EntityNotFoundById(EntityIdentifier::Id( + id_to_add_to.to_string(), + )))?; + let t_link = match e_type { + EntityType::Character => Role::Govern, + EntityType::Player => Role::Govern, + EntityType::Town => Role::Capital, + EntityType::Monster => Role::Undefined, + EntityType::Blocker => Role::Undefined, + EntityType::Event => Role::Undefined, + }; + e.add_to_links(TypedLink::new(id_to_add, t_link)); + Ok(()) + } + + /// Removes a link from an entity inside the epoch. + /// + /// The removal is performed on the *target* entity (`id_to_add_to`). If the + /// target entity cannot be found, an `EpochError::EntityNotFoundById` error + /// is returned. The removal itself is delegated to the entity’s + /// `del_from_links` method, which silently ignores missing links. + pub fn del_from_links( + &mut self, + id_to_remove_from: Uuid, + e_type: &EntityType, + id_to_remove: Uuid, + ) -> Result<(), EpochError> { + let e = self + .vec_entities_mut(e_type) + .iter_mut() + .find(|entity| entity.id == id_to_remove_from) + .ok_or(EpochError::EntityNotFoundById(EntityIdentifier::Id( + id_to_remove_from.to_string(), + )))?; + + let t_link = match e_type { + EntityType::Character => Role::Govern, + EntityType::Player => Role::Govern, + EntityType::Town => Role::Capital, + EntityType::Monster => Role::Undefined, + EntityType::Blocker => Role::Undefined, + EntityType::Event => Role::Undefined, + }; + e.del_from_links(TypedLink::new(id_to_remove, t_link)); + Ok(()) + } + /// Find an entity by its UUID. /// /// This function searches the currently loaded epoch for an entity whose diff --git a/lib_efo/src/stats.rs b/lib_efo/src/stats.rs index 88cedcf..973f267 100644 --- a/lib_efo/src/stats.rs +++ b/lib_efo/src/stats.rs @@ -391,13 +391,8 @@ pub struct MetaStats { /// UIDs of all entities the entity is linked to (roads, trade routes, /// alliances, war declarations, etc.). - /// - /// **Purpose** - Connectivity network. - /// **Effect** - Influences economic, military, and diplomatic - /// interactions. - /// **Source** - `links = Vec` collected from the entity's - /// network manager. - pub links: Vec, + // TODO: Type this vector, with a smart type: (Uuid, EntityType) + pub links: Vec, /// Prestige / reputation of the entity in the eyes of the empire /// and foreign powers. @@ -597,6 +592,50 @@ thin_newtype!(TownId, Uuid); thin_newtype!(CharacterId, Uuid); thin_newtype!(FactionId, usize, derives: [Add, Sub]); +#[derive(Copy, Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Display, Default)] +/// A typed link between two entities. +/// +/// A link is a lightweight association that ties an entity’s **identifier** +/// (`id`) to a *semantic role* (`role`). The role is expressed by the +/// [`Role`] enum and defines what the link actually means in the +/// domain model. +#[display("{id}:{role}")] +pub struct TypedLink { + /// The UUID of the entity that is linked. + /// + /// The link is *unidirectional*; the `TypedLink` itself does not + /// keep a back‑reference to the source entity. + pub id: Uuid, + /// The semantic role that this link plays. + /// + /// For example, a link with `Role::Capital` indicates that the entity + /// identified by `id` is the capital of the entity that owns the link. + pub role: Role, +} + +impl TypedLink { + /// Simple initializer for the TypedLink type + pub fn new(id: Uuid, role: Role) -> Self { + Self { id, role } + } +} + +#[derive(Copy, Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Display, Default)] +/// Semantic role of a link. +/// +/// The role encodes *what the link represents* in the model. The +/// variants are intentionally limited to the most common use‑cases, +/// but the enum can be extended if the domain evolves. +pub enum Role { + /// The linked entity has governing authority over the link owner + Govern, + /// The linked entity is the capital of the link owner + Capital, + #[default] + /// No role has been assigned. + Undefined, +} + // --- TRAITS --------------------------------------------------------------- /// A stat is a *game value* that can be converted to two different /// normalised ranges - a 100-point range for “gaming” logic and a