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