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//!
55//! ### Persistence
56//!
57//! - [`Simulation::snapshot()`](crate::sim::Simulation::snapshot) — capture full
58//! state as a serializable [`WorldSnapshot`](crate::snapshot::WorldSnapshot).
59//! - [`WorldSnapshot::restore()`](crate::snapshot::WorldSnapshot::restore)
60//! — rebuild a `Simulation` from a snapshot.
61//!
62//! Everything else (phase-runners, world-level accessors, energy, tag
63//! metrics, topology queries) is available for advanced use but is not
64//! required for the common case.
65
66mod construction;
67mod lifecycle;
68mod topology;
69
70use crate::components::{
71 Accel, AccessControl, Orientation, Patience, Preferences, Rider, RiderPhase, Route,
72 SpatialPosition, Speed, Velocity, Weight,
73};
74use crate::dispatch::{BuiltinReposition, DispatchStrategy, ElevatorGroup, RepositionStrategy};
75use crate::entity::EntityId;
76use crate::error::{EtaError, SimError};
77use crate::events::{Event, EventBus};
78use crate::hooks::{Phase, PhaseHooks};
79use crate::ids::GroupId;
80use crate::metrics::Metrics;
81use crate::rider_index::RiderIndex;
82use crate::stop::{StopId, StopRef};
83use crate::systems::PhaseContext;
84use crate::time::TimeAdapter;
85use crate::topology::TopologyGraph;
86use crate::world::World;
87use std::collections::{BTreeMap, HashMap, HashSet};
88use std::fmt;
89use std::sync::Mutex;
90use std::time::Duration;
91
92/// Parameters for creating a new elevator at runtime.
93#[derive(Debug, Clone)]
94pub struct ElevatorParams {
95 /// Maximum travel speed (distance/tick).
96 pub max_speed: Speed,
97 /// Acceleration rate (distance/tick^2).
98 pub acceleration: Accel,
99 /// Deceleration rate (distance/tick^2).
100 pub deceleration: Accel,
101 /// Maximum weight the car can carry.
102 pub weight_capacity: Weight,
103 /// Ticks for a door open/close transition.
104 pub door_transition_ticks: u32,
105 /// Ticks the door stays fully open.
106 pub door_open_ticks: u32,
107 /// Stop entity IDs this elevator cannot serve (access restriction).
108 pub restricted_stops: HashSet<EntityId>,
109 /// Speed multiplier for Inspection mode (0.0..1.0).
110 pub inspection_speed_factor: f64,
111}
112
113impl Default for ElevatorParams {
114 fn default() -> Self {
115 Self {
116 max_speed: Speed::from(2.0),
117 acceleration: Accel::from(1.5),
118 deceleration: Accel::from(2.0),
119 weight_capacity: Weight::from(800.0),
120 door_transition_ticks: 5,
121 door_open_ticks: 10,
122 restricted_stops: HashSet::new(),
123 inspection_speed_factor: 0.25,
124 }
125 }
126}
127
128/// Parameters for creating a new line at runtime.
129#[derive(Debug, Clone)]
130pub struct LineParams {
131 /// Human-readable name.
132 pub name: String,
133 /// Dispatch group to add this line to.
134 pub group: GroupId,
135 /// Physical orientation.
136 pub orientation: Orientation,
137 /// Lowest reachable position on the line axis.
138 pub min_position: f64,
139 /// Highest reachable position on the line axis.
140 pub max_position: f64,
141 /// Optional floor-plan position.
142 pub position: Option<SpatialPosition>,
143 /// Maximum cars on this line (None = unlimited).
144 pub max_cars: Option<usize>,
145}
146
147impl LineParams {
148 /// Create line parameters with the given name and group, defaulting
149 /// everything else.
150 pub fn new(name: impl Into<String>, group: GroupId) -> Self {
151 Self {
152 name: name.into(),
153 group,
154 orientation: Orientation::default(),
155 min_position: 0.0,
156 max_position: 0.0,
157 position: None,
158 max_cars: None,
159 }
160 }
161}
162
163/// Fluent builder for spawning riders with optional configuration.
164///
165/// Created via [`Simulation::build_rider`].
166///
167/// ```
168/// use elevator_core::prelude::*;
169///
170/// let mut sim = SimulationBuilder::demo().build().unwrap();
171/// let rider = sim.build_rider(StopId(0), StopId(1))
172/// .unwrap()
173/// .weight(80.0)
174/// .spawn()
175/// .unwrap();
176/// ```
177pub struct RiderBuilder<'a> {
178 /// Mutable reference to the simulation (consumed on spawn).
179 sim: &'a mut Simulation,
180 /// Origin stop entity.
181 origin: EntityId,
182 /// Destination stop entity.
183 destination: EntityId,
184 /// Rider weight (default: 75.0).
185 weight: Weight,
186 /// Explicit dispatch group (skips auto-detection).
187 group: Option<GroupId>,
188 /// Explicit multi-leg route.
189 route: Option<Route>,
190 /// Maximum wait ticks before abandoning.
191 patience: Option<u64>,
192 /// Boarding preferences.
193 preferences: Option<Preferences>,
194 /// Per-rider access control.
195 access_control: Option<AccessControl>,
196}
197
198impl RiderBuilder<'_> {
199 /// Set the rider's weight (default: 75.0).
200 #[must_use]
201 pub fn weight(mut self, weight: impl Into<Weight>) -> Self {
202 self.weight = weight.into();
203 self
204 }
205
206 /// Set the dispatch group explicitly, skipping auto-detection.
207 #[must_use]
208 pub const fn group(mut self, group: GroupId) -> Self {
209 self.group = Some(group);
210 self
211 }
212
213 /// Provide an explicit multi-leg route.
214 #[must_use]
215 pub fn route(mut self, route: Route) -> Self {
216 self.route = Some(route);
217 self
218 }
219
220 /// Set maximum wait ticks before the rider abandons.
221 #[must_use]
222 pub const fn patience(mut self, max_wait_ticks: u64) -> Self {
223 self.patience = Some(max_wait_ticks);
224 self
225 }
226
227 /// Set boarding preferences.
228 #[must_use]
229 pub const fn preferences(mut self, prefs: Preferences) -> Self {
230 self.preferences = Some(prefs);
231 self
232 }
233
234 /// Set per-rider access control (allowed stops).
235 #[must_use]
236 pub fn access_control(mut self, ac: AccessControl) -> Self {
237 self.access_control = Some(ac);
238 self
239 }
240
241 /// Spawn the rider with the configured options.
242 ///
243 /// # Errors
244 ///
245 /// Returns [`SimError::NoRoute`] if no group serves both stops (when auto-detecting).
246 /// Returns [`SimError::AmbiguousRoute`] if multiple groups serve both stops (when auto-detecting).
247 /// Returns [`SimError::GroupNotFound`] if an explicit group does not exist.
248 /// Returns [`SimError::RouteOriginMismatch`] if an explicit route's first leg
249 /// does not start at `origin`.
250 pub fn spawn(self) -> Result<EntityId, SimError> {
251 let route = if let Some(route) = self.route {
252 // Validate route origin matches the spawn origin.
253 if let Some(leg) = route.current()
254 && leg.from != self.origin
255 {
256 return Err(SimError::RouteOriginMismatch {
257 expected_origin: self.origin,
258 route_origin: leg.from,
259 });
260 }
261 route
262 } else if let Some(group) = self.group {
263 if !self.sim.groups.iter().any(|g| g.id() == group) {
264 return Err(SimError::GroupNotFound(group));
265 }
266 Route::direct(self.origin, self.destination, group)
267 } else {
268 // Auto-detect group (same logic as spawn_rider).
269 let matching: Vec<GroupId> = self
270 .sim
271 .groups
272 .iter()
273 .filter(|g| {
274 g.stop_entities().contains(&self.origin)
275 && g.stop_entities().contains(&self.destination)
276 })
277 .map(ElevatorGroup::id)
278 .collect();
279
280 match matching.len() {
281 0 => {
282 let origin_groups: Vec<GroupId> = self
283 .sim
284 .groups
285 .iter()
286 .filter(|g| g.stop_entities().contains(&self.origin))
287 .map(ElevatorGroup::id)
288 .collect();
289 let destination_groups: Vec<GroupId> = self
290 .sim
291 .groups
292 .iter()
293 .filter(|g| g.stop_entities().contains(&self.destination))
294 .map(ElevatorGroup::id)
295 .collect();
296 return Err(SimError::NoRoute {
297 origin: self.origin,
298 destination: self.destination,
299 origin_groups,
300 destination_groups,
301 });
302 }
303 1 => Route::direct(self.origin, self.destination, matching[0]),
304 _ => {
305 return Err(SimError::AmbiguousRoute {
306 origin: self.origin,
307 destination: self.destination,
308 groups: matching,
309 });
310 }
311 }
312 };
313
314 let eid = self
315 .sim
316 .spawn_rider_inner(self.origin, self.destination, self.weight, route);
317
318 // Apply optional components.
319 if let Some(max_wait) = self.patience {
320 self.sim.world.set_patience(
321 eid,
322 Patience {
323 max_wait_ticks: max_wait,
324 waited_ticks: 0,
325 },
326 );
327 }
328 if let Some(prefs) = self.preferences {
329 self.sim.world.set_preferences(eid, prefs);
330 }
331 if let Some(ac) = self.access_control {
332 self.sim.world.set_access_control(eid, ac);
333 }
334
335 Ok(eid)
336 }
337}
338
339/// The core simulation state, advanced by calling `step()`.
340pub struct Simulation {
341 /// The ECS world containing all entity data.
342 world: World,
343 /// Internal event bus — only holds events from the current tick.
344 events: EventBus,
345 /// Events from completed ticks, available to consumers via `drain_events()`.
346 pending_output: Vec<Event>,
347 /// Current simulation tick.
348 tick: u64,
349 /// Time delta per tick (seconds).
350 dt: f64,
351 /// Elevator groups in this simulation.
352 groups: Vec<ElevatorGroup>,
353 /// Config `StopId` to `EntityId` mapping for spawn helpers.
354 stop_lookup: HashMap<StopId, EntityId>,
355 /// Dispatch strategies keyed by group.
356 dispatchers: BTreeMap<GroupId, Box<dyn DispatchStrategy>>,
357 /// Serializable strategy identifiers (for snapshot).
358 strategy_ids: BTreeMap<GroupId, crate::dispatch::BuiltinStrategy>,
359 /// Reposition strategies keyed by group (optional per group).
360 repositioners: BTreeMap<GroupId, Box<dyn RepositionStrategy>>,
361 /// Serializable reposition strategy identifiers (for snapshot).
362 reposition_ids: BTreeMap<GroupId, BuiltinReposition>,
363 /// Aggregated metrics.
364 metrics: Metrics,
365 /// Time conversion utility.
366 time: TimeAdapter,
367 /// Lifecycle hooks (before/after each phase).
368 hooks: PhaseHooks,
369 /// Reusable buffer for elevator IDs (avoids per-tick allocation).
370 elevator_ids_buf: Vec<EntityId>,
371 /// Reusable buffer for reposition decisions (avoids per-tick allocation).
372 reposition_buf: Vec<(EntityId, EntityId)>,
373 /// Lazy-rebuilt connectivity graph for cross-line topology queries.
374 topo_graph: Mutex<TopologyGraph>,
375 /// Phase-partitioned reverse index for O(1) population queries.
376 rider_index: RiderIndex,
377}
378
379impl Simulation {
380 // ── Accessors ────────────────────────────────────────────────────
381
382 /// Get a shared reference to the world.
383 //
384 // Intentionally non-`const`: a `const` qualifier on a runtime accessor
385 // signals "usable in const context", which these methods are not in
386 // practice (the `World` is heap-allocated and mutated). Marking them
387 // `const` misleads readers without unlocking any call sites.
388 #[must_use]
389 #[allow(clippy::missing_const_for_fn)]
390 pub fn world(&self) -> &World {
391 &self.world
392 }
393
394 /// Get a mutable reference to the world.
395 ///
396 /// Exposed for advanced use cases (manual rider management, custom
397 /// component attachment). Prefer `spawn_rider` / `build_rider`
398 /// for standard operations.
399 #[allow(clippy::missing_const_for_fn)]
400 pub fn world_mut(&mut self) -> &mut World {
401 &mut self.world
402 }
403
404 /// Current simulation tick.
405 #[must_use]
406 pub const fn current_tick(&self) -> u64 {
407 self.tick
408 }
409
410 /// Time delta per tick (seconds).
411 #[must_use]
412 pub const fn dt(&self) -> f64 {
413 self.dt
414 }
415
416 /// Interpolated position between the previous and current tick.
417 ///
418 /// `alpha` is clamped to `[0.0, 1.0]`, where `0.0` returns the entity's
419 /// position at the start of the last completed tick and `1.0` returns
420 /// the current position. Intended for smooth rendering when a render
421 /// frame falls between simulation ticks.
422 ///
423 /// Returns `None` if the entity has no position component. Returns the
424 /// current position unchanged if no previous snapshot exists (i.e. before
425 /// the first [`step`](Self::step)).
426 ///
427 /// [`step`]: Self::step
428 #[must_use]
429 pub fn position_at(&self, id: EntityId, alpha: f64) -> Option<f64> {
430 let current = self.world.position(id)?.value;
431 let alpha = if alpha.is_nan() {
432 0.0
433 } else {
434 alpha.clamp(0.0, 1.0)
435 };
436 let prev = self.world.prev_position(id).map_or(current, |p| p.value);
437 Some((current - prev).mul_add(alpha, prev))
438 }
439
440 /// Current velocity of an entity along the shaft axis (signed: +up, -down).
441 ///
442 /// Convenience wrapper over [`World::velocity`] that returns the raw
443 /// `f64` value. Returns `None` if the entity has no velocity component.
444 #[must_use]
445 pub fn velocity(&self, id: EntityId) -> Option<f64> {
446 self.world.velocity(id).map(Velocity::value)
447 }
448
449 /// Get current simulation metrics.
450 #[must_use]
451 pub const fn metrics(&self) -> &Metrics {
452 &self.metrics
453 }
454
455 /// The time adapter for tick↔wall-clock conversion.
456 #[must_use]
457 pub const fn time(&self) -> &TimeAdapter {
458 &self.time
459 }
460
461 /// Get the elevator groups.
462 #[must_use]
463 pub fn groups(&self) -> &[ElevatorGroup] {
464 &self.groups
465 }
466
467 /// Mutable access to the group collection. Use this to flip a group
468 /// into [`HallCallMode::Destination`](crate::dispatch::HallCallMode)
469 /// or tune its `ack_latency_ticks` after construction. Changing the
470 /// line/elevator structure here is not supported — use the dedicated
471 /// topology mutators for that.
472 pub fn groups_mut(&mut self) -> &mut [ElevatorGroup] {
473 &mut self.groups
474 }
475
476 /// Resolve a config `StopId` to its runtime `EntityId`.
477 #[must_use]
478 pub fn stop_entity(&self, id: StopId) -> Option<EntityId> {
479 self.stop_lookup.get(&id).copied()
480 }
481
482 /// Resolve a [`StopRef`] to its runtime [`EntityId`].
483 fn resolve_stop(&self, stop: StopRef) -> Result<EntityId, SimError> {
484 match stop {
485 StopRef::ByEntity(id) => Ok(id),
486 StopRef::ById(sid) => self.stop_entity(sid).ok_or(SimError::StopNotFound(sid)),
487 }
488 }
489
490 /// Get the strategy identifier for a group.
491 #[must_use]
492 pub fn strategy_id(&self, group: GroupId) -> Option<&crate::dispatch::BuiltinStrategy> {
493 self.strategy_ids.get(&group)
494 }
495
496 /// Iterate over the stop ID → entity ID mapping.
497 pub fn stop_lookup_iter(&self) -> impl Iterator<Item = (&StopId, &EntityId)> {
498 self.stop_lookup.iter()
499 }
500
501 /// Peek at events pending for consumer retrieval.
502 #[must_use]
503 pub fn pending_events(&self) -> &[Event] {
504 &self.pending_output
505 }
506
507 // ── Destination queue (imperative dispatch) ────────────────────
508
509 /// Read-only view of an elevator's destination queue (FIFO of target
510 /// stop `EntityId`s).
511 ///
512 /// Returns `None` if `elev` is not an elevator entity. Returns
513 /// `Some(&[])` for elevators with an empty queue.
514 #[must_use]
515 pub fn destination_queue(&self, elev: EntityId) -> Option<&[EntityId]> {
516 self.world
517 .destination_queue(elev)
518 .map(crate::components::DestinationQueue::queue)
519 }
520
521 /// Push a stop onto the back of an elevator's destination queue.
522 ///
523 /// Adjacent duplicates are suppressed: if the last entry already equals
524 /// `stop`, the queue is unchanged and no event is emitted.
525 /// Otherwise emits [`Event::DestinationQueued`].
526 ///
527 /// # Errors
528 ///
529 /// - [`SimError::NotAnElevator`] if `elev` is not an elevator.
530 /// - [`SimError::NotAStop`] if `stop` is not a stop.
531 pub fn push_destination(
532 &mut self,
533 elev: EntityId,
534 stop: impl Into<StopRef>,
535 ) -> Result<(), SimError> {
536 let stop = self.resolve_stop(stop.into())?;
537 self.validate_push_targets(elev, stop)?;
538 let appended = self
539 .world
540 .destination_queue_mut(elev)
541 .is_some_and(|q| q.push_back(stop));
542 if appended {
543 self.events.emit(Event::DestinationQueued {
544 elevator: elev,
545 stop,
546 tick: self.tick,
547 });
548 }
549 Ok(())
550 }
551
552 /// Insert a stop at the front of an elevator's destination queue —
553 /// "go here next, before anything else in the queue".
554 ///
555 /// On the next `AdvanceQueue` phase (between Dispatch and Movement),
556 /// the elevator redirects to this new front if it differs from the
557 /// current target.
558 ///
559 /// Adjacent duplicates are suppressed: if the first entry already equals
560 /// `stop`, the queue is unchanged and no event is emitted.
561 ///
562 /// # Errors
563 ///
564 /// - [`SimError::NotAnElevator`] if `elev` is not an elevator.
565 /// - [`SimError::NotAStop`] if `stop` is not a stop.
566 pub fn push_destination_front(
567 &mut self,
568 elev: EntityId,
569 stop: impl Into<StopRef>,
570 ) -> Result<(), SimError> {
571 let stop = self.resolve_stop(stop.into())?;
572 self.validate_push_targets(elev, stop)?;
573 let inserted = self
574 .world
575 .destination_queue_mut(elev)
576 .is_some_and(|q| q.push_front(stop));
577 if inserted {
578 self.events.emit(Event::DestinationQueued {
579 elevator: elev,
580 stop,
581 tick: self.tick,
582 });
583 }
584 Ok(())
585 }
586
587 /// Clear an elevator's destination queue.
588 ///
589 /// TODO: clearing does not currently abort an in-flight movement — the
590 /// elevator will finish its current leg and then go idle (since the
591 /// queue is empty). A future change can add a phase transition to
592 /// cancel mid-flight.
593 ///
594 /// # Errors
595 ///
596 /// Returns [`SimError::NotAnElevator`] if `elev` is not an elevator.
597 pub fn clear_destinations(&mut self, elev: EntityId) -> Result<(), SimError> {
598 if self.world.elevator(elev).is_none() {
599 return Err(SimError::NotAnElevator(elev));
600 }
601 if let Some(q) = self.world.destination_queue_mut(elev) {
602 q.clear();
603 }
604 Ok(())
605 }
606
607 /// Validate that `elev` is an elevator and `stop` is a stop.
608 fn validate_push_targets(&self, elev: EntityId, stop: EntityId) -> Result<(), SimError> {
609 if self.world.elevator(elev).is_none() {
610 return Err(SimError::NotAnElevator(elev));
611 }
612 if self.world.stop(stop).is_none() {
613 return Err(SimError::NotAStop(stop));
614 }
615 Ok(())
616 }
617
618 // ── ETA queries ─────────────────────────────────────────────────
619
620 /// Estimated time until `elev` arrives at `stop`, summing closed-form
621 /// trapezoidal travel time for every leg up to (and including) the leg
622 /// that ends at `stop`, plus the door dwell at every *intermediate* stop.
623 ///
624 /// "Arrival" is the moment the door cycle begins at `stop` — door time
625 /// at `stop` itself is **not** added; door time at earlier stops along
626 /// the route **is**.
627 ///
628 /// # Errors
629 ///
630 /// - [`EtaError::NotAnElevator`] if `elev` is not an elevator entity.
631 /// - [`EtaError::NotAStop`] if `stop` is not a stop entity.
632 /// - [`EtaError::ServiceModeExcluded`] if the elevator's
633 /// [`ServiceMode`](crate::components::ServiceMode) is dispatch-excluded
634 /// (`Manual` / `Independent`).
635 /// - [`EtaError::StopNotQueued`] if `stop` is neither the elevator's
636 /// current movement target nor anywhere in its
637 /// [`destination_queue`](Self::destination_queue).
638 /// - [`EtaError::StopVanished`] if a stop in the route lost its position
639 /// during calculation.
640 ///
641 /// The estimate is best-effort. It assumes the queue is served in order
642 /// with no mid-trip insertions; dispatch decisions, manual door commands,
643 /// and rider boarding/exiting beyond the configured dwell will perturb
644 /// the actual arrival.
645 pub fn eta(&self, elev: EntityId, stop: EntityId) -> Result<Duration, EtaError> {
646 let elevator = self
647 .world
648 .elevator(elev)
649 .ok_or(EtaError::NotAnElevator(elev))?;
650 self.world.stop(stop).ok_or(EtaError::NotAStop(stop))?;
651 let svc = self.world.service_mode(elev).copied().unwrap_or_default();
652 if svc.is_dispatch_excluded() {
653 return Err(EtaError::ServiceModeExcluded(elev));
654 }
655
656 // Build the route in service order: current target first (if any),
657 // then queue entries, with adjacent duplicates collapsed.
658 let mut route: Vec<EntityId> = Vec::new();
659 if let Some(t) = elevator.phase().moving_target() {
660 route.push(t);
661 }
662 if let Some(q) = self.world.destination_queue(elev) {
663 for &s in q.queue() {
664 if route.last() != Some(&s) {
665 route.push(s);
666 }
667 }
668 }
669 if !route.contains(&stop) {
670 return Err(EtaError::StopNotQueued {
671 elevator: elev,
672 stop,
673 });
674 }
675
676 let max_speed = elevator.max_speed().value();
677 let accel = elevator.acceleration().value();
678 let decel = elevator.deceleration().value();
679 let door_cycle_ticks =
680 u64::from(elevator.door_transition_ticks()) * 2 + u64::from(elevator.door_open_ticks());
681 let door_cycle_secs = (door_cycle_ticks as f64) * self.dt;
682
683 // Account for any in-progress door cycle before the first travel leg:
684 // the elevator is parked at its current stop and won't move until the
685 // door FSM returns to Closed.
686 let mut total = match elevator.door() {
687 crate::door::DoorState::Opening {
688 ticks_remaining,
689 open_duration,
690 close_duration,
691 } => f64::from(*ticks_remaining + *open_duration + *close_duration) * self.dt,
692 crate::door::DoorState::Open {
693 ticks_remaining,
694 close_duration,
695 } => f64::from(*ticks_remaining + *close_duration) * self.dt,
696 crate::door::DoorState::Closing { ticks_remaining } => {
697 f64::from(*ticks_remaining) * self.dt
698 }
699 crate::door::DoorState::Closed => 0.0,
700 };
701
702 let in_door_cycle = !matches!(elevator.door(), crate::door::DoorState::Closed);
703 let mut pos = self
704 .world
705 .position(elev)
706 .ok_or(EtaError::NotAnElevator(elev))?
707 .value;
708 let vel_signed = self.world.velocity(elev).map_or(0.0, Velocity::value);
709
710 for (idx, &s) in route.iter().enumerate() {
711 let s_pos = self
712 .world
713 .stop_position(s)
714 .ok_or(EtaError::StopVanished(s))?;
715 let dist = (s_pos - pos).abs();
716 // Only the first leg can carry initial velocity, and only if
717 // the car is already moving toward this stop and not stuck in
718 // a door cycle (which forces it to stop first).
719 let v0 = if idx == 0 && !in_door_cycle && vel_signed.abs() > f64::EPSILON {
720 let dir = (s_pos - pos).signum();
721 if dir * vel_signed > 0.0 {
722 vel_signed.abs()
723 } else {
724 0.0
725 }
726 } else {
727 0.0
728 };
729 total += crate::eta::travel_time(dist, v0, max_speed, accel, decel);
730 if s == stop {
731 return Ok(Duration::from_secs_f64(total.max(0.0)));
732 }
733 total += door_cycle_secs;
734 pos = s_pos;
735 }
736 // `route.contains(&stop)` was true above, so the loop must hit `stop`.
737 // Fall through as a defensive backstop.
738 Err(EtaError::StopNotQueued {
739 elevator: elev,
740 stop,
741 })
742 }
743
744 /// Best ETA to `stop` across all dispatch-eligible elevators, optionally
745 /// filtered by indicator-lamp [`Direction`](crate::components::Direction).
746 ///
747 /// Pass [`Direction::Either`](crate::components::Direction::Either) to
748 /// consider every car. Otherwise, only cars whose committed direction is
749 /// `Either` or matches the requested direction are considered — useful
750 /// for hall-call assignment ("which up-going car arrives first?").
751 ///
752 /// Returns the entity ID of the winning elevator and its ETA, or `None`
753 /// if no eligible car has `stop` queued.
754 #[must_use]
755 pub fn best_eta(
756 &self,
757 stop: impl Into<StopRef>,
758 direction: crate::components::Direction,
759 ) -> Option<(EntityId, Duration)> {
760 use crate::components::Direction;
761 let stop = self.resolve_stop(stop.into()).ok()?;
762 self.world
763 .iter_elevators()
764 .filter_map(|(eid, _, elev)| {
765 let car_dir = elev.direction();
766 let direction_ok = match direction {
767 Direction::Either => true,
768 requested => car_dir == Direction::Either || car_dir == requested,
769 };
770 if !direction_ok {
771 return None;
772 }
773 self.eta(eid, stop).ok().map(|d| (eid, d))
774 })
775 .min_by_key(|(_, d)| *d)
776 }
777
778 // ── Runtime elevator upgrades ────────────────────────────────────
779 //
780 // Games that want to mutate elevator parameters at runtime (e.g.
781 // an RPG speed-upgrade purchase, a scripted capacity boost) go
782 // through these setters rather than poking `Elevator` directly via
783 // `world_mut()`. Each setter validates its input, updates the
784 // underlying component, and emits an [`Event::ElevatorUpgraded`]
785 // so game code can react without polling.
786 //
787 // ### Semantics
788 //
789 // - `max_speed`, `acceleration`, `deceleration`: applied on the next
790 // movement integration step. The car's **current velocity is
791 // preserved** — there is no instantaneous jerk. If `max_speed`
792 // is lowered below the current velocity, the movement integrator
793 // clamps velocity to the new cap on the next tick.
794 // - `weight_capacity`: applied immediately. If the new capacity is
795 // below `current_load` the car ends up temporarily overweight —
796 // no riders are ejected, but the next boarding pass will reject
797 // any rider that would push the load further over the new cap.
798 // - `door_transition_ticks`, `door_open_ticks`: applied on the
799 // **next** door cycle. An in-progress door transition keeps its
800 // original timing, so setters never cause visual glitches.
801
802 /// Set the maximum travel speed for an elevator at runtime.
803 ///
804 /// The new value applies on the next movement integration step;
805 /// the car's current velocity is preserved (see the
806 /// [runtime upgrades section](crate#runtime-upgrades) of the crate
807 /// docs). If the new cap is below the current velocity, the movement
808 /// system clamps velocity down on the next tick.
809 ///
810 /// # Errors
811 ///
812 /// - [`SimError::NotAnElevator`] if `elevator` is not an elevator entity.
813 /// - [`SimError::InvalidConfig`] if `speed` is not a positive finite number.
814 ///
815 /// # Example
816 ///
817 /// ```
818 /// use elevator_core::prelude::*;
819 ///
820 /// let mut sim = SimulationBuilder::demo().build().unwrap();
821 /// let elev = sim.world().iter_elevators().next().unwrap().0;
822 /// sim.set_max_speed(elev, 4.0).unwrap();
823 /// assert_eq!(sim.world().elevator(elev).unwrap().max_speed().value(), 4.0);
824 /// ```
825 pub fn set_max_speed(&mut self, elevator: EntityId, speed: f64) -> Result<(), SimError> {
826 Self::validate_positive_finite_f64(speed, "elevators.max_speed")?;
827 let old = self.require_elevator(elevator)?.max_speed.value();
828 let speed = Speed::from(speed);
829 if let Some(car) = self.world.elevator_mut(elevator) {
830 car.max_speed = speed;
831 }
832 self.emit_upgrade(
833 elevator,
834 crate::events::UpgradeField::MaxSpeed,
835 crate::events::UpgradeValue::float(old),
836 crate::events::UpgradeValue::float(speed.value()),
837 );
838 Ok(())
839 }
840
841 /// Set the acceleration rate for an elevator at runtime.
842 ///
843 /// See [`set_max_speed`](Self::set_max_speed) for the general
844 /// velocity-preservation rules that apply to kinematic setters.
845 ///
846 /// # Errors
847 ///
848 /// - [`SimError::NotAnElevator`] if `elevator` is not an elevator entity.
849 /// - [`SimError::InvalidConfig`] if `accel` is not a positive finite number.
850 ///
851 /// # Example
852 ///
853 /// ```
854 /// use elevator_core::prelude::*;
855 ///
856 /// let mut sim = SimulationBuilder::demo().build().unwrap();
857 /// let elev = sim.world().iter_elevators().next().unwrap().0;
858 /// sim.set_acceleration(elev, 3.0).unwrap();
859 /// assert_eq!(sim.world().elevator(elev).unwrap().acceleration().value(), 3.0);
860 /// ```
861 pub fn set_acceleration(&mut self, elevator: EntityId, accel: f64) -> Result<(), SimError> {
862 Self::validate_positive_finite_f64(accel, "elevators.acceleration")?;
863 let old = self.require_elevator(elevator)?.acceleration.value();
864 let accel = Accel::from(accel);
865 if let Some(car) = self.world.elevator_mut(elevator) {
866 car.acceleration = accel;
867 }
868 self.emit_upgrade(
869 elevator,
870 crate::events::UpgradeField::Acceleration,
871 crate::events::UpgradeValue::float(old),
872 crate::events::UpgradeValue::float(accel.value()),
873 );
874 Ok(())
875 }
876
877 /// Set the deceleration rate for an elevator at runtime.
878 ///
879 /// See [`set_max_speed`](Self::set_max_speed) for the general
880 /// velocity-preservation rules that apply to kinematic setters.
881 ///
882 /// # Errors
883 ///
884 /// - [`SimError::NotAnElevator`] if `elevator` is not an elevator entity.
885 /// - [`SimError::InvalidConfig`] if `decel` is not a positive finite number.
886 ///
887 /// # Example
888 ///
889 /// ```
890 /// use elevator_core::prelude::*;
891 ///
892 /// let mut sim = SimulationBuilder::demo().build().unwrap();
893 /// let elev = sim.world().iter_elevators().next().unwrap().0;
894 /// sim.set_deceleration(elev, 3.5).unwrap();
895 /// assert_eq!(sim.world().elevator(elev).unwrap().deceleration().value(), 3.5);
896 /// ```
897 pub fn set_deceleration(&mut self, elevator: EntityId, decel: f64) -> Result<(), SimError> {
898 Self::validate_positive_finite_f64(decel, "elevators.deceleration")?;
899 let old = self.require_elevator(elevator)?.deceleration.value();
900 let decel = Accel::from(decel);
901 if let Some(car) = self.world.elevator_mut(elevator) {
902 car.deceleration = decel;
903 }
904 self.emit_upgrade(
905 elevator,
906 crate::events::UpgradeField::Deceleration,
907 crate::events::UpgradeValue::float(old),
908 crate::events::UpgradeValue::float(decel.value()),
909 );
910 Ok(())
911 }
912
913 /// Set the weight capacity for an elevator at runtime.
914 ///
915 /// Applied immediately. If the new capacity is below the car's
916 /// current load the car is temporarily overweight; no riders are
917 /// ejected, but subsequent boarding attempts that would push load
918 /// further over the cap will be rejected as
919 /// [`RejectionReason::OverCapacity`](crate::error::RejectionReason::OverCapacity).
920 ///
921 /// # Errors
922 ///
923 /// - [`SimError::NotAnElevator`] if `elevator` is not an elevator entity.
924 /// - [`SimError::InvalidConfig`] if `capacity` is not a positive finite number.
925 ///
926 /// # Example
927 ///
928 /// ```
929 /// use elevator_core::prelude::*;
930 ///
931 /// let mut sim = SimulationBuilder::demo().build().unwrap();
932 /// let elev = sim.world().iter_elevators().next().unwrap().0;
933 /// sim.set_weight_capacity(elev, 1200.0).unwrap();
934 /// assert_eq!(sim.world().elevator(elev).unwrap().weight_capacity().value(), 1200.0);
935 /// ```
936 pub fn set_weight_capacity(
937 &mut self,
938 elevator: EntityId,
939 capacity: f64,
940 ) -> Result<(), SimError> {
941 Self::validate_positive_finite_f64(capacity, "elevators.weight_capacity")?;
942 let old = self.require_elevator(elevator)?.weight_capacity.value();
943 let capacity = Weight::from(capacity);
944 if let Some(car) = self.world.elevator_mut(elevator) {
945 car.weight_capacity = capacity;
946 }
947 self.emit_upgrade(
948 elevator,
949 crate::events::UpgradeField::WeightCapacity,
950 crate::events::UpgradeValue::float(old),
951 crate::events::UpgradeValue::float(capacity.value()),
952 );
953 Ok(())
954 }
955
956 /// Set the door open/close transition duration for an elevator.
957 ///
958 /// Applied on the **next** door cycle — an in-progress transition
959 /// keeps its original timing to avoid visual glitches.
960 ///
961 /// # Errors
962 ///
963 /// - [`SimError::NotAnElevator`] if `elevator` is not an elevator entity.
964 /// - [`SimError::InvalidConfig`] if `ticks` is zero.
965 ///
966 /// # Example
967 ///
968 /// ```
969 /// use elevator_core::prelude::*;
970 ///
971 /// let mut sim = SimulationBuilder::demo().build().unwrap();
972 /// let elev = sim.world().iter_elevators().next().unwrap().0;
973 /// sim.set_door_transition_ticks(elev, 3).unwrap();
974 /// assert_eq!(sim.world().elevator(elev).unwrap().door_transition_ticks(), 3);
975 /// ```
976 pub fn set_door_transition_ticks(
977 &mut self,
978 elevator: EntityId,
979 ticks: u32,
980 ) -> Result<(), SimError> {
981 Self::validate_nonzero_u32(ticks, "elevators.door_transition_ticks")?;
982 let old = self.require_elevator(elevator)?.door_transition_ticks;
983 if let Some(car) = self.world.elevator_mut(elevator) {
984 car.door_transition_ticks = ticks;
985 }
986 self.emit_upgrade(
987 elevator,
988 crate::events::UpgradeField::DoorTransitionTicks,
989 crate::events::UpgradeValue::ticks(old),
990 crate::events::UpgradeValue::ticks(ticks),
991 );
992 Ok(())
993 }
994
995 /// Set how long doors hold fully open for an elevator.
996 ///
997 /// Applied on the **next** door cycle — a door that is currently
998 /// holding open will complete its original dwell before the new
999 /// value takes effect.
1000 ///
1001 /// # Errors
1002 ///
1003 /// - [`SimError::NotAnElevator`] if `elevator` is not an elevator entity.
1004 /// - [`SimError::InvalidConfig`] if `ticks` is zero.
1005 ///
1006 /// # Example
1007 ///
1008 /// ```
1009 /// use elevator_core::prelude::*;
1010 ///
1011 /// let mut sim = SimulationBuilder::demo().build().unwrap();
1012 /// let elev = sim.world().iter_elevators().next().unwrap().0;
1013 /// sim.set_door_open_ticks(elev, 20).unwrap();
1014 /// assert_eq!(sim.world().elevator(elev).unwrap().door_open_ticks(), 20);
1015 /// ```
1016 pub fn set_door_open_ticks(&mut self, elevator: EntityId, ticks: u32) -> Result<(), SimError> {
1017 Self::validate_nonzero_u32(ticks, "elevators.door_open_ticks")?;
1018 let old = self.require_elevator(elevator)?.door_open_ticks;
1019 if let Some(car) = self.world.elevator_mut(elevator) {
1020 car.door_open_ticks = ticks;
1021 }
1022 self.emit_upgrade(
1023 elevator,
1024 crate::events::UpgradeField::DoorOpenTicks,
1025 crate::events::UpgradeValue::ticks(old),
1026 crate::events::UpgradeValue::ticks(ticks),
1027 );
1028 Ok(())
1029 }
1030
1031 // ── Manual door control ──────────────────────────────────────────
1032 //
1033 // These methods let games drive door state directly — e.g. a
1034 // cab-panel open/close button in a first-person game, or an RPG
1035 // where the player *is* the elevator and decides when to cycle doors.
1036 //
1037 // Each method either applies the command immediately (if the car is
1038 // in a matching door-FSM state) or queues it on the elevator for
1039 // application at the next valid moment. This way games can call
1040 // these any time without worrying about FSM timing, and get a clean
1041 // success/failure split between "bad entity" and "bad moment".
1042
1043 /// Request the doors to open.
1044 ///
1045 /// Applied immediately if the car is stopped at a stop with closed
1046 /// or closing doors; otherwise queued until the car next arrives.
1047 /// A no-op if the doors are already open or opening.
1048 ///
1049 /// # Errors
1050 ///
1051 /// - [`SimError::NotAnElevator`] if `elevator` is not an elevator entity.
1052 /// - [`SimError::ElevatorDisabled`] if the elevator is disabled.
1053 ///
1054 /// # Example
1055 ///
1056 /// ```
1057 /// use elevator_core::prelude::*;
1058 ///
1059 /// let mut sim = SimulationBuilder::demo().build().unwrap();
1060 /// let elev = sim.world().iter_elevators().next().unwrap().0;
1061 /// sim.open_door(elev).unwrap();
1062 /// ```
1063 pub fn open_door(&mut self, elevator: EntityId) -> Result<(), SimError> {
1064 self.require_enabled_elevator(elevator)?;
1065 self.enqueue_door_command(elevator, crate::door::DoorCommand::Open);
1066 Ok(())
1067 }
1068
1069 /// Request the doors to close now.
1070 ///
1071 /// Applied immediately if the doors are open or loading — forcing an
1072 /// early close — unless a rider is mid-boarding/exiting this car, in
1073 /// which case the close waits for the rider to finish. If doors are
1074 /// currently opening, the close queues and fires once fully open.
1075 ///
1076 /// # Errors
1077 ///
1078 /// - [`SimError::NotAnElevator`] if `elevator` is not an elevator entity.
1079 /// - [`SimError::ElevatorDisabled`] if the elevator is disabled.
1080 ///
1081 /// # Example
1082 ///
1083 /// ```
1084 /// use elevator_core::prelude::*;
1085 ///
1086 /// let mut sim = SimulationBuilder::demo().build().unwrap();
1087 /// let elev = sim.world().iter_elevators().next().unwrap().0;
1088 /// sim.close_door(elev).unwrap();
1089 /// ```
1090 pub fn close_door(&mut self, elevator: EntityId) -> Result<(), SimError> {
1091 self.require_enabled_elevator(elevator)?;
1092 self.enqueue_door_command(elevator, crate::door::DoorCommand::Close);
1093 Ok(())
1094 }
1095
1096 /// Extend the doors' open dwell by `ticks`.
1097 ///
1098 /// Cumulative — two calls of 30 ticks each extend the dwell by 60
1099 /// ticks in total. If the doors aren't open yet, the hold is queued
1100 /// and applied when they next reach the fully-open state.
1101 ///
1102 /// # Errors
1103 ///
1104 /// - [`SimError::NotAnElevator`] if `elevator` is not an elevator entity.
1105 /// - [`SimError::ElevatorDisabled`] if the elevator is disabled.
1106 /// - [`SimError::InvalidConfig`] if `ticks` is zero.
1107 ///
1108 /// # Example
1109 ///
1110 /// ```
1111 /// use elevator_core::prelude::*;
1112 ///
1113 /// let mut sim = SimulationBuilder::demo().build().unwrap();
1114 /// let elev = sim.world().iter_elevators().next().unwrap().0;
1115 /// sim.hold_door(elev, 30).unwrap();
1116 /// ```
1117 pub fn hold_door(&mut self, elevator: EntityId, ticks: u32) -> Result<(), SimError> {
1118 Self::validate_nonzero_u32(ticks, "hold_door.ticks")?;
1119 self.require_enabled_elevator(elevator)?;
1120 self.enqueue_door_command(elevator, crate::door::DoorCommand::HoldOpen { ticks });
1121 Ok(())
1122 }
1123
1124 /// Cancel any pending hold extension.
1125 ///
1126 /// If the base open timer has already elapsed the doors close on
1127 /// the next doors-phase tick.
1128 ///
1129 /// # Errors
1130 ///
1131 /// - [`SimError::NotAnElevator`] if `elevator` is not an elevator entity.
1132 /// - [`SimError::ElevatorDisabled`] if the elevator is disabled.
1133 ///
1134 /// # Example
1135 ///
1136 /// ```
1137 /// use elevator_core::prelude::*;
1138 ///
1139 /// let mut sim = SimulationBuilder::demo().build().unwrap();
1140 /// let elev = sim.world().iter_elevators().next().unwrap().0;
1141 /// sim.hold_door(elev, 100).unwrap();
1142 /// sim.cancel_door_hold(elev).unwrap();
1143 /// ```
1144 pub fn cancel_door_hold(&mut self, elevator: EntityId) -> Result<(), SimError> {
1145 self.require_enabled_elevator(elevator)?;
1146 self.enqueue_door_command(elevator, crate::door::DoorCommand::CancelHold);
1147 Ok(())
1148 }
1149
1150 /// Set the target velocity for a manual-mode elevator.
1151 ///
1152 /// The velocity is clamped to the elevator's `[-max_speed, max_speed]`
1153 /// range after validation. The car ramps toward the target each tick
1154 /// using `acceleration` (speeding up, or starting from rest) or
1155 /// `deceleration` (slowing down, or reversing direction). Positive
1156 /// values command upward travel, negative values command downward travel.
1157 ///
1158 /// # Errors
1159 /// - [`SimError::NotAnElevator`] if the entity is not an elevator.
1160 /// - [`SimError::ElevatorDisabled`] if the elevator is disabled.
1161 /// - [`SimError::WrongServiceMode`] if the elevator is not in [`ServiceMode::Manual`].
1162 /// - [`SimError::InvalidConfig`] if `velocity` is not finite (NaN or infinite).
1163 ///
1164 /// [`ServiceMode::Manual`]: crate::components::ServiceMode::Manual
1165 pub fn set_target_velocity(
1166 &mut self,
1167 elevator: EntityId,
1168 velocity: f64,
1169 ) -> Result<(), SimError> {
1170 self.require_enabled_elevator(elevator)?;
1171 self.require_manual_mode(elevator)?;
1172 if !velocity.is_finite() {
1173 return Err(SimError::InvalidConfig {
1174 field: "target_velocity",
1175 reason: format!("must be finite, got {velocity}"),
1176 });
1177 }
1178 let max = self
1179 .world
1180 .elevator(elevator)
1181 .map_or(f64::INFINITY, |c| c.max_speed.value());
1182 let clamped = velocity.clamp(-max, max);
1183 if let Some(car) = self.world.elevator_mut(elevator) {
1184 car.manual_target_velocity = Some(clamped);
1185 }
1186 self.events.emit(Event::ManualVelocityCommanded {
1187 elevator,
1188 target_velocity: Some(ordered_float::OrderedFloat(clamped)),
1189 tick: self.tick,
1190 });
1191 Ok(())
1192 }
1193
1194 /// Command an immediate stop on a manual-mode elevator.
1195 ///
1196 /// Sets the target velocity to zero; the car decelerates at its
1197 /// configured `deceleration` rate. Equivalent to
1198 /// `set_target_velocity(elevator, 0.0)` but emits a distinct
1199 /// [`Event::ManualVelocityCommanded`] with `None` payload so games can
1200 /// distinguish an emergency stop from a deliberate hold.
1201 ///
1202 /// # Errors
1203 /// Same as [`set_target_velocity`](Self::set_target_velocity), minus
1204 /// the finite-velocity check.
1205 pub fn emergency_stop(&mut self, elevator: EntityId) -> Result<(), SimError> {
1206 self.require_enabled_elevator(elevator)?;
1207 self.require_manual_mode(elevator)?;
1208 if let Some(car) = self.world.elevator_mut(elevator) {
1209 car.manual_target_velocity = Some(0.0);
1210 }
1211 self.events.emit(Event::ManualVelocityCommanded {
1212 elevator,
1213 target_velocity: None,
1214 tick: self.tick,
1215 });
1216 Ok(())
1217 }
1218
1219 /// Internal: require an elevator be in `ServiceMode::Manual`.
1220 fn require_manual_mode(&self, elevator: EntityId) -> Result<(), SimError> {
1221 let actual = self
1222 .world
1223 .service_mode(elevator)
1224 .copied()
1225 .unwrap_or_default();
1226 if actual != crate::components::ServiceMode::Manual {
1227 return Err(SimError::WrongServiceMode {
1228 entity: elevator,
1229 expected: crate::components::ServiceMode::Manual,
1230 actual,
1231 });
1232 }
1233 Ok(())
1234 }
1235
1236 /// Internal: push a command onto the queue, collapsing adjacent
1237 /// duplicates, capping length, and emitting `DoorCommandQueued`.
1238 fn enqueue_door_command(&mut self, elevator: EntityId, command: crate::door::DoorCommand) {
1239 if let Some(car) = self.world.elevator_mut(elevator) {
1240 let q = &mut car.door_command_queue;
1241 // Collapse adjacent duplicates for idempotent commands
1242 // (Open/Close/CancelHold) — repeating them adds nothing.
1243 // HoldOpen is explicitly cumulative, so never collapsed.
1244 let collapse = matches!(
1245 command,
1246 crate::door::DoorCommand::Open
1247 | crate::door::DoorCommand::Close
1248 | crate::door::DoorCommand::CancelHold
1249 ) && q.last().copied() == Some(command);
1250 if !collapse {
1251 q.push(command);
1252 if q.len() > crate::components::DOOR_COMMAND_QUEUE_CAP {
1253 q.remove(0);
1254 }
1255 }
1256 }
1257 self.events.emit(Event::DoorCommandQueued {
1258 elevator,
1259 command,
1260 tick: self.tick,
1261 });
1262 }
1263
1264 /// Internal: resolve an elevator entity that is not disabled.
1265 fn require_enabled_elevator(&self, elevator: EntityId) -> Result<(), SimError> {
1266 if self.world.elevator(elevator).is_none() {
1267 return Err(SimError::NotAnElevator(elevator));
1268 }
1269 if self.world.is_disabled(elevator) {
1270 return Err(SimError::ElevatorDisabled(elevator));
1271 }
1272 Ok(())
1273 }
1274
1275 /// Internal: resolve an elevator entity or return a clear error.
1276 fn require_elevator(
1277 &self,
1278 elevator: EntityId,
1279 ) -> Result<&crate::components::Elevator, SimError> {
1280 self.world
1281 .elevator(elevator)
1282 .ok_or(SimError::NotAnElevator(elevator))
1283 }
1284
1285 /// Internal: positive-finite validator matching the construction-time
1286 /// error shape in `sim/construction.rs::validate_elevator_config`.
1287 fn validate_positive_finite_f64(value: f64, field: &'static str) -> Result<(), SimError> {
1288 if !value.is_finite() {
1289 return Err(SimError::InvalidConfig {
1290 field,
1291 reason: format!("must be finite, got {value}"),
1292 });
1293 }
1294 if value <= 0.0 {
1295 return Err(SimError::InvalidConfig {
1296 field,
1297 reason: format!("must be positive, got {value}"),
1298 });
1299 }
1300 Ok(())
1301 }
1302
1303 /// Internal: reject zero-tick timings.
1304 fn validate_nonzero_u32(value: u32, field: &'static str) -> Result<(), SimError> {
1305 if value == 0 {
1306 return Err(SimError::InvalidConfig {
1307 field,
1308 reason: "must be > 0".into(),
1309 });
1310 }
1311 Ok(())
1312 }
1313
1314 /// Internal: emit a single `ElevatorUpgraded` event for the current tick.
1315 fn emit_upgrade(
1316 &mut self,
1317 elevator: EntityId,
1318 field: crate::events::UpgradeField,
1319 old: crate::events::UpgradeValue,
1320 new: crate::events::UpgradeValue,
1321 ) {
1322 self.events.emit(Event::ElevatorUpgraded {
1323 elevator,
1324 field,
1325 old,
1326 new,
1327 tick: self.tick,
1328 });
1329 }
1330
1331 // Dispatch & reposition management live in `sim/construction.rs`.
1332
1333 // ── Tagging ──────────────────────────────────────────────────────
1334
1335 /// Attach a metric tag to an entity (rider, stop, elevator, etc.).
1336 ///
1337 /// Tags enable per-tag metric breakdowns. An entity can have multiple tags.
1338 /// Riders automatically inherit tags from their origin stop when spawned.
1339 ///
1340 /// # Errors
1341 ///
1342 /// Returns [`SimError::EntityNotFound`] if the entity does not exist in
1343 /// the world.
1344 pub fn tag_entity(&mut self, id: EntityId, tag: impl Into<String>) -> Result<(), SimError> {
1345 if !self.world.is_alive(id) {
1346 return Err(SimError::EntityNotFound(id));
1347 }
1348 if let Some(tags) = self
1349 .world
1350 .resource_mut::<crate::tagged_metrics::MetricTags>()
1351 {
1352 tags.tag(id, tag);
1353 }
1354 Ok(())
1355 }
1356
1357 /// Remove a metric tag from an entity.
1358 pub fn untag_entity(&mut self, id: EntityId, tag: &str) {
1359 if let Some(tags) = self
1360 .world
1361 .resource_mut::<crate::tagged_metrics::MetricTags>()
1362 {
1363 tags.untag(id, tag);
1364 }
1365 }
1366
1367 /// Query the metric accumulator for a specific tag.
1368 #[must_use]
1369 pub fn metrics_for_tag(&self, tag: &str) -> Option<&crate::tagged_metrics::TaggedMetric> {
1370 self.world
1371 .resource::<crate::tagged_metrics::MetricTags>()
1372 .and_then(|tags| tags.metric(tag))
1373 }
1374
1375 /// List all registered metric tags.
1376 pub fn all_tags(&self) -> Vec<&str> {
1377 self.world
1378 .resource::<crate::tagged_metrics::MetricTags>()
1379 .map_or_else(Vec::new, |tags| tags.all_tags().collect())
1380 }
1381
1382 // ── Rider spawning ───────────────────────────────────────────────
1383
1384 /// Create a rider builder for fluent rider spawning.
1385 ///
1386 /// Accepts [`EntityId`] or [`StopId`] for origin and destination
1387 /// (anything that implements `Into<StopRef>`).
1388 ///
1389 /// # Errors
1390 ///
1391 /// Returns [`SimError::StopNotFound`] if a [`StopId`] does not exist
1392 /// in the building configuration.
1393 ///
1394 /// ```
1395 /// use elevator_core::prelude::*;
1396 ///
1397 /// let mut sim = SimulationBuilder::demo().build().unwrap();
1398 /// let rider = sim.build_rider(StopId(0), StopId(1))
1399 /// .unwrap()
1400 /// .weight(80.0)
1401 /// .spawn()
1402 /// .unwrap();
1403 /// ```
1404 pub fn build_rider(
1405 &mut self,
1406 origin: impl Into<StopRef>,
1407 destination: impl Into<StopRef>,
1408 ) -> Result<RiderBuilder<'_>, SimError> {
1409 let origin = self.resolve_stop(origin.into())?;
1410 let destination = self.resolve_stop(destination.into())?;
1411 Ok(RiderBuilder {
1412 sim: self,
1413 origin,
1414 destination,
1415 weight: Weight::from(75.0),
1416 group: None,
1417 route: None,
1418 patience: None,
1419 preferences: None,
1420 access_control: None,
1421 })
1422 }
1423
1424 /// Spawn a rider with default preferences (convenience shorthand).
1425 ///
1426 /// Equivalent to `build_rider(origin, destination)?.weight(weight).spawn()`.
1427 /// Use [`build_rider`](Self::build_rider) instead when you need to set
1428 /// patience, preferences, access control, or an explicit route.
1429 ///
1430 /// Auto-detects the elevator group by finding groups that serve both origin
1431 /// and destination stops.
1432 ///
1433 /// # Errors
1434 ///
1435 /// Returns [`SimError::NoRoute`] if no group serves both stops.
1436 /// Returns [`SimError::AmbiguousRoute`] if multiple groups serve both stops.
1437 pub fn spawn_rider(
1438 &mut self,
1439 origin: impl Into<StopRef>,
1440 destination: impl Into<StopRef>,
1441 weight: impl Into<Weight>,
1442 ) -> Result<EntityId, SimError> {
1443 let origin = self.resolve_stop(origin.into())?;
1444 let destination = self.resolve_stop(destination.into())?;
1445 let weight: Weight = weight.into();
1446 let matching: Vec<GroupId> = self
1447 .groups
1448 .iter()
1449 .filter(|g| {
1450 g.stop_entities().contains(&origin) && g.stop_entities().contains(&destination)
1451 })
1452 .map(ElevatorGroup::id)
1453 .collect();
1454
1455 let group = match matching.len() {
1456 0 => {
1457 let origin_groups: Vec<GroupId> = self
1458 .groups
1459 .iter()
1460 .filter(|g| g.stop_entities().contains(&origin))
1461 .map(ElevatorGroup::id)
1462 .collect();
1463 let destination_groups: Vec<GroupId> = self
1464 .groups
1465 .iter()
1466 .filter(|g| g.stop_entities().contains(&destination))
1467 .map(ElevatorGroup::id)
1468 .collect();
1469 return Err(SimError::NoRoute {
1470 origin,
1471 destination,
1472 origin_groups,
1473 destination_groups,
1474 });
1475 }
1476 1 => matching[0],
1477 _ => {
1478 return Err(SimError::AmbiguousRoute {
1479 origin,
1480 destination,
1481 groups: matching,
1482 });
1483 }
1484 };
1485
1486 let route = Route::direct(origin, destination, group);
1487 Ok(self.spawn_rider_inner(origin, destination, weight, route))
1488 }
1489
1490 /// Internal helper: spawn a rider entity with the given route.
1491 fn spawn_rider_inner(
1492 &mut self,
1493 origin: EntityId,
1494 destination: EntityId,
1495 weight: Weight,
1496 route: Route,
1497 ) -> EntityId {
1498 let eid = self.world.spawn();
1499 self.world.set_rider(
1500 eid,
1501 Rider {
1502 weight,
1503 phase: RiderPhase::Waiting,
1504 current_stop: Some(origin),
1505 spawn_tick: self.tick,
1506 board_tick: None,
1507 },
1508 );
1509 self.world.set_route(eid, route);
1510 self.rider_index.insert_waiting(origin, eid);
1511 self.events.emit(Event::RiderSpawned {
1512 rider: eid,
1513 origin,
1514 destination,
1515 tick: self.tick,
1516 });
1517
1518 // Auto-press the hall button for this rider. Direction is the
1519 // sign of `dest_pos - origin_pos`; if the two coincide (walk
1520 // leg, identity trip) no call is registered.
1521 if let (Some(op), Some(dp)) = (
1522 self.world.stop_position(origin),
1523 self.world.stop_position(destination),
1524 ) && let Some(direction) = crate::components::CallDirection::between(op, dp)
1525 {
1526 self.register_hall_call_for_rider(origin, direction, eid, destination);
1527 }
1528
1529 // Auto-tag the rider with "stop:{name}" for per-stop wait time tracking.
1530 let stop_tag = self
1531 .world
1532 .stop(origin)
1533 .map(|s| format!("stop:{}", s.name()));
1534
1535 // Inherit metric tags from the origin stop.
1536 if let Some(tags_res) = self
1537 .world
1538 .resource_mut::<crate::tagged_metrics::MetricTags>()
1539 {
1540 let origin_tags: Vec<String> = tags_res.tags_for(origin).to_vec();
1541 for tag in origin_tags {
1542 tags_res.tag(eid, tag);
1543 }
1544 // Apply the origin stop tag.
1545 if let Some(tag) = stop_tag {
1546 tags_res.tag(eid, tag);
1547 }
1548 }
1549
1550 eid
1551 }
1552
1553 /// Drain all pending events from completed ticks.
1554 ///
1555 /// Events emitted during `step()` (or per-phase methods) are buffered
1556 /// and made available here after `advance_tick()` is called.
1557 /// Events emitted outside the tick loop (e.g., `spawn_rider`, `disable`)
1558 /// are also included.
1559 ///
1560 /// ```
1561 /// use elevator_core::prelude::*;
1562 ///
1563 /// let mut sim = SimulationBuilder::demo().build().unwrap();
1564 ///
1565 /// sim.spawn_rider(StopId(0), StopId(1), 70.0).unwrap();
1566 /// sim.step();
1567 ///
1568 /// let events = sim.drain_events();
1569 /// assert!(!events.is_empty());
1570 /// ```
1571 pub fn drain_events(&mut self) -> Vec<Event> {
1572 // Flush any events still in the bus (from spawn_rider, disable, etc.)
1573 self.pending_output.extend(self.events.drain());
1574 std::mem::take(&mut self.pending_output)
1575 }
1576
1577 /// Drain only events matching a predicate.
1578 ///
1579 /// Events that don't match the predicate remain in the buffer
1580 /// and will be returned by future `drain_events` or
1581 /// `drain_events_where` calls.
1582 ///
1583 /// ```
1584 /// use elevator_core::prelude::*;
1585 ///
1586 /// let mut sim = SimulationBuilder::demo().build().unwrap();
1587 /// sim.spawn_rider(StopId(0), StopId(1), 70.0).unwrap();
1588 /// sim.step();
1589 ///
1590 /// let spawns: Vec<Event> = sim.drain_events_where(|e| {
1591 /// matches!(e, Event::RiderSpawned { .. })
1592 /// });
1593 /// ```
1594 pub fn drain_events_where(&mut self, predicate: impl Fn(&Event) -> bool) -> Vec<Event> {
1595 // Flush bus into pending_output first.
1596 self.pending_output.extend(self.events.drain());
1597
1598 let mut matched = Vec::new();
1599 let mut remaining = Vec::new();
1600 for event in std::mem::take(&mut self.pending_output) {
1601 if predicate(&event) {
1602 matched.push(event);
1603 } else {
1604 remaining.push(event);
1605 }
1606 }
1607 self.pending_output = remaining;
1608 matched
1609 }
1610
1611 // ── Sub-stepping ────────────────────────────────────────────────
1612
1613 /// Get the dispatch strategies map (for advanced sub-stepping).
1614 #[must_use]
1615 pub fn dispatchers(&self) -> &BTreeMap<GroupId, Box<dyn DispatchStrategy>> {
1616 &self.dispatchers
1617 }
1618
1619 /// Get the dispatch strategies map mutably (for advanced sub-stepping).
1620 pub fn dispatchers_mut(&mut self) -> &mut BTreeMap<GroupId, Box<dyn DispatchStrategy>> {
1621 &mut self.dispatchers
1622 }
1623
1624 /// Get a mutable reference to the event bus.
1625 pub const fn events_mut(&mut self) -> &mut EventBus {
1626 &mut self.events
1627 }
1628
1629 /// Get a mutable reference to the metrics.
1630 pub const fn metrics_mut(&mut self) -> &mut Metrics {
1631 &mut self.metrics
1632 }
1633
1634 /// Build the `PhaseContext` for the current tick.
1635 #[must_use]
1636 pub const fn phase_context(&self) -> PhaseContext {
1637 PhaseContext {
1638 tick: self.tick,
1639 dt: self.dt,
1640 }
1641 }
1642
1643 /// Run only the `advance_transient` phase (with hooks).
1644 pub fn run_advance_transient(&mut self) {
1645 self.hooks
1646 .run_before(Phase::AdvanceTransient, &mut self.world);
1647 for group in &self.groups {
1648 self.hooks
1649 .run_before_group(Phase::AdvanceTransient, group.id(), &mut self.world);
1650 }
1651 let ctx = self.phase_context();
1652 crate::systems::advance_transient::run(
1653 &mut self.world,
1654 &mut self.events,
1655 &ctx,
1656 &mut self.rider_index,
1657 );
1658 for group in &self.groups {
1659 self.hooks
1660 .run_after_group(Phase::AdvanceTransient, group.id(), &mut self.world);
1661 }
1662 self.hooks
1663 .run_after(Phase::AdvanceTransient, &mut self.world);
1664 }
1665
1666 /// Run only the dispatch phase (with hooks).
1667 pub fn run_dispatch(&mut self) {
1668 self.hooks.run_before(Phase::Dispatch, &mut self.world);
1669 for group in &self.groups {
1670 self.hooks
1671 .run_before_group(Phase::Dispatch, group.id(), &mut self.world);
1672 }
1673 let ctx = self.phase_context();
1674 crate::systems::dispatch::run(
1675 &mut self.world,
1676 &mut self.events,
1677 &ctx,
1678 &self.groups,
1679 &mut self.dispatchers,
1680 &self.rider_index,
1681 );
1682 for group in &self.groups {
1683 self.hooks
1684 .run_after_group(Phase::Dispatch, group.id(), &mut self.world);
1685 }
1686 self.hooks.run_after(Phase::Dispatch, &mut self.world);
1687 }
1688
1689 /// Run only the movement phase (with hooks).
1690 pub fn run_movement(&mut self) {
1691 self.hooks.run_before(Phase::Movement, &mut self.world);
1692 for group in &self.groups {
1693 self.hooks
1694 .run_before_group(Phase::Movement, group.id(), &mut self.world);
1695 }
1696 let ctx = self.phase_context();
1697 self.world.elevator_ids_into(&mut self.elevator_ids_buf);
1698 crate::systems::movement::run(
1699 &mut self.world,
1700 &mut self.events,
1701 &ctx,
1702 &self.elevator_ids_buf,
1703 &mut self.metrics,
1704 );
1705 for group in &self.groups {
1706 self.hooks
1707 .run_after_group(Phase::Movement, group.id(), &mut self.world);
1708 }
1709 self.hooks.run_after(Phase::Movement, &mut self.world);
1710 }
1711
1712 /// Run only the doors phase (with hooks).
1713 pub fn run_doors(&mut self) {
1714 self.hooks.run_before(Phase::Doors, &mut self.world);
1715 for group in &self.groups {
1716 self.hooks
1717 .run_before_group(Phase::Doors, group.id(), &mut self.world);
1718 }
1719 let ctx = self.phase_context();
1720 self.world.elevator_ids_into(&mut self.elevator_ids_buf);
1721 crate::systems::doors::run(
1722 &mut self.world,
1723 &mut self.events,
1724 &ctx,
1725 &self.elevator_ids_buf,
1726 );
1727 for group in &self.groups {
1728 self.hooks
1729 .run_after_group(Phase::Doors, group.id(), &mut self.world);
1730 }
1731 self.hooks.run_after(Phase::Doors, &mut self.world);
1732 }
1733
1734 /// Run only the loading phase (with hooks).
1735 pub fn run_loading(&mut self) {
1736 self.hooks.run_before(Phase::Loading, &mut self.world);
1737 for group in &self.groups {
1738 self.hooks
1739 .run_before_group(Phase::Loading, group.id(), &mut self.world);
1740 }
1741 let ctx = self.phase_context();
1742 self.world.elevator_ids_into(&mut self.elevator_ids_buf);
1743 crate::systems::loading::run(
1744 &mut self.world,
1745 &mut self.events,
1746 &ctx,
1747 &self.elevator_ids_buf,
1748 &mut self.rider_index,
1749 );
1750 for group in &self.groups {
1751 self.hooks
1752 .run_after_group(Phase::Loading, group.id(), &mut self.world);
1753 }
1754 self.hooks.run_after(Phase::Loading, &mut self.world);
1755 }
1756
1757 /// Run only the advance-queue phase (with hooks).
1758 ///
1759 /// Reconciles each elevator's phase/target with the front of its
1760 /// [`DestinationQueue`](crate::components::DestinationQueue). Runs
1761 /// between Reposition and Movement.
1762 pub fn run_advance_queue(&mut self) {
1763 self.hooks.run_before(Phase::AdvanceQueue, &mut self.world);
1764 for group in &self.groups {
1765 self.hooks
1766 .run_before_group(Phase::AdvanceQueue, group.id(), &mut self.world);
1767 }
1768 let ctx = self.phase_context();
1769 self.world.elevator_ids_into(&mut self.elevator_ids_buf);
1770 crate::systems::advance_queue::run(
1771 &mut self.world,
1772 &mut self.events,
1773 &ctx,
1774 &self.elevator_ids_buf,
1775 );
1776 for group in &self.groups {
1777 self.hooks
1778 .run_after_group(Phase::AdvanceQueue, group.id(), &mut self.world);
1779 }
1780 self.hooks.run_after(Phase::AdvanceQueue, &mut self.world);
1781 }
1782
1783 /// Run only the reposition phase (with hooks).
1784 ///
1785 /// Only runs if at least one group has a [`RepositionStrategy`] configured.
1786 /// Idle elevators with no pending dispatch assignment are repositioned
1787 /// according to their group's strategy.
1788 pub fn run_reposition(&mut self) {
1789 if self.repositioners.is_empty() {
1790 return;
1791 }
1792 self.hooks.run_before(Phase::Reposition, &mut self.world);
1793 // Only run per-group hooks for groups that have a repositioner.
1794 for group in &self.groups {
1795 if self.repositioners.contains_key(&group.id()) {
1796 self.hooks
1797 .run_before_group(Phase::Reposition, group.id(), &mut self.world);
1798 }
1799 }
1800 let ctx = self.phase_context();
1801 crate::systems::reposition::run(
1802 &mut self.world,
1803 &mut self.events,
1804 &ctx,
1805 &self.groups,
1806 &mut self.repositioners,
1807 &mut self.reposition_buf,
1808 );
1809 for group in &self.groups {
1810 if self.repositioners.contains_key(&group.id()) {
1811 self.hooks
1812 .run_after_group(Phase::Reposition, group.id(), &mut self.world);
1813 }
1814 }
1815 self.hooks.run_after(Phase::Reposition, &mut self.world);
1816 }
1817
1818 /// Run the energy system (no hooks — inline phase).
1819 #[cfg(feature = "energy")]
1820 fn run_energy(&mut self) {
1821 let ctx = self.phase_context();
1822 self.world.elevator_ids_into(&mut self.elevator_ids_buf);
1823 crate::systems::energy::run(
1824 &mut self.world,
1825 &mut self.events,
1826 &ctx,
1827 &self.elevator_ids_buf,
1828 );
1829 }
1830
1831 /// Run only the metrics phase (with hooks).
1832 pub fn run_metrics(&mut self) {
1833 self.hooks.run_before(Phase::Metrics, &mut self.world);
1834 for group in &self.groups {
1835 self.hooks
1836 .run_before_group(Phase::Metrics, group.id(), &mut self.world);
1837 }
1838 let ctx = self.phase_context();
1839 crate::systems::metrics::run(
1840 &mut self.world,
1841 &self.events,
1842 &mut self.metrics,
1843 &ctx,
1844 &self.groups,
1845 );
1846 for group in &self.groups {
1847 self.hooks
1848 .run_after_group(Phase::Metrics, group.id(), &mut self.world);
1849 }
1850 self.hooks.run_after(Phase::Metrics, &mut self.world);
1851 }
1852
1853 // Phase-hook registration lives in `sim/construction.rs`.
1854
1855 /// Increment the tick counter and flush events to the output buffer.
1856 ///
1857 /// Call after running all desired phases. Events emitted during this tick
1858 /// are moved to the output buffer and available via `drain_events()`.
1859 pub fn advance_tick(&mut self) {
1860 self.pending_output.extend(self.events.drain());
1861 self.tick += 1;
1862 }
1863
1864 /// Advance the simulation by one tick.
1865 ///
1866 /// Events from this tick are buffered internally and available via
1867 /// `drain_events()`. The metrics system only processes events from
1868 /// the current tick, regardless of whether the consumer drains them.
1869 ///
1870 /// ```
1871 /// use elevator_core::prelude::*;
1872 ///
1873 /// let mut sim = SimulationBuilder::demo().build().unwrap();
1874 /// sim.step();
1875 /// assert_eq!(sim.current_tick(), 1);
1876 /// ```
1877 pub fn step(&mut self) {
1878 self.world.snapshot_prev_positions();
1879 self.run_advance_transient();
1880 self.run_dispatch();
1881 self.run_reposition();
1882 self.run_advance_queue();
1883 self.run_movement();
1884 self.run_doors();
1885 self.run_loading();
1886 #[cfg(feature = "energy")]
1887 self.run_energy();
1888 self.run_metrics();
1889 self.advance_tick();
1890 }
1891
1892 // ── Hall / car call API ─────────────────────────────────────────
1893
1894 /// Press an up/down hall button at `stop` without associating it
1895 /// with any particular rider. Useful for scripted NPCs, player
1896 /// input, or cutscene cues.
1897 ///
1898 /// If a call in this direction already exists at `stop`, the press
1899 /// tick is left untouched (first press wins for latency purposes).
1900 ///
1901 /// # Errors
1902 /// Returns [`SimError::EntityNotFound`] if `stop` is not a valid
1903 /// stop entity.
1904 pub fn press_hall_button(
1905 &mut self,
1906 stop: impl Into<StopRef>,
1907 direction: crate::components::CallDirection,
1908 ) -> Result<(), SimError> {
1909 let stop = self.resolve_stop(stop.into())?;
1910 if self.world.stop(stop).is_none() {
1911 return Err(SimError::EntityNotFound(stop));
1912 }
1913 self.ensure_hall_call(stop, direction, None, None);
1914 Ok(())
1915 }
1916
1917 /// Press a floor button from inside `car`. No-op if the car already
1918 /// has a pending call for `floor`.
1919 ///
1920 /// # Errors
1921 /// Returns [`SimError::EntityNotFound`] if `car` or `floor` is invalid.
1922 pub fn press_car_button(
1923 &mut self,
1924 car: EntityId,
1925 floor: impl Into<StopRef>,
1926 ) -> Result<(), SimError> {
1927 let floor = self.resolve_stop(floor.into())?;
1928 if self.world.elevator(car).is_none() {
1929 return Err(SimError::EntityNotFound(car));
1930 }
1931 if self.world.stop(floor).is_none() {
1932 return Err(SimError::EntityNotFound(floor));
1933 }
1934 self.ensure_car_call(car, floor, None);
1935 Ok(())
1936 }
1937
1938 /// Pin the hall call at `(stop, direction)` to `car`. Dispatch is
1939 /// forbidden from reassigning the call to a different car until
1940 /// [`unpin_assignment`](Self::unpin_assignment) is called or the
1941 /// call is cleared.
1942 ///
1943 /// # Errors
1944 /// - [`SimError::EntityNotFound`] — `car` is not a valid elevator.
1945 /// - [`SimError::HallCallNotFound`] — no hall call exists at that
1946 /// `(stop, direction)` pair yet.
1947 /// - [`SimError::LineDoesNotServeStop`] — the car's line does not
1948 /// serve `stop`. Without this check a cross-line pin would be
1949 /// silently dropped at dispatch time yet leave the call `pinned`,
1950 /// blocking every other car.
1951 pub fn pin_assignment(
1952 &mut self,
1953 car: EntityId,
1954 stop: EntityId,
1955 direction: crate::components::CallDirection,
1956 ) -> Result<(), SimError> {
1957 let Some(elev) = self.world.elevator(car) else {
1958 return Err(SimError::EntityNotFound(car));
1959 };
1960 let car_line = elev.line;
1961 // Validate the car's line can reach the stop. If the line has
1962 // an entry in any group, we consult its `serves` list. A car
1963 // whose line entity doesn't match any line in any group falls
1964 // through — older test fixtures create elevators without a
1965 // line entity, and we don't want to regress them.
1966 let line_serves_stop = self
1967 .groups
1968 .iter()
1969 .flat_map(|g| g.lines().iter())
1970 .find(|li| li.entity() == car_line)
1971 .map(|li| li.serves().contains(&stop));
1972 if line_serves_stop == Some(false) {
1973 return Err(SimError::LineDoesNotServeStop {
1974 line_or_car: car,
1975 stop,
1976 });
1977 }
1978 let Some(call) = self.world.hall_call_mut(stop, direction) else {
1979 return Err(SimError::HallCallNotFound { stop, direction });
1980 };
1981 call.assigned_car = Some(car);
1982 call.pinned = true;
1983 Ok(())
1984 }
1985
1986 /// Release a previous pin at `(stop, direction)`. No-op if the call
1987 /// doesn't exist or wasn't pinned.
1988 pub fn unpin_assignment(
1989 &mut self,
1990 stop: EntityId,
1991 direction: crate::components::CallDirection,
1992 ) {
1993 if let Some(call) = self.world.hall_call_mut(stop, direction) {
1994 call.pinned = false;
1995 }
1996 }
1997
1998 /// Iterate every active hall call across the simulation. Yields a
1999 /// reference per live `(stop, direction)` press; games use this to
2000 /// render lobby lamp states, pending-rider counts, or per-floor
2001 /// button animations.
2002 pub fn hall_calls(&self) -> impl Iterator<Item = &crate::components::HallCall> {
2003 self.world.iter_hall_calls()
2004 }
2005
2006 /// Floor buttons currently pressed inside `car`. Returns an empty
2007 /// slice when the car has no aboard riders or hasn't been used.
2008 #[must_use]
2009 pub fn car_calls(&self, car: EntityId) -> &[crate::components::CarCall] {
2010 self.world.car_calls(car)
2011 }
2012
2013 /// Car currently assigned to serve the call at `(stop, direction)`,
2014 /// if dispatch has made an assignment yet.
2015 #[must_use]
2016 pub fn assigned_car(
2017 &self,
2018 stop: EntityId,
2019 direction: crate::components::CallDirection,
2020 ) -> Option<EntityId> {
2021 self.world
2022 .hall_call(stop, direction)
2023 .and_then(|c| c.assigned_car)
2024 }
2025
2026 /// Estimated ticks remaining before the assigned car reaches the
2027 /// call at `(stop, direction)`.
2028 ///
2029 /// # Errors
2030 ///
2031 /// - [`EtaError::NotAStop`] if no hall call exists at `(stop, direction)`.
2032 /// - [`EtaError::StopNotQueued`] if no car is assigned to the call.
2033 /// - [`EtaError::NotAnElevator`] if the assigned car has no positional
2034 /// data or is not a valid elevator.
2035 pub fn eta_for_call(
2036 &self,
2037 stop: EntityId,
2038 direction: crate::components::CallDirection,
2039 ) -> Result<u64, EtaError> {
2040 let call = self
2041 .world
2042 .hall_call(stop, direction)
2043 .ok_or(EtaError::NotAStop(stop))?;
2044 let car = call.assigned_car.ok_or(EtaError::NoCarAssigned(stop))?;
2045 let car_pos = self
2046 .world
2047 .position(car)
2048 .ok_or(EtaError::NotAnElevator(car))?
2049 .value;
2050 let stop_pos = self
2051 .world
2052 .stop_position(stop)
2053 .ok_or(EtaError::StopVanished(stop))?;
2054 let max_speed = self
2055 .world
2056 .elevator(car)
2057 .ok_or(EtaError::NotAnElevator(car))?
2058 .max_speed()
2059 .value();
2060 if max_speed <= 0.0 {
2061 return Err(EtaError::NotAnElevator(car));
2062 }
2063 let distance = (car_pos - stop_pos).abs();
2064 // Simple kinematic estimate. The `eta` module has a richer
2065 // trapezoidal model; the one-liner suits most hall-display use.
2066 Ok((distance / max_speed).ceil() as u64)
2067 }
2068
2069 // ── Internal helpers ────────────────────────────────────────────
2070
2071 /// Register (or aggregate) a hall call on behalf of a specific
2072 /// rider, including their destination in DCS mode.
2073 fn register_hall_call_for_rider(
2074 &mut self,
2075 stop: EntityId,
2076 direction: crate::components::CallDirection,
2077 rider: EntityId,
2078 destination: EntityId,
2079 ) {
2080 let mode = self
2081 .groups
2082 .iter()
2083 .find(|g| g.stop_entities().contains(&stop))
2084 .map(crate::dispatch::ElevatorGroup::hall_call_mode);
2085 let dest = match mode {
2086 Some(crate::dispatch::HallCallMode::Destination) => Some(destination),
2087 _ => None,
2088 };
2089 self.ensure_hall_call(stop, direction, Some(rider), dest);
2090 }
2091
2092 /// Create or aggregate into the hall call at `(stop, direction)`.
2093 /// Emits [`Event::HallButtonPressed`] only on the *first* press.
2094 fn ensure_hall_call(
2095 &mut self,
2096 stop: EntityId,
2097 direction: crate::components::CallDirection,
2098 rider: Option<EntityId>,
2099 destination: Option<EntityId>,
2100 ) {
2101 let mut fresh_press = false;
2102 if self.world.hall_call(stop, direction).is_none() {
2103 let mut call = crate::components::HallCall::new(stop, direction, self.tick);
2104 call.destination = destination;
2105 call.ack_latency_ticks = self.ack_latency_for_stop(stop);
2106 if call.ack_latency_ticks == 0 {
2107 // Controller has zero-tick latency — mark acknowledged
2108 // immediately so dispatch sees the call this same tick.
2109 call.acknowledged_at = Some(self.tick);
2110 }
2111 if let Some(rid) = rider {
2112 call.pending_riders.push(rid);
2113 }
2114 self.world.set_hall_call(call);
2115 fresh_press = true;
2116 } else if let Some(existing) = self.world.hall_call_mut(stop, direction) {
2117 if let Some(rid) = rider
2118 && !existing.pending_riders.contains(&rid)
2119 {
2120 existing.pending_riders.push(rid);
2121 }
2122 // Prefer a populated destination over None; don't overwrite
2123 // an existing destination even if a later press omits it.
2124 if existing.destination.is_none() {
2125 existing.destination = destination;
2126 }
2127 }
2128 if fresh_press {
2129 self.events.emit(Event::HallButtonPressed {
2130 stop,
2131 direction,
2132 tick: self.tick,
2133 });
2134 // Zero-latency controllers acknowledge on the press tick.
2135 if let Some(call) = self.world.hall_call(stop, direction)
2136 && call.acknowledged_at == Some(self.tick)
2137 {
2138 self.events.emit(Event::HallCallAcknowledged {
2139 stop,
2140 direction,
2141 tick: self.tick,
2142 });
2143 }
2144 }
2145 }
2146
2147 /// Ack latency for the group whose `members` slice contains `entity`.
2148 /// Defaults to 0 if no group matches (unreachable in normal builds).
2149 fn ack_latency_for(
2150 &self,
2151 entity: EntityId,
2152 members: impl Fn(&crate::dispatch::ElevatorGroup) -> &[EntityId],
2153 ) -> u32 {
2154 self.groups
2155 .iter()
2156 .find(|g| members(g).contains(&entity))
2157 .map_or(0, crate::dispatch::ElevatorGroup::ack_latency_ticks)
2158 }
2159
2160 /// Ack latency for the group that owns `stop` (0 if no group).
2161 fn ack_latency_for_stop(&self, stop: EntityId) -> u32 {
2162 self.ack_latency_for(stop, crate::dispatch::ElevatorGroup::stop_entities)
2163 }
2164
2165 /// Ack latency for the group that owns `car` (0 if no group).
2166 fn ack_latency_for_car(&self, car: EntityId) -> u32 {
2167 self.ack_latency_for(car, crate::dispatch::ElevatorGroup::elevator_entities)
2168 }
2169
2170 /// Create or aggregate into a car call for `(car, floor)`.
2171 /// Emits [`Event::CarButtonPressed`] on first press; repeat presses
2172 /// by other riders append to `pending_riders` without re-emitting.
2173 fn ensure_car_call(&mut self, car: EntityId, floor: EntityId, rider: Option<EntityId>) {
2174 let press_tick = self.tick;
2175 let ack_latency = self.ack_latency_for_car(car);
2176 let Some(queue) = self.world.car_calls_mut(car) else {
2177 return;
2178 };
2179 let existing_idx = queue.iter().position(|c| c.floor == floor);
2180 let fresh = existing_idx.is_none();
2181 if let Some(idx) = existing_idx {
2182 if let Some(rid) = rider
2183 && !queue[idx].pending_riders.contains(&rid)
2184 {
2185 queue[idx].pending_riders.push(rid);
2186 }
2187 } else {
2188 let mut call = crate::components::CarCall::new(car, floor, press_tick);
2189 call.ack_latency_ticks = ack_latency;
2190 if ack_latency == 0 {
2191 call.acknowledged_at = Some(press_tick);
2192 }
2193 if let Some(rid) = rider {
2194 call.pending_riders.push(rid);
2195 }
2196 queue.push(call);
2197 }
2198 if fresh {
2199 self.events.emit(Event::CarButtonPressed {
2200 car,
2201 floor,
2202 rider,
2203 tick: press_tick,
2204 });
2205 }
2206 }
2207}
2208
2209impl fmt::Debug for Simulation {
2210 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2211 f.debug_struct("Simulation")
2212 .field("tick", &self.tick)
2213 .field("dt", &self.dt)
2214 .field("groups", &self.groups.len())
2215 .field("entities", &self.world.entity_count())
2216 .finish_non_exhaustive()
2217 }
2218}