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