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, LineKind, 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`] for malformed bounds —
224    /// non-finite `min`/`max` or `min > max` on a `Linear` line, or
225    /// non-finite / non-positive `circumference` on a `Loop` line. For
226    /// `Loop` lines, also rejects `max_cars * min_headway > circumference`
227    /// — without enough room around the loop for every car at full
228    /// headway, the no-overtake invariant is unsatisfiable.
229    pub fn add_line(&mut self, params: &LineParams) -> Result<EntityId, SimError> {
230        // Resolve the requested kind; flat fields are the fallback only
231        // when no explicit kind was provided. Validation runs against
232        // the *resolved* kind so callers passing an explicit Loop don't
233        // get a spurious flat-field complaint.
234        let kind = params.kind.unwrap_or(LineKind::Linear {
235            min: params.min_position,
236            max: params.max_position,
237        });
238        kind.validate()
239            .map_err(|(field, reason)| SimError::InvalidConfig { field, reason })?;
240
241        // Loop-specific cross-field invariant — runtime mirror of the
242        // check in `validate_explicit_topology`.
243        //
244        // Asymmetric with the config-time path on `max_cars = None`:
245        // `validate_explicit_topology` falls back to `lc.elevators.len()`
246        // because the config-time line-config bundles its elevators, but
247        // a runtime-added line is always *empty* at this point — cars
248        // attach later via `add_elevator_to_line`. With no concrete car
249        // count to validate against and no upper bound on future
250        // attachments, we can't fire here. PR 3 closes the gap by
251        // running the same check at car-attach time.
252        #[cfg(feature = "loop_lines")]
253        if let LineKind::Loop {
254            circumference,
255            min_headway,
256        } = kind
257            && let Some(max_cars) = params.max_cars
258            && max_cars > 0
259        {
260            #[allow(
261                clippy::cast_precision_loss,
262                reason = "max_cars is bounded by usize; the comparison is against a finite f64"
263            )]
264            let required = (max_cars as f64) * min_headway;
265            if required > circumference {
266                return Err(SimError::InvalidConfig {
267                    field: "line.kind",
268                    reason: format!(
269                        "loop line: {max_cars} cars × min_headway {min_headway} = {required} \
270                         exceeds circumference {circumference}",
271                    ),
272                });
273            }
274        }
275
276        let group_id = params.group;
277        let group = self
278            .groups
279            .iter_mut()
280            .find(|g| g.id() == group_id)
281            .ok_or(SimError::GroupNotFound(group_id))?;
282
283        let line_tag = format!("line:{}", params.name);
284
285        let eid = self.world.spawn();
286        self.world.set_line(
287            eid,
288            Line {
289                name: params.name.clone(),
290                group: group_id,
291                orientation: params.orientation,
292                position: params.position,
293                kind,
294                max_cars: params.max_cars,
295            },
296        );
297
298        group
299            .lines_mut()
300            .push(LineInfo::new(eid, Vec::new(), Vec::new()));
301
302        // Tag the line entity with "line:{name}" for per-line metrics.
303        if let Some(tags) = self
304            .world
305            .resource_mut::<crate::tagged_metrics::MetricTags>()
306        {
307            tags.tag(eid, line_tag);
308        }
309
310        self.mark_topo_dirty();
311        self.events.emit(Event::LineAdded {
312            line: eid,
313            group: group_id,
314            tick: self.tick,
315        });
316        Ok(eid)
317    }
318
319    /// Set the reachable position range of a line.
320    ///
321    /// Cars whose current position falls outside the new `[min, max]` are
322    /// clamped to the boundary. Phase is left untouched — a car mid-travel
323    /// keeps `MovingToStop` and the movement system reconciles on the
324    /// next tick.
325    ///
326    /// # Errors
327    ///
328    /// Returns [`SimError::LineNotFound`] if the line entity does not exist.
329    /// Returns [`SimError::InvalidConfig`] if `min` or `max` is non-finite
330    /// or `min > max`.
331    pub fn set_line_range(&mut self, line: EntityId, min: f64, max: f64) -> Result<(), SimError> {
332        if !min.is_finite() || !max.is_finite() {
333            return Err(SimError::InvalidConfig {
334                field: "line.range",
335                reason: format!("min/max must be finite (got min={min}, max={max})"),
336            });
337        }
338        if min > max {
339            return Err(SimError::InvalidConfig {
340                field: "line.range",
341                reason: format!("min ({min}) must be <= max ({max})"),
342            });
343        }
344        let line_ref = self
345            .world
346            .line_mut(line)
347            .ok_or(SimError::LineNotFound(line))?;
348        // `set_line_range` is a Linear-only operation; loops have no
349        // endpoints to set. Reject early so callers don't silently mutate
350        // the wrong field on a Loop line.
351        match &mut line_ref.kind {
352            LineKind::Linear {
353                min: kmin,
354                max: kmax,
355            } => {
356                *kmin = min;
357                *kmax = max;
358            }
359            #[cfg(feature = "loop_lines")]
360            LineKind::Loop { .. } => {
361                return Err(SimError::InvalidConfig {
362                    field: "line.range",
363                    reason: "set_line_range is not valid on a Loop line; \
364                            change circumference via a future API instead"
365                        .to_string(),
366                });
367            }
368        }
369
370        // Clamp any cars on this line whose position falls outside the new range.
371        let car_ids: Vec<EntityId> = self
372            .world
373            .iter_elevators()
374            .filter_map(|(eid, _, car)| (car.line == line).then_some(eid))
375            .collect();
376        for eid in car_ids {
377            // Skip cars without a Position component — clamping requires
378            // a real reading, and writing velocity alone (without a
379            // matching position update) would silently desync the two.
380            let Some(pos) = self.world.position(eid).map(|p| p.value) else {
381                continue;
382            };
383            if pos < min || pos > max {
384                let clamped = pos.clamp(min, max);
385                if let Some(p) = self.world.position_mut(eid) {
386                    p.value = clamped;
387                }
388                if let Some(v) = self.world.velocity_mut(eid) {
389                    v.value = 0.0;
390                }
391            }
392        }
393
394        self.mark_topo_dirty();
395        Ok(())
396    }
397
398    /// Remove a line and all its elevators from the simulation.
399    ///
400    /// Elevators on the line are disabled (not despawned) so riders are
401    /// properly ejected to the nearest stop.
402    ///
403    /// # Errors
404    ///
405    /// Returns [`SimError::LineNotFound`] if the line entity is not found
406    /// in any group.
407    pub fn remove_line(&mut self, line: EntityId) -> Result<(), SimError> {
408        let (group_idx, line_idx) = self.find_line(line)?;
409
410        let group_id = self.groups[group_idx].id();
411
412        // Collect elevator entities to disable.
413        let elevator_ids: Vec<EntityId> = self.groups[group_idx].lines()[line_idx]
414            .elevators()
415            .to_vec();
416
417        // Disable each elevator (ejects riders properly).
418        for eid in &elevator_ids {
419            // Ignore errors from already-disabled elevators.
420            let _ = self.disable(*eid);
421        }
422
423        // Remove the LineInfo from the group.
424        self.groups[group_idx].lines_mut().remove(line_idx);
425
426        // Rebuild flat caches.
427        self.groups[group_idx].rebuild_caches();
428
429        // Remove Line component from world.
430        self.world.remove_line(line);
431
432        self.mark_topo_dirty();
433        self.events.emit(Event::LineRemoved {
434            line,
435            group: group_id,
436            tick: self.tick,
437        });
438        Ok(())
439    }
440
441    /// Remove an elevator from the simulation.
442    ///
443    /// The elevator is disabled first (ejecting any riders), then removed
444    /// from its line and despawned from the world.
445    ///
446    /// # Errors
447    ///
448    /// Returns [`SimError::EntityNotFound`] if the elevator does not exist.
449    pub fn remove_elevator(&mut self, elevator: EntityId) -> Result<(), SimError> {
450        let line = self
451            .world
452            .elevator(elevator)
453            .ok_or(SimError::EntityNotFound(elevator))?
454            .line();
455
456        // Disable first to eject riders and reset state.
457        let _ = self.disable(elevator);
458
459        // Find and remove from group/line topology. If `find_line` fails
460        // the elevator's `line` ref points at a removed/moved line — an
461        // inconsistent state, but we still want to despawn for cleanup.
462        //
463        // The `disable` call above already fired `notify_removed` on the
464        // group's dispatcher — the cache still includes the elevator at
465        // that point — so no additional notify is needed here. Custom
466        // `DispatchStrategy::notify_removed` impls that count invocations
467        // (e.g. tests with an `AtomicUsize`) can assume exactly one call
468        // per removal.
469        let resolved_group: Option<GroupId> = match self.find_line(line) {
470            Ok((group_idx, line_idx)) => {
471                self.groups[group_idx].lines_mut()[line_idx].remove_elevator(elevator);
472                self.groups[group_idx].rebuild_caches();
473                Some(self.groups[group_idx].id())
474            }
475            Err(_) => None,
476        };
477
478        // Only emit ElevatorRemoved when we resolved the actual group.
479        // Pre-fix this fired with `GroupId(0)` as a sentinel, masquerading
480        // a dangling-line cleanup as a legitimate group-0 removal (#266).
481        if let Some(group_id) = resolved_group {
482            self.events.emit(Event::ElevatorRemoved {
483                elevator,
484                line,
485                group: group_id,
486                tick: self.tick,
487            });
488        }
489
490        // Despawn from world.
491        self.world.despawn(elevator);
492
493        self.mark_topo_dirty();
494        Ok(())
495    }
496
497    /// Remove a stop from the simulation.
498    ///
499    /// The stop is disabled first (invalidating routes that reference it),
500    /// then removed from all lines and despawned from the world.
501    ///
502    /// # Errors
503    ///
504    /// Returns [`SimError::EntityNotFound`] if the stop does not exist.
505    pub fn remove_stop(&mut self, stop: EntityId) -> Result<(), SimError> {
506        if self.world.stop(stop).is_none() {
507            return Err(SimError::EntityNotFound(stop));
508        }
509
510        // Warn if resident riders exist at the stop before we disable it
511        // (disabling will abandon them, clearing the residents index).
512        let residents: Vec<EntityId> = self
513            .rider_index
514            .residents_at(stop)
515            .iter()
516            .copied()
517            .collect();
518        if !residents.is_empty() {
519            self.events
520                .emit(Event::ResidentsAtRemovedStop { stop, residents });
521        }
522
523        // Disable first to invalidate routes referencing this stop.
524        // Use the stop-specific helper so route-invalidation events
525        // carry `StopRemoved` rather than `StopDisabled`.
526        self.disable_stop_inner(stop, true);
527        self.world.disable(stop);
528        self.events.emit(Event::EntityDisabled {
529            entity: stop,
530            tick: self.tick,
531        });
532
533        // Scrub references to the removed stop from every elevator so the
534        // post-despawn tick loop does not chase a dead EntityId through
535        // `target_stop`, the destination queue, or access-control checks.
536        let elevator_ids: Vec<EntityId> =
537            self.world.iter_elevators().map(|(eid, _, _)| eid).collect();
538        for eid in elevator_ids {
539            if let Some(car) = self.world.elevator_mut(eid) {
540                if car.target_stop == Some(stop) {
541                    car.target_stop = None;
542                }
543                car.restricted_stops.remove(&stop);
544            }
545            if let Some(q) = self.world.destination_queue_mut(eid) {
546                q.retain(|s| s != stop);
547            }
548            // Drop any car-call whose floor is the removed stop. Built-in
549            // strategies don't currently route on car_calls but the public
550            // `sim.car_calls(car)` accessor and custom strategies (via
551            // `car_calls_for`) would otherwise return dangling refs (#293).
552            if let Some(calls) = self.world.car_calls_mut(eid) {
553                calls.retain(|c| c.floor != stop);
554            }
555        }
556
557        // Remove from all lines and groups.
558        for group in &mut self.groups {
559            for line_info in group.lines_mut() {
560                line_info.remove_stop(stop);
561            }
562            group.rebuild_caches();
563        }
564
565        // Remove from SortedStops resource.
566        if let Some(sorted) = self.world.resource_mut::<crate::world::SortedStops>() {
567            sorted.0.retain(|&(_, s)| s != stop);
568        }
569
570        // Remove from stop_lookup.
571        self.stop_lookup.retain(|_, &mut eid| eid != stop);
572
573        self.events.emit(Event::StopRemoved {
574            stop,
575            tick: self.tick,
576        });
577
578        // Despawn from world.
579        self.world.despawn(stop);
580
581        // Rebuild the rider index to evict any stale per-stop entries
582        // pointing at the despawned stop. Cheap (O(riders)) and the only
583        // safe option once the stop EntityId is gone.
584        self.rider_index.rebuild(&self.world);
585
586        self.mark_topo_dirty();
587        Ok(())
588    }
589
590    /// Create a new dispatch group. Returns the group ID.
591    pub fn add_group(
592        &mut self,
593        name: impl Into<String>,
594        dispatch: impl DispatchStrategy + 'static,
595    ) -> GroupId {
596        let next_id = self
597            .groups
598            .iter()
599            .map(|g| g.id().0)
600            .max()
601            .map_or(0, |m| m + 1);
602        let group_id = GroupId(next_id);
603
604        self.groups
605            .push(ElevatorGroup::new(group_id, name.into(), Vec::new()));
606
607        self.dispatcher_set
608            .insert(group_id, Box::new(dispatch), BuiltinStrategy::Scan);
609        self.mark_topo_dirty();
610        group_id
611    }
612
613    /// Reassign a line to a different group. Returns the old `GroupId`.
614    ///
615    /// # Errors
616    ///
617    /// Returns [`SimError::LineNotFound`] if the line is not found in any group.
618    /// Returns [`SimError::GroupNotFound`] if `new_group` does not exist.
619    pub fn assign_line_to_group(
620        &mut self,
621        line: EntityId,
622        new_group: GroupId,
623    ) -> Result<GroupId, SimError> {
624        let (old_group_idx, line_idx) = self.find_line(line)?;
625
626        // Verify new group exists.
627        if !self.groups.iter().any(|g| g.id() == new_group) {
628            return Err(SimError::GroupNotFound(new_group));
629        }
630
631        let old_group_id = self.groups[old_group_idx].id();
632
633        // Same-group reassign is a no-op. Skip BEFORE the notify_removed
634        // calls or we'd needlessly clear each elevator's dispatcher state
635        // (direction tracking in SCAN/LOOK, etc.) on a redundant move.
636        // Matches the early-return pattern in `reassign_elevator_to_line`.
637        if old_group_id == new_group {
638            return Ok(old_group_id);
639        }
640
641        // Notify the old dispatcher that these elevators are leaving — its
642        // per-elevator state (e.g. ScanDispatch.direction keyed by EntityId)
643        // would otherwise leak indefinitely as lines move between groups.
644        // Mirrors the cleanup `reassign_elevator_to_line` already does. (#257)
645        let elevators_to_notify: Vec<EntityId> = self.groups[old_group_idx].lines()[line_idx]
646            .elevators()
647            .to_vec();
648        if let Some(dispatcher) = self.dispatcher_set.strategies_mut().get_mut(&old_group_id) {
649            for eid in &elevators_to_notify {
650                dispatcher.notify_removed(*eid);
651            }
652        }
653
654        // Remove LineInfo from old group.
655        let line_info = self.groups[old_group_idx].lines_mut().remove(line_idx);
656        self.groups[old_group_idx].rebuild_caches();
657
658        // Re-lookup new_group_idx by ID — we didn't capture it before the
659        // mutation. (Removal of a `LineInfo` from a group's inner `lines`
660        // vec doesn't shift `self.groups` indices, so this is purely about
661        // not having stored the index earlier, not about index invalidation.)
662        let new_group_idx = self
663            .groups
664            .iter()
665            .position(|g| g.id() == new_group)
666            .ok_or(SimError::GroupNotFound(new_group))?;
667        self.groups[new_group_idx].lines_mut().push(line_info);
668        self.groups[new_group_idx].rebuild_caches();
669
670        // Update Line component's group field.
671        if let Some(line_comp) = self.world.line_mut(line) {
672            line_comp.group = new_group;
673        }
674
675        self.mark_topo_dirty();
676        self.events.emit(Event::LineReassigned {
677            line,
678            old_group: old_group_id,
679            new_group,
680            tick: self.tick,
681        });
682
683        Ok(old_group_id)
684    }
685
686    /// Reassign an elevator to a different line (swing-car pattern).
687    ///
688    /// The elevator is moved from its current line to the target line.
689    /// Both lines must be in the same group, or you must reassign the
690    /// line first via [`assign_line_to_group`](Self::assign_line_to_group).
691    ///
692    /// # Errors
693    ///
694    /// Returns [`SimError::EntityNotFound`] if the elevator does not exist.
695    /// Returns [`SimError::LineNotFound`] if the target line is not found in any group.
696    pub fn reassign_elevator_to_line(
697        &mut self,
698        elevator: EntityId,
699        new_line: EntityId,
700    ) -> Result<(), SimError> {
701        let old_line = self
702            .world
703            .elevator(elevator)
704            .ok_or(SimError::EntityNotFound(elevator))?
705            .line();
706
707        if old_line == new_line {
708            return Ok(());
709        }
710
711        // Validate both lines exist BEFORE mutating anything.
712        let (old_group_idx, old_line_idx) = self.find_line(old_line)?;
713        let (new_group_idx, new_line_idx) = self.find_line(new_line)?;
714
715        // Enforce max_cars on target line.
716        if let Some(max) = self.world.line(new_line).and_then(Line::max_cars) {
717            let current_count = self.groups[new_group_idx].lines()[new_line_idx]
718                .elevators()
719                .len();
720            if current_count >= max {
721                return Err(SimError::InvalidConfig {
722                    field: "line.max_cars",
723                    reason: format!("target line already has {current_count} cars (max {max})"),
724                });
725            }
726        }
727
728        let old_group_id = self.groups[old_group_idx].id();
729        let new_group_id = self.groups[new_group_idx].id();
730
731        self.groups[old_group_idx].lines_mut()[old_line_idx].remove_elevator(elevator);
732        self.groups[new_group_idx].lines_mut()[new_line_idx].add_elevator(elevator);
733
734        if let Some(car) = self.world.elevator_mut(elevator) {
735            car.line = new_line;
736        }
737
738        self.groups[old_group_idx].rebuild_caches();
739        if new_group_idx != old_group_idx {
740            self.groups[new_group_idx].rebuild_caches();
741
742            // Notify the old group's dispatcher so it clears per-elevator
743            // state (ScanDispatch/LookDispatch track direction by
744            // EntityId). Matches the symmetry with `remove_elevator`.
745            if let Some(old_dispatcher) =
746                self.dispatcher_set.strategies_mut().get_mut(&old_group_id)
747            {
748                old_dispatcher.notify_removed(elevator);
749            }
750        }
751
752        self.mark_topo_dirty();
753
754        let _ = new_group_id; // reserved for symmetric notify_added once the trait gains one
755        self.events.emit(Event::ElevatorReassigned {
756            elevator,
757            old_line,
758            new_line,
759            tick: self.tick,
760        });
761
762        Ok(())
763    }
764
765    /// Add a stop to a line's served stops.
766    ///
767    /// # Errors
768    ///
769    /// Returns [`SimError::EntityNotFound`] if the stop does not exist.
770    /// Returns [`SimError::LineNotFound`] if the line is not found in any group.
771    pub fn add_stop_to_line(&mut self, stop: EntityId, line: EntityId) -> Result<(), SimError> {
772        // Verify stop exists.
773        if self.world.stop(stop).is_none() {
774            return Err(SimError::EntityNotFound(stop));
775        }
776
777        let (group_idx, line_idx) = self.find_line(line)?;
778
779        let li = &mut self.groups[group_idx].lines_mut()[line_idx];
780        li.add_stop(stop);
781
782        self.groups[group_idx].push_stop(stop);
783
784        self.mark_topo_dirty();
785        Ok(())
786    }
787
788    /// Remove a stop from a line's served stops.
789    ///
790    /// # Errors
791    ///
792    /// Returns [`SimError::LineNotFound`] if the line is not found in any group.
793    pub fn remove_stop_from_line(
794        &mut self,
795        stop: EntityId,
796        line: EntityId,
797    ) -> Result<(), SimError> {
798        let (group_idx, line_idx) = self.find_line(line)?;
799
800        self.groups[group_idx].lines_mut()[line_idx].remove_stop(stop);
801
802        // Rebuild group's stop_entities from all lines.
803        self.groups[group_idx].rebuild_caches();
804
805        self.mark_topo_dirty();
806        Ok(())
807    }
808
809    // ── Line / group queries ────────────────────────────────────────
810
811    /// Get all line entities across all groups.
812    #[must_use]
813    pub fn all_lines(&self) -> Vec<EntityId> {
814        self.groups
815            .iter()
816            .flat_map(|g| g.lines().iter().map(LineInfo::entity))
817            .collect()
818    }
819
820    /// Number of lines in the simulation.
821    #[must_use]
822    pub fn line_count(&self) -> usize {
823        self.groups.iter().map(|g| g.lines().len()).sum()
824    }
825
826    /// Get all line entities in a group.
827    #[must_use]
828    pub fn lines_in_group(&self, group: GroupId) -> Vec<EntityId> {
829        self.groups
830            .iter()
831            .find(|g| g.id() == group)
832            .map_or_else(Vec::new, |g| {
833                g.lines().iter().map(LineInfo::entity).collect()
834            })
835    }
836
837    /// Get elevator entities on a specific line.
838    #[must_use]
839    pub fn elevators_on_line(&self, line: EntityId) -> Vec<EntityId> {
840        self.groups
841            .iter()
842            .flat_map(ElevatorGroup::lines)
843            .find(|li| li.entity() == line)
844            .map_or_else(Vec::new, |li| li.elevators().to_vec())
845    }
846
847    /// Get stop entities served by a specific line.
848    #[must_use]
849    pub fn stops_served_by_line(&self, line: EntityId) -> Vec<EntityId> {
850        self.groups
851            .iter()
852            .flat_map(ElevatorGroup::lines)
853            .find(|li| li.entity() == line)
854            .map_or_else(Vec::new, |li| li.serves().to_vec())
855    }
856
857    /// Find the stop at `position` that's served by `line`.
858    ///
859    /// Disambiguates the case where two stops on different lines share
860    /// the same physical position (e.g. parallel shafts at the same
861    /// floor, or a sky-lobby served by both a low and high bank). The
862    /// global [`World::find_stop_at_position`](crate::world::World::find_stop_at_position)
863    /// returns whichever stop wins the linear scan; this variant
864    /// scopes the lookup to the line's `serves` list so consumers
865    /// always get the stop *on the line they asked about*.
866    ///
867    /// Returns `None` if the line doesn't exist or no served stop
868    /// matches the position.
869    #[must_use]
870    pub fn find_stop_at_position_on_line(&self, position: f64, line: EntityId) -> Option<EntityId> {
871        let line_info = self
872            .groups
873            .iter()
874            .flat_map(ElevatorGroup::lines)
875            .find(|li| li.entity() == line)?;
876        self.world
877            .find_stop_at_position_in(position, line_info.serves())
878    }
879
880    /// Get the line entity for an elevator.
881    #[must_use]
882    pub fn line_for_elevator(&self, elevator: EntityId) -> Option<EntityId> {
883        self.groups
884            .iter()
885            .flat_map(ElevatorGroup::lines)
886            .find(|li| li.elevators().contains(&elevator))
887            .map(LineInfo::entity)
888    }
889
890    /// Iterate over elevators currently repositioning.
891    pub fn iter_repositioning_elevators(&self) -> impl Iterator<Item = EntityId> + '_ {
892        self.world
893            .iter_elevators()
894            .filter_map(|(id, _pos, car)| if car.repositioning() { Some(id) } else { None })
895    }
896
897    /// Get all line entities that serve a given stop.
898    #[must_use]
899    pub fn lines_serving_stop(&self, stop: EntityId) -> Vec<EntityId> {
900        self.groups
901            .iter()
902            .flat_map(ElevatorGroup::lines)
903            .filter(|li| li.serves().contains(&stop))
904            .map(LineInfo::entity)
905            .collect()
906    }
907
908    /// Get all group IDs that serve a given stop.
909    #[must_use]
910    pub fn groups_serving_stop(&self, stop: EntityId) -> Vec<GroupId> {
911        self.groups
912            .iter()
913            .filter(|g| g.stop_entities().contains(&stop))
914            .map(ElevatorGroup::id)
915            .collect()
916    }
917
918    // ── Topology queries ─────────────────────────────────────────────
919
920    /// Rebuild the topology graph if any mutation has invalidated it.
921    fn ensure_graph_built(&self) {
922        if let Ok(mut graph) = self.topo_graph.lock()
923            && graph.is_dirty()
924        {
925            graph.rebuild(&self.groups);
926        }
927    }
928
929    /// All stops reachable from a given stop through the line/group topology.
930    pub fn reachable_stops_from(&self, stop: EntityId) -> Vec<EntityId> {
931        self.ensure_graph_built();
932        self.topo_graph
933            .lock()
934            .map_or_else(|_| Vec::new(), |g| g.reachable_stops_from(stop))
935    }
936
937    /// Stops that serve as transfer points between groups.
938    pub fn transfer_points(&self) -> Vec<EntityId> {
939        self.ensure_graph_built();
940        TopologyGraph::transfer_points(&self.groups)
941    }
942
943    /// Find the shortest route between two stops, possibly spanning multiple groups.
944    pub fn shortest_route(&self, from: EntityId, to: EntityId) -> Option<Route> {
945        self.ensure_graph_built();
946        self.topo_graph
947            .lock()
948            .ok()
949            .and_then(|g| g.shortest_route(from, to))
950    }
951}