Skip to main content

elevator_core/
sim.rs

1//! Top-level simulation runner and tick loop.
2//!
3//! # Essential API
4//!
5//! `Simulation` exposes a large surface, but most users only need the
6//! ~15 methods below, grouped by the order they appear in a typical
7//! game loop.
8//!
9//! ### Construction
10//!
11//! - [`SimulationBuilder::demo()`](crate::builder::SimulationBuilder::demo)
12//!   or [`SimulationBuilder::from_config()`](crate::builder::SimulationBuilder::from_config)
13//!   — fluent entry point; call [`.build()`](crate::builder::SimulationBuilder::build)
14//!   to get a `Simulation`.
15//! - [`Simulation::new()`](crate::sim::Simulation::new) — direct construction from
16//!   `&SimConfig` + a dispatch strategy.
17//!
18//! ### Per-tick driving
19//!
20//! - [`Simulation::step()`](crate::sim::Simulation::step) — run all 8 phases.
21//! - [`Simulation::current_tick()`](crate::sim::Simulation::current_tick) — the
22//!   current tick counter.
23//!
24//! ### Spawning and rerouting riders
25//!
26//! - [`Simulation::spawn_rider()`](crate::sim::Simulation::spawn_rider)
27//!   — simple origin/destination/weight spawn (accepts `EntityId` or `StopId`).
28//! - [`Simulation::build_rider()`](crate::sim::Simulation::build_rider)
29//!   — fluent [`RiderBuilder`](crate::sim::RiderBuilder) for patience, preferences, access
30//!   control, explicit groups, multi-leg routes (accepts `EntityId` or `StopId`).
31//! - [`Simulation::reroute()`](crate::sim::Simulation::reroute) — change a waiting
32//!   rider's destination mid-trip.
33//! - [`Simulation::settle_rider()`](crate::sim::Simulation::settle_rider) /
34//!   [`Simulation::despawn_rider()`](crate::sim::Simulation::despawn_rider) —
35//!   terminal-state cleanup for `Arrived`/`Abandoned` riders.
36//!
37//! ### Observability
38//!
39//! - [`Simulation::drain_events()`](crate::sim::Simulation::drain_events) — consume
40//!   the event stream emitted by the last tick.
41//! - [`Simulation::metrics()`](crate::sim::Simulation::metrics) — aggregate
42//!   wait/ride/throughput stats.
43//! - [`Simulation::waiting_at()`](crate::sim::Simulation::waiting_at) /
44//!   [`Simulation::residents_at()`](crate::sim::Simulation::residents_at) — O(1)
45//!   population queries by stop.
46//!
47//! ### Imperative control
48//!
49//! - [`Simulation::push_destination()`](crate::sim::Simulation::push_destination) /
50//!   [`Simulation::push_destination_front()`](crate::sim::Simulation::push_destination_front) /
51//!   [`Simulation::clear_destinations()`](crate::sim::Simulation::clear_destinations)
52//!   — override dispatch by pushing/clearing stops on an elevator's
53//!   [`DestinationQueue`](crate::components::DestinationQueue).
54//! - [`Simulation::abort_movement()`](crate::sim::Simulation::abort_movement)
55//!   — hard-abort an in-flight trip, braking the car to the nearest
56//!   reachable stop without opening doors (riders stay aboard).
57//!
58//! ### Persistence
59//!
60//! - [`Simulation::snapshot()`](crate::sim::Simulation::snapshot) — capture full
61//!   state as a serializable [`WorldSnapshot`](crate::snapshot::WorldSnapshot).
62//! - [`WorldSnapshot::restore()`](crate::snapshot::WorldSnapshot::restore)
63//!   — rebuild a `Simulation` from a snapshot.
64//!
65//! Everything else (phase-runners, world-level accessors, energy, tag
66//! metrics, topology queries) is available for advanced use but is not
67//! required for the common case.
68
69mod accessors;
70mod calls;
71mod construction;
72mod destinations;
73mod eta;
74mod lifecycle;
75mod manual;
76mod rider;
77mod runtime;
78pub(crate) mod strategy_set;
79mod substep;
80mod tagging;
81mod topology;
82
83pub(crate) use strategy_set::{DispatcherSet, RepositionerSet};
84#[allow(clippy::redundant_pub_crate)]
85pub(crate) mod transition;
86
87pub use rider::RiderBuilder;
88
89use crate::components::{Accel, Orientation, SpatialPosition, Speed, Weight};
90use crate::dispatch::ElevatorGroup;
91use crate::entity::EntityId;
92use crate::events::{Event, EventBus};
93use crate::hooks::PhaseHooks;
94use crate::ids::GroupId;
95use crate::metrics::Metrics;
96use crate::rider_index::RiderIndex;
97use crate::stop::StopId;
98use crate::time::TimeAdapter;
99use crate::topology::TopologyGraph;
100use crate::world::World;
101use std::collections::{HashMap, HashSet};
102use std::fmt;
103use std::sync::Mutex;
104
105/// Parameters for creating a new elevator at runtime.
106#[derive(Debug, Clone)]
107pub struct ElevatorParams {
108    /// Maximum travel speed (distance/tick).
109    pub max_speed: Speed,
110    /// Acceleration rate (distance/tick^2).
111    pub acceleration: Accel,
112    /// Deceleration rate (distance/tick^2).
113    pub deceleration: Accel,
114    /// Maximum weight the car can carry.
115    pub weight_capacity: Weight,
116    /// Ticks for a door open/close transition.
117    pub door_transition_ticks: u32,
118    /// Ticks the door stays fully open.
119    pub door_open_ticks: u32,
120    /// Stop entity IDs this elevator cannot serve (access restriction).
121    pub restricted_stops: HashSet<EntityId>,
122    /// Speed multiplier for Inspection mode (0.0..1.0).
123    pub inspection_speed_factor: f64,
124    /// Full-load bypass threshold for upward pickups (see
125    /// [`Elevator::bypass_load_up_pct`](crate::components::Elevator::bypass_load_up_pct)).
126    pub bypass_load_up_pct: Option<f64>,
127    /// Full-load bypass threshold for downward pickups.
128    pub bypass_load_down_pct: Option<f64>,
129}
130
131impl Default for ElevatorParams {
132    fn default() -> Self {
133        Self {
134            max_speed: Speed::from(2.0),
135            acceleration: Accel::from(1.5),
136            deceleration: Accel::from(2.0),
137            weight_capacity: Weight::from(800.0),
138            door_transition_ticks: 5,
139            door_open_ticks: 10,
140            restricted_stops: HashSet::new(),
141            inspection_speed_factor: 0.25,
142            bypass_load_up_pct: None,
143            bypass_load_down_pct: None,
144        }
145    }
146}
147
148/// Parameters for creating a new line at runtime.
149#[derive(Debug, Clone)]
150pub struct LineParams {
151    /// Human-readable name.
152    pub name: String,
153    /// Dispatch group to add this line to.
154    pub group: GroupId,
155    /// Physical orientation.
156    pub orientation: Orientation,
157    /// Lowest reachable position on the line axis.
158    pub min_position: f64,
159    /// Highest reachable position on the line axis.
160    pub max_position: f64,
161    /// Optional floor-plan position.
162    pub position: Option<SpatialPosition>,
163    /// Maximum cars on this line (None = unlimited).
164    pub max_cars: Option<usize>,
165}
166
167impl LineParams {
168    /// Create line parameters with the given name and group, defaulting
169    /// everything else.
170    pub fn new(name: impl Into<String>, group: GroupId) -> Self {
171        Self {
172            name: name.into(),
173            group,
174            orientation: Orientation::default(),
175            min_position: 0.0,
176            max_position: 0.0,
177            position: None,
178            max_cars: None,
179        }
180    }
181}
182
183/// The core simulation state, advanced by calling `step()`.
184pub struct Simulation {
185    /// The ECS world containing all entity data.
186    world: World,
187    /// Internal event bus — only holds events from the current tick.
188    events: EventBus,
189    /// Events from completed ticks, available to consumers via `drain_events()`.
190    pending_output: Vec<Event>,
191    /// Current simulation tick.
192    tick: u64,
193    /// Time delta per tick (seconds).
194    dt: f64,
195    /// Elevator groups in this simulation.
196    groups: Vec<ElevatorGroup>,
197    /// Config `StopId` to `EntityId` mapping for spawn helpers.
198    stop_lookup: HashMap<StopId, EntityId>,
199    /// Dispatch strategies + their snapshot identities, keyed by group.
200    /// Owns both halves so insert/remove stay atomic — see
201    /// [`DispatcherSet`].
202    dispatcher_set: DispatcherSet,
203    /// Reposition strategies + their snapshot identities, keyed by group.
204    /// Empty when no group opts into the reposition phase.
205    repositioner_set: RepositionerSet,
206    /// Aggregated metrics.
207    metrics: Metrics,
208    /// Time conversion utility.
209    time: TimeAdapter,
210    /// Lifecycle hooks (before/after each phase).
211    hooks: PhaseHooks,
212    /// Reusable buffer for elevator IDs (avoids per-tick allocation).
213    elevator_ids_buf: Vec<EntityId>,
214    /// Reusable buffer for reposition decisions (avoids per-tick allocation).
215    reposition_buf: Vec<(EntityId, EntityId)>,
216    /// Scratch buffers owned by the dispatch phase — the cost matrix,
217    /// pending-stops list, servicing slice, pinned / committed /
218    /// idle-elevator filters. Holding them on the sim means each
219    /// dispatch pass reuses capacity instead of re-allocating.
220    ///
221    /// Stays `pub(crate)` rather than method-encapsulated because the
222    /// dispatch phase needs simultaneous disjoint mutable borrows of
223    /// `world`, `events`, and the scratch — a getter returning
224    /// `&mut DispatchScratch` would borrow all of `self`, conflicting
225    /// with `&mut self.world` in the same call.
226    pub(crate) dispatch_scratch: crate::dispatch::DispatchScratch,
227    /// Lazy-rebuilt connectivity graph for cross-line topology queries.
228    topo_graph: Mutex<TopologyGraph>,
229    /// Phase-partitioned reverse index for O(1) population queries.
230    rider_index: RiderIndex,
231    /// True between the first per-phase `run_*` call and the matching
232    /// `advance_tick()`. Used by [`try_snapshot`](Self::try_snapshot) to
233    /// reject mid-tick captures that would lose in-progress event-bus
234    /// state. Always false outside the substep API path because
235    /// [`step()`](Self::step) takes `&mut self` and snapshots take
236    /// `&self`. (#297) Read via [`tick_in_progress`](Self::tick_in_progress);
237    /// the substep loop owns the mutation through
238    /// [`set_tick_in_progress`](Self::set_tick_in_progress).
239    tick_in_progress: bool,
240}
241
242impl Simulation {
243    /// Whether the sim is between [`run_advance_transient`] and
244    /// [`advance_tick`] — i.e. mid-tick. Snapshot capture needs this
245    /// to reject mid-tick saves that would lose in-progress
246    /// event-bus state.
247    ///
248    /// [`run_advance_transient`]: Self::run_advance_transient
249    /// [`advance_tick`]: Self::advance_tick
250    #[must_use]
251    pub(crate) const fn tick_in_progress(&self) -> bool {
252        self.tick_in_progress
253    }
254
255    /// Set the mid-tick guard. Owned by the substep runner — only
256    /// `run_advance_transient` flips it on and `advance_tick` flips
257    /// it off.
258    pub(crate) const fn set_tick_in_progress(&mut self, in_progress: bool) {
259        self.tick_in_progress = in_progress;
260    }
261}
262
263impl fmt::Debug for Simulation {
264    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
265        f.debug_struct("Simulation")
266            .field("tick", &self.tick)
267            .field("dt", &self.dt)
268            .field("groups", &self.groups.len())
269            .field("entities", &self.world.entity_count())
270            .finish_non_exhaustive()
271    }
272}