Skip to main content

elevator_core/sim/
construction.rs

1//! Simulation construction, validation, and topology assembly.
2//!
3//! Split out from `sim.rs` to keep each concern readable. Holds:
4//!
5//! - [`Simulation::new`] and [`Simulation::new_with_hooks`]
6//! - Config validation ([`Simulation::validate_config`] and helpers)
7//! - Legacy and explicit topology builders
8//! - [`Simulation::from_parts`] for snapshot restore
9//! - Dispatch, reposition, and hook registration helpers
10//!
11//! Since this is a child module of `crate::sim`, it can access `Simulation`'s
12//! private fields directly — no visibility relaxation required.
13
14use std::collections::{BTreeMap, HashMap, HashSet};
15use std::sync::Mutex;
16
17use crate::components::{
18    Elevator, ElevatorPhase, Line, LineKind, Orientation, Position, Stop, Velocity,
19};
20use crate::config::SimConfig;
21use crate::dispatch::{
22    BuiltinReposition, BuiltinStrategy, DispatchStrategy, ElevatorGroup, LineInfo,
23    RepositionStrategy,
24};
25use crate::door::DoorState;
26use crate::entity::EntityId;
27use crate::error::SimError;
28use crate::events::EventBus;
29use crate::hooks::{Phase, PhaseHooks};
30use crate::ids::GroupId;
31use crate::metrics::Metrics;
32use crate::rider_index::RiderIndex;
33use crate::stop::StopId;
34use crate::time::TimeAdapter;
35use crate::topology::TopologyGraph;
36use crate::world::World;
37
38use super::Simulation;
39
40/// Bundled topology result: groups, dispatchers, and strategy IDs.
41type TopologyResult = (
42    Vec<ElevatorGroup>,
43    BTreeMap<GroupId, Box<dyn DispatchStrategy>>,
44    BTreeMap<GroupId, BuiltinStrategy>,
45);
46
47/// Canonical [`HallCallMode`](crate::dispatch::HallCallMode) for a
48/// built-in dispatch strategy.
49///
50/// Returns `None` for [`BuiltinStrategy::Custom`] — custom strategies
51/// don't have a canonical mode and keep whatever the group already
52/// carries. Returns `Some(Destination)` only for the destination
53/// dispatch; every other built-in is `Some(Classic)`.
54///
55/// One source of truth for the construction-time and runtime sync paths
56/// (`sync_hall_call_modes` and [`Simulation::set_dispatch`]). Add the
57/// match arm here when introducing a new built-in dispatch.
58pub(super) const fn canonical_hall_call_mode(
59    strategy: &BuiltinStrategy,
60) -> Option<crate::dispatch::HallCallMode> {
61    match strategy {
62        BuiltinStrategy::Destination => Some(crate::dispatch::HallCallMode::Destination),
63        BuiltinStrategy::Custom(_) => None,
64        BuiltinStrategy::Scan
65        | BuiltinStrategy::Look
66        | BuiltinStrategy::NearestCar
67        | BuiltinStrategy::Etd
68        | BuiltinStrategy::Rsr => Some(crate::dispatch::HallCallMode::Classic),
69    }
70}
71
72/// Ensure DCS groups have `HallCallMode::Destination` at construction
73/// time. Non-DCS groups are left at whatever the config specified —
74/// forcing Classic here would clobber explicit config overrides (e.g. a
75/// Scan group that the author deliberately set to Destination mode).
76///
77/// Runtime swaps via [`Simulation::set_dispatch`] do a full bidirectional
78/// sync because a strategy change is an explicit user action where
79/// resetting the mode is expected.
80fn sync_hall_call_modes(
81    groups: &mut [ElevatorGroup],
82    strategy_ids: &BTreeMap<GroupId, BuiltinStrategy>,
83) {
84    for group in groups.iter_mut() {
85        if let Some(strategy) = strategy_ids.get(&group.id())
86            && canonical_hall_call_mode(strategy)
87                == Some(crate::dispatch::HallCallMode::Destination)
88        {
89            group.set_hall_call_mode(crate::dispatch::HallCallMode::Destination);
90        }
91    }
92}
93
94/// Validate the physics fields shared by [`crate::config::ElevatorConfig`]
95/// and [`super::ElevatorParams`]. Both construction-time validation and
96/// the runtime `add_elevator` path call this so an invalid set of params
97/// can never reach the world (zeroes blow up movement; zero door ticks
98/// stall the door FSM).
99#[allow(clippy::too_many_arguments)]
100pub(super) fn validate_elevator_physics(
101    max_speed: f64,
102    acceleration: f64,
103    deceleration: f64,
104    weight_capacity: f64,
105    inspection_speed_factor: f64,
106    door_transition_ticks: u32,
107    door_open_ticks: u32,
108    bypass_load_up_pct: Option<f64>,
109    bypass_load_down_pct: Option<f64>,
110) -> Result<(), SimError> {
111    if !max_speed.is_finite() || max_speed <= 0.0 {
112        return Err(SimError::InvalidConfig {
113            field: "elevators.max_speed",
114            reason: format!("must be finite and positive, got {max_speed}"),
115        });
116    }
117    if !acceleration.is_finite() || acceleration <= 0.0 {
118        return Err(SimError::InvalidConfig {
119            field: "elevators.acceleration",
120            reason: format!("must be finite and positive, got {acceleration}"),
121        });
122    }
123    if !deceleration.is_finite() || deceleration <= 0.0 {
124        return Err(SimError::InvalidConfig {
125            field: "elevators.deceleration",
126            reason: format!("must be finite and positive, got {deceleration}"),
127        });
128    }
129    if !weight_capacity.is_finite() || weight_capacity <= 0.0 {
130        return Err(SimError::InvalidConfig {
131            field: "elevators.weight_capacity",
132            reason: format!("must be finite and positive, got {weight_capacity}"),
133        });
134    }
135    if !inspection_speed_factor.is_finite() || inspection_speed_factor <= 0.0 {
136        return Err(SimError::InvalidConfig {
137            field: "elevators.inspection_speed_factor",
138            reason: format!("must be finite and positive, got {inspection_speed_factor}"),
139        });
140    }
141    if door_transition_ticks == 0 {
142        return Err(SimError::InvalidConfig {
143            field: "elevators.door_transition_ticks",
144            reason: "must be > 0".into(),
145        });
146    }
147    if door_open_ticks == 0 {
148        return Err(SimError::InvalidConfig {
149            field: "elevators.door_open_ticks",
150            reason: "must be > 0".into(),
151        });
152    }
153    validate_bypass_pct("elevators.bypass_load_up_pct", bypass_load_up_pct)?;
154    validate_bypass_pct("elevators.bypass_load_down_pct", bypass_load_down_pct)?;
155    Ok(())
156}
157
158/// `bypass_load_{up,down}_pct` must be a finite fraction in `(0.0, 1.0]`
159/// when set. `pct = 0.0` would bypass at an empty car (nonsense); `NaN`
160/// and infinities silently disable the bypass under the dispatch guard,
161/// which is a silent foot-gun. Reject at config time instead.
162fn validate_bypass_pct(field: &'static str, pct: Option<f64>) -> Result<(), SimError> {
163    let Some(pct) = pct else {
164        return Ok(());
165    };
166    if !pct.is_finite() || pct <= 0.0 || pct > 1.0 {
167        return Err(SimError::InvalidConfig {
168            field,
169            reason: format!("must be finite in (0.0, 1.0] when set, got {pct}"),
170        });
171    }
172    Ok(())
173}
174
175impl Simulation {
176    /// Create a new simulation from config and a dispatch strategy.
177    ///
178    /// Returns `Err` if the config is invalid (zero stops, duplicate IDs,
179    /// negative speeds, etc.).
180    ///
181    /// # Errors
182    ///
183    /// Returns [`SimError::InvalidConfig`] if the configuration has zero stops,
184    /// duplicate stop IDs, zero elevators, non-positive physics parameters,
185    /// invalid starting stops, or non-positive tick rate.
186    pub fn new(
187        config: &SimConfig,
188        dispatch: impl DispatchStrategy + 'static,
189    ) -> Result<Self, SimError> {
190        let mut dispatchers = BTreeMap::new();
191        dispatchers.insert(GroupId(0), Box::new(dispatch) as Box<dyn DispatchStrategy>);
192        Self::new_with_hooks(config, dispatchers, PhaseHooks::default())
193    }
194
195    /// Create a simulation with pre-configured lifecycle hooks.
196    ///
197    /// Used by [`SimulationBuilder`](crate::builder::SimulationBuilder).
198    #[allow(clippy::too_many_lines)]
199    pub(crate) fn new_with_hooks(
200        config: &SimConfig,
201        builder_dispatchers: BTreeMap<GroupId, Box<dyn DispatchStrategy>>,
202        hooks: PhaseHooks,
203    ) -> Result<Self, SimError> {
204        Self::validate_config(config)?;
205
206        let mut world = World::new();
207
208        // Create stop entities.
209        let mut stop_lookup: HashMap<StopId, EntityId> = HashMap::new();
210        for sc in &config.building.stops {
211            let eid = world.spawn();
212            world.set_stop(
213                eid,
214                Stop {
215                    name: sc.name.clone(),
216                    position: sc.position,
217                },
218            );
219            world.set_position(eid, Position { value: sc.position });
220            stop_lookup.insert(sc.id, eid);
221        }
222
223        // Build sorted-stops index for O(log n) PassingFloor detection.
224        let mut sorted: Vec<(f64, EntityId)> = world
225            .iter_stops()
226            .map(|(eid, stop)| (stop.position, eid))
227            .collect();
228        sorted.sort_by(|a, b| a.0.total_cmp(&b.0));
229        world.insert_resource(crate::world::SortedStops(sorted));
230
231        // Per-stop arrival signal, appended on rider spawn and queried
232        // by dispatch/reposition strategies to drive traffic-mode
233        // switches and predictive parking. The destination mirror is
234        // what powers down-peak detection — without it the classifier
235        // sees `total_dest = 0` and silently never emits `DownPeak`.
236        // Both resources must exist before the first `RiderSpawned`
237        // event fires (i.e. before any user-driven `spawn_rider` call):
238        // `record_spawn` is fire-and-forget on missing resources, so a
239        // later insert wouldn't replay history.
240        world.insert_resource(crate::arrival_log::ArrivalLog::default());
241        world.insert_resource(crate::arrival_log::DestinationLog::default());
242        world.insert_resource(crate::arrival_log::CurrentTick::default());
243        world.insert_resource(crate::arrival_log::ArrivalLogRetention::default());
244        // Traffic-mode classifier. Auto-refreshed in the metrics phase
245        // from the same rolling window; strategies read the current
246        // mode via `World::resource::<TrafficDetector>()`.
247        world.insert_resource(crate::traffic_detector::TrafficDetector::default());
248        // Per-car reposition cooldown. Populated by the movement
249        // phase when a repositioning car arrives; consulted by the
250        // reposition phase to skip cars that just parked so the
251        // hot-stop ranking can't flip them around again the next
252        // tick.
253        world.insert_resource(crate::dispatch::reposition::RepositionCooldowns::default());
254        // Expose tick rate to strategies that need to unit-convert
255        // tick-denominated elevator fields (door cycle, ack latency)
256        // into the second-denominated terms of their cost functions.
257        // Without this, ETD's door-overhead term was summing ticks
258        // into a seconds expression and getting ~60× over-weighted.
259        world.insert_resource(crate::time::TickRate(config.simulation.ticks_per_second));
260
261        let (mut groups, dispatchers, strategy_ids) =
262            if let Some(line_configs) = &config.building.lines {
263                Self::build_explicit_topology(
264                    &mut world,
265                    config,
266                    line_configs,
267                    &stop_lookup,
268                    builder_dispatchers,
269                )
270            } else {
271                Self::build_legacy_topology(&mut world, config, &stop_lookup, builder_dispatchers)
272            };
273        sync_hall_call_modes(&mut groups, &strategy_ids);
274
275        let dt = 1.0 / config.simulation.ticks_per_second;
276
277        world.insert_resource(crate::tagged_metrics::MetricTags::default());
278
279        // Auto-register dispatch-internal extension types the sim itself
280        // owns. The same registration runs in `from_parts` (the
281        // snapshot-restore path); doing it here too means snapshot bytes
282        // taken from a fresh sim and from a restored sim agree on the
283        // extensions BTreeMap shape (#534's review surfaced this
284        // asymmetry: pre-fix, fresh sims had no `assigned_car` extension
285        // entry while restored sims did, breaking byte-equality of the
286        // snapshot bytes round-trip and the lockstep checksum).
287        world.register_ext::<crate::dispatch::destination::AssignedCar>(
288            crate::dispatch::destination::ASSIGNED_CAR_KEY,
289        );
290
291        // Collect line tag info (entity + name + elevator entities) before
292        // borrowing world mutably for MetricTags.
293        let line_tag_info: Vec<(EntityId, String, Vec<EntityId>)> = groups
294            .iter()
295            .flat_map(|group| {
296                group.lines().iter().filter_map(|li| {
297                    let line_comp = world.line(li.entity())?;
298                    Some((li.entity(), line_comp.name.clone(), li.elevators().to_vec()))
299                })
300            })
301            .collect();
302
303        // Tag line entities and their elevators with "line:{name}".
304        if let Some(tags) = world.resource_mut::<crate::tagged_metrics::MetricTags>() {
305            for (line_eid, name, elevators) in &line_tag_info {
306                let tag = format!("line:{name}");
307                tags.tag(*line_eid, tag.clone());
308                for elev_eid in elevators {
309                    tags.tag(*elev_eid, tag.clone());
310                }
311            }
312        }
313
314        // Wire reposition strategies from group configs.
315        let mut repositioners: BTreeMap<GroupId, Box<dyn RepositionStrategy>> = BTreeMap::new();
316        let mut reposition_ids: BTreeMap<GroupId, BuiltinReposition> = BTreeMap::new();
317        if let Some(group_configs) = &config.building.groups {
318            for gc in group_configs {
319                if let Some(ref repo_id) = gc.reposition
320                    && let Some(strategy) = repo_id.instantiate()
321                {
322                    let gid = GroupId(gc.id);
323                    repositioners.insert(gid, strategy);
324                    reposition_ids.insert(gid, repo_id.clone());
325                }
326            }
327        }
328
329        Ok(Self {
330            world,
331            events: EventBus::default(),
332            pending_output: Vec::new(),
333            tick: 0,
334            dt,
335            groups,
336            stop_lookup,
337            dispatcher_set: super::DispatcherSet::from_parts(dispatchers, strategy_ids),
338            repositioner_set: super::RepositionerSet::from_parts(repositioners, reposition_ids),
339            metrics: Metrics::new(),
340            time: TimeAdapter::new(config.simulation.ticks_per_second),
341            hooks,
342            elevator_ids_buf: Vec::new(),
343            reposition_buf: Vec::new(),
344            dispatch_scratch: crate::dispatch::DispatchScratch::default(),
345            topo_graph: Mutex::new(TopologyGraph::new()),
346            rider_index: RiderIndex::default(),
347            tick_in_progress: false,
348        })
349    }
350
351    /// Spawn a single elevator entity from an `ElevatorConfig` onto `line`.
352    ///
353    /// Sets position, velocity, all `Elevator` fields, optional energy profile,
354    /// optional service mode, and an empty `DestinationQueue`.
355    /// Returns the new entity ID.
356    fn spawn_elevator_entity(
357        world: &mut World,
358        ec: &crate::config::ElevatorConfig,
359        line: EntityId,
360        stop_lookup: &HashMap<StopId, EntityId>,
361        start_pos_lookup: &[crate::stop::StopConfig],
362    ) -> EntityId {
363        let eid = world.spawn();
364        let start_pos = start_pos_lookup
365            .iter()
366            .find(|s| s.id == ec.starting_stop)
367            .map_or(0.0, |s| s.position);
368        world.set_position(eid, Position { value: start_pos });
369        world.set_velocity(eid, Velocity { value: 0.0 });
370        let restricted: HashSet<EntityId> = ec
371            .restricted_stops
372            .iter()
373            .filter_map(|sid| stop_lookup.get(sid).copied())
374            .collect();
375        world.set_elevator(
376            eid,
377            Elevator {
378                phase: ElevatorPhase::Idle,
379                door: DoorState::Closed,
380                max_speed: ec.max_speed,
381                acceleration: ec.acceleration,
382                deceleration: ec.deceleration,
383                weight_capacity: ec.weight_capacity,
384                current_load: crate::components::Weight::ZERO,
385                riders: Vec::new(),
386                target_stop: None,
387                door_transition_ticks: ec.door_transition_ticks,
388                door_open_ticks: ec.door_open_ticks,
389                line,
390                repositioning: false,
391                restricted_stops: restricted,
392                inspection_speed_factor: ec.inspection_speed_factor,
393                going_up: true,
394                going_down: true,
395                move_count: 0,
396                door_command_queue: Vec::new(),
397                manual_target_velocity: None,
398                bypass_load_up_pct: ec.bypass_load_up_pct,
399                bypass_load_down_pct: ec.bypass_load_down_pct,
400                home_stop: None,
401            },
402        );
403        #[cfg(feature = "energy")]
404        if let Some(ref profile) = ec.energy_profile {
405            world.set_energy_profile(eid, profile.clone());
406            world.set_energy_metrics(eid, crate::energy::EnergyMetrics::default());
407        }
408        if let Some(mode) = ec.service_mode {
409            world.set_service_mode(eid, mode);
410        }
411        world.set_destination_queue(eid, crate::components::DestinationQueue::new());
412        eid
413    }
414
415    /// Build topology from the legacy flat elevator list (single default line + group).
416    fn build_legacy_topology(
417        world: &mut World,
418        config: &SimConfig,
419        stop_lookup: &HashMap<StopId, EntityId>,
420        builder_dispatchers: BTreeMap<GroupId, Box<dyn DispatchStrategy>>,
421    ) -> TopologyResult {
422        // Iterate the config's stop list (deterministic Vec order) and
423        // resolve each through the lookup. Walking `stop_lookup.values()`
424        // would expose `HashMap` iteration order — which varies by
425        // per-process hash seed — into `LineInfo.serves` and from
426        // there into snapshot bytes.
427        let all_stop_entities: Vec<EntityId> = config
428            .building
429            .stops
430            .iter()
431            .filter_map(|s| stop_lookup.get(&s.id).copied())
432            .collect();
433        let stop_positions: Vec<f64> = config.building.stops.iter().map(|s| s.position).collect();
434        let min_pos = stop_positions.iter().copied().fold(f64::INFINITY, f64::min);
435        let max_pos = stop_positions
436            .iter()
437            .copied()
438            .fold(f64::NEG_INFINITY, f64::max);
439
440        let default_line_eid = world.spawn();
441        world.set_line(
442            default_line_eid,
443            Line {
444                name: "Default".into(),
445                group: GroupId(0),
446                orientation: Orientation::Vertical,
447                position: None,
448                kind: LineKind::Linear {
449                    min: min_pos,
450                    max: max_pos,
451                },
452                max_cars: None,
453            },
454        );
455
456        let mut elevator_entities = Vec::new();
457        for ec in &config.elevators {
458            let eid = Self::spawn_elevator_entity(
459                world,
460                ec,
461                default_line_eid,
462                stop_lookup,
463                &config.building.stops,
464            );
465            elevator_entities.push(eid);
466        }
467
468        let default_line_info =
469            LineInfo::new(default_line_eid, elevator_entities, all_stop_entities);
470
471        let group = ElevatorGroup::new(GroupId(0), "Default".into(), vec![default_line_info]);
472
473        // Legacy topology has exactly one group: GroupId(0). Take a builder
474        // entry keyed on that group; ignore entries keyed on any other group
475        // (they would have nothing to attach to in the legacy schema).
476        let mut dispatchers = BTreeMap::new();
477        let mut strategy_ids = BTreeMap::new();
478        let user_dispatcher = builder_dispatchers
479            .into_iter()
480            .find_map(|(gid, d)| if gid == GroupId(0) { Some(d) } else { None });
481        // Snapshot identity comes from the dispatcher's own `builtin_id`, not
482        // from a hard-coded variant — otherwise a snapshot round-trip would
483        // silently swap a custom strategy back to Scan. Strategies that
484        // return `None` fall back to Scan for snapshot fidelity.
485        let inferred_id = user_dispatcher
486            .as_ref()
487            .and_then(|d| d.builtin_id())
488            .unwrap_or(BuiltinStrategy::Scan);
489        if let Some(d) = user_dispatcher {
490            dispatchers.insert(GroupId(0), d);
491        } else {
492            dispatchers.insert(
493                GroupId(0),
494                Box::new(crate::dispatch::scan::ScanDispatch::new()) as Box<dyn DispatchStrategy>,
495            );
496        }
497        strategy_ids.insert(GroupId(0), inferred_id);
498
499        (vec![group], dispatchers, strategy_ids)
500    }
501
502    /// Build topology from explicit `LineConfig`/`GroupConfig` definitions.
503    #[allow(clippy::too_many_lines)]
504    fn build_explicit_topology(
505        world: &mut World,
506        config: &SimConfig,
507        line_configs: &[crate::config::LineConfig],
508        stop_lookup: &HashMap<StopId, EntityId>,
509        builder_dispatchers: BTreeMap<GroupId, Box<dyn DispatchStrategy>>,
510    ) -> TopologyResult {
511        // Map line config id → (line EntityId, LineInfo). `BTreeMap`
512        // (not `HashMap`) so the auto-inferred-groups branch iterates
513        // `.values()` in deterministic key order — otherwise the
514        // resulting `LineInfo` sequence permutes across processes and
515        // leaks into snapshot bytes via `GroupSnapshot::lines`.
516        let mut line_map: BTreeMap<u32, (EntityId, LineInfo)> = BTreeMap::new();
517
518        for lc in line_configs {
519            // Resolve served stop entities.
520            let served_entities: Vec<EntityId> = lc
521                .serves
522                .iter()
523                .filter_map(|sid| stop_lookup.get(sid).copied())
524                .collect();
525
526            // Compute min/max from stops if not explicitly set.
527            let stop_positions: Vec<f64> = lc
528                .serves
529                .iter()
530                .filter_map(|sid| {
531                    config
532                        .building
533                        .stops
534                        .iter()
535                        .find(|s| s.id == *sid)
536                        .map(|s| s.position)
537                })
538                .collect();
539            let auto_min = stop_positions.iter().copied().fold(f64::INFINITY, f64::min);
540            let auto_max = stop_positions
541                .iter()
542                .copied()
543                .fold(f64::NEG_INFINITY, f64::max);
544
545            let min_pos = lc.min_position.unwrap_or(auto_min);
546            let max_pos = lc.max_position.unwrap_or(auto_max);
547
548            let line_eid = world.spawn();
549            // The group assignment will be set when we process GroupConfigs.
550            // Default to GroupId(0) initially. `kind` was validated in
551            // `validate_explicit_topology` before this builder ran.
552            world.set_line(
553                line_eid,
554                Line {
555                    name: lc.name.clone(),
556                    group: GroupId(0),
557                    orientation: lc.orientation,
558                    position: lc.position,
559                    kind: lc.kind.unwrap_or(LineKind::Linear {
560                        min: min_pos,
561                        max: max_pos,
562                    }),
563                    max_cars: lc.max_cars,
564                },
565            );
566
567            // Spawn elevators for this line.
568            let mut elevator_entities = Vec::new();
569            for ec in &lc.elevators {
570                let eid = Self::spawn_elevator_entity(
571                    world,
572                    ec,
573                    line_eid,
574                    stop_lookup,
575                    &config.building.stops,
576                );
577                elevator_entities.push(eid);
578            }
579
580            let line_info = LineInfo::new(line_eid, elevator_entities, served_entities);
581            line_map.insert(lc.id, (line_eid, line_info));
582        }
583
584        // Build groups from GroupConfigs, or auto-infer a single group.
585        let group_configs = config.building.groups.as_deref();
586        let mut groups = Vec::new();
587        let mut dispatchers = BTreeMap::new();
588        let mut strategy_ids = BTreeMap::new();
589
590        if let Some(gcs) = group_configs {
591            for gc in gcs {
592                let group_id = GroupId(gc.id);
593
594                let mut group_lines = Vec::new();
595
596                for &lid in &gc.lines {
597                    if let Some((line_eid, li)) = line_map.get(&lid) {
598                        // Update the line's group assignment.
599                        if let Some(line_comp) = world.line_mut(*line_eid) {
600                            line_comp.group = group_id;
601                        }
602                        group_lines.push(li.clone());
603                    }
604                }
605
606                let mut group = ElevatorGroup::new(group_id, gc.name.clone(), group_lines);
607                if let Some(mode) = gc.hall_call_mode {
608                    group.set_hall_call_mode(mode);
609                }
610                if let Some(ticks) = gc.ack_latency_ticks {
611                    group.set_ack_latency_ticks(ticks);
612                }
613                groups.push(group);
614
615                // GroupConfig strategy; builder overrides applied after this loop.
616                let dispatch: Box<dyn DispatchStrategy> = gc
617                    .dispatch
618                    .instantiate()
619                    .unwrap_or_else(|| Box::new(crate::dispatch::scan::ScanDispatch::new()));
620                dispatchers.insert(group_id, dispatch);
621                strategy_ids.insert(group_id, gc.dispatch.clone());
622            }
623        } else {
624            // No explicit groups — create a single default group with all lines.
625            let group_id = GroupId(0);
626            let mut group_lines = Vec::new();
627
628            for (line_eid, li) in line_map.values() {
629                if let Some(line_comp) = world.line_mut(*line_eid) {
630                    line_comp.group = group_id;
631                }
632                group_lines.push(li.clone());
633            }
634
635            let group = ElevatorGroup::new(group_id, "Default".into(), group_lines);
636            groups.push(group);
637
638            let dispatch: Box<dyn DispatchStrategy> =
639                Box::new(crate::dispatch::scan::ScanDispatch::new());
640            dispatchers.insert(group_id, dispatch);
641            strategy_ids.insert(group_id, BuiltinStrategy::Scan);
642        }
643
644        // Builder-provided dispatchers override the config. For the matching
645        // `strategy_ids` entry, prefer the dispatcher's own `builtin_id()`
646        // (snapshot fidelity); fall back to the config id only when the
647        // dispatcher is unidentified (custom strategies that don't override).
648        for (gid, d) in builder_dispatchers {
649            let inferred_id = d.builtin_id();
650            dispatchers.insert(gid, d);
651            match inferred_id {
652                Some(id) => {
653                    strategy_ids.insert(gid, id);
654                }
655                None => {
656                    strategy_ids
657                        .entry(gid)
658                        .or_insert_with(|| BuiltinStrategy::Custom("user-supplied".into()));
659                }
660            }
661        }
662
663        (groups, dispatchers, strategy_ids)
664    }
665
666    /// Restore a simulation from pre-built parts (used by snapshot restore).
667    #[allow(clippy::too_many_arguments)]
668    pub(crate) fn from_parts(
669        world: World,
670        tick: u64,
671        dt: f64,
672        groups: Vec<ElevatorGroup>,
673        stop_lookup: HashMap<StopId, EntityId>,
674        dispatchers: BTreeMap<GroupId, Box<dyn DispatchStrategy>>,
675        strategy_ids: BTreeMap<GroupId, crate::dispatch::BuiltinStrategy>,
676        metrics: Metrics,
677        ticks_per_second: f64,
678    ) -> Self {
679        let mut rider_index = RiderIndex::default();
680        rider_index.rebuild(&world);
681        // Forward-compat: snapshots predating these resources won't carry
682        // them. `TickRate` would otherwise default to 60 Hz and silently
683        // halve ETD's door-cost scale on a 30 Hz sim; the traffic detector
684        // would no-op forever in the metrics phase. `insert_resource` is
685        // last-writer-wins, so snapshots that already carry them are kept.
686        let mut world = world;
687        world.insert_resource(crate::time::TickRate(ticks_per_second));
688        if world
689            .resource::<crate::traffic_detector::TrafficDetector>()
690            .is_none()
691        {
692            world.insert_resource(crate::traffic_detector::TrafficDetector::default());
693        }
694        // Same forward-compat pattern for the destination log. An
695        // older snapshot would leave the detector unable to detect
696        // down-peak post-restore; a fresh empty log lets it resume
697        // classification after a few ticks of observed traffic.
698        if world
699            .resource::<crate::arrival_log::DestinationLog>()
700            .is_none()
701        {
702            world.insert_resource(crate::arrival_log::DestinationLog::default());
703        }
704        // Auto-register dispatch-internal extension types the sim itself
705        // owns, and immediately load their data from the pending
706        // resource. Without this, DCS sticky assignments
707        // (`AssignedCar`) evaporate across snapshot round-trip and
708        // `DestinationDispatch` re-computes every commitment from
709        // scratch — producing different decisions than the original
710        // sim and breaking tick-for-tick determinism.
711        //
712        // `deserialize_extensions` takes a `&` of the pending map and
713        // silently skips types that aren't registered, so the call is
714        // safe to make with user-owned extensions still in the map.
715        // The `PendingExtensions` resource stays in place for a later
716        // `load_extensions_with` call to materialize the caller's own
717        // types.
718        world.register_ext::<crate::dispatch::destination::AssignedCar>(
719            crate::dispatch::destination::ASSIGNED_CAR_KEY,
720        );
721        if let Some(pending) = world.resource::<crate::snapshot::PendingExtensions>() {
722            let data = pending.0.clone();
723            world.deserialize_extensions(&data);
724        }
725        Self {
726            world,
727            events: EventBus::default(),
728            pending_output: Vec::new(),
729            tick,
730            dt,
731            groups,
732            stop_lookup,
733            dispatcher_set: super::DispatcherSet::from_parts(dispatchers, strategy_ids),
734            repositioner_set: super::RepositionerSet::new(),
735            metrics,
736            time: TimeAdapter::new(ticks_per_second),
737            hooks: PhaseHooks::default(),
738            elevator_ids_buf: Vec::new(),
739            reposition_buf: Vec::new(),
740            dispatch_scratch: crate::dispatch::DispatchScratch::default(),
741            topo_graph: Mutex::new(TopologyGraph::new()),
742            rider_index,
743            tick_in_progress: false,
744        }
745    }
746
747    /// Validate configuration before constructing the simulation.
748    pub(crate) fn validate_config(config: &SimConfig) -> Result<(), SimError> {
749        // Schema-version gate: reject forward-incompatible configs (a
750        // future build's RON would silently mis-deserialize fields a
751        // current build doesn't know about) and surface legacy
752        // pre-versioning configs (`schema_version = 0`) as an explicit
753        // upgrade prompt rather than a silent serde-default smear. See
754        // `docs/src/config-versioning.md` for the migration playbook.
755        if config.schema_version > crate::config::CURRENT_CONFIG_SCHEMA_VERSION {
756            return Err(SimError::InvalidConfig {
757                field: "schema_version",
758                reason: format!(
759                    "config schema_version={} is newer than this build's CURRENT_CONFIG_SCHEMA_VERSION={}; upgrade elevator-core or downgrade the config",
760                    config.schema_version,
761                    crate::config::CURRENT_CONFIG_SCHEMA_VERSION,
762                ),
763            });
764        }
765        if config.schema_version == 0 {
766            return Err(SimError::InvalidConfig {
767                field: "schema_version",
768                reason: format!(
769                    "config schema_version=0 (pre-versioning legacy file) — set schema_version: {} explicitly after auditing field defaults; see docs/src/config-versioning.md",
770                    crate::config::CURRENT_CONFIG_SCHEMA_VERSION,
771                ),
772            });
773        }
774
775        if config.building.stops.is_empty() {
776            return Err(SimError::InvalidConfig {
777                field: "building.stops",
778                reason: "at least one stop is required".into(),
779            });
780        }
781
782        // Check for duplicate stop IDs and validate positions.
783        let mut seen_ids = HashSet::new();
784        for stop in &config.building.stops {
785            if !seen_ids.insert(stop.id) {
786                return Err(SimError::InvalidConfig {
787                    field: "building.stops",
788                    reason: format!("duplicate {}", stop.id),
789                });
790            }
791            if !stop.position.is_finite() {
792                return Err(SimError::InvalidConfig {
793                    field: "building.stops.position",
794                    reason: format!("{} has non-finite position {}", stop.id, stop.position),
795                });
796            }
797        }
798
799        let stop_ids: HashSet<StopId> = config.building.stops.iter().map(|s| s.id).collect();
800
801        if let Some(line_configs) = &config.building.lines {
802            // ── Explicit topology validation ──
803            Self::validate_explicit_topology(line_configs, &stop_ids, &config.building)?;
804        } else {
805            // ── Legacy flat elevator list validation ──
806            Self::validate_legacy_elevators(&config.elevators, &config.building)?;
807        }
808
809        if !config.simulation.ticks_per_second.is_finite()
810            || config.simulation.ticks_per_second <= 0.0
811        {
812            return Err(SimError::InvalidConfig {
813                field: "simulation.ticks_per_second",
814                reason: format!(
815                    "must be finite and positive, got {}",
816                    config.simulation.ticks_per_second
817                ),
818            });
819        }
820
821        Self::validate_passenger_spawning(&config.passenger_spawning)?;
822
823        Ok(())
824    }
825
826    /// Validate `PassengerSpawnConfig`. Without this, bad inputs reach
827    /// `PoissonSource::from_config` and panic later (NaN/negative weights
828    /// crash `random_range`/`Weight::from`; zero `mean_interval_ticks`
829    /// burst-fires every catch-up tick). (#272)
830    fn validate_passenger_spawning(
831        spawn: &crate::config::PassengerSpawnConfig,
832    ) -> Result<(), SimError> {
833        let (lo, hi) = spawn.weight_range;
834        if !lo.is_finite() || !hi.is_finite() {
835            return Err(SimError::InvalidConfig {
836                field: "passenger_spawning.weight_range",
837                reason: format!("both endpoints must be finite, got ({lo}, {hi})"),
838            });
839        }
840        if lo < 0.0 || hi < 0.0 {
841            return Err(SimError::InvalidConfig {
842                field: "passenger_spawning.weight_range",
843                reason: format!("both endpoints must be non-negative, got ({lo}, {hi})"),
844            });
845        }
846        if lo > hi {
847            return Err(SimError::InvalidConfig {
848                field: "passenger_spawning.weight_range",
849                reason: format!("min must be <= max, got ({lo}, {hi})"),
850            });
851        }
852        if spawn.mean_interval_ticks == 0 {
853            return Err(SimError::InvalidConfig {
854                field: "passenger_spawning.mean_interval_ticks",
855                reason: "must be > 0; mean_interval_ticks=0 burst-fires \
856                         every catch-up tick"
857                    .into(),
858            });
859        }
860        Ok(())
861    }
862
863    /// Validate the legacy flat elevator list.
864    fn validate_legacy_elevators(
865        elevators: &[crate::config::ElevatorConfig],
866        building: &crate::config::BuildingConfig,
867    ) -> Result<(), SimError> {
868        if elevators.is_empty() {
869            return Err(SimError::InvalidConfig {
870                field: "elevators",
871                reason: "at least one elevator is required".into(),
872            });
873        }
874
875        for elev in elevators {
876            Self::validate_elevator_config(elev, building)?;
877        }
878
879        Ok(())
880    }
881
882    /// Validate a single elevator config's physics and starting stop.
883    fn validate_elevator_config(
884        elev: &crate::config::ElevatorConfig,
885        building: &crate::config::BuildingConfig,
886    ) -> Result<(), SimError> {
887        validate_elevator_physics(
888            elev.max_speed.value(),
889            elev.acceleration.value(),
890            elev.deceleration.value(),
891            elev.weight_capacity.value(),
892            elev.inspection_speed_factor,
893            elev.door_transition_ticks,
894            elev.door_open_ticks,
895            elev.bypass_load_up_pct,
896            elev.bypass_load_down_pct,
897        )?;
898        if !building.stops.iter().any(|s| s.id == elev.starting_stop) {
899            return Err(SimError::InvalidConfig {
900                field: "elevators.starting_stop",
901                reason: format!("references non-existent {}", elev.starting_stop),
902            });
903        }
904        Ok(())
905    }
906
907    /// Validate explicit line/group topology.
908    #[allow(
909        clippy::too_many_lines,
910        reason = "validation reads top-to-bottom; extracting helpers would scatter related rejections across files"
911    )]
912    fn validate_explicit_topology(
913        line_configs: &[crate::config::LineConfig],
914        stop_ids: &HashSet<StopId>,
915        building: &crate::config::BuildingConfig,
916    ) -> Result<(), SimError> {
917        // No duplicate line IDs.
918        let mut seen_line_ids = HashSet::new();
919        for lc in line_configs {
920            if !seen_line_ids.insert(lc.id) {
921                return Err(SimError::InvalidConfig {
922                    field: "building.lines",
923                    reason: format!("duplicate line id {}", lc.id),
924                });
925            }
926        }
927
928        // Every line's serves must reference existing stops and be non-empty.
929        for lc in line_configs {
930            if lc.serves.is_empty() {
931                return Err(SimError::InvalidConfig {
932                    field: "building.lines.serves",
933                    reason: format!("line {} has no stops", lc.id),
934                });
935            }
936            for sid in &lc.serves {
937                if !stop_ids.contains(sid) {
938                    return Err(SimError::InvalidConfig {
939                        field: "building.lines.serves",
940                        reason: format!("line {} references non-existent {}", lc.id, sid),
941                    });
942                }
943            }
944            // Validate elevators within each line.
945            for ec in &lc.elevators {
946                Self::validate_elevator_config(ec, building)?;
947            }
948
949            // Validate max_cars is not exceeded.
950            if let Some(max) = lc.max_cars
951                && lc.elevators.len() > max
952            {
953                return Err(SimError::InvalidConfig {
954                    field: "building.lines.max_cars",
955                    reason: format!(
956                        "line {} has {} elevators but max_cars is {max}",
957                        lc.id,
958                        lc.elevators.len()
959                    ),
960                });
961            }
962
963            // Validate the explicit topology kind, if any. Linear-only
964            // configs (kind = None) are validated by the auto-derived
965            // bounds check inside `build_explicit_topology` instead.
966            if let Some(kind) = lc.kind
967                && let Err((field, reason)) = kind.validate()
968            {
969                return Err(SimError::InvalidConfig { field, reason });
970            }
971
972            // Loop-specific cross-field invariant: every car must fit
973            // around the loop with at least `min_headway` between
974            // successive cars. Without this guard, the second car
975            // configured on a too-short loop would instantly violate
976            // the no-overtake invariant the headway clamp is designed
977            // to preserve.
978            #[cfg(feature = "loop_lines")]
979            if let Some(crate::components::LineKind::Loop {
980                circumference,
981                min_headway,
982            }) = lc.kind
983            {
984                let car_count = lc
985                    .max_cars
986                    .map_or_else(|| lc.elevators.len(), |max| max.max(lc.elevators.len()));
987                if car_count > 0 {
988                    #[allow(
989                        clippy::cast_precision_loss,
990                        reason = "car_count is bounded by usize and the comparison is against a finite f64"
991                    )]
992                    let required = (car_count as f64) * min_headway;
993                    if required > circumference {
994                        return Err(SimError::InvalidConfig {
995                            field: "building.lines.kind",
996                            reason: format!(
997                                "loop line {}: {car_count} cars × min_headway {min_headway} = {required} \
998                                 exceeds circumference {circumference}",
999                                lc.id,
1000                            ),
1001                        });
1002                    }
1003                }
1004            }
1005        }
1006
1007        // At least one line with at least one elevator.
1008        let has_elevator = line_configs.iter().any(|lc| !lc.elevators.is_empty());
1009        if !has_elevator {
1010            return Err(SimError::InvalidConfig {
1011                field: "building.lines",
1012                reason: "at least one line must have at least one elevator".into(),
1013            });
1014        }
1015
1016        // No orphaned stops: every stop must be served by at least one line.
1017        let served: HashSet<StopId> = line_configs
1018            .iter()
1019            .flat_map(|lc| lc.serves.iter().copied())
1020            .collect();
1021        for sid in stop_ids {
1022            if !served.contains(sid) {
1023                return Err(SimError::InvalidConfig {
1024                    field: "building.lines",
1025                    reason: format!("orphaned stop {sid} not served by any line"),
1026                });
1027            }
1028        }
1029
1030        // Validate groups if present.
1031        if let Some(group_configs) = &building.groups {
1032            let line_id_set: HashSet<u32> = line_configs.iter().map(|lc| lc.id).collect();
1033
1034            let mut seen_group_ids = HashSet::new();
1035            for gc in group_configs {
1036                if !seen_group_ids.insert(gc.id) {
1037                    return Err(SimError::InvalidConfig {
1038                        field: "building.groups",
1039                        reason: format!("duplicate group id {}", gc.id),
1040                    });
1041                }
1042                for &lid in &gc.lines {
1043                    if !line_id_set.contains(&lid) {
1044                        return Err(SimError::InvalidConfig {
1045                            field: "building.groups.lines",
1046                            reason: format!(
1047                                "group {} references non-existent line id {}",
1048                                gc.id, lid
1049                            ),
1050                        });
1051                    }
1052                }
1053            }
1054
1055            // Check for orphaned lines (not referenced by any group).
1056            let referenced_line_ids: HashSet<u32> = group_configs
1057                .iter()
1058                .flat_map(|g| g.lines.iter().copied())
1059                .collect();
1060            for lc in line_configs {
1061                if !referenced_line_ids.contains(&lc.id) {
1062                    return Err(SimError::InvalidConfig {
1063                        field: "building.lines",
1064                        reason: format!("line {} is not assigned to any group", lc.id),
1065                    });
1066                }
1067            }
1068        }
1069
1070        Ok(())
1071    }
1072
1073    // ── Dispatch management ──────────────────────────────────────────
1074
1075    /// Replace the dispatch strategy for a group.
1076    ///
1077    /// Also synchronises `HallCallMode`: `Destination` for DCS, `Classic`
1078    /// for other built-ins; `Custom` strategies leave the mode untouched.
1079    ///
1080    /// The stored snapshot identity is taken from the strategy's own
1081    /// [`DispatchStrategy::builtin_id`] when it returns `Some(..)`, so
1082    /// built-in strategies always round-trip as themselves even if the
1083    /// `id` argument drifts out of sync with the actual impl. Custom
1084    /// strategies that don't override `builtin_id` fall back to the
1085    /// caller-supplied `id`, preserving the prior API for registered
1086    /// custom factories. Mirrors the pattern applied to
1087    /// [`set_reposition`](Self::set_reposition) in #414.
1088    pub fn set_dispatch(
1089        &mut self,
1090        group: GroupId,
1091        strategy: Box<dyn DispatchStrategy>,
1092        id: crate::dispatch::BuiltinStrategy,
1093    ) {
1094        let resolved_id = strategy.builtin_id().unwrap_or(id);
1095        if let Some(mode) = canonical_hall_call_mode(&resolved_id)
1096            && let Some(g) = self.groups.iter_mut().find(|g| g.id() == group)
1097        {
1098            g.set_hall_call_mode(mode);
1099        }
1100        self.dispatcher_set.insert(group, strategy, resolved_id);
1101    }
1102
1103    // ── Reposition management ─────────────────────────────────────────
1104
1105    /// Set the reposition strategy for a group.
1106    ///
1107    /// Enables the reposition phase for this group. Idle elevators will
1108    /// be repositioned according to the strategy after each dispatch phase.
1109    ///
1110    /// The stored snapshot identity is taken from the strategy's own
1111    /// [`RepositionStrategy::builtin_id`] when it returns `Some(..)`,
1112    /// so built-in strategies always round-trip as themselves even if
1113    /// the `id` argument drifts out of sync with the actual impl.
1114    /// Custom strategies that don't override `builtin_id` fall back
1115    /// to the caller-supplied `id`, preserving the prior API for
1116    /// registered custom factories.
1117    ///
1118    /// ## Retention
1119    /// Widens [`ArrivalLogRetention`](crate::arrival_log::ArrivalLogRetention)
1120    /// to the strategy's
1121    /// [`min_arrival_log_window`](crate::dispatch::RepositionStrategy::min_arrival_log_window)
1122    /// when that exceeds current retention, never narrows it. This is
1123    /// monotonic by design — replacing a wide-window strategy with a
1124    /// narrow one (or [`remove_reposition`](Self::remove_reposition))
1125    /// leaves retention at the high-water mark rather than recomputing
1126    /// across the remaining strategies, since shrinking would also
1127    /// clobber any explicit
1128    /// [`set_arrival_log_retention_ticks`](Self::set_arrival_log_retention_ticks)
1129    /// the caller made afterwards. Long-running sims that hot-swap
1130    /// strategies pay a memory cost equal to the largest historic
1131    /// window; if that matters, call `set_arrival_log_retention_ticks`
1132    /// explicitly after the swap.
1133    pub fn set_reposition(
1134        &mut self,
1135        group: GroupId,
1136        strategy: Box<dyn RepositionStrategy>,
1137        id: BuiltinReposition,
1138    ) {
1139        let resolved_id = strategy.builtin_id().unwrap_or(id);
1140        let needed_window = strategy.min_arrival_log_window();
1141        self.repositioner_set.insert(group, strategy, resolved_id);
1142        // Widen the arrival-log retention if the freshly installed
1143        // strategy queries a window the pruner would otherwise truncate
1144        // under it. Without this, `PredictiveParking::with_window_ticks`
1145        // (or any custom strategy advertising a longer window) silently
1146        // sees only the last `DEFAULT_ARRIVAL_WINDOW_TICKS` of arrivals.
1147        if needed_window > 0
1148            && let Some(retention) = self
1149                .world
1150                .resource_mut::<crate::arrival_log::ArrivalLogRetention>()
1151            && needed_window > retention.0
1152        {
1153            retention.0 = needed_window;
1154        }
1155    }
1156
1157    /// Remove the reposition strategy for a group, disabling repositioning.
1158    ///
1159    /// Does not narrow
1160    /// [`ArrivalLogRetention`](crate::arrival_log::ArrivalLogRetention)
1161    /// — see the retention note on
1162    /// [`set_reposition`](Self::set_reposition) for why retention is
1163    /// monotonic across strategy lifecycle changes. Call
1164    /// [`set_arrival_log_retention_ticks`](Self::set_arrival_log_retention_ticks)
1165    /// explicitly to shrink retention after removing a wide-window
1166    /// strategy.
1167    pub fn remove_reposition(&mut self, group: GroupId) {
1168        self.repositioner_set.remove(group);
1169    }
1170
1171    /// Get the reposition strategy identifier for a group.
1172    #[must_use]
1173    pub fn reposition_id(&self, group: GroupId) -> Option<&BuiltinReposition> {
1174        self.repositioner_set.id_for(group)
1175    }
1176
1177    // ── Hooks ────────────────────────────────────────────────────────
1178
1179    /// Register a hook to run before a simulation phase.
1180    ///
1181    /// Hooks are called in registration order. The hook receives mutable
1182    /// access to the world, allowing entity inspection or modification.
1183    pub fn add_before_hook(
1184        &mut self,
1185        phase: Phase,
1186        hook: impl Fn(&mut World) + Send + Sync + 'static,
1187    ) {
1188        self.hooks.add_before(phase, Box::new(hook));
1189    }
1190
1191    /// Register a hook to run after a simulation phase.
1192    ///
1193    /// Hooks are called in registration order. The hook receives mutable
1194    /// access to the world, allowing entity inspection or modification.
1195    pub fn add_after_hook(
1196        &mut self,
1197        phase: Phase,
1198        hook: impl Fn(&mut World) + Send + Sync + 'static,
1199    ) {
1200        self.hooks.add_after(phase, Box::new(hook));
1201    }
1202
1203    /// Register a hook to run before a phase for a specific group.
1204    pub fn add_before_group_hook(
1205        &mut self,
1206        phase: Phase,
1207        group: GroupId,
1208        hook: impl Fn(&mut World) + Send + Sync + 'static,
1209    ) {
1210        self.hooks.add_before_group(phase, group, Box::new(hook));
1211    }
1212
1213    /// Register a hook to run after a phase for a specific group.
1214    pub fn add_after_group_hook(
1215        &mut self,
1216        phase: Phase,
1217        group: GroupId,
1218        hook: impl Fn(&mut World) + Send + Sync + 'static,
1219    ) {
1220        self.hooks.add_after_group(phase, group, Box::new(hook));
1221    }
1222}