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