feat: add reversible roads and travel

This commit is contained in:
Dandaedre 2026-09-22 00:41:09 +02:00
parent c5e4cf27d1
commit 0b62ab9968
Signed by: Dandaedre
GPG Key ID: 440C6592E8A26D99
15 changed files with 814 additions and 13 deletions

View File

@ -197,14 +197,15 @@ workspace validation without clamping real population counts.
### Checkpoint 2 — roads, residency, and travel
- [ ] Add stable, validated road edges between positioned place entities.
- [ ] Model resident, roaming, and travelling character states without
- [x] Add stable, validated road edges between positioned place entities.
- [x] Model resident, roaming, and travelling character states without
overloading governance links.
- [ ] Implement deterministic shortest-time routing with road speed and slower
- [x] Implement deterministic shortest-time routing with road speed and slower
direct-travel fallback.
- [ ] Preview travel plans and advance progress only through staged simulation
- [x] Preview travel plans and advance progress only through staged simulation
ticks with clear restore/revert guidance.
- [ ] Fuzz disconnected, cyclic, duplicate, and malformed topology.
- [x] Exercise disconnected, cyclic, duplicate, malformed, and legacy topology
in deterministic tests; broader cargo-fuzz targets remain release hardening.
### Checkpoint 3 — spatial event diffusion

View File

@ -74,7 +74,7 @@ Run `efo --help`, `efo <command> --help`, or see the
| Repository | Initialise format 1.0; inspect; lock and recover transactional writes | Future 1.x migration tooling; discovery from child directories; integrity repair |
| Timeline | Commit, advance, switch, log, tag, summarise, diff, reviewable/committed revert, backed-up pruning, and explicit hard reset | Branching and merging |
| Entities | Add, edit, list, inspect, diff, and delete six built-in types | Custom types and custom fields; bulk operations |
| Generation | Generate names and deterministic seeded events, settlements, regions, or worlds from embedded/override configuration | Roads, diffusion, and setting template packs |
| Generation and simulation | Generate deterministic seeded worlds; define roads and preview/apply deterministic character travel | Event diffusion and setting template packs |
| Interfaces | Complete CLI; `efo-tui` browser and entity editor | TUI staging/commits; GUI/web (out of scope) |
`efo show all` gives a world overview; per-type commands such as

View File

@ -18,5 +18,6 @@ pub mod safety;
pub mod show;
pub mod state;
pub mod status;
pub mod travel;
// pub mod diff;
// pub mod utils;

View File

@ -0,0 +1,253 @@
//! Preview-first character travel commands.
use std::path::Path;
use clap::{Args, Subcommand};
use lib_efo::{
entity::EntityIdentifier,
simulation::{Road, begin_travel, plan_travel, tick_travel, validate_roads},
stats::EntityType,
workspace::Workspace,
};
use crate::error::AppError;
/// Spatial travel operations.
#[derive(Debug, Subcommand)]
pub enum TravelCmd {
/// List configured roads.
Roads,
/// Preview or add a road between two towns.
RoadAdd(RoadAddArgs),
/// Preview or remove a road by @UUID.
RoadRemove(RoadRemoveArgs),
/// Preview or begin a journey to a town.
Plan(TravelPlanArgs),
/// Preview or advance every active journey.
Tick(TravelTickArgs),
}
/// New-road arguments.
#[derive(Debug, Args)]
pub struct RoadAddArgs {
/// First town name/prefix or @UUID.
from: EntityIdentifier,
/// Second town name/prefix or @UUID.
to: EntityIdentifier,
/// Road travel speed percentage.
#[arg(long, default_value_t = 150)]
speed: u32,
/// Add the road to the worktree; preview is the default.
#[arg(long)]
apply: bool,
}
/// Road-removal arguments.
#[derive(Debug, Args)]
pub struct RoadRemoveArgs {
/// Exact road UUID, with or without `@`.
id: String,
/// Remove the road from the worktree; preview is the default.
#[arg(long)]
apply: bool,
}
/// Route-planning arguments.
#[derive(Debug, Args)]
#[command(
after_long_help = "EXAMPLES:\n efo travel plan Aria Haven\n efo travel plan @CHARACTER @TOWN --offroad-speed 50 --apply"
)]
pub struct TravelPlanArgs {
/// Character name/prefix or @UUID.
character: EntityIdentifier,
/// Destination town name/prefix or @UUID.
destination: EntityIdentifier,
/// Direct-travel speed percentage; roads carry their own speed.
#[arg(long, default_value_t = 50)]
offroad_speed: u32,
/// Store this plan in the worktree; preview is the default.
#[arg(long)]
apply: bool,
}
/// Simulation-tick arguments.
#[derive(Debug, Args)]
pub struct TravelTickArgs {
/// Number of ticks to advance.
#[arg(default_value_t = 1)]
amount: u64,
/// Update the worktree; preview is the default.
#[arg(long)]
apply: bool,
}
/// Dispatch one travel operation.
pub fn handle(cmd: &TravelCmd) -> Result<(), AppError> {
match cmd {
TravelCmd::Roads => roads(),
TravelCmd::RoadAdd(args) => road_add(args),
TravelCmd::RoadRemove(args) => road_remove(args),
TravelCmd::Plan(args) => plan(args),
TravelCmd::Tick(args) => tick(args),
}
}
/// List the stable travel topology.
fn roads() -> Result<(), AppError> {
let workspace = Workspace::open(Path::new("."))?;
validate_roads(&workspace.worktree.world)?;
println!("Roads ({})", workspace.worktree.world.roads.len());
for road in &workspace.worktree.world.roads {
let name = |id| {
workspace
.worktree
.world
.towns
.iter()
.find(|town| town.id == id)
.map_or("unknown", |town| town.name.as_str())
};
println!(
" • {} ↔ {} · {}% · @{}",
name(road.from),
name(road.to),
road.speed_percent,
road.id
);
}
Ok(())
}
/// Preview and optionally add one validated road.
fn road_add(args: &RoadAddArgs) -> Result<(), AppError> {
let mut workspace = Workspace::open(Path::new("."))?;
let from = workspace
.worktree
.world
.find_entity_of_type(&Some(args.from.clone()), &EntityType::Town)?
.id;
let to = workspace
.worktree
.world
.find_entity_of_type(&Some(args.to.clone()), &EntityType::Town)?
.id;
println!("Road preview · @{from} ↔ @{to} · {}%", args.speed);
if !args.apply {
println!("Nothing changed. Re-run with `--apply` to update the worktree.");
return Ok(());
}
workspace.worktree.world.roads.push(Road {
id: uuid::Uuid::new_v4(),
from,
to,
speed_percent: args.speed,
tags: Vec::new(),
});
validate_roads(&workspace.worktree.world)?;
workspace.save_worktree("add road")?;
println!("✓ Road added to the worktree. Undo: efo restore --worktree --all");
Ok(())
}
/// Preview and optionally remove one road.
fn road_remove(args: &RoadRemoveArgs) -> Result<(), AppError> {
let mut workspace = Workspace::open(Path::new("."))?;
let raw = args.id.strip_prefix('@').unwrap_or(&args.id);
let id =
uuid::Uuid::parse_str(raw).map_err(|_| lib_efo::error::EpochError::ParsingArgument {
argument_parsed: args.id.clone(),
while_parsing: "road UUID",
})?;
if !workspace
.worktree
.world
.roads
.iter()
.any(|road| road.id == id)
{
return Err(lib_efo::simulation::SimulationError::InvalidRoad {
id,
reason: "road does not exist".into(),
}
.into());
}
println!("Road removal preview · @{id}");
if !args.apply {
println!("Nothing changed. Re-run with `--apply` to update the worktree.");
return Ok(());
}
workspace.worktree.world.roads.retain(|road| road.id != id);
workspace.save_worktree("remove road")?;
println!("✓ Road removed from the worktree. Undo: efo restore --worktree --all");
Ok(())
}
/// Preview and optionally persist a selected route.
fn plan(args: &TravelPlanArgs) -> Result<(), AppError> {
let mut workspace = Workspace::open(Path::new("."))?;
let character = workspace
.worktree
.world
.find_entity_of_type(&Some(args.character.clone()), &EntityType::Character)?
.id;
let destination = workspace
.worktree
.world
.find_entity_of_type(&Some(args.destination.clone()), &EntityType::Town)?
.id;
let plan = plan_travel(
&workspace.worktree.world,
character,
destination,
args.offroad_speed,
)?;
println!(
"Travel preview · {} · {} tick(s)",
if plan.uses_roads { "roads" } else { "direct" },
plan.total_ticks
);
if plan.route.is_empty() {
println!("└─ Direct off-road fallback");
} else {
for (index, place) in plan.route.iter().enumerate() {
let marker = if index + 1 == plan.route.len() {
"└─"
} else {
"├─"
};
let name = workspace
.worktree
.world
.towns
.iter()
.find(|town| town.id == *place)
.map_or("unknown", |town| town.name.as_str());
println!("{marker} {name} @{place}");
}
}
if !args.apply {
println!("Nothing changed. Re-run with `--apply` to update the worktree.");
return Ok(());
}
begin_travel(&mut workspace.worktree.world, character, destination, &plan)?;
workspace.save_worktree("begin travel")?;
println!("✓ Journey stored in the worktree. Undo: efo restore --worktree --all");
Ok(())
}
/// Preview and optionally persist travel progress.
fn tick(args: &TravelTickArgs) -> Result<(), AppError> {
let mut workspace = Workspace::open(Path::new("."))?;
let mut preview = workspace.worktree.world.clone();
let arrived = tick_travel(&mut preview, args.amount);
println!("Travel tick preview · {} tick(s)", args.amount);
println!("└─ {} arrival(s)", arrived.len());
if !args.apply {
println!("Nothing changed. Re-run with `--apply` to update the worktree.");
return Ok(());
}
workspace.worktree.world = preview;
workspace.save_worktree("advance travel")?;
println!("✓ Travel advanced in the worktree. Undo: efo restore --worktree --all");
Ok(())
}

View File

@ -8,6 +8,7 @@
use lib_efo::{
error::{EpochError, StorageError},
repository_format::FormatError,
simulation::SimulationError,
transaction::TransactionError,
workspace::WorkspaceError,
worldgen::WorldGenError,
@ -53,6 +54,10 @@ pub enum AppError {
/// World-generation configuration or validation failed.
#[error("World generation stopped: {0}")]
WorldGen(#[from] WorldGenError),
/// Spatial topology or travel planning failed.
#[error("Simulation stopped: {0}")]
Simulation(#[from] SimulationError),
// /// Anything else we didn't anticipate.
// #[error("Unknown error: {0}")]
// Other(String),

View File

@ -38,6 +38,7 @@ use crate::{
show::ShowArgs,
state::{RestoreCmd, StageCmd, StateDiffCmd},
status::StatusCmd,
travel::TravelCmd,
},
error::AppError,
};
@ -129,6 +130,9 @@ enum TopLevelCmd {
/// Generate random structures and display them
#[command(subcommand)]
Gen(GenCmd),
/// Plan or advance deterministic spatial travel.
#[command(subcommand)]
Travel(TravelCmd),
}
/// Program entry point.
@ -188,6 +192,7 @@ 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::Travel(cmd) => commands::travel::handle(&cmd),
TopLevelCmd::Chr(cmd) => commands::entity_generic::handle_entity_commands(
&cmd,
&lib_efo::stats::EntityType::Character,

View File

@ -642,3 +642,58 @@ fn fsck_validates_links_inside_historical_epochs() {
assert!(!check.status.success());
assert!(stderr(&check).contains("links to missing or mistyped"));
}
#[test]
fn roads_and_travel_are_previewed_applied_and_restorable() {
let repo = TestRepo::new();
assert_success(&efo(&repo, &["init"]));
assert_success(&efo(&repo, &["town", "add", "Haven", "--position", "0,0"]));
assert_success(&efo(
&repo,
&["town", "add", "Northwatch", "--position", "20,0"],
));
assert_success(&efo(&repo, &["chr", "add", "Aria", "--position", "0,0"]));
let preview = efo(&repo, &["travel", "road-add", "Haven", "Northwatch"]);
assert_success(&preview);
assert!(stdout(&preview).contains("Nothing changed"));
assert!(
snapshot(&repo, 0)["roads"]
.as_array()
.expect("roads")
.is_empty()
);
assert_success(&efo(
&repo,
&[
"travel",
"road-add",
"Haven",
"Northwatch",
"--speed",
"200",
"--apply",
],
));
let plan = efo(&repo, &["travel", "plan", "Aria", "Northwatch"]);
assert_success(&plan);
assert!(stdout(&plan).contains("roads"));
assert_success(&efo(
&repo,
&["travel", "plan", "Aria", "Northwatch", "--apply"],
));
assert_success(&efo(&repo, &["travel", "tick", "10", "--apply"]));
assert_eq!(
snapshot(&repo, 0)["characters"][0]["metadata"]["position"],
serde_json::json!([20, 0])
);
assert_success(&efo(&repo, &["restore", "--worktree", "--all"]));
assert!(
snapshot(&repo, 0)["roads"]
.as_array()
.expect("roads")
.is_empty()
);
}

View File

@ -73,8 +73,8 @@ prints a warning and immediately creates the inverse commit. Overlap with later
changes aborts without mutation. `efo prune-future` previews future epochs,
while `--yes` moves them into a backup. Restore using the exact command printed
after pruning; this also restores the former next-epoch allocator and tags.
After pruning, new linear history begins at `HEAD + 1` rather than retaining a
gap for the removed epochs. `efo reset --hard ID --yes` is the explicitly destructive
After pruning, the next epoch allocator remains monotonic, so removed IDs are
not reused. `efo reset --hard ID --yes` is the explicitly destructive
alternative: it discards transient changes, removes newer epochs without a
backup, removes tags that point to them, and restarts the epoch allocator after
the retained target.
@ -92,6 +92,24 @@ controls output density. `efo show epoch` lists committed epoch summaries and
accepts the same `--epoch` and detail options. Use `<noun> show IDENTIFIER` for
the complete details of one entity by its name or stable ID.
## Roads and travel
Spatial changes are preview-first and affect only the worktree with `--apply`:
```text
efo travel road-add Haven Northwatch --speed 180
efo travel road-add Haven Northwatch --speed 180 --apply
efo travel roads
efo travel plan Aria Northwatch --offroad-speed 50
efo travel plan Aria Northwatch --offroad-speed 50 --apply
efo travel tick 3 --apply
```
Routing minimizes integer travel ticks with deterministic tie-breaking. Roads
carry their own speed; disconnected characters fall back to slower direct
travel. Characters have explicit resident, roaming, or travelling state. Use
`efo restore --worktree --all` to discard applied simulation changes.
## Generation and output
`efo gen character|town|event|exotic|calamity|blocker` prints generated content

View File

@ -19,9 +19,8 @@ absent.
| [#11 Epoch Diffing](https://proxy.dandaedre.com/gitea/idle-org/epoch_forge/issues/11) | Addressed: epoch and layer comparisons share a deterministic, serializable typed diff with changed-field details and importance classification. | Extend the type rather than parsing terminal output when structured formats arrive. |
| [#10 Display functions](https://proxy.dandaedre.com/gitea/idle-org/epoch_forge/issues/10) | Addressed for inspection: unified `show` and diff rendering build complete strings before a single output write, and `Displayable::full_display` no longer forces library output through `println!`. | Apply the same boundary opportunistically to mutation confirmations. |
| [#9 Adding influx](https://proxy.dandaedre.com/gitea/idle-org/epoch_forge/issues/9) | Open and underspecified. | Define versioned deterministic severity and avoidance rules before commands. |
| [#8 Event diffusion](https://proxy.dandaedre.com/gitea/idle-org/epoch_forge/issues/8) | Planned in the simulation roadmap; blocked on roads, residency, and deterministic routing. | Complete simulation checkpoints 2–3 in order. |
| [#8 Event diffusion](https://proxy.dandaedre.com/gitea/idle-org/epoch_forge/issues/8) | Spatial prerequisite complete: stable roads, explicit mobility, deterministic routing, direct fallback, and previewed ticks are implemented. Diffusion itself remains open. | Implement checkpoint 3 on the shared topology. |
| [#6 HashMap/HashSet](https://proxy.dandaedre.com/gitea/idle-org/epoch_forge/issues/6) | Addressed without format churn: `EntityIndex` provides ephemeral UUID/name hash indexes and duplicate-ID detection over the stable vector representation. Repository validation uses the index and hash lookup for relationships. | Rebuild indexes after mutation; never persist them. |
Preferred order: finish display buffering/structured output and custom fields,
implement roads/residency, then build influx,
fight/war, and diffusion on those foundations.
Roads and residency now provide the shared spatial foundation. Next build
influx, fight/war, and diffusion on it; issue #13 remains explicitly deferred.

View File

@ -8,6 +8,7 @@
use cli_table::Table;
use derive_more::Display;
use serde::{Deserialize, Serialize};
use std::collections::BTreeMap;
use std::fs::create_dir_all;
use uuid::Uuid;
@ -18,6 +19,7 @@ use crate::{
epoch_traits::{ConfigWritable, Prettiable},
},
error::EpochError,
simulation::{MobilityState, Road},
stats::{EntityType, Position, PositionIdentifier, Symbols, TypedLink},
};
@ -82,6 +84,14 @@ pub struct EpochInfo {
#[table(skip)]
/// The list of blockers currently present
pub blockers: Vec<Entity>,
/// Stable travel edges between towns.
#[serde(default)]
#[table(skip)]
pub roads: Vec<Road>,
/// Explicit character residency and travel intent, keyed by character UUID.
#[serde(default)]
#[table(skip)]
pub mobility: BTreeMap<Uuid, MobilityState>,
}
impl Prettiable for EpochInfo {}
@ -101,6 +111,8 @@ impl Default for EpochInfo {
towns: Vec::new(),
calamities: Vec::new(),
blockers: Vec::new(),
roads: Vec::new(),
mobility: BTreeMap::new(),
}
}
}

View File

@ -20,6 +20,7 @@ pub mod epoch;
pub mod naming;
pub mod output;
pub mod repository_format;
pub mod simulation;
pub mod stats;
pub mod transaction;
pub mod utils;

343
lib_efo/src/simulation.rs Normal file
View File

@ -0,0 +1,343 @@
//! Deterministic spatial travel primitives.
use std::{
cmp::Reverse,
collections::{BTreeMap, BinaryHeap, HashMap, HashSet},
};
use serde::{Deserialize, Serialize};
use uuid::Uuid;
use crate::{epoch::EpochInfo, stats::Position};
/// An undirected, stable road between two towns.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Road {
/// Stable road identity.
pub id: Uuid,
/// First town endpoint.
pub from: Uuid,
/// Second town endpoint.
pub to: Uuid,
/// Travel speed as a percentage of one map unit per tick.
pub speed_percent: u32,
/// Setting-specific searchable labels.
#[serde(default)]
pub tags: Vec<String>,
}
/// Persisted character relationship to space.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "state", rename_all = "snake_case")]
pub enum MobilityState {
/// Character remains tied to one town.
Resident {
/// Town containing the resident.
place: Uuid,
},
/// Character is not tied to a town and may travel directly.
Roaming {
/// Current unconstrained position.
position: Position,
},
/// Character is following a reviewable travel plan.
Travelling {
/// Position at the start of this plan.
origin: Position,
/// Destination town.
destination: Uuid,
/// Towns selected by the pathfinder, including destination.
route: Vec<Uuid>,
/// Applied ticks.
elapsed_ticks: u64,
/// Ticks required to arrive.
total_ticks: u64,
},
}
/// A deterministic route preview.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct TravelPlan {
/// Towns traversed; empty means direct off-road travel.
pub route: Vec<Uuid>,
/// Required simulation ticks.
pub total_ticks: u64,
/// Whether the selected route uses roads.
pub uses_roads: bool,
}
/// Invalid topology or travel request.
#[derive(Debug, thiserror::Error)]
pub enum SimulationError {
/// A referenced character does not exist.
#[error("character @{0} does not exist")]
CharacterMissing(Uuid),
/// A referenced town does not exist.
#[error("town @{0} does not exist")]
TownMissing(Uuid),
/// A road violates a topology invariant.
#[error("invalid road @{id}: {reason}")]
InvalidRoad {
/// Offending road identity.
id: Uuid,
/// Violated invariant.
reason: String,
},
/// Travel speed must be positive.
#[error("off-road speed must be greater than zero")]
InvalidSpeed,
}
/// Validate road identities, endpoints, and speeds.
pub fn validate_roads(world: &EpochInfo) -> Result<(), SimulationError> {
let towns = world
.towns
.iter()
.map(|town| town.id)
.collect::<HashSet<_>>();
let mut ids = HashSet::new();
let mut edges = HashSet::new();
for road in &world.roads {
let edge = if road.from < road.to {
(road.from, road.to)
} else {
(road.to, road.from)
};
let reason = if road.id.is_nil() || !ids.insert(road.id) {
Some("missing or duplicate identity")
} else if road.from == road.to {
Some("endpoints are identical")
} else if !towns.contains(&road.from) || !towns.contains(&road.to) {
Some("endpoint is not a town")
} else if road.speed_percent == 0 {
Some("speed percentage is zero")
} else if !edges.insert(edge) {
Some("duplicate endpoints")
} else {
None
};
if let Some(reason) = reason {
return Err(SimulationError::InvalidRoad {
id: road.id,
reason: reason.into(),
});
}
}
Ok(())
}
/// Validate that mobility keys and place references match stored entities.
pub fn validate_mobility(world: &EpochInfo) -> Result<(), SimulationError> {
let characters = world
.characters
.iter()
.map(|entity| entity.id)
.collect::<HashSet<_>>();
let towns = world
.towns
.iter()
.map(|entity| entity.id)
.collect::<HashSet<_>>();
for (character, state) in &world.mobility {
if !characters.contains(character) {
return Err(SimulationError::CharacterMissing(*character));
}
let place = match state {
MobilityState::Resident { place } => Some(*place),
MobilityState::Travelling { destination, .. } => Some(*destination),
MobilityState::Roaming { .. } => None,
};
if let Some(place) = place
&& !towns.contains(&place)
{
return Err(SimulationError::TownMissing(place));
}
}
Ok(())
}
/// Select the fastest road route, falling back to slower direct travel.
pub fn plan_travel(
world: &EpochInfo,
character: Uuid,
destination: Uuid,
offroad_speed: u32,
) -> Result<TravelPlan, SimulationError> {
validate_roads(world)?;
if offroad_speed == 0 {
return Err(SimulationError::InvalidSpeed);
}
let person = world
.characters
.iter()
.find(|entity| entity.id == character)
.ok_or(SimulationError::CharacterMissing(character))?;
let target = world
.towns
.iter()
.find(|entity| entity.id == destination)
.ok_or(SimulationError::TownMissing(destination))?;
let direct = ticks(person.position(), target.position(), offroad_speed);
let start = world
.mobility
.get(&character)
.and_then(|state| match state {
MobilityState::Resident { place } => Some(*place),
_ => None,
})
.or_else(|| {
world
.towns
.iter()
.find(|town| town.position() == person.position())
.map(|town| town.id)
});
let Some(start) = start else {
return Ok(TravelPlan {
route: Vec::new(),
total_ticks: direct,
uses_roads: false,
});
};
let Some((cost, route)) = road_route(world, start, destination) else {
return Ok(TravelPlan {
route: Vec::new(),
total_ticks: direct,
uses_roads: false,
});
};
if cost < direct {
Ok(TravelPlan {
route,
total_ticks: cost,
uses_roads: true,
})
} else {
Ok(TravelPlan {
route: Vec::new(),
total_ticks: direct,
uses_roads: false,
})
}
}
/// Store a previewed plan as worktree travel intent.
pub fn begin_travel(
world: &mut EpochInfo,
character: Uuid,
destination: Uuid,
plan: &TravelPlan,
) -> Result<(), SimulationError> {
let origin = world
.characters
.iter()
.find(|entity| entity.id == character)
.ok_or(SimulationError::CharacterMissing(character))?
.position()
.clone();
world.mobility.insert(
character,
MobilityState::Travelling {
origin,
destination,
route: plan.route.clone(),
elapsed_ticks: 0,
total_ticks: plan.total_ticks,
},
);
Ok(())
}
/// Advance every active journey and return the characters that arrived.
pub fn tick_travel(world: &mut EpochInfo, amount: u64) -> Vec<Uuid> {
let towns = world
.towns
.iter()
.map(|town| (town.id, town.position().clone()))
.collect::<HashMap<_, _>>();
let mut arrived = Vec::new();
for (character, state) in &mut world.mobility {
if let MobilityState::Travelling {
destination,
elapsed_ticks,
total_ticks,
..
} = state
{
*elapsed_ticks = elapsed_ticks.saturating_add(amount).min(*total_ticks);
if *elapsed_ticks == *total_ticks {
if let Some(position) = towns.get(destination)
&& let Some(entity) = world
.characters
.iter_mut()
.find(|entity| entity.id == *character)
{
entity.modify_position(position.clone());
}
let place = *destination;
*state = MobilityState::Resident { place };
arrived.push(*character);
}
}
}
arrived.sort_unstable();
arrived
}
/// Find the deterministic shortest road-time path.
fn road_route(world: &EpochInfo, start: Uuid, destination: Uuid) -> Option<(u64, Vec<Uuid>)> {
if start == destination {
return Some((0, vec![destination]));
}
let towns = world
.towns
.iter()
.map(|town| (town.id, town.position()))
.collect::<HashMap<_, _>>();
let mut graph: HashMap<Uuid, Vec<(Uuid, u64)>> = HashMap::new();
for road in &world.roads {
let cost = ticks(towns[&road.from], towns[&road.to], road.speed_percent);
graph.entry(road.from).or_default().push((road.to, cost));
graph.entry(road.to).or_default().push((road.from, cost));
}
for edges in graph.values_mut() {
edges.sort_unstable_by_key(|edge| edge.0);
}
let mut distances = HashMap::from([(start, 0_u64)]);
let mut previous = BTreeMap::new();
let mut queue = BinaryHeap::from([Reverse((0_u64, start))]);
while let Some(Reverse((cost, node))) = queue.pop() {
if node == destination {
break;
}
if cost > *distances.get(&node).unwrap_or(&u64::MAX) {
continue;
}
for &(next, edge) in graph.get(&node).map_or(&[][..], Vec::as_slice) {
let candidate = cost.saturating_add(edge);
if candidate < *distances.get(&next).unwrap_or(&u64::MAX) {
distances.insert(next, candidate);
previous.insert(next, node);
queue.push(Reverse((candidate, next)));
}
}
}
let cost = *distances.get(&destination)?;
let mut route = vec![destination];
let mut cursor = destination;
while cursor != start {
cursor = *previous.get(&cursor)?;
route.push(cursor);
}
route.reverse();
Some((cost, route))
}
/// Convert geometric distance and integer speed into at least one tick.
fn ticks(from: &Position, to: &Position, speed_percent: u32) -> u64 {
let distance = from.distance(to).unsigned_abs() as u64;
distance
.saturating_mul(100)
.div_ceil(u64::from(speed_percent))
.max(1)
}

View File

@ -489,7 +489,7 @@ pub struct StatPair {
///
/// The struct is a thin wrapper around a pair of `isize` values
/// representing the X and Y coordinates.
#[derive(Debug, Default, Serialize, Deserialize, Clone, Add, Sub, Mul)]
#[derive(Debug, Default, Serialize, Deserialize, Clone, PartialEq, Eq, Add, Sub, Mul)]
pub struct Position(isize, isize);
/// A grid-aligned position used for chunk look-ups.

View File

@ -14,6 +14,7 @@ use crate::{
entity::EntityIdentifier,
epoch::{EntityIndex, EpochInfo},
repository_format::{FormatError, RepositoryManifest, RepositorySnapshot, decode_manifest},
simulation::{validate_mobility, validate_roads},
stats::EntityType,
transaction::{
RepositoryLock, TransactionError, replace_file, replace_files, replace_files_locked,
@ -824,6 +825,9 @@ fn copy_world_metadata(source: &EpochInfo, destination: &mut EpochInfo) {
/// Validate stable identity, collection type, and relationship targets.
fn validate_world(label: &str, world: &EpochInfo) -> Result<(), WorkspaceError> {
validate_roads(world)
.and_then(|()| validate_mobility(world))
.map_err(|error| WorkspaceError::Inconsistent(format!("{label} {error}")))?;
let index = EntityIndex::build(world);
if !index.duplicate_ids().is_empty() {
return Err(WorkspaceError::Inconsistent(format!(

104
lib_efo/tests/simulation.rs Normal file
View File

@ -0,0 +1,104 @@
use lib_efo::{
entity::Entity,
epoch::EpochInfo,
simulation::{MobilityState, Road, begin_travel, plan_travel, tick_travel, validate_roads},
stats::EntityType,
};
use uuid::Uuid;
fn entity(id: u128, kind: EntityType, position: &str) -> Entity {
let mut entity = Entity::default();
entity.id = Uuid::from_u128(id);
entity.name = format!("entity {id}");
entity.entity_type = kind;
entity.modify_position(position.parse().expect("position"));
entity
}
fn world() -> EpochInfo {
let mut world = EpochInfo {
towns: vec![
entity(1, EntityType::Town, "0,0"),
entity(2, EntityType::Town, "10,0"),
entity(3, EntityType::Town, "20,0"),
],
characters: vec![entity(4, EntityType::Character, "0,0")],
..EpochInfo::default()
};
world.mobility.insert(
Uuid::from_u128(4),
MobilityState::Resident {
place: Uuid::from_u128(1),
},
);
world.roads = vec![
Road {
id: Uuid::from_u128(10),
from: Uuid::from_u128(1),
to: Uuid::from_u128(2),
speed_percent: 200,
tags: vec!["paved".into()],
},
Road {
id: Uuid::from_u128(11),
from: Uuid::from_u128(2),
to: Uuid::from_u128(3),
speed_percent: 200,
tags: Vec::new(),
},
];
world
}
#[test]
fn fastest_route_is_deterministic_and_travel_arrives_reversibly() {
let mut world = world();
let plan =
plan_travel(&world, Uuid::from_u128(4), Uuid::from_u128(3), 50).expect("travel plan");
assert!(plan.uses_roads);
assert_eq!(
plan.route,
[Uuid::from_u128(1), Uuid::from_u128(2), Uuid::from_u128(3)]
);
assert_eq!(plan.total_ticks, 10);
begin_travel(&mut world, Uuid::from_u128(4), Uuid::from_u128(3), &plan).expect("begin");
assert!(tick_travel(&mut world, 9).is_empty());
assert_eq!(tick_travel(&mut world, 1), [Uuid::from_u128(4)]);
assert_eq!(
world.mobility[&Uuid::from_u128(4)],
MobilityState::Resident {
place: Uuid::from_u128(3)
}
);
assert_eq!(world.characters[0].position().to_inner(), (20, 0));
}
#[test]
fn direct_fallback_and_invalid_topology_are_explicit() {
let mut world = world();
world.roads.clear();
let plan =
plan_travel(&world, Uuid::from_u128(4), Uuid::from_u128(3), 50).expect("direct plan");
assert!(!plan.uses_roads);
assert_eq!(plan.total_ticks, 40);
world.roads.push(Road {
id: Uuid::from_u128(12),
from: Uuid::from_u128(1),
to: Uuid::from_u128(1),
speed_percent: 100,
tags: Vec::new(),
});
assert!(validate_roads(&world).is_err());
}
#[test]
fn old_snapshots_default_new_spatial_fields() {
let mut value = serde_json::to_value(EpochInfo::default()).expect("serialize");
value.as_object_mut().expect("object").remove("roads");
value.as_object_mut().expect("object").remove("mobility");
let decoded: EpochInfo = serde_json::from_value(value).expect("old snapshot");
assert!(decoded.roads.is_empty());
assert!(decoded.mobility.is_empty());
}