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