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        // Iterate the config's stop list (deterministic Vec order) and
391        // resolve each through the lookup. Walking `stop_lookup.values()`
392        // would expose `HashMap` iteration order — which varies by
393        // per-process hash seed — into `LineInfo.serves` and from
394        // there into snapshot bytes.
395        let all_stop_entities: Vec<EntityId> = config
396            .building
397            .stops
398            .iter()
399            .filter_map(|s| stop_lookup.get(&s.id).copied())
400            .collect();
401        let stop_positions: Vec<f64> = config.building.stops.iter().map(|s| s.position).collect();
402        let min_pos = stop_positions.iter().copied().fold(f64::INFINITY, f64::min);
403        let max_pos = stop_positions
404            .iter()
405            .copied()
406            .fold(f64::NEG_INFINITY, f64::max);
407
408        let default_line_eid = world.spawn();
409        world.set_line(
410            default_line_eid,
411            Line {
412                name: "Default".into(),
413                group: GroupId(0),
414                orientation: Orientation::Vertical,
415                position: None,
416                min_position: min_pos,
417                max_position: max_pos,
418                max_cars: None,
419            },
420        );
421
422        let mut elevator_entities = Vec::new();
423        for ec in &config.elevators {
424            let eid = Self::spawn_elevator_entity(
425                world,
426                ec,
427                default_line_eid,
428                stop_lookup,
429                &config.building.stops,
430            );
431            elevator_entities.push(eid);
432        }
433
434        let default_line_info =
435            LineInfo::new(default_line_eid, elevator_entities, all_stop_entities);
436
437        let group = ElevatorGroup::new(GroupId(0), "Default".into(), vec![default_line_info]);
438
439        // Legacy topology has exactly one group: GroupId(0). Take a builder
440        // entry keyed on that group; ignore entries keyed on any other group
441        // (they would have nothing to attach to in the legacy schema).
442        let mut dispatchers = BTreeMap::new();
443        let mut strategy_ids = BTreeMap::new();
444        let user_dispatcher = builder_dispatchers
445            .into_iter()
446            .find_map(|(gid, d)| if gid == GroupId(0) { Some(d) } else { None });
447        // Snapshot identity comes from the dispatcher's own `builtin_id`, not
448        // from a hard-coded variant — otherwise a snapshot round-trip would
449        // silently swap a custom strategy back to Scan. Strategies that
450        // return `None` fall back to Scan for snapshot fidelity.
451        let inferred_id = user_dispatcher
452            .as_ref()
453            .and_then(|d| d.builtin_id())
454            .unwrap_or(BuiltinStrategy::Scan);
455        if let Some(d) = user_dispatcher {
456            dispatchers.insert(GroupId(0), d);
457        } else {
458            dispatchers.insert(
459                GroupId(0),
460                Box::new(crate::dispatch::scan::ScanDispatch::new()) as Box<dyn DispatchStrategy>,
461            );
462        }
463        strategy_ids.insert(GroupId(0), inferred_id);
464
465        (vec![group], dispatchers, strategy_ids)
466    }
467
468    /// Build topology from explicit `LineConfig`/`GroupConfig` definitions.
469    #[allow(clippy::too_many_lines)]
470    fn build_explicit_topology(
471        world: &mut World,
472        config: &SimConfig,
473        line_configs: &[crate::config::LineConfig],
474        stop_lookup: &HashMap<StopId, EntityId>,
475        builder_dispatchers: BTreeMap<GroupId, Box<dyn DispatchStrategy>>,
476    ) -> TopologyResult {
477        // Map line config id → (line EntityId, LineInfo). `BTreeMap`
478        // (not `HashMap`) so the auto-inferred-groups branch iterates
479        // `.values()` in deterministic key order — otherwise the
480        // resulting `LineInfo` sequence permutes across processes and
481        // leaks into snapshot bytes via `GroupSnapshot::lines`.
482        let mut line_map: BTreeMap<u32, (EntityId, LineInfo)> = BTreeMap::new();
483
484        for lc in line_configs {
485            // Resolve served stop entities.
486            let served_entities: Vec<EntityId> = lc
487                .serves
488                .iter()
489                .filter_map(|sid| stop_lookup.get(sid).copied())
490                .collect();
491
492            // Compute min/max from stops if not explicitly set.
493            let stop_positions: Vec<f64> = lc
494                .serves
495                .iter()
496                .filter_map(|sid| {
497                    config
498                        .building
499                        .stops
500                        .iter()
501                        .find(|s| s.id == *sid)
502                        .map(|s| s.position)
503                })
504                .collect();
505            let auto_min = stop_positions.iter().copied().fold(f64::INFINITY, f64::min);
506            let auto_max = stop_positions
507                .iter()
508                .copied()
509                .fold(f64::NEG_INFINITY, f64::max);
510
511            let min_pos = lc.min_position.unwrap_or(auto_min);
512            let max_pos = lc.max_position.unwrap_or(auto_max);
513
514            let line_eid = world.spawn();
515            // The group assignment will be set when we process GroupConfigs.
516            // Default to GroupId(0) initially.
517            world.set_line(
518                line_eid,
519                Line {
520                    name: lc.name.clone(),
521                    group: GroupId(0),
522                    orientation: lc.orientation,
523                    position: lc.position,
524                    min_position: min_pos,
525                    max_position: max_pos,
526                    max_cars: lc.max_cars,
527                },
528            );
529
530            // Spawn elevators for this line.
531            let mut elevator_entities = Vec::new();
532            for ec in &lc.elevators {
533                let eid = Self::spawn_elevator_entity(
534                    world,
535                    ec,
536                    line_eid,
537                    stop_lookup,
538                    &config.building.stops,
539                );
540                elevator_entities.push(eid);
541            }
542
543            let line_info = LineInfo::new(line_eid, elevator_entities, served_entities);
544            line_map.insert(lc.id, (line_eid, line_info));
545        }
546
547        // Build groups from GroupConfigs, or auto-infer a single group.
548        let group_configs = config.building.groups.as_deref();
549        let mut groups = Vec::new();
550        let mut dispatchers = BTreeMap::new();
551        let mut strategy_ids = BTreeMap::new();
552
553        if let Some(gcs) = group_configs {
554            for gc in gcs {
555                let group_id = GroupId(gc.id);
556
557                let mut group_lines = Vec::new();
558
559                for &lid in &gc.lines {
560                    if let Some((line_eid, li)) = line_map.get(&lid) {
561                        // Update the line's group assignment.
562                        if let Some(line_comp) = world.line_mut(*line_eid) {
563                            line_comp.group = group_id;
564                        }
565                        group_lines.push(li.clone());
566                    }
567                }
568
569                let mut group = ElevatorGroup::new(group_id, gc.name.clone(), group_lines);
570                if let Some(mode) = gc.hall_call_mode {
571                    group.set_hall_call_mode(mode);
572                }
573                if let Some(ticks) = gc.ack_latency_ticks {
574                    group.set_ack_latency_ticks(ticks);
575                }
576                groups.push(group);
577
578                // GroupConfig strategy; builder overrides applied after this loop.
579                let dispatch: Box<dyn DispatchStrategy> = gc
580                    .dispatch
581                    .instantiate()
582                    .unwrap_or_else(|| Box::new(crate::dispatch::scan::ScanDispatch::new()));
583                dispatchers.insert(group_id, dispatch);
584                strategy_ids.insert(group_id, gc.dispatch.clone());
585            }
586        } else {
587            // No explicit groups — create a single default group with all lines.
588            let group_id = GroupId(0);
589            let mut group_lines = Vec::new();
590
591            for (line_eid, li) in line_map.values() {
592                if let Some(line_comp) = world.line_mut(*line_eid) {
593                    line_comp.group = group_id;
594                }
595                group_lines.push(li.clone());
596            }
597
598            let group = ElevatorGroup::new(group_id, "Default".into(), group_lines);
599            groups.push(group);
600
601            let dispatch: Box<dyn DispatchStrategy> =
602                Box::new(crate::dispatch::scan::ScanDispatch::new());
603            dispatchers.insert(group_id, dispatch);
604            strategy_ids.insert(group_id, BuiltinStrategy::Scan);
605        }
606
607        // Builder-provided dispatchers override the config. For the matching
608        // `strategy_ids` entry, prefer the dispatcher's own `builtin_id()`
609        // (snapshot fidelity); fall back to the config id only when the
610        // dispatcher is unidentified (custom strategies that don't override).
611        for (gid, d) in builder_dispatchers {
612            let inferred_id = d.builtin_id();
613            dispatchers.insert(gid, d);
614            match inferred_id {
615                Some(id) => {
616                    strategy_ids.insert(gid, id);
617                }
618                None => {
619                    strategy_ids
620                        .entry(gid)
621                        .or_insert_with(|| BuiltinStrategy::Custom("user-supplied".into()));
622                }
623            }
624        }
625
626        (groups, dispatchers, strategy_ids)
627    }
628
629    /// Restore a simulation from pre-built parts (used by snapshot restore).
630    #[allow(clippy::too_many_arguments)]
631    pub(crate) fn from_parts(
632        world: World,
633        tick: u64,
634        dt: f64,
635        groups: Vec<ElevatorGroup>,
636        stop_lookup: HashMap<StopId, EntityId>,
637        dispatchers: BTreeMap<GroupId, Box<dyn DispatchStrategy>>,
638        strategy_ids: BTreeMap<GroupId, crate::dispatch::BuiltinStrategy>,
639        metrics: Metrics,
640        ticks_per_second: f64,
641    ) -> Self {
642        let mut rider_index = RiderIndex::default();
643        rider_index.rebuild(&world);
644        // Forward-compat: snapshots predating these resources won't carry
645        // them. `TickRate` would otherwise default to 60 Hz and silently
646        // halve ETD's door-cost scale on a 30 Hz sim; the traffic detector
647        // would no-op forever in the metrics phase. `insert_resource` is
648        // last-writer-wins, so snapshots that already carry them are kept.
649        let mut world = world;
650        world.insert_resource(crate::time::TickRate(ticks_per_second));
651        if world
652            .resource::<crate::traffic_detector::TrafficDetector>()
653            .is_none()
654        {
655            world.insert_resource(crate::traffic_detector::TrafficDetector::default());
656        }
657        // Same forward-compat pattern for the destination log. An
658        // older snapshot would leave the detector unable to detect
659        // down-peak post-restore; a fresh empty log lets it resume
660        // classification after a few ticks of observed traffic.
661        if world
662            .resource::<crate::arrival_log::DestinationLog>()
663            .is_none()
664        {
665            world.insert_resource(crate::arrival_log::DestinationLog::default());
666        }
667        // Auto-register dispatch-internal extension types the sim itself
668        // owns, and immediately load their data from the pending
669        // resource. Without this, DCS sticky assignments
670        // (`AssignedCar`) evaporate across snapshot round-trip and
671        // `DestinationDispatch` re-computes every commitment from
672        // scratch — producing different decisions than the original
673        // sim and breaking tick-for-tick determinism.
674        //
675        // `deserialize_extensions` takes a `&` of the pending map and
676        // silently skips types that aren't registered, so the call is
677        // safe to make with user-owned extensions still in the map.
678        // The `PendingExtensions` resource stays in place for a later
679        // `load_extensions_with` call to materialize the caller's own
680        // types.
681        world.register_ext::<crate::dispatch::destination::AssignedCar>(
682            crate::dispatch::destination::ASSIGNED_CAR_KEY,
683        );
684        if let Some(pending) = world.resource::<crate::snapshot::PendingExtensions>() {
685            let data = pending.0.clone();
686            world.deserialize_extensions(&data);
687        }
688        Self {
689            world,
690            events: EventBus::default(),
691            pending_output: Vec::new(),
692            tick,
693            dt,
694            groups,
695            stop_lookup,
696            dispatchers,
697            strategy_ids,
698            repositioners: BTreeMap::new(),
699            reposition_ids: BTreeMap::new(),
700            metrics,
701            time: TimeAdapter::new(ticks_per_second),
702            hooks: PhaseHooks::default(),
703            elevator_ids_buf: Vec::new(),
704            reposition_buf: Vec::new(),
705            dispatch_scratch: crate::dispatch::DispatchScratch::default(),
706            topo_graph: Mutex::new(TopologyGraph::new()),
707            rider_index,
708            tick_in_progress: false,
709        }
710    }
711
712    /// Validate configuration before constructing the simulation.
713    pub(crate) fn validate_config(config: &SimConfig) -> Result<(), SimError> {
714        // Schema-version gate: reject forward-incompatible configs (a
715        // future build's RON would silently mis-deserialize fields a
716        // current build doesn't know about) and surface legacy
717        // pre-versioning configs (`schema_version = 0`) as an explicit
718        // upgrade prompt rather than a silent serde-default smear. See
719        // `docs/src/config-versioning.md` for the migration playbook.
720        if config.schema_version > crate::config::CURRENT_CONFIG_SCHEMA_VERSION {
721            return Err(SimError::InvalidConfig {
722                field: "schema_version",
723                reason: format!(
724                    "config schema_version={} is newer than this build's CURRENT_CONFIG_SCHEMA_VERSION={}; upgrade elevator-core or downgrade the config",
725                    config.schema_version,
726                    crate::config::CURRENT_CONFIG_SCHEMA_VERSION,
727                ),
728            });
729        }
730        if config.schema_version == 0 {
731            return Err(SimError::InvalidConfig {
732                field: "schema_version",
733                reason: format!(
734                    "config schema_version=0 (pre-versioning legacy file) — set schema_version: {} explicitly after auditing field defaults; see docs/src/config-versioning.md",
735                    crate::config::CURRENT_CONFIG_SCHEMA_VERSION,
736                ),
737            });
738        }
739
740        if config.building.stops.is_empty() {
741            return Err(SimError::InvalidConfig {
742                field: "building.stops",
743                reason: "at least one stop is required".into(),
744            });
745        }
746
747        // Check for duplicate stop IDs and validate positions.
748        let mut seen_ids = HashSet::new();
749        for stop in &config.building.stops {
750            if !seen_ids.insert(stop.id) {
751                return Err(SimError::InvalidConfig {
752                    field: "building.stops",
753                    reason: format!("duplicate {}", stop.id),
754                });
755            }
756            if !stop.position.is_finite() {
757                return Err(SimError::InvalidConfig {
758                    field: "building.stops.position",
759                    reason: format!("{} has non-finite position {}", stop.id, stop.position),
760                });
761            }
762        }
763
764        let stop_ids: HashSet<StopId> = config.building.stops.iter().map(|s| s.id).collect();
765
766        if let Some(line_configs) = &config.building.lines {
767            // ── Explicit topology validation ──
768            Self::validate_explicit_topology(line_configs, &stop_ids, &config.building)?;
769        } else {
770            // ── Legacy flat elevator list validation ──
771            Self::validate_legacy_elevators(&config.elevators, &config.building)?;
772        }
773
774        if !config.simulation.ticks_per_second.is_finite()
775            || config.simulation.ticks_per_second <= 0.0
776        {
777            return Err(SimError::InvalidConfig {
778                field: "simulation.ticks_per_second",
779                reason: format!(
780                    "must be finite and positive, got {}",
781                    config.simulation.ticks_per_second
782                ),
783            });
784        }
785
786        Self::validate_passenger_spawning(&config.passenger_spawning)?;
787
788        Ok(())
789    }
790
791    /// Validate `PassengerSpawnConfig`. Without this, bad inputs reach
792    /// `PoissonSource::from_config` and panic later (NaN/negative weights
793    /// crash `random_range`/`Weight::from`; zero `mean_interval_ticks`
794    /// burst-fires every catch-up tick). (#272)
795    fn validate_passenger_spawning(
796        spawn: &crate::config::PassengerSpawnConfig,
797    ) -> Result<(), SimError> {
798        let (lo, hi) = spawn.weight_range;
799        if !lo.is_finite() || !hi.is_finite() {
800            return Err(SimError::InvalidConfig {
801                field: "passenger_spawning.weight_range",
802                reason: format!("both endpoints must be finite, got ({lo}, {hi})"),
803            });
804        }
805        if lo < 0.0 || hi < 0.0 {
806            return Err(SimError::InvalidConfig {
807                field: "passenger_spawning.weight_range",
808                reason: format!("both endpoints must be non-negative, got ({lo}, {hi})"),
809            });
810        }
811        if lo > hi {
812            return Err(SimError::InvalidConfig {
813                field: "passenger_spawning.weight_range",
814                reason: format!("min must be <= max, got ({lo}, {hi})"),
815            });
816        }
817        if spawn.mean_interval_ticks == 0 {
818            return Err(SimError::InvalidConfig {
819                field: "passenger_spawning.mean_interval_ticks",
820                reason: "must be > 0; mean_interval_ticks=0 burst-fires \
821                         every catch-up tick"
822                    .into(),
823            });
824        }
825        Ok(())
826    }
827
828    /// Validate the legacy flat elevator list.
829    fn validate_legacy_elevators(
830        elevators: &[crate::config::ElevatorConfig],
831        building: &crate::config::BuildingConfig,
832    ) -> Result<(), SimError> {
833        if elevators.is_empty() {
834            return Err(SimError::InvalidConfig {
835                field: "elevators",
836                reason: "at least one elevator is required".into(),
837            });
838        }
839
840        for elev in elevators {
841            Self::validate_elevator_config(elev, building)?;
842        }
843
844        Ok(())
845    }
846
847    /// Validate a single elevator config's physics and starting stop.
848    fn validate_elevator_config(
849        elev: &crate::config::ElevatorConfig,
850        building: &crate::config::BuildingConfig,
851    ) -> Result<(), SimError> {
852        validate_elevator_physics(
853            elev.max_speed.value(),
854            elev.acceleration.value(),
855            elev.deceleration.value(),
856            elev.weight_capacity.value(),
857            elev.inspection_speed_factor,
858            elev.door_transition_ticks,
859            elev.door_open_ticks,
860            elev.bypass_load_up_pct,
861            elev.bypass_load_down_pct,
862        )?;
863        if !building.stops.iter().any(|s| s.id == elev.starting_stop) {
864            return Err(SimError::InvalidConfig {
865                field: "elevators.starting_stop",
866                reason: format!("references non-existent {}", elev.starting_stop),
867            });
868        }
869        Ok(())
870    }
871
872    /// Validate explicit line/group topology.
873    fn validate_explicit_topology(
874        line_configs: &[crate::config::LineConfig],
875        stop_ids: &HashSet<StopId>,
876        building: &crate::config::BuildingConfig,
877    ) -> Result<(), SimError> {
878        // No duplicate line IDs.
879        let mut seen_line_ids = HashSet::new();
880        for lc in line_configs {
881            if !seen_line_ids.insert(lc.id) {
882                return Err(SimError::InvalidConfig {
883                    field: "building.lines",
884                    reason: format!("duplicate line id {}", lc.id),
885                });
886            }
887        }
888
889        // Every line's serves must reference existing stops and be non-empty.
890        for lc in line_configs {
891            if lc.serves.is_empty() {
892                return Err(SimError::InvalidConfig {
893                    field: "building.lines.serves",
894                    reason: format!("line {} has no stops", lc.id),
895                });
896            }
897            for sid in &lc.serves {
898                if !stop_ids.contains(sid) {
899                    return Err(SimError::InvalidConfig {
900                        field: "building.lines.serves",
901                        reason: format!("line {} references non-existent {}", lc.id, sid),
902                    });
903                }
904            }
905            // Validate elevators within each line.
906            for ec in &lc.elevators {
907                Self::validate_elevator_config(ec, building)?;
908            }
909
910            // Validate max_cars is not exceeded.
911            if let Some(max) = lc.max_cars
912                && lc.elevators.len() > max
913            {
914                return Err(SimError::InvalidConfig {
915                    field: "building.lines.max_cars",
916                    reason: format!(
917                        "line {} has {} elevators but max_cars is {max}",
918                        lc.id,
919                        lc.elevators.len()
920                    ),
921                });
922            }
923        }
924
925        // At least one line with at least one elevator.
926        let has_elevator = line_configs.iter().any(|lc| !lc.elevators.is_empty());
927        if !has_elevator {
928            return Err(SimError::InvalidConfig {
929                field: "building.lines",
930                reason: "at least one line must have at least one elevator".into(),
931            });
932        }
933
934        // No orphaned stops: every stop must be served by at least one line.
935        let served: HashSet<StopId> = line_configs
936            .iter()
937            .flat_map(|lc| lc.serves.iter().copied())
938            .collect();
939        for sid in stop_ids {
940            if !served.contains(sid) {
941                return Err(SimError::InvalidConfig {
942                    field: "building.lines",
943                    reason: format!("orphaned stop {sid} not served by any line"),
944                });
945            }
946        }
947
948        // Validate groups if present.
949        if let Some(group_configs) = &building.groups {
950            let line_id_set: HashSet<u32> = line_configs.iter().map(|lc| lc.id).collect();
951
952            let mut seen_group_ids = HashSet::new();
953            for gc in group_configs {
954                if !seen_group_ids.insert(gc.id) {
955                    return Err(SimError::InvalidConfig {
956                        field: "building.groups",
957                        reason: format!("duplicate group id {}", gc.id),
958                    });
959                }
960                for &lid in &gc.lines {
961                    if !line_id_set.contains(&lid) {
962                        return Err(SimError::InvalidConfig {
963                            field: "building.groups.lines",
964                            reason: format!(
965                                "group {} references non-existent line id {}",
966                                gc.id, lid
967                            ),
968                        });
969                    }
970                }
971            }
972
973            // Check for orphaned lines (not referenced by any group).
974            let referenced_line_ids: HashSet<u32> = group_configs
975                .iter()
976                .flat_map(|g| g.lines.iter().copied())
977                .collect();
978            for lc in line_configs {
979                if !referenced_line_ids.contains(&lc.id) {
980                    return Err(SimError::InvalidConfig {
981                        field: "building.lines",
982                        reason: format!("line {} is not assigned to any group", lc.id),
983                    });
984                }
985            }
986        }
987
988        Ok(())
989    }
990
991    // ── Dispatch management ──────────────────────────────────────────
992
993    /// Replace the dispatch strategy for a group.
994    ///
995    /// Also synchronises `HallCallMode`: `Destination` for DCS, `Classic`
996    /// for other built-ins; `Custom` strategies leave the mode untouched.
997    ///
998    /// The stored snapshot identity is taken from the strategy's own
999    /// [`DispatchStrategy::builtin_id`] when it returns `Some(..)`, so
1000    /// built-in strategies always round-trip as themselves even if the
1001    /// `id` argument drifts out of sync with the actual impl. Custom
1002    /// strategies that don't override `builtin_id` fall back to the
1003    /// caller-supplied `id`, preserving the prior API for registered
1004    /// custom factories. Mirrors the pattern applied to
1005    /// [`set_reposition`](Self::set_reposition) in #414.
1006    pub fn set_dispatch(
1007        &mut self,
1008        group: GroupId,
1009        strategy: Box<dyn DispatchStrategy>,
1010        id: crate::dispatch::BuiltinStrategy,
1011    ) {
1012        let resolved_id = strategy.builtin_id().unwrap_or(id);
1013        let mode = match &resolved_id {
1014            BuiltinStrategy::Destination => Some(crate::dispatch::HallCallMode::Destination),
1015            BuiltinStrategy::Custom(_) => None,
1016            BuiltinStrategy::Scan
1017            | BuiltinStrategy::Look
1018            | BuiltinStrategy::NearestCar
1019            | BuiltinStrategy::Etd
1020            | BuiltinStrategy::Rsr => Some(crate::dispatch::HallCallMode::Classic),
1021        };
1022        if let Some(mode) = mode
1023            && let Some(g) = self.groups.iter_mut().find(|g| g.id() == group)
1024        {
1025            g.set_hall_call_mode(mode);
1026        }
1027        self.dispatchers.insert(group, strategy);
1028        self.strategy_ids.insert(group, resolved_id);
1029    }
1030
1031    // ── Reposition management ─────────────────────────────────────────
1032
1033    /// Set the reposition strategy for a group.
1034    ///
1035    /// Enables the reposition phase for this group. Idle elevators will
1036    /// be repositioned according to the strategy after each dispatch phase.
1037    ///
1038    /// The stored snapshot identity is taken from the strategy's own
1039    /// [`RepositionStrategy::builtin_id`] when it returns `Some(..)`,
1040    /// so built-in strategies always round-trip as themselves even if
1041    /// the `id` argument drifts out of sync with the actual impl.
1042    /// Custom strategies that don't override `builtin_id` fall back
1043    /// to the caller-supplied `id`, preserving the prior API for
1044    /// registered custom factories.
1045    ///
1046    /// ## Retention
1047    /// Widens [`ArrivalLogRetention`](crate::arrival_log::ArrivalLogRetention)
1048    /// to the strategy's
1049    /// [`min_arrival_log_window`](crate::dispatch::RepositionStrategy::min_arrival_log_window)
1050    /// when that exceeds current retention, never narrows it. This is
1051    /// monotonic by design — replacing a wide-window strategy with a
1052    /// narrow one (or [`remove_reposition`](Self::remove_reposition))
1053    /// leaves retention at the high-water mark rather than recomputing
1054    /// across the remaining strategies, since shrinking would also
1055    /// clobber any explicit
1056    /// [`set_arrival_log_retention_ticks`](Self::set_arrival_log_retention_ticks)
1057    /// the caller made afterwards. Long-running sims that hot-swap
1058    /// strategies pay a memory cost equal to the largest historic
1059    /// window; if that matters, call `set_arrival_log_retention_ticks`
1060    /// explicitly after the swap.
1061    pub fn set_reposition(
1062        &mut self,
1063        group: GroupId,
1064        strategy: Box<dyn RepositionStrategy>,
1065        id: BuiltinReposition,
1066    ) {
1067        let resolved_id = strategy.builtin_id().unwrap_or(id);
1068        let needed_window = strategy.min_arrival_log_window();
1069        self.repositioners.insert(group, strategy);
1070        self.reposition_ids.insert(group, resolved_id);
1071        // Widen the arrival-log retention if the freshly installed
1072        // strategy queries a window the pruner would otherwise truncate
1073        // under it. Without this, `PredictiveParking::with_window_ticks`
1074        // (or any custom strategy advertising a longer window) silently
1075        // sees only the last `DEFAULT_ARRIVAL_WINDOW_TICKS` of arrivals.
1076        if needed_window > 0
1077            && let Some(retention) = self
1078                .world
1079                .resource_mut::<crate::arrival_log::ArrivalLogRetention>()
1080            && needed_window > retention.0
1081        {
1082            retention.0 = needed_window;
1083        }
1084    }
1085
1086    /// Remove the reposition strategy for a group, disabling repositioning.
1087    ///
1088    /// Does not narrow
1089    /// [`ArrivalLogRetention`](crate::arrival_log::ArrivalLogRetention)
1090    /// — see the retention note on
1091    /// [`set_reposition`](Self::set_reposition) for why retention is
1092    /// monotonic across strategy lifecycle changes. Call
1093    /// [`set_arrival_log_retention_ticks`](Self::set_arrival_log_retention_ticks)
1094    /// explicitly to shrink retention after removing a wide-window
1095    /// strategy.
1096    pub fn remove_reposition(&mut self, group: GroupId) {
1097        self.repositioners.remove(&group);
1098        self.reposition_ids.remove(&group);
1099    }
1100
1101    /// Get the reposition strategy identifier for a group.
1102    #[must_use]
1103    pub fn reposition_id(&self, group: GroupId) -> Option<&BuiltinReposition> {
1104        self.reposition_ids.get(&group)
1105    }
1106
1107    // ── Hooks ────────────────────────────────────────────────────────
1108
1109    /// Register a hook to run before a simulation phase.
1110    ///
1111    /// Hooks are called in registration order. The hook receives mutable
1112    /// access to the world, allowing entity inspection or modification.
1113    pub fn add_before_hook(
1114        &mut self,
1115        phase: Phase,
1116        hook: impl Fn(&mut World) + Send + Sync + 'static,
1117    ) {
1118        self.hooks.add_before(phase, Box::new(hook));
1119    }
1120
1121    /// Register a hook to run after a simulation phase.
1122    ///
1123    /// Hooks are called in registration order. The hook receives mutable
1124    /// access to the world, allowing entity inspection or modification.
1125    pub fn add_after_hook(
1126        &mut self,
1127        phase: Phase,
1128        hook: impl Fn(&mut World) + Send + Sync + 'static,
1129    ) {
1130        self.hooks.add_after(phase, Box::new(hook));
1131    }
1132
1133    /// Register a hook to run before a phase for a specific group.
1134    pub fn add_before_group_hook(
1135        &mut self,
1136        phase: Phase,
1137        group: GroupId,
1138        hook: impl Fn(&mut World) + Send + Sync + 'static,
1139    ) {
1140        self.hooks.add_before_group(phase, group, Box::new(hook));
1141    }
1142
1143    /// Register a hook to run after a phase for a specific group.
1144    pub fn add_after_group_hook(
1145        &mut self,
1146        phase: Phase,
1147        group: GroupId,
1148        hook: impl Fn(&mut World) + Send + Sync + 'static,
1149    ) {
1150        self.hooks.add_after_group(phase, group, Box::new(hook));
1151    }
1152}