Skip to main content

elevator_core/sim/
lifecycle.rs

1//! Rider lifecycle, population queries, and entity state control.
2//!
3//! Covers reroute/settle/despawn/disable/enable, population queries,
4//! per-entity metrics, service mode, and route invalidation. Split out
5//! from `sim.rs` to keep each concern readable.
6
7use std::collections::HashSet;
8
9use crate::components::{Elevator, ElevatorPhase, RiderPhase, RiderPhaseKind, Route};
10use crate::entity::{ElevatorId, EntityId, RiderId};
11use crate::error::SimError;
12use crate::events::Event;
13use crate::ids::GroupId;
14
15use super::Simulation;
16
17impl Simulation {
18    // ── Extension restore ────────────────────────────────────────────
19
20    /// Deserialize extension components from a snapshot.
21    ///
22    /// Call this after restoring from a snapshot and registering all
23    /// extension types via `world.register_ext::<T>(key)`.
24    ///
25    /// Returns the names of any extension types present in the snapshot
26    /// that were not registered. An empty vec means all extensions were
27    /// deserialized successfully.
28    ///
29    /// Prefer [`load_extensions_with`](Self::load_extensions_with) which
30    /// combines registration and loading in one call.
31    #[must_use]
32    pub fn load_extensions(&mut self) -> Vec<String> {
33        let Some(pending) = self
34            .world
35            .remove_resource::<crate::snapshot::PendingExtensions>()
36        else {
37            return Vec::new();
38        };
39        let unregistered = self.world.unregistered_ext_names(pending.0.keys());
40        self.world.deserialize_extensions(&pending.0);
41        unregistered
42    }
43
44    /// Register extension types and load their data from a snapshot
45    /// in one step.
46    ///
47    /// This is the recommended way to restore extensions. It replaces the
48    /// manual 3-step ceremony of `register_ext` → `load_extensions`:
49    ///
50    /// ```ignore
51    /// // Before (3-step ceremony):
52    /// let mut sim = snapshot.restore(None)?;
53    /// sim.world_mut().register_ext::<VipTag>(ExtKey::from_type_name());
54    /// sim.world_mut().register_ext::<TeamId>(ExtKey::from_type_name());
55    /// sim.load_extensions();
56    ///
57    /// // After:
58    /// let mut sim = snapshot.restore(None)?;
59    /// let unregistered = sim.load_extensions_with(|world| {
60    ///     register_extensions!(world, VipTag, TeamId);
61    /// });
62    /// assert!(unregistered.is_empty(), "missing: {unregistered:?}");
63    /// ```
64    ///
65    /// Returns the names of any extension types in the snapshot that were
66    /// not registered. This catches "forgot to register" bugs at load time.
67    #[must_use]
68    pub fn load_extensions_with<F>(&mut self, register: F) -> Vec<String>
69    where
70        F: FnOnce(&mut crate::world::World),
71    {
72        register(&mut self.world);
73        self.load_extensions()
74    }
75
76    // ── Helpers ──────────────────────────────────────────────────────
77
78    /// Extract the `GroupId` from the current leg of a route.
79    ///
80    /// For Walk legs, looks ahead to the next leg to find the group.
81    /// Falls back to `GroupId(0)` when no route exists or no group leg is found.
82    pub(super) fn group_from_route(&self, route: Option<&Route>) -> GroupId {
83        if let Some(route) = route {
84            // Scan forward from current_leg looking for a Group or Line transport mode.
85            for leg in route.legs.iter().skip(route.current_leg) {
86                match leg.via {
87                    crate::components::TransportMode::Group(g) => return g,
88                    crate::components::TransportMode::Line(l) => {
89                        if let Some(line) = self.world.line(l) {
90                            return line.group();
91                        }
92                    }
93                    crate::components::TransportMode::Walk => {}
94                }
95            }
96        }
97        GroupId(0)
98    }
99
100    // ── Re-routing ───────────────────────────────────────────────────
101
102    /// Change a rider's destination mid-route.
103    ///
104    /// Replaces remaining route legs with a single direct leg to `new_destination`,
105    /// keeping the rider's current stop as origin.
106    ///
107    /// Returns `Err` if the rider does not exist or is not in `Waiting` phase
108    /// (riding/boarding riders cannot be rerouted until they exit).
109    ///
110    /// # Errors
111    ///
112    /// Returns [`SimError::EntityNotFound`] if `rider` does not exist.
113    /// Returns [`SimError::WrongRiderPhase`] if the rider is not in
114    /// [`RiderPhase::Waiting`], or [`SimError::RiderHasNoStop`] if the
115    /// rider has no current stop.
116    pub fn reroute(&mut self, rider: RiderId, new_destination: EntityId) -> Result<(), SimError> {
117        let rider = rider.entity();
118        let r = self
119            .world
120            .rider(rider)
121            .ok_or(SimError::EntityNotFound(rider))?;
122
123        if r.phase != RiderPhase::Waiting {
124            return Err(SimError::WrongRiderPhase {
125                rider,
126                expected: RiderPhaseKind::Waiting,
127                actual: r.phase.kind(),
128            });
129        }
130
131        let origin = r.current_stop.ok_or(SimError::RiderHasNoStop(rider))?;
132
133        let group = self.group_from_route(self.world.route(rider));
134        self.world
135            .set_route(rider, Route::direct(origin, new_destination, group));
136
137        self.events.emit(Event::RiderRerouted {
138            rider,
139            new_destination,
140            tick: self.tick,
141        });
142
143        Ok(())
144    }
145
146    /// Replace a rider's entire remaining route.
147    ///
148    /// # Errors
149    ///
150    /// Returns [`SimError::EntityNotFound`] if `rider` does not exist.
151    pub fn set_rider_route(&mut self, rider: EntityId, route: Route) -> Result<(), SimError> {
152        if self.world.rider(rider).is_none() {
153            return Err(SimError::EntityNotFound(rider));
154        }
155        self.world.set_route(rider, route);
156        Ok(())
157    }
158
159    // ── Rider settlement & population ─────────────────────────────
160
161    /// Transition an `Arrived` or `Abandoned` rider to `Resident` at their
162    /// current stop.
163    ///
164    /// Resident riders are parked — invisible to dispatch and loading, but
165    /// queryable via [`residents_at()`](Self::residents_at). They can later
166    /// be given a new route via [`reroute_rider()`](Self::reroute_rider).
167    ///
168    /// # Errors
169    ///
170    /// Returns [`SimError::EntityNotFound`] if `id` does not exist.
171    /// Returns [`SimError::WrongRiderPhase`] if the rider is not in
172    /// `Arrived` or `Abandoned` phase, or [`SimError::RiderHasNoStop`]
173    /// if the rider has no current stop.
174    pub fn settle_rider(&mut self, id: RiderId) -> Result<(), SimError> {
175        let id = id.entity();
176        let rider = self.world.rider(id).ok_or(SimError::EntityNotFound(id))?;
177
178        let old_phase = rider.phase;
179        match old_phase {
180            RiderPhase::Arrived | RiderPhase::Abandoned => {}
181            _ => {
182                return Err(SimError::WrongRiderPhase {
183                    rider: id,
184                    expected: RiderPhaseKind::Arrived,
185                    actual: old_phase.kind(),
186                });
187            }
188        }
189
190        let stop = rider.current_stop.ok_or(SimError::RiderHasNoStop(id))?;
191
192        // Update index: remove from old partition (only Abandoned is indexed).
193        if old_phase == RiderPhase::Abandoned {
194            self.rider_index.remove_abandoned(stop, id);
195        }
196        self.rider_index.insert_resident(stop, id);
197
198        if let Some(r) = self.world.rider_mut(id) {
199            r.phase = RiderPhase::Resident;
200        }
201
202        self.metrics.record_settle();
203        self.events.emit(Event::RiderSettled {
204            rider: id,
205            stop,
206            tick: self.tick,
207        });
208        Ok(())
209    }
210
211    /// Give a `Resident` rider a new route, transitioning them to `Waiting`.
212    ///
213    /// The rider begins waiting at their current stop for an elevator
214    /// matching the route's transport mode. If the rider has a
215    /// [`Patience`](crate::components::Patience) component, its
216    /// `waited_ticks` is reset to zero.
217    ///
218    /// # Errors
219    ///
220    /// Returns [`SimError::EntityNotFound`] if `id` does not exist.
221    /// Returns [`SimError::WrongRiderPhase`] if the rider is not in `Resident`
222    /// phase, [`SimError::EmptyRoute`] if the route has no legs, or
223    /// [`SimError::RouteOriginMismatch`] if the route's first leg origin does
224    /// not match the rider's current stop.
225    pub fn reroute_rider(&mut self, id: EntityId, route: Route) -> Result<(), SimError> {
226        let rider = self.world.rider(id).ok_or(SimError::EntityNotFound(id))?;
227
228        if rider.phase != RiderPhase::Resident {
229            return Err(SimError::WrongRiderPhase {
230                rider: id,
231                expected: RiderPhaseKind::Resident,
232                actual: rider.phase.kind(),
233            });
234        }
235
236        let stop = rider.current_stop.ok_or(SimError::RiderHasNoStop(id))?;
237
238        let new_destination = route.final_destination().ok_or(SimError::EmptyRoute)?;
239
240        // Validate that the route departs from the rider's current stop.
241        if let Some(leg) = route.current()
242            && leg.from != stop
243        {
244            return Err(SimError::RouteOriginMismatch {
245                expected_origin: stop,
246                route_origin: leg.from,
247            });
248        }
249
250        self.rider_index.remove_resident(stop, id);
251        self.rider_index.insert_waiting(stop, id);
252
253        if let Some(r) = self.world.rider_mut(id) {
254            r.phase = RiderPhase::Waiting;
255        }
256        self.world.set_route(id, route);
257
258        // Reset patience if present.
259        if let Some(p) = self.world.patience_mut(id) {
260            p.waited_ticks = 0;
261        }
262
263        self.metrics.record_reroute();
264        self.events.emit(Event::RiderRerouted {
265            rider: id,
266            new_destination,
267            tick: self.tick,
268        });
269        Ok(())
270    }
271
272    /// Remove a rider from the simulation entirely.
273    ///
274    /// Cleans up the population index, metric tags, and elevator cross-references
275    /// (if the rider is currently aboard). Emits [`Event::RiderDespawned`].
276    ///
277    /// All rider removal should go through this method rather than calling
278    /// `world.despawn()` directly, to keep the population index consistent.
279    ///
280    /// # Errors
281    ///
282    /// Returns [`SimError::EntityNotFound`] if `id` does not exist or is
283    /// not a rider.
284    pub fn despawn_rider(&mut self, id: RiderId) -> Result<(), SimError> {
285        let id = id.entity();
286        let rider = self.world.rider(id).ok_or(SimError::EntityNotFound(id))?;
287
288        // Targeted index removal based on current phase (O(1) vs O(n) scan).
289        if let Some(stop) = rider.current_stop {
290            match rider.phase {
291                RiderPhase::Waiting => self.rider_index.remove_waiting(stop, id),
292                RiderPhase::Resident => self.rider_index.remove_resident(stop, id),
293                RiderPhase::Abandoned => self.rider_index.remove_abandoned(stop, id),
294                _ => {} // Boarding/Riding/Exiting/Walking/Arrived — not indexed
295            }
296        }
297
298        if let Some(tags) = self
299            .world
300            .resource_mut::<crate::tagged_metrics::MetricTags>()
301        {
302            tags.remove_entity(id);
303        }
304
305        self.world.despawn(id);
306
307        self.events.emit(Event::RiderDespawned {
308            rider: id,
309            tick: self.tick,
310        });
311        Ok(())
312    }
313
314    // ── Access control ──────────────────────────────────────────────
315
316    /// Set the allowed stops for a rider.
317    ///
318    /// When set, the rider will only be allowed to board elevators that
319    /// can take them to a stop in the allowed set. See
320    /// [`AccessControl`](crate::components::AccessControl) for details.
321    ///
322    /// # Errors
323    ///
324    /// Returns [`SimError::EntityNotFound`] if the rider does not exist.
325    pub fn set_rider_access(
326        &mut self,
327        rider: EntityId,
328        allowed_stops: HashSet<EntityId>,
329    ) -> Result<(), SimError> {
330        if self.world.rider(rider).is_none() {
331            return Err(SimError::EntityNotFound(rider));
332        }
333        self.world
334            .set_access_control(rider, crate::components::AccessControl::new(allowed_stops));
335        Ok(())
336    }
337
338    /// Set the restricted stops for an elevator.
339    ///
340    /// Riders whose current destination is in this set will be rejected
341    /// with [`RejectionReason::AccessDenied`](crate::error::RejectionReason::AccessDenied)
342    /// during the loading phase.
343    ///
344    /// # Errors
345    ///
346    /// Returns [`SimError::EntityNotFound`] if the elevator does not exist.
347    pub fn set_elevator_restricted_stops(
348        &mut self,
349        elevator: EntityId,
350        restricted_stops: HashSet<EntityId>,
351    ) -> Result<(), SimError> {
352        let car = self
353            .world
354            .elevator_mut(elevator)
355            .ok_or(SimError::EntityNotFound(elevator))?;
356        car.restricted_stops = restricted_stops;
357        Ok(())
358    }
359
360    // ── Population queries ──────────────────────────────────────────
361
362    /// Iterate over resident rider IDs at a stop (O(1) lookup).
363    pub fn residents_at(&self, stop: EntityId) -> impl Iterator<Item = EntityId> + '_ {
364        self.rider_index.residents_at(stop).iter().copied()
365    }
366
367    /// Count of residents at a stop (O(1)).
368    #[must_use]
369    pub fn resident_count_at(&self, stop: EntityId) -> usize {
370        self.rider_index.resident_count_at(stop)
371    }
372
373    /// Iterate over waiting rider IDs at a stop (O(1) lookup).
374    pub fn waiting_at(&self, stop: EntityId) -> impl Iterator<Item = EntityId> + '_ {
375        self.rider_index.waiting_at(stop).iter().copied()
376    }
377
378    /// Count of waiting riders at a stop (O(1)).
379    #[must_use]
380    pub fn waiting_count_at(&self, stop: EntityId) -> usize {
381        self.rider_index.waiting_count_at(stop)
382    }
383
384    /// Iterate over abandoned rider IDs at a stop (O(1) lookup).
385    pub fn abandoned_at(&self, stop: EntityId) -> impl Iterator<Item = EntityId> + '_ {
386        self.rider_index.abandoned_at(stop).iter().copied()
387    }
388
389    /// Count of abandoned riders at a stop (O(1)).
390    #[must_use]
391    pub fn abandoned_count_at(&self, stop: EntityId) -> usize {
392        self.rider_index.abandoned_count_at(stop)
393    }
394
395    /// Get the rider entities currently aboard an elevator.
396    ///
397    /// Returns an empty slice if the elevator does not exist.
398    #[must_use]
399    pub fn riders_on(&self, elevator: EntityId) -> &[EntityId] {
400        self.world
401            .elevator(elevator)
402            .map_or(&[], |car| car.riders())
403    }
404
405    /// Get the number of riders aboard an elevator.
406    ///
407    /// Returns 0 if the elevator does not exist.
408    #[must_use]
409    pub fn occupancy(&self, elevator: EntityId) -> usize {
410        self.world
411            .elevator(elevator)
412            .map_or(0, |car| car.riders().len())
413    }
414
415    // ── Entity lifecycle ────────────────────────────────────────────
416
417    /// Disable an entity. Disabled entities are skipped by all systems.
418    ///
419    /// If the entity is an elevator in motion, it is reset to `Idle` with
420    /// zero velocity to prevent stale target references on re-enable.
421    ///
422    /// **Note on residents:** disabling a stop does not automatically handle
423    /// `Resident` riders parked there. Callers should listen for
424    /// [`Event::EntityDisabled`] and manually reroute or despawn any
425    /// residents at the affected stop.
426    ///
427    /// Emits `EntityDisabled`. Returns `Err` if the entity does not exist.
428    ///
429    /// # Errors
430    ///
431    /// Returns [`SimError::EntityNotFound`] if `id` does not refer to a
432    /// living entity.
433    pub fn disable(&mut self, id: EntityId) -> Result<(), SimError> {
434        if !self.world.is_alive(id) {
435            return Err(SimError::EntityNotFound(id));
436        }
437        // If this is an elevator, eject all riders and reset state.
438        if let Some(car) = self.world.elevator(id) {
439            let rider_ids = car.riders.clone();
440            let pos = self.world.position(id).map_or(0.0, |p| p.value);
441            let nearest_stop = self.world.find_nearest_stop(pos);
442
443            for rid in &rider_ids {
444                if let Some(r) = self.world.rider_mut(*rid) {
445                    r.phase = RiderPhase::Waiting;
446                    r.current_stop = nearest_stop;
447                    r.board_tick = None;
448                }
449                if let Some(stop) = nearest_stop {
450                    self.rider_index.insert_waiting(stop, *rid);
451                    self.events.emit(Event::RiderEjected {
452                        rider: *rid,
453                        elevator: id,
454                        stop,
455                        tick: self.tick,
456                    });
457                }
458            }
459
460            let had_load = self
461                .world
462                .elevator(id)
463                .is_some_and(|c| c.current_load.value() > 0.0);
464            let capacity = self.world.elevator(id).map(|c| c.weight_capacity.value());
465            if let Some(car) = self.world.elevator_mut(id) {
466                car.riders.clear();
467                car.current_load = crate::components::Weight::ZERO;
468                car.phase = ElevatorPhase::Idle;
469                car.target_stop = None;
470            }
471            if had_load && let Some(cap) = capacity {
472                self.events.emit(Event::CapacityChanged {
473                    elevator: id,
474                    current_load: ordered_float::OrderedFloat(0.0),
475                    capacity: ordered_float::OrderedFloat(cap),
476                    tick: self.tick,
477                });
478            }
479        }
480        if let Some(vel) = self.world.velocity_mut(id) {
481            vel.value = 0.0;
482        }
483
484        // If this is a stop, invalidate routes that reference it.
485        if self.world.stop(id).is_some() {
486            self.invalidate_routes_for_stop(id);
487        }
488
489        self.world.disable(id);
490        self.events.emit(Event::EntityDisabled {
491            entity: id,
492            tick: self.tick,
493        });
494        Ok(())
495    }
496
497    /// Re-enable a disabled entity.
498    ///
499    /// Emits `EntityEnabled`. Returns `Err` if the entity does not exist.
500    ///
501    /// # Errors
502    ///
503    /// Returns [`SimError::EntityNotFound`] if `id` does not refer to a
504    /// living entity.
505    pub fn enable(&mut self, id: EntityId) -> Result<(), SimError> {
506        if !self.world.is_alive(id) {
507            return Err(SimError::EntityNotFound(id));
508        }
509        self.world.enable(id);
510        self.events.emit(Event::EntityEnabled {
511            entity: id,
512            tick: self.tick,
513        });
514        Ok(())
515    }
516
517    /// Invalidate routes for all riders referencing a disabled stop.
518    ///
519    /// Attempts to reroute riders to the nearest enabled alternative stop.
520    /// If no alternative exists, emits `RouteInvalidated` with `NoAlternative`.
521    fn invalidate_routes_for_stop(&mut self, disabled_stop: EntityId) {
522        use crate::events::RouteInvalidReason;
523
524        // Find the group this stop belongs to.
525        let group_stops: Vec<EntityId> = self
526            .groups
527            .iter()
528            .filter(|g| g.stop_entities().contains(&disabled_stop))
529            .flat_map(|g| g.stop_entities().iter().copied())
530            .filter(|&s| s != disabled_stop && !self.world.is_disabled(s))
531            .collect();
532
533        // Find all Waiting riders whose route references this stop.
534        // Riding riders are skipped — they'll be rerouted when they exit.
535        let rider_ids: Vec<EntityId> = self.world.rider_ids();
536        for rid in rider_ids {
537            let is_waiting = self
538                .world
539                .rider(rid)
540                .is_some_and(|r| r.phase == RiderPhase::Waiting);
541
542            if !is_waiting {
543                continue;
544            }
545
546            let references_stop = self.world.route(rid).is_some_and(|route| {
547                route
548                    .legs
549                    .iter()
550                    .skip(route.current_leg)
551                    .any(|leg| leg.to == disabled_stop || leg.from == disabled_stop)
552            });
553
554            if !references_stop {
555                continue;
556            }
557
558            // Try to find nearest alternative (excluding rider's current stop).
559            let rider_current_stop = self.world.rider(rid).and_then(|r| r.current_stop);
560
561            let disabled_stop_pos = self.world.stop(disabled_stop).map_or(0.0, |s| s.position);
562
563            let alternative = group_stops
564                .iter()
565                .filter(|&&s| Some(s) != rider_current_stop)
566                .filter_map(|&s| {
567                    self.world
568                        .stop(s)
569                        .map(|stop| (s, (stop.position - disabled_stop_pos).abs()))
570                })
571                .min_by(|a, b| a.1.total_cmp(&b.1))
572                .map(|(s, _)| s);
573
574            if let Some(alt_stop) = alternative {
575                // Reroute to nearest alternative.
576                let origin = rider_current_stop.unwrap_or(alt_stop);
577                let group = self.group_from_route(self.world.route(rid));
578                self.world
579                    .set_route(rid, Route::direct(origin, alt_stop, group));
580                self.events.emit(Event::RouteInvalidated {
581                    rider: rid,
582                    affected_stop: disabled_stop,
583                    reason: RouteInvalidReason::StopDisabled,
584                    tick: self.tick,
585                });
586            } else {
587                // No alternative — rider abandons immediately.
588                let abandon_stop = rider_current_stop.unwrap_or(disabled_stop);
589                self.events.emit(Event::RouteInvalidated {
590                    rider: rid,
591                    affected_stop: disabled_stop,
592                    reason: RouteInvalidReason::NoAlternative,
593                    tick: self.tick,
594                });
595                if let Some(r) = self.world.rider_mut(rid) {
596                    r.phase = RiderPhase::Abandoned;
597                }
598                if let Some(stop) = rider_current_stop {
599                    self.rider_index.remove_waiting(stop, rid);
600                    self.rider_index.insert_abandoned(stop, rid);
601                }
602                self.events.emit(Event::RiderAbandoned {
603                    rider: rid,
604                    stop: abandon_stop,
605                    tick: self.tick,
606                });
607            }
608        }
609    }
610
611    /// Check if an entity is disabled.
612    #[must_use]
613    pub fn is_disabled(&self, id: EntityId) -> bool {
614        self.world.is_disabled(id)
615    }
616
617    // ── Entity type queries ─────────────────────────────────────────
618
619    /// Check if an entity is an elevator.
620    ///
621    /// ```
622    /// use elevator_core::prelude::*;
623    ///
624    /// let sim = SimulationBuilder::demo().build().unwrap();
625    /// let stop = sim.stop_entity(StopId(0)).unwrap();
626    /// assert!(!sim.is_elevator(stop));
627    /// assert!(sim.is_stop(stop));
628    /// ```
629    #[must_use]
630    pub fn is_elevator(&self, id: EntityId) -> bool {
631        self.world.elevator(id).is_some()
632    }
633
634    /// Check if an entity is a rider.
635    #[must_use]
636    pub fn is_rider(&self, id: EntityId) -> bool {
637        self.world.rider(id).is_some()
638    }
639
640    /// Check if an entity is a stop.
641    #[must_use]
642    pub fn is_stop(&self, id: EntityId) -> bool {
643        self.world.stop(id).is_some()
644    }
645
646    // ── Aggregate queries ───────────────────────────────────────────
647
648    /// Count of elevators currently in the [`Idle`](ElevatorPhase::Idle) phase.
649    ///
650    /// Excludes disabled elevators (whose phase is reset to `Idle` on disable).
651    ///
652    /// ```
653    /// use elevator_core::prelude::*;
654    ///
655    /// let sim = SimulationBuilder::demo().build().unwrap();
656    /// assert_eq!(sim.idle_elevator_count(), 1);
657    /// ```
658    #[must_use]
659    pub fn idle_elevator_count(&self) -> usize {
660        self.world.iter_idle_elevators().count()
661    }
662
663    /// Current total weight aboard an elevator, or `None` if the entity is
664    /// not an elevator.
665    ///
666    /// ```
667    /// use elevator_core::prelude::*;
668    ///
669    /// let sim = SimulationBuilder::demo().build().unwrap();
670    /// let stop = sim.stop_entity(StopId(0)).unwrap();
671    /// assert_eq!(sim.elevator_load(ElevatorId::from(stop)), None); // not an elevator
672    /// ```
673    #[must_use]
674    pub fn elevator_load(&self, id: ElevatorId) -> Option<f64> {
675        let id = id.entity();
676        self.world.elevator(id).map(|e| e.current_load.value())
677    }
678
679    /// Whether the elevator's up-direction indicator lamp is lit.
680    ///
681    /// Returns `None` if the entity is not an elevator. See
682    /// [`Elevator::going_up`] for semantics.
683    #[must_use]
684    pub fn elevator_going_up(&self, id: EntityId) -> Option<bool> {
685        self.world.elevator(id).map(Elevator::going_up)
686    }
687
688    /// Whether the elevator's down-direction indicator lamp is lit.
689    ///
690    /// Returns `None` if the entity is not an elevator. See
691    /// [`Elevator::going_down`] for semantics.
692    #[must_use]
693    pub fn elevator_going_down(&self, id: EntityId) -> Option<bool> {
694        self.world.elevator(id).map(Elevator::going_down)
695    }
696
697    /// Direction the elevator is currently signalling, derived from the
698    /// indicator-lamp pair. Returns `None` if the entity is not an elevator.
699    #[must_use]
700    pub fn elevator_direction(&self, id: EntityId) -> Option<crate::components::Direction> {
701        self.world.elevator(id).map(Elevator::direction)
702    }
703
704    /// Count of rounded-floor transitions for an elevator (passing-floor
705    /// crossings plus arrivals). Returns `None` if the entity is not an
706    /// elevator.
707    #[must_use]
708    pub fn elevator_move_count(&self, id: EntityId) -> Option<u64> {
709        self.world.elevator(id).map(Elevator::move_count)
710    }
711
712    /// Distance the elevator would travel while braking to a stop from its
713    /// current velocity, at its configured deceleration rate.
714    ///
715    /// Uses the standard `v² / (2·a)` kinematic formula. A stationary
716    /// elevator returns `Some(0.0)`. Returns `None` if the entity is not
717    /// an elevator or lacks a velocity component.
718    ///
719    /// Useful for writing opportunistic dispatch strategies (e.g. "stop at
720    /// this floor if we can brake in time") without duplicating the physics
721    /// computation.
722    #[must_use]
723    pub fn braking_distance(&self, id: EntityId) -> Option<f64> {
724        let car = self.world.elevator(id)?;
725        let vel = self.world.velocity(id)?.value;
726        Some(crate::movement::braking_distance(
727            vel,
728            car.deceleration.value(),
729        ))
730    }
731
732    /// The position where the elevator would come to rest if it began braking
733    /// this instant. Current position plus a signed braking distance in the
734    /// direction of travel.
735    ///
736    /// Returns `None` if the entity is not an elevator or lacks the required
737    /// components.
738    #[must_use]
739    pub fn future_stop_position(&self, id: EntityId) -> Option<f64> {
740        let pos = self.world.position(id)?.value;
741        let vel = self.world.velocity(id)?.value;
742        let car = self.world.elevator(id)?;
743        let dist = crate::movement::braking_distance(vel, car.deceleration.value());
744        Some(vel.signum().mul_add(dist, pos))
745    }
746
747    /// Count of elevators currently in the given phase.
748    ///
749    /// Excludes disabled elevators (whose phase is reset to `Idle` on disable).
750    ///
751    /// ```
752    /// use elevator_core::prelude::*;
753    ///
754    /// let sim = SimulationBuilder::demo().build().unwrap();
755    /// assert_eq!(sim.elevators_in_phase(ElevatorPhase::Idle), 1);
756    /// assert_eq!(sim.elevators_in_phase(ElevatorPhase::Loading), 0);
757    /// ```
758    #[must_use]
759    pub fn elevators_in_phase(&self, phase: ElevatorPhase) -> usize {
760        self.world
761            .iter_elevators()
762            .filter(|(id, _, e)| e.phase() == phase && !self.world.is_disabled(*id))
763            .count()
764    }
765
766    // ── Service mode ────────────────────────────────────────────────
767
768    /// Set the service mode for an elevator.
769    ///
770    /// Emits [`Event::ServiceModeChanged`] if the mode actually changes.
771    ///
772    /// # Errors
773    ///
774    /// Returns [`SimError::EntityNotFound`] if the elevator does not exist.
775    pub fn set_service_mode(
776        &mut self,
777        elevator: EntityId,
778        mode: crate::components::ServiceMode,
779    ) -> Result<(), SimError> {
780        if self.world.elevator(elevator).is_none() {
781            return Err(SimError::EntityNotFound(elevator));
782        }
783        let old = self
784            .world
785            .service_mode(elevator)
786            .copied()
787            .unwrap_or_default();
788        if old == mode {
789            return Ok(());
790        }
791        // Leaving Manual: clear the pending velocity command and zero
792        // the velocity component. Otherwise a car moving at transition
793        // time is stranded — the Normal movement system only runs for
794        // MovingToStop/Repositioning phases, so velocity would linger
795        // forever without producing any position change.
796        if old == crate::components::ServiceMode::Manual {
797            if let Some(car) = self.world.elevator_mut(elevator) {
798                car.manual_target_velocity = None;
799            }
800            if let Some(v) = self.world.velocity_mut(elevator) {
801                v.value = 0.0;
802            }
803        }
804        self.world.set_service_mode(elevator, mode);
805        self.events.emit(Event::ServiceModeChanged {
806            elevator,
807            from: old,
808            to: mode,
809            tick: self.tick,
810        });
811        Ok(())
812    }
813
814    /// Get the current service mode for an elevator.
815    #[must_use]
816    pub fn service_mode(&self, elevator: EntityId) -> crate::components::ServiceMode {
817        self.world
818            .service_mode(elevator)
819            .copied()
820            .unwrap_or_default()
821    }
822}