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