Skip to main content

elevator_core/sim/
topology.rs

1//! Dynamic topology mutation and queries.
2//!
3//! Add/remove/reassign lines, elevators, stops, and groups at runtime, plus
4//! read-only topology queries (reachability, shortest route, transfer
5//! points). Split out from `sim.rs` to keep each concern readable.
6
7use crate::components::Route;
8use crate::components::{Elevator, ElevatorPhase, Line, Position, Stop, Velocity};
9use crate::dispatch::{BuiltinStrategy, DispatchStrategy, ElevatorGroup, LineInfo};
10use crate::door::DoorState;
11use crate::entity::EntityId;
12use crate::error::SimError;
13use crate::events::Event;
14use crate::ids::GroupId;
15use crate::topology::TopologyGraph;
16
17use super::{ElevatorParams, LineParams, Simulation};
18
19impl Simulation {
20    // ── Dynamic topology ────────────────────────────────────────────
21
22    /// Mark the topology graph dirty so it is rebuilt on next query.
23    fn mark_topo_dirty(&self) {
24        if let Ok(mut g) = self.topo_graph.lock() {
25            g.mark_dirty();
26        }
27    }
28
29    /// Find the (`group_index`, `line_index`) for a line entity.
30    fn find_line(&self, line: EntityId) -> Result<(usize, usize), SimError> {
31        self.groups
32            .iter()
33            .enumerate()
34            .find_map(|(gi, g)| {
35                g.lines()
36                    .iter()
37                    .position(|li| li.entity() == line)
38                    .map(|li_idx| (gi, li_idx))
39            })
40            .ok_or(SimError::LineNotFound(line))
41    }
42
43    /// Add a new stop to a group at runtime. Returns its `EntityId`.
44    ///
45    /// Runtime-added stops have no `StopId` — they are identified purely
46    /// by `EntityId`. The `stop_lookup` (config `StopId` → `EntityId`)
47    /// is not updated.
48    ///
49    /// # Errors
50    ///
51    /// Returns [`SimError::LineNotFound`] if the line entity does not exist.
52    pub fn add_stop(
53        &mut self,
54        name: String,
55        position: f64,
56        line: EntityId,
57    ) -> Result<EntityId, SimError> {
58        if !position.is_finite() {
59            return Err(SimError::InvalidConfig {
60                field: "position",
61                reason: format!(
62                    "stop position must be finite (got {position}); NaN/±inf \
63                     corrupt SortedStops ordering and find_stop_at_position lookup"
64                ),
65            });
66        }
67
68        let group_id = self
69            .world
70            .line(line)
71            .map(|l| l.group)
72            .ok_or(SimError::LineNotFound(line))?;
73
74        let (group_idx, line_idx) = self.find_line(line)?;
75
76        let eid = self.world.spawn();
77        self.world.set_stop(eid, Stop { name, position });
78        self.world.set_position(eid, Position { value: position });
79
80        // Add to the line's serves list.
81        self.groups[group_idx].lines_mut()[line_idx].add_stop(eid);
82
83        // Add to the group's flat cache.
84        self.groups[group_idx].push_stop(eid);
85
86        // Maintain sorted-stops index for O(log n) PassingFloor detection.
87        if let Some(sorted) = self.world.resource_mut::<crate::world::SortedStops>() {
88            let idx = sorted.0.partition_point(|&(p, _)| p < position);
89            sorted.0.insert(idx, (position, eid));
90        }
91
92        self.mark_topo_dirty();
93        self.events.emit(Event::StopAdded {
94            stop: eid,
95            line,
96            group: group_id,
97            tick: self.tick,
98        });
99        Ok(eid)
100    }
101
102    /// Add a new elevator to a line at runtime. Returns its `EntityId`.
103    ///
104    /// # Errors
105    ///
106    /// Returns [`SimError::LineNotFound`] if the line entity does not exist.
107    pub fn add_elevator(
108        &mut self,
109        params: &ElevatorParams,
110        line: EntityId,
111        starting_position: f64,
112    ) -> Result<EntityId, SimError> {
113        // Reject malformed params before they reach the world. Without this,
114        // zero/negative physics or zero door ticks crash later phases.
115        super::construction::validate_elevator_physics(
116            params.max_speed.value(),
117            params.acceleration.value(),
118            params.deceleration.value(),
119            params.weight_capacity.value(),
120            params.inspection_speed_factor,
121            params.door_transition_ticks,
122            params.door_open_ticks,
123            params.bypass_load_up_pct,
124            params.bypass_load_down_pct,
125        )?;
126        if !starting_position.is_finite() {
127            return Err(SimError::InvalidConfig {
128                field: "starting_position",
129                reason: format!(
130                    "must be finite (got {starting_position}); NaN/±inf corrupt \
131                     SortedStops ordering and find_stop_at_position lookup"
132                ),
133            });
134        }
135
136        let group_id = self
137            .world
138            .line(line)
139            .map(|l| l.group)
140            .ok_or(SimError::LineNotFound(line))?;
141
142        let (group_idx, line_idx) = self.find_line(line)?;
143
144        // Enforce max_cars limit.
145        if let Some(max) = self.world.line(line).and_then(Line::max_cars) {
146            let current_count = self.groups[group_idx].lines()[line_idx].elevators().len();
147            if current_count >= max {
148                return Err(SimError::InvalidConfig {
149                    field: "line.max_cars",
150                    reason: format!("line already has {current_count} cars (max {max})"),
151                });
152            }
153        }
154
155        let eid = self.world.spawn();
156        self.world.set_position(
157            eid,
158            Position {
159                value: starting_position,
160            },
161        );
162        self.world.set_velocity(eid, Velocity { value: 0.0 });
163        self.world.set_elevator(
164            eid,
165            Elevator {
166                phase: ElevatorPhase::Idle,
167                door: DoorState::Closed,
168                max_speed: params.max_speed,
169                acceleration: params.acceleration,
170                deceleration: params.deceleration,
171                weight_capacity: params.weight_capacity,
172                current_load: crate::components::Weight::ZERO,
173                riders: Vec::new(),
174                target_stop: None,
175                door_transition_ticks: params.door_transition_ticks,
176                door_open_ticks: params.door_open_ticks,
177                line,
178                repositioning: false,
179                restricted_stops: params.restricted_stops.clone(),
180                inspection_speed_factor: params.inspection_speed_factor,
181                going_up: true,
182                going_down: true,
183                move_count: 0,
184                door_command_queue: Vec::new(),
185                manual_target_velocity: None,
186                bypass_load_up_pct: params.bypass_load_up_pct,
187                bypass_load_down_pct: params.bypass_load_down_pct,
188                home_stop: None,
189            },
190        );
191        self.world
192            .set_destination_queue(eid, crate::components::DestinationQueue::new());
193        self.groups[group_idx].lines_mut()[line_idx].add_elevator(eid);
194        self.groups[group_idx].push_elevator(eid);
195
196        // Tag the elevator with its line's "line:{name}" tag.
197        let line_name = self.world.line(line).map(|l| l.name.clone());
198        if let Some(name) = line_name
199            && let Some(tags) = self
200                .world
201                .resource_mut::<crate::tagged_metrics::MetricTags>()
202        {
203            tags.tag(eid, format!("line:{name}"));
204        }
205
206        self.mark_topo_dirty();
207        self.events.emit(Event::ElevatorAdded {
208            elevator: eid,
209            line,
210            group: group_id,
211            tick: self.tick,
212        });
213        Ok(eid)
214    }
215
216    // ── Line / group topology ───────────────────────────────────────
217
218    /// Add a new line to a group. Returns the line entity.
219    ///
220    /// # Errors
221    ///
222    /// Returns [`SimError::GroupNotFound`] if the specified group does not exist.
223    /// Returns [`SimError::InvalidConfig`] if `min_position` / `max_position`
224    /// is non-finite or `min_position > max_position` — broken bounds
225    /// would produce NaN positions on every car added to the line.
226    pub fn add_line(&mut self, params: &LineParams) -> Result<EntityId, SimError> {
227        if !params.min_position.is_finite() || !params.max_position.is_finite() {
228            return Err(SimError::InvalidConfig {
229                field: "line.range",
230                reason: format!(
231                    "min/max must be finite (got min={}, max={})",
232                    params.min_position, params.max_position
233                ),
234            });
235        }
236        if params.min_position > params.max_position {
237            return Err(SimError::InvalidConfig {
238                field: "line.range",
239                reason: format!(
240                    "min ({}) must be <= max ({})",
241                    params.min_position, params.max_position
242                ),
243            });
244        }
245
246        let group_id = params.group;
247        let group = self
248            .groups
249            .iter_mut()
250            .find(|g| g.id() == group_id)
251            .ok_or(SimError::GroupNotFound(group_id))?;
252
253        let line_tag = format!("line:{}", params.name);
254
255        let eid = self.world.spawn();
256        self.world.set_line(
257            eid,
258            Line {
259                name: params.name.clone(),
260                group: group_id,
261                orientation: params.orientation,
262                position: params.position,
263                min_position: params.min_position,
264                max_position: params.max_position,
265                max_cars: params.max_cars,
266            },
267        );
268
269        group
270            .lines_mut()
271            .push(LineInfo::new(eid, Vec::new(), Vec::new()));
272
273        // Tag the line entity with "line:{name}" for per-line metrics.
274        if let Some(tags) = self
275            .world
276            .resource_mut::<crate::tagged_metrics::MetricTags>()
277        {
278            tags.tag(eid, line_tag);
279        }
280
281        self.mark_topo_dirty();
282        self.events.emit(Event::LineAdded {
283            line: eid,
284            group: group_id,
285            tick: self.tick,
286        });
287        Ok(eid)
288    }
289
290    /// Set the reachable position range of a line.
291    ///
292    /// Cars whose current position falls outside the new `[min, max]` are
293    /// clamped to the boundary. Phase is left untouched — a car mid-travel
294    /// keeps `MovingToStop` and the movement system reconciles on the
295    /// next tick.
296    ///
297    /// # Errors
298    ///
299    /// Returns [`SimError::LineNotFound`] if the line entity does not exist.
300    /// Returns [`SimError::InvalidConfig`] if `min` or `max` is non-finite
301    /// or `min > max`.
302    pub fn set_line_range(&mut self, line: EntityId, min: f64, max: f64) -> Result<(), SimError> {
303        if !min.is_finite() || !max.is_finite() {
304            return Err(SimError::InvalidConfig {
305                field: "line.range",
306                reason: format!("min/max must be finite (got min={min}, max={max})"),
307            });
308        }
309        if min > max {
310            return Err(SimError::InvalidConfig {
311                field: "line.range",
312                reason: format!("min ({min}) must be <= max ({max})"),
313            });
314        }
315        let line_ref = self
316            .world
317            .line_mut(line)
318            .ok_or(SimError::LineNotFound(line))?;
319        line_ref.min_position = min;
320        line_ref.max_position = max;
321
322        // Clamp any cars on this line whose position falls outside the new range.
323        let car_ids: Vec<EntityId> = self
324            .world
325            .iter_elevators()
326            .filter_map(|(eid, _, car)| (car.line == line).then_some(eid))
327            .collect();
328        for eid in car_ids {
329            // Skip cars without a Position component — clamping requires
330            // a real reading, and writing velocity alone (without a
331            // matching position update) would silently desync the two.
332            let Some(pos) = self.world.position(eid).map(|p| p.value) else {
333                continue;
334            };
335            if pos < min || pos > max {
336                let clamped = pos.clamp(min, max);
337                if let Some(p) = self.world.position_mut(eid) {
338                    p.value = clamped;
339                }
340                if let Some(v) = self.world.velocity_mut(eid) {
341                    v.value = 0.0;
342                }
343            }
344        }
345
346        self.mark_topo_dirty();
347        Ok(())
348    }
349
350    /// Remove a line and all its elevators from the simulation.
351    ///
352    /// Elevators on the line are disabled (not despawned) so riders are
353    /// properly ejected to the nearest stop.
354    ///
355    /// # Errors
356    ///
357    /// Returns [`SimError::LineNotFound`] if the line entity is not found
358    /// in any group.
359    pub fn remove_line(&mut self, line: EntityId) -> Result<(), SimError> {
360        let (group_idx, line_idx) = self.find_line(line)?;
361
362        let group_id = self.groups[group_idx].id();
363
364        // Collect elevator entities to disable.
365        let elevator_ids: Vec<EntityId> = self.groups[group_idx].lines()[line_idx]
366            .elevators()
367            .to_vec();
368
369        // Disable each elevator (ejects riders properly).
370        for eid in &elevator_ids {
371            // Ignore errors from already-disabled elevators.
372            let _ = self.disable(*eid);
373        }
374
375        // Remove the LineInfo from the group.
376        self.groups[group_idx].lines_mut().remove(line_idx);
377
378        // Rebuild flat caches.
379        self.groups[group_idx].rebuild_caches();
380
381        // Remove Line component from world.
382        self.world.remove_line(line);
383
384        self.mark_topo_dirty();
385        self.events.emit(Event::LineRemoved {
386            line,
387            group: group_id,
388            tick: self.tick,
389        });
390        Ok(())
391    }
392
393    /// Remove an elevator from the simulation.
394    ///
395    /// The elevator is disabled first (ejecting any riders), then removed
396    /// from its line and despawned from the world.
397    ///
398    /// # Errors
399    ///
400    /// Returns [`SimError::EntityNotFound`] if the elevator does not exist.
401    pub fn remove_elevator(&mut self, elevator: EntityId) -> Result<(), SimError> {
402        let line = self
403            .world
404            .elevator(elevator)
405            .ok_or(SimError::EntityNotFound(elevator))?
406            .line();
407
408        // Disable first to eject riders and reset state.
409        let _ = self.disable(elevator);
410
411        // Find and remove from group/line topology. If `find_line` fails
412        // the elevator's `line` ref points at a removed/moved line — an
413        // inconsistent state, but we still want to despawn for cleanup.
414        //
415        // The `disable` call above already fired `notify_removed` on the
416        // group's dispatcher — the cache still includes the elevator at
417        // that point — so no additional notify is needed here. Custom
418        // `DispatchStrategy::notify_removed` impls that count invocations
419        // (e.g. tests with an `AtomicUsize`) can assume exactly one call
420        // per removal.
421        let resolved_group: Option<GroupId> = match self.find_line(line) {
422            Ok((group_idx, line_idx)) => {
423                self.groups[group_idx].lines_mut()[line_idx].remove_elevator(elevator);
424                self.groups[group_idx].rebuild_caches();
425                Some(self.groups[group_idx].id())
426            }
427            Err(_) => None,
428        };
429
430        // Only emit ElevatorRemoved when we resolved the actual group.
431        // Pre-fix this fired with `GroupId(0)` as a sentinel, masquerading
432        // a dangling-line cleanup as a legitimate group-0 removal (#266).
433        if let Some(group_id) = resolved_group {
434            self.events.emit(Event::ElevatorRemoved {
435                elevator,
436                line,
437                group: group_id,
438                tick: self.tick,
439            });
440        }
441
442        // Despawn from world.
443        self.world.despawn(elevator);
444
445        self.mark_topo_dirty();
446        Ok(())
447    }
448
449    /// Remove a stop from the simulation.
450    ///
451    /// The stop is disabled first (invalidating routes that reference it),
452    /// then removed from all lines and despawned from the world.
453    ///
454    /// # Errors
455    ///
456    /// Returns [`SimError::EntityNotFound`] if the stop does not exist.
457    pub fn remove_stop(&mut self, stop: EntityId) -> Result<(), SimError> {
458        if self.world.stop(stop).is_none() {
459            return Err(SimError::EntityNotFound(stop));
460        }
461
462        // Warn if resident riders exist at the stop before we disable it
463        // (disabling will abandon them, clearing the residents index).
464        let residents: Vec<EntityId> = self
465            .rider_index
466            .residents_at(stop)
467            .iter()
468            .copied()
469            .collect();
470        if !residents.is_empty() {
471            self.events
472                .emit(Event::ResidentsAtRemovedStop { stop, residents });
473        }
474
475        // Disable first to invalidate routes referencing this stop.
476        // Use the stop-specific helper so route-invalidation events
477        // carry `StopRemoved` rather than `StopDisabled`.
478        self.disable_stop_inner(stop, true);
479        self.world.disable(stop);
480        self.events.emit(Event::EntityDisabled {
481            entity: stop,
482            tick: self.tick,
483        });
484
485        // Scrub references to the removed stop from every elevator so the
486        // post-despawn tick loop does not chase a dead EntityId through
487        // `target_stop`, the destination queue, or access-control checks.
488        let elevator_ids: Vec<EntityId> =
489            self.world.iter_elevators().map(|(eid, _, _)| eid).collect();
490        for eid in elevator_ids {
491            if let Some(car) = self.world.elevator_mut(eid) {
492                if car.target_stop == Some(stop) {
493                    car.target_stop = None;
494                }
495                car.restricted_stops.remove(&stop);
496            }
497            if let Some(q) = self.world.destination_queue_mut(eid) {
498                q.retain(|s| s != stop);
499            }
500            // Drop any car-call whose floor is the removed stop. Built-in
501            // strategies don't currently route on car_calls but the public
502            // `sim.car_calls(car)` accessor and custom strategies (via
503            // `car_calls_for`) would otherwise return dangling refs (#293).
504            if let Some(calls) = self.world.car_calls_mut(eid) {
505                calls.retain(|c| c.floor != stop);
506            }
507        }
508
509        // Remove from all lines and groups.
510        for group in &mut self.groups {
511            for line_info in group.lines_mut() {
512                line_info.remove_stop(stop);
513            }
514            group.rebuild_caches();
515        }
516
517        // Remove from SortedStops resource.
518        if let Some(sorted) = self.world.resource_mut::<crate::world::SortedStops>() {
519            sorted.0.retain(|&(_, s)| s != stop);
520        }
521
522        // Remove from stop_lookup.
523        self.stop_lookup.retain(|_, &mut eid| eid != stop);
524
525        self.events.emit(Event::StopRemoved {
526            stop,
527            tick: self.tick,
528        });
529
530        // Despawn from world.
531        self.world.despawn(stop);
532
533        // Rebuild the rider index to evict any stale per-stop entries
534        // pointing at the despawned stop. Cheap (O(riders)) and the only
535        // safe option once the stop EntityId is gone.
536        self.rider_index.rebuild(&self.world);
537
538        self.mark_topo_dirty();
539        Ok(())
540    }
541
542    /// Create a new dispatch group. Returns the group ID.
543    pub fn add_group(
544        &mut self,
545        name: impl Into<String>,
546        dispatch: impl DispatchStrategy + 'static,
547    ) -> GroupId {
548        let next_id = self
549            .groups
550            .iter()
551            .map(|g| g.id().0)
552            .max()
553            .map_or(0, |m| m + 1);
554        let group_id = GroupId(next_id);
555
556        self.groups
557            .push(ElevatorGroup::new(group_id, name.into(), Vec::new()));
558
559        self.dispatchers.insert(group_id, Box::new(dispatch));
560        self.strategy_ids.insert(group_id, BuiltinStrategy::Scan);
561        self.mark_topo_dirty();
562        group_id
563    }
564
565    /// Reassign a line to a different group. Returns the old `GroupId`.
566    ///
567    /// # Errors
568    ///
569    /// Returns [`SimError::LineNotFound`] if the line is not found in any group.
570    /// Returns [`SimError::GroupNotFound`] if `new_group` does not exist.
571    pub fn assign_line_to_group(
572        &mut self,
573        line: EntityId,
574        new_group: GroupId,
575    ) -> Result<GroupId, SimError> {
576        let (old_group_idx, line_idx) = self.find_line(line)?;
577
578        // Verify new group exists.
579        if !self.groups.iter().any(|g| g.id() == new_group) {
580            return Err(SimError::GroupNotFound(new_group));
581        }
582
583        let old_group_id = self.groups[old_group_idx].id();
584
585        // Same-group reassign is a no-op. Skip BEFORE the notify_removed
586        // calls or we'd needlessly clear each elevator's dispatcher state
587        // (direction tracking in SCAN/LOOK, etc.) on a redundant move.
588        // Matches the early-return pattern in `reassign_elevator_to_line`.
589        if old_group_id == new_group {
590            return Ok(old_group_id);
591        }
592
593        // Notify the old dispatcher that these elevators are leaving — its
594        // per-elevator state (e.g. ScanDispatch.direction keyed by EntityId)
595        // would otherwise leak indefinitely as lines move between groups.
596        // Mirrors the cleanup `reassign_elevator_to_line` already does. (#257)
597        let elevators_to_notify: Vec<EntityId> = self.groups[old_group_idx].lines()[line_idx]
598            .elevators()
599            .to_vec();
600        if let Some(dispatcher) = self.dispatchers.get_mut(&old_group_id) {
601            for eid in &elevators_to_notify {
602                dispatcher.notify_removed(*eid);
603            }
604        }
605
606        // Remove LineInfo from old group.
607        let line_info = self.groups[old_group_idx].lines_mut().remove(line_idx);
608        self.groups[old_group_idx].rebuild_caches();
609
610        // Re-lookup new_group_idx by ID — we didn't capture it before the
611        // mutation. (Removal of a `LineInfo` from a group's inner `lines`
612        // vec doesn't shift `self.groups` indices, so this is purely about
613        // not having stored the index earlier, not about index invalidation.)
614        let new_group_idx = self
615            .groups
616            .iter()
617            .position(|g| g.id() == new_group)
618            .ok_or(SimError::GroupNotFound(new_group))?;
619        self.groups[new_group_idx].lines_mut().push(line_info);
620        self.groups[new_group_idx].rebuild_caches();
621
622        // Update Line component's group field.
623        if let Some(line_comp) = self.world.line_mut(line) {
624            line_comp.group = new_group;
625        }
626
627        self.mark_topo_dirty();
628        self.events.emit(Event::LineReassigned {
629            line,
630            old_group: old_group_id,
631            new_group,
632            tick: self.tick,
633        });
634
635        Ok(old_group_id)
636    }
637
638    /// Reassign an elevator to a different line (swing-car pattern).
639    ///
640    /// The elevator is moved from its current line to the target line.
641    /// Both lines must be in the same group, or you must reassign the
642    /// line first via [`assign_line_to_group`](Self::assign_line_to_group).
643    ///
644    /// # Errors
645    ///
646    /// Returns [`SimError::EntityNotFound`] if the elevator does not exist.
647    /// Returns [`SimError::LineNotFound`] if the target line is not found in any group.
648    pub fn reassign_elevator_to_line(
649        &mut self,
650        elevator: EntityId,
651        new_line: EntityId,
652    ) -> Result<(), SimError> {
653        let old_line = self
654            .world
655            .elevator(elevator)
656            .ok_or(SimError::EntityNotFound(elevator))?
657            .line();
658
659        if old_line == new_line {
660            return Ok(());
661        }
662
663        // Validate both lines exist BEFORE mutating anything.
664        let (old_group_idx, old_line_idx) = self.find_line(old_line)?;
665        let (new_group_idx, new_line_idx) = self.find_line(new_line)?;
666
667        // Enforce max_cars on target line.
668        if let Some(max) = self.world.line(new_line).and_then(Line::max_cars) {
669            let current_count = self.groups[new_group_idx].lines()[new_line_idx]
670                .elevators()
671                .len();
672            if current_count >= max {
673                return Err(SimError::InvalidConfig {
674                    field: "line.max_cars",
675                    reason: format!("target line already has {current_count} cars (max {max})"),
676                });
677            }
678        }
679
680        let old_group_id = self.groups[old_group_idx].id();
681        let new_group_id = self.groups[new_group_idx].id();
682
683        self.groups[old_group_idx].lines_mut()[old_line_idx].remove_elevator(elevator);
684        self.groups[new_group_idx].lines_mut()[new_line_idx].add_elevator(elevator);
685
686        if let Some(car) = self.world.elevator_mut(elevator) {
687            car.line = new_line;
688        }
689
690        self.groups[old_group_idx].rebuild_caches();
691        if new_group_idx != old_group_idx {
692            self.groups[new_group_idx].rebuild_caches();
693
694            // Notify the old group's dispatcher so it clears per-elevator
695            // state (ScanDispatch/LookDispatch track direction by
696            // EntityId). Matches the symmetry with `remove_elevator`.
697            if let Some(old_dispatcher) = self.dispatchers.get_mut(&old_group_id) {
698                old_dispatcher.notify_removed(elevator);
699            }
700        }
701
702        self.mark_topo_dirty();
703
704        let _ = new_group_id; // reserved for symmetric notify_added once the trait gains one
705        self.events.emit(Event::ElevatorReassigned {
706            elevator,
707            old_line,
708            new_line,
709            tick: self.tick,
710        });
711
712        Ok(())
713    }
714
715    /// Add a stop to a line's served stops.
716    ///
717    /// # Errors
718    ///
719    /// Returns [`SimError::EntityNotFound`] if the stop does not exist.
720    /// Returns [`SimError::LineNotFound`] if the line is not found in any group.
721    pub fn add_stop_to_line(&mut self, stop: EntityId, line: EntityId) -> Result<(), SimError> {
722        // Verify stop exists.
723        if self.world.stop(stop).is_none() {
724            return Err(SimError::EntityNotFound(stop));
725        }
726
727        let (group_idx, line_idx) = self.find_line(line)?;
728
729        let li = &mut self.groups[group_idx].lines_mut()[line_idx];
730        li.add_stop(stop);
731
732        self.groups[group_idx].push_stop(stop);
733
734        self.mark_topo_dirty();
735        Ok(())
736    }
737
738    /// Remove a stop from a line's served stops.
739    ///
740    /// # Errors
741    ///
742    /// Returns [`SimError::LineNotFound`] if the line is not found in any group.
743    pub fn remove_stop_from_line(
744        &mut self,
745        stop: EntityId,
746        line: EntityId,
747    ) -> Result<(), SimError> {
748        let (group_idx, line_idx) = self.find_line(line)?;
749
750        self.groups[group_idx].lines_mut()[line_idx].remove_stop(stop);
751
752        // Rebuild group's stop_entities from all lines.
753        self.groups[group_idx].rebuild_caches();
754
755        self.mark_topo_dirty();
756        Ok(())
757    }
758
759    // ── Line / group queries ────────────────────────────────────────
760
761    /// Get all line entities across all groups.
762    #[must_use]
763    pub fn all_lines(&self) -> Vec<EntityId> {
764        self.groups
765            .iter()
766            .flat_map(|g| g.lines().iter().map(LineInfo::entity))
767            .collect()
768    }
769
770    /// Number of lines in the simulation.
771    #[must_use]
772    pub fn line_count(&self) -> usize {
773        self.groups.iter().map(|g| g.lines().len()).sum()
774    }
775
776    /// Get all line entities in a group.
777    #[must_use]
778    pub fn lines_in_group(&self, group: GroupId) -> Vec<EntityId> {
779        self.groups
780            .iter()
781            .find(|g| g.id() == group)
782            .map_or_else(Vec::new, |g| {
783                g.lines().iter().map(LineInfo::entity).collect()
784            })
785    }
786
787    /// Get elevator entities on a specific line.
788    #[must_use]
789    pub fn elevators_on_line(&self, line: EntityId) -> Vec<EntityId> {
790        self.groups
791            .iter()
792            .flat_map(ElevatorGroup::lines)
793            .find(|li| li.entity() == line)
794            .map_or_else(Vec::new, |li| li.elevators().to_vec())
795    }
796
797    /// Get stop entities served by a specific line.
798    #[must_use]
799    pub fn stops_served_by_line(&self, line: EntityId) -> Vec<EntityId> {
800        self.groups
801            .iter()
802            .flat_map(ElevatorGroup::lines)
803            .find(|li| li.entity() == line)
804            .map_or_else(Vec::new, |li| li.serves().to_vec())
805    }
806
807    /// Find the stop at `position` that's served by `line`.
808    ///
809    /// Disambiguates the case where two stops on different lines share
810    /// the same physical position (e.g. parallel shafts at the same
811    /// floor, or a sky-lobby served by both a low and high bank). The
812    /// global [`World::find_stop_at_position`](crate::world::World::find_stop_at_position)
813    /// returns whichever stop wins the linear scan; this variant
814    /// scopes the lookup to the line's `serves` list so consumers
815    /// always get the stop *on the line they asked about*.
816    ///
817    /// Returns `None` if the line doesn't exist or no served stop
818    /// matches the position.
819    #[must_use]
820    pub fn find_stop_at_position_on_line(&self, position: f64, line: EntityId) -> Option<EntityId> {
821        let line_info = self
822            .groups
823            .iter()
824            .flat_map(ElevatorGroup::lines)
825            .find(|li| li.entity() == line)?;
826        self.world
827            .find_stop_at_position_in(position, line_info.serves())
828    }
829
830    /// Get the line entity for an elevator.
831    #[must_use]
832    pub fn line_for_elevator(&self, elevator: EntityId) -> Option<EntityId> {
833        self.groups
834            .iter()
835            .flat_map(ElevatorGroup::lines)
836            .find(|li| li.elevators().contains(&elevator))
837            .map(LineInfo::entity)
838    }
839
840    /// Iterate over elevators currently repositioning.
841    pub fn iter_repositioning_elevators(&self) -> impl Iterator<Item = EntityId> + '_ {
842        self.world
843            .iter_elevators()
844            .filter_map(|(id, _pos, car)| if car.repositioning() { Some(id) } else { None })
845    }
846
847    /// Get all line entities that serve a given stop.
848    #[must_use]
849    pub fn lines_serving_stop(&self, stop: EntityId) -> Vec<EntityId> {
850        self.groups
851            .iter()
852            .flat_map(ElevatorGroup::lines)
853            .filter(|li| li.serves().contains(&stop))
854            .map(LineInfo::entity)
855            .collect()
856    }
857
858    /// Get all group IDs that serve a given stop.
859    #[must_use]
860    pub fn groups_serving_stop(&self, stop: EntityId) -> Vec<GroupId> {
861        self.groups
862            .iter()
863            .filter(|g| g.stop_entities().contains(&stop))
864            .map(ElevatorGroup::id)
865            .collect()
866    }
867
868    // ── Topology queries ─────────────────────────────────────────────
869
870    /// Rebuild the topology graph if any mutation has invalidated it.
871    fn ensure_graph_built(&self) {
872        if let Ok(mut graph) = self.topo_graph.lock()
873            && graph.is_dirty()
874        {
875            graph.rebuild(&self.groups);
876        }
877    }
878
879    /// All stops reachable from a given stop through the line/group topology.
880    pub fn reachable_stops_from(&self, stop: EntityId) -> Vec<EntityId> {
881        self.ensure_graph_built();
882        self.topo_graph
883            .lock()
884            .map_or_else(|_| Vec::new(), |g| g.reachable_stops_from(stop))
885    }
886
887    /// Stops that serve as transfer points between groups.
888    pub fn transfer_points(&self) -> Vec<EntityId> {
889        self.ensure_graph_built();
890        TopologyGraph::transfer_points(&self.groups)
891    }
892
893    /// Find the shortest route between two stops, possibly spanning multiple groups.
894    pub fn shortest_route(&self, from: EntityId, to: EntityId) -> Option<Route> {
895        self.ensure_graph_built();
896        self.topo_graph
897            .lock()
898            .ok()
899            .and_then(|g| g.shortest_route(from, to))
900    }
901}