1use std::collections::{BTreeMap, HashMap, HashSet};
15use std::sync::Mutex;
16
17use crate::components::{
18 Elevator, ElevatorPhase, Line, LineKind, Orientation, Position, Stop, Velocity,
19};
20use crate::config::SimConfig;
21use crate::dispatch::{
22 BuiltinReposition, BuiltinStrategy, DispatchStrategy, ElevatorGroup, LineInfo,
23 RepositionStrategy,
24};
25use crate::door::DoorState;
26use crate::entity::EntityId;
27use crate::error::SimError;
28use crate::events::EventBus;
29use crate::hooks::{Phase, PhaseHooks};
30use crate::ids::GroupId;
31use crate::metrics::Metrics;
32use crate::rider_index::RiderIndex;
33use crate::stop::StopId;
34use crate::time::TimeAdapter;
35use crate::topology::TopologyGraph;
36use crate::world::World;
37
38use super::Simulation;
39
40type TopologyResult = (
42 Vec<ElevatorGroup>,
43 BTreeMap<GroupId, Box<dyn DispatchStrategy>>,
44 BTreeMap<GroupId, BuiltinStrategy>,
45);
46
47pub(super) const fn canonical_hall_call_mode(
59 strategy: &BuiltinStrategy,
60) -> Option<crate::dispatch::HallCallMode> {
61 match strategy {
62 BuiltinStrategy::Destination => Some(crate::dispatch::HallCallMode::Destination),
63 BuiltinStrategy::Custom(_) => None,
64 BuiltinStrategy::Scan
65 | BuiltinStrategy::Look
66 | BuiltinStrategy::NearestCar
67 | BuiltinStrategy::Etd
68 | BuiltinStrategy::Rsr => Some(crate::dispatch::HallCallMode::Classic),
69 #[cfg(feature = "loop_lines")]
74 BuiltinStrategy::LoopSweep | BuiltinStrategy::LoopSchedule => {
75 Some(crate::dispatch::HallCallMode::Classic)
76 }
77 }
78}
79
80fn sync_hall_call_modes(
89 groups: &mut [ElevatorGroup],
90 strategy_ids: &BTreeMap<GroupId, BuiltinStrategy>,
91) {
92 for group in groups.iter_mut() {
93 if let Some(strategy) = strategy_ids.get(&group.id())
94 && canonical_hall_call_mode(strategy)
95 == Some(crate::dispatch::HallCallMode::Destination)
96 {
97 group.set_hall_call_mode(crate::dispatch::HallCallMode::Destination);
98 }
99 }
100}
101
102#[allow(clippy::too_many_arguments)]
108pub(super) fn validate_elevator_physics(
109 max_speed: f64,
110 acceleration: f64,
111 deceleration: f64,
112 weight_capacity: f64,
113 inspection_speed_factor: f64,
114 door_transition_ticks: u32,
115 door_open_ticks: u32,
116 bypass_load_up_pct: Option<f64>,
117 bypass_load_down_pct: Option<f64>,
118) -> Result<(), SimError> {
119 if !max_speed.is_finite() || max_speed <= 0.0 {
120 return Err(SimError::InvalidConfig {
121 field: "elevators.max_speed",
122 reason: format!("must be finite and positive, got {max_speed}"),
123 });
124 }
125 if !acceleration.is_finite() || acceleration <= 0.0 {
126 return Err(SimError::InvalidConfig {
127 field: "elevators.acceleration",
128 reason: format!("must be finite and positive, got {acceleration}"),
129 });
130 }
131 if !deceleration.is_finite() || deceleration <= 0.0 {
132 return Err(SimError::InvalidConfig {
133 field: "elevators.deceleration",
134 reason: format!("must be finite and positive, got {deceleration}"),
135 });
136 }
137 if !weight_capacity.is_finite() || weight_capacity <= 0.0 {
138 return Err(SimError::InvalidConfig {
139 field: "elevators.weight_capacity",
140 reason: format!("must be finite and positive, got {weight_capacity}"),
141 });
142 }
143 if !inspection_speed_factor.is_finite() || inspection_speed_factor <= 0.0 {
144 return Err(SimError::InvalidConfig {
145 field: "elevators.inspection_speed_factor",
146 reason: format!("must be finite and positive, got {inspection_speed_factor}"),
147 });
148 }
149 if door_transition_ticks == 0 {
150 return Err(SimError::InvalidConfig {
151 field: "elevators.door_transition_ticks",
152 reason: "must be > 0".into(),
153 });
154 }
155 if door_open_ticks == 0 {
156 return Err(SimError::InvalidConfig {
157 field: "elevators.door_open_ticks",
158 reason: "must be > 0".into(),
159 });
160 }
161 validate_bypass_pct("elevators.bypass_load_up_pct", bypass_load_up_pct)?;
162 validate_bypass_pct("elevators.bypass_load_down_pct", bypass_load_down_pct)?;
163 Ok(())
164}
165
166fn validate_bypass_pct(field: &'static str, pct: Option<f64>) -> Result<(), SimError> {
171 let Some(pct) = pct else {
172 return Ok(());
173 };
174 if !pct.is_finite() || pct <= 0.0 || pct > 1.0 {
175 return Err(SimError::InvalidConfig {
176 field,
177 reason: format!("must be finite in (0.0, 1.0] when set, got {pct}"),
178 });
179 }
180 Ok(())
181}
182
183impl Simulation {
184 pub fn new(
195 config: &SimConfig,
196 dispatch: impl DispatchStrategy + 'static,
197 ) -> Result<Self, SimError> {
198 let mut dispatchers = BTreeMap::new();
199 dispatchers.insert(GroupId(0), Box::new(dispatch) as Box<dyn DispatchStrategy>);
200 Self::new_with_hooks(config, dispatchers, PhaseHooks::default())
201 }
202
203 #[allow(clippy::too_many_lines)]
207 pub(crate) fn new_with_hooks(
208 config: &SimConfig,
209 builder_dispatchers: BTreeMap<GroupId, Box<dyn DispatchStrategy>>,
210 hooks: PhaseHooks,
211 ) -> Result<Self, SimError> {
212 Self::validate_config(config)?;
213
214 let mut world = World::new();
215
216 let mut stop_lookup: HashMap<StopId, EntityId> = HashMap::new();
218 for sc in &config.building.stops {
219 let eid = world.spawn();
220 world.set_stop(
221 eid,
222 Stop {
223 name: sc.name.clone(),
224 position: sc.position,
225 },
226 );
227 world.set_position(eid, Position { value: sc.position });
228 stop_lookup.insert(sc.id, eid);
229 }
230
231 let mut sorted: Vec<(f64, EntityId)> = world
233 .iter_stops()
234 .map(|(eid, stop)| (stop.position, eid))
235 .collect();
236 sorted.sort_by(|a, b| a.0.total_cmp(&b.0));
237 world.insert_resource(crate::world::SortedStops(sorted));
238
239 world.insert_resource(crate::arrival_log::ArrivalLog::default());
249 world.insert_resource(crate::arrival_log::DestinationLog::default());
250 world.insert_resource(crate::arrival_log::CurrentTick::default());
251 world.insert_resource(crate::arrival_log::ArrivalLogRetention::default());
252 world.insert_resource(crate::traffic_detector::TrafficDetector::default());
256 world.insert_resource(crate::dispatch::reposition::RepositionCooldowns::default());
262 world.insert_resource(crate::time::TickRate(config.simulation.ticks_per_second));
268
269 let (mut groups, dispatchers, strategy_ids) =
270 if let Some(line_configs) = &config.building.lines {
271 Self::build_explicit_topology(
272 &mut world,
273 config,
274 line_configs,
275 &stop_lookup,
276 builder_dispatchers,
277 )
278 } else {
279 Self::build_legacy_topology(&mut world, config, &stop_lookup, builder_dispatchers)
280 };
281 sync_hall_call_modes(&mut groups, &strategy_ids);
282
283 let dt = 1.0 / config.simulation.ticks_per_second;
284
285 world.insert_resource(crate::tagged_metrics::MetricTags::default());
286
287 world.register_ext::<crate::dispatch::destination::AssignedCar>(
296 crate::dispatch::destination::ASSIGNED_CAR_KEY,
297 );
298
299 let line_tag_info: Vec<(EntityId, String, Vec<EntityId>)> = groups
302 .iter()
303 .flat_map(|group| {
304 group.lines().iter().filter_map(|li| {
305 let line_comp = world.line(li.entity())?;
306 Some((li.entity(), line_comp.name.clone(), li.elevators().to_vec()))
307 })
308 })
309 .collect();
310
311 if let Some(tags) = world.resource_mut::<crate::tagged_metrics::MetricTags>() {
313 for (line_eid, name, elevators) in &line_tag_info {
314 let tag = format!("line:{name}");
315 tags.tag(*line_eid, tag.clone());
316 for elev_eid in elevators {
317 tags.tag(*elev_eid, tag.clone());
318 }
319 }
320 }
321
322 let mut repositioners: BTreeMap<GroupId, Box<dyn RepositionStrategy>> = BTreeMap::new();
324 let mut reposition_ids: BTreeMap<GroupId, BuiltinReposition> = BTreeMap::new();
325 if let Some(group_configs) = &config.building.groups {
326 for gc in group_configs {
327 if let Some(ref repo_id) = gc.reposition
328 && let Some(strategy) = repo_id.instantiate()
329 {
330 let gid = GroupId(gc.id);
331 repositioners.insert(gid, strategy);
332 reposition_ids.insert(gid, repo_id.clone());
333 }
334 }
335 }
336
337 Ok(Self {
338 world,
339 events: EventBus::default(),
340 pending_output: Vec::new(),
341 tick: 0,
342 dt,
343 groups,
344 stop_lookup,
345 dispatcher_set: super::DispatcherSet::from_parts(dispatchers, strategy_ids),
346 repositioner_set: super::RepositionerSet::from_parts(repositioners, reposition_ids),
347 metrics: Metrics::new(),
348 time: TimeAdapter::new(config.simulation.ticks_per_second),
349 hooks,
350 elevator_ids_buf: Vec::new(),
351 reposition_buf: Vec::new(),
352 dispatch_scratch: crate::dispatch::DispatchScratch::default(),
353 topo_graph: Mutex::new(TopologyGraph::new()),
354 rider_index: RiderIndex::default(),
355 tick_in_progress: false,
356 })
357 }
358
359 fn spawn_elevator_entity(
365 world: &mut World,
366 ec: &crate::config::ElevatorConfig,
367 line: EntityId,
368 stop_lookup: &HashMap<StopId, EntityId>,
369 start_pos_lookup: &[crate::stop::StopConfig],
370 ) -> EntityId {
371 let eid = world.spawn();
372 let start_pos = start_pos_lookup
373 .iter()
374 .find(|s| s.id == ec.starting_stop)
375 .map_or(0.0, |s| s.position);
376 world.set_position(eid, Position { value: start_pos });
377 world.set_velocity(eid, Velocity { value: 0.0 });
378 let restricted: HashSet<EntityId> = ec
379 .restricted_stops
380 .iter()
381 .filter_map(|sid| stop_lookup.get(sid).copied())
382 .collect();
383 world.set_elevator(
384 eid,
385 Elevator {
386 phase: ElevatorPhase::Idle,
387 door: DoorState::Closed,
388 max_speed: ec.max_speed,
389 acceleration: ec.acceleration,
390 deceleration: ec.deceleration,
391 weight_capacity: ec.weight_capacity,
392 current_load: crate::components::Weight::ZERO,
393 riders: Vec::new(),
394 target_stop: None,
395 door_transition_ticks: ec.door_transition_ticks,
396 door_open_ticks: ec.door_open_ticks,
397 line,
398 repositioning: false,
399 restricted_stops: restricted,
400 inspection_speed_factor: ec.inspection_speed_factor,
401 going_up: true,
402 going_down: true,
403 going_forward: false,
404 move_count: 0,
405 door_command_queue: Vec::new(),
406 manual_target_velocity: None,
407 bypass_load_up_pct: ec.bypass_load_up_pct,
408 bypass_load_down_pct: ec.bypass_load_down_pct,
409 home_stop: None,
410 },
411 );
412 #[cfg(feature = "energy")]
413 if let Some(ref profile) = ec.energy_profile {
414 world.set_energy_profile(eid, profile.clone());
415 world.set_energy_metrics(eid, crate::energy::EnergyMetrics::default());
416 }
417 if let Some(mode) = ec.service_mode {
418 world.set_service_mode(eid, mode);
419 }
420 world.set_destination_queue(eid, crate::components::DestinationQueue::new());
421 eid
422 }
423
424 fn build_legacy_topology(
426 world: &mut World,
427 config: &SimConfig,
428 stop_lookup: &HashMap<StopId, EntityId>,
429 builder_dispatchers: BTreeMap<GroupId, Box<dyn DispatchStrategy>>,
430 ) -> TopologyResult {
431 let all_stop_entities: Vec<EntityId> = config
437 .building
438 .stops
439 .iter()
440 .filter_map(|s| stop_lookup.get(&s.id).copied())
441 .collect();
442 let stop_positions: Vec<f64> = config.building.stops.iter().map(|s| s.position).collect();
443 let min_pos = stop_positions.iter().copied().fold(f64::INFINITY, f64::min);
444 let max_pos = stop_positions
445 .iter()
446 .copied()
447 .fold(f64::NEG_INFINITY, f64::max);
448
449 let default_line_eid = world.spawn();
450 world.set_line(
451 default_line_eid,
452 Line {
453 name: "Default".into(),
454 group: GroupId(0),
455 orientation: Orientation::Vertical,
456 position: None,
457 kind: LineKind::Linear {
458 min: min_pos,
459 max: max_pos,
460 },
461 max_cars: None,
462 },
463 );
464
465 let mut elevator_entities = Vec::new();
466 for ec in &config.elevators {
467 let eid = Self::spawn_elevator_entity(
468 world,
469 ec,
470 default_line_eid,
471 stop_lookup,
472 &config.building.stops,
473 );
474 elevator_entities.push(eid);
475 }
476
477 let default_line_info =
478 LineInfo::new(default_line_eid, elevator_entities, all_stop_entities);
479
480 let group = ElevatorGroup::new(GroupId(0), "Default".into(), vec![default_line_info]);
481
482 let mut dispatchers = BTreeMap::new();
486 let mut strategy_ids = BTreeMap::new();
487 let user_dispatcher = builder_dispatchers
488 .into_iter()
489 .find_map(|(gid, d)| if gid == GroupId(0) { Some(d) } else { None });
490 let inferred_id = user_dispatcher
495 .as_ref()
496 .and_then(|d| d.builtin_id())
497 .unwrap_or(BuiltinStrategy::Scan);
498 if let Some(d) = user_dispatcher {
499 dispatchers.insert(GroupId(0), d);
500 } else {
501 dispatchers.insert(
502 GroupId(0),
503 Box::new(crate::dispatch::scan::ScanDispatch::new()) as Box<dyn DispatchStrategy>,
504 );
505 }
506 strategy_ids.insert(GroupId(0), inferred_id);
507
508 (vec![group], dispatchers, strategy_ids)
509 }
510
511 #[allow(clippy::too_many_lines)]
513 fn build_explicit_topology(
514 world: &mut World,
515 config: &SimConfig,
516 line_configs: &[crate::config::LineConfig],
517 stop_lookup: &HashMap<StopId, EntityId>,
518 builder_dispatchers: BTreeMap<GroupId, Box<dyn DispatchStrategy>>,
519 ) -> TopologyResult {
520 let mut line_map: BTreeMap<u32, (EntityId, LineInfo)> = BTreeMap::new();
526
527 for lc in line_configs {
528 let served_entities: Vec<EntityId> = lc
530 .serves
531 .iter()
532 .filter_map(|sid| stop_lookup.get(sid).copied())
533 .collect();
534
535 let stop_positions: Vec<f64> = lc
537 .serves
538 .iter()
539 .filter_map(|sid| {
540 config
541 .building
542 .stops
543 .iter()
544 .find(|s| s.id == *sid)
545 .map(|s| s.position)
546 })
547 .collect();
548 let auto_min = stop_positions.iter().copied().fold(f64::INFINITY, f64::min);
549 let auto_max = stop_positions
550 .iter()
551 .copied()
552 .fold(f64::NEG_INFINITY, f64::max);
553
554 let min_pos = lc.min_position.unwrap_or(auto_min);
555 let max_pos = lc.max_position.unwrap_or(auto_max);
556
557 let line_eid = world.spawn();
558 world.set_line(
562 line_eid,
563 Line {
564 name: lc.name.clone(),
565 group: GroupId(0),
566 orientation: lc.orientation,
567 position: lc.position,
568 kind: lc.kind.unwrap_or(LineKind::Linear {
569 min: min_pos,
570 max: max_pos,
571 }),
572 max_cars: lc.max_cars,
573 },
574 );
575
576 let mut elevator_entities = Vec::new();
578 for ec in &lc.elevators {
579 let eid = Self::spawn_elevator_entity(
580 world,
581 ec,
582 line_eid,
583 stop_lookup,
584 &config.building.stops,
585 );
586 elevator_entities.push(eid);
587 }
588
589 let line_info = LineInfo::new(line_eid, elevator_entities, served_entities);
590 line_map.insert(lc.id, (line_eid, line_info));
591 }
592
593 let group_configs = config.building.groups.as_deref();
595 let mut groups = Vec::new();
596 let mut dispatchers = BTreeMap::new();
597 let mut strategy_ids = BTreeMap::new();
598
599 if let Some(gcs) = group_configs {
600 for gc in gcs {
601 let group_id = GroupId(gc.id);
602
603 let mut group_lines = Vec::new();
604
605 for &lid in &gc.lines {
606 if let Some((line_eid, li)) = line_map.get(&lid) {
607 if let Some(line_comp) = world.line_mut(*line_eid) {
609 line_comp.group = group_id;
610 }
611 group_lines.push(li.clone());
612 }
613 }
614
615 let mut group = ElevatorGroup::new(group_id, gc.name.clone(), group_lines);
616 if let Some(mode) = gc.hall_call_mode {
617 group.set_hall_call_mode(mode);
618 }
619 if let Some(ticks) = gc.ack_latency_ticks {
620 group.set_ack_latency_ticks(ticks);
621 }
622 groups.push(group);
623
624 let dispatch: Box<dyn DispatchStrategy> = gc
626 .dispatch
627 .instantiate()
628 .unwrap_or_else(|| Box::new(crate::dispatch::scan::ScanDispatch::new()));
629 dispatchers.insert(group_id, dispatch);
630 strategy_ids.insert(group_id, gc.dispatch.clone());
631 }
632 } else {
633 let group_id = GroupId(0);
635 let mut group_lines = Vec::new();
636
637 for (line_eid, li) in line_map.values() {
638 if let Some(line_comp) = world.line_mut(*line_eid) {
639 line_comp.group = group_id;
640 }
641 group_lines.push(li.clone());
642 }
643
644 let group = ElevatorGroup::new(group_id, "Default".into(), group_lines);
645 groups.push(group);
646
647 let dispatch: Box<dyn DispatchStrategy> =
648 Box::new(crate::dispatch::scan::ScanDispatch::new());
649 dispatchers.insert(group_id, dispatch);
650 strategy_ids.insert(group_id, BuiltinStrategy::Scan);
651 }
652
653 for (gid, d) in builder_dispatchers {
658 let inferred_id = d.builtin_id();
659 dispatchers.insert(gid, d);
660 match inferred_id {
661 Some(id) => {
662 strategy_ids.insert(gid, id);
663 }
664 None => {
665 strategy_ids
666 .entry(gid)
667 .or_insert_with(|| BuiltinStrategy::Custom("user-supplied".into()));
668 }
669 }
670 }
671
672 (groups, dispatchers, strategy_ids)
673 }
674
675 #[allow(clippy::too_many_arguments)]
677 pub(crate) fn from_parts(
678 world: World,
679 tick: u64,
680 dt: f64,
681 groups: Vec<ElevatorGroup>,
682 stop_lookup: HashMap<StopId, EntityId>,
683 dispatchers: BTreeMap<GroupId, Box<dyn DispatchStrategy>>,
684 strategy_ids: BTreeMap<GroupId, crate::dispatch::BuiltinStrategy>,
685 metrics: Metrics,
686 ticks_per_second: f64,
687 ) -> Self {
688 let mut rider_index = RiderIndex::default();
689 rider_index.rebuild(&world);
690 let mut world = world;
696 world.insert_resource(crate::time::TickRate(ticks_per_second));
697 if world
698 .resource::<crate::traffic_detector::TrafficDetector>()
699 .is_none()
700 {
701 world.insert_resource(crate::traffic_detector::TrafficDetector::default());
702 }
703 if world
708 .resource::<crate::arrival_log::DestinationLog>()
709 .is_none()
710 {
711 world.insert_resource(crate::arrival_log::DestinationLog::default());
712 }
713 world.register_ext::<crate::dispatch::destination::AssignedCar>(
728 crate::dispatch::destination::ASSIGNED_CAR_KEY,
729 );
730 if let Some(pending) = world.resource::<crate::snapshot::PendingExtensions>() {
731 let data = pending.0.clone();
732 world.deserialize_extensions(&data);
733 }
734 Self {
735 world,
736 events: EventBus::default(),
737 pending_output: Vec::new(),
738 tick,
739 dt,
740 groups,
741 stop_lookup,
742 dispatcher_set: super::DispatcherSet::from_parts(dispatchers, strategy_ids),
743 repositioner_set: super::RepositionerSet::new(),
744 metrics,
745 time: TimeAdapter::new(ticks_per_second),
746 hooks: PhaseHooks::default(),
747 elevator_ids_buf: Vec::new(),
748 reposition_buf: Vec::new(),
749 dispatch_scratch: crate::dispatch::DispatchScratch::default(),
750 topo_graph: Mutex::new(TopologyGraph::new()),
751 rider_index,
752 tick_in_progress: false,
753 }
754 }
755
756 pub(crate) fn validate_config(config: &SimConfig) -> Result<(), SimError> {
758 if config.schema_version > crate::config::CURRENT_CONFIG_SCHEMA_VERSION {
765 return Err(SimError::InvalidConfig {
766 field: "schema_version",
767 reason: format!(
768 "config schema_version={} is newer than this build's CURRENT_CONFIG_SCHEMA_VERSION={}; upgrade elevator-core or downgrade the config",
769 config.schema_version,
770 crate::config::CURRENT_CONFIG_SCHEMA_VERSION,
771 ),
772 });
773 }
774 if config.schema_version == 0 {
775 return Err(SimError::InvalidConfig {
776 field: "schema_version",
777 reason: format!(
778 "config schema_version=0 (pre-versioning legacy file) — set schema_version: {} explicitly after auditing field defaults; see docs/src/config-versioning.md",
779 crate::config::CURRENT_CONFIG_SCHEMA_VERSION,
780 ),
781 });
782 }
783
784 if config.building.stops.is_empty() {
785 return Err(SimError::InvalidConfig {
786 field: "building.stops",
787 reason: "at least one stop is required".into(),
788 });
789 }
790
791 let mut seen_ids = HashSet::new();
793 for stop in &config.building.stops {
794 if !seen_ids.insert(stop.id) {
795 return Err(SimError::InvalidConfig {
796 field: "building.stops",
797 reason: format!("duplicate {}", stop.id),
798 });
799 }
800 if !stop.position.is_finite() {
801 return Err(SimError::InvalidConfig {
802 field: "building.stops.position",
803 reason: format!("{} has non-finite position {}", stop.id, stop.position),
804 });
805 }
806 }
807
808 let stop_ids: HashSet<StopId> = config.building.stops.iter().map(|s| s.id).collect();
809
810 if let Some(line_configs) = &config.building.lines {
811 Self::validate_explicit_topology(line_configs, &stop_ids, &config.building)?;
813 } else {
814 Self::validate_legacy_elevators(&config.elevators, &config.building)?;
816 }
817
818 if !config.simulation.ticks_per_second.is_finite()
819 || config.simulation.ticks_per_second <= 0.0
820 {
821 return Err(SimError::InvalidConfig {
822 field: "simulation.ticks_per_second",
823 reason: format!(
824 "must be finite and positive, got {}",
825 config.simulation.ticks_per_second
826 ),
827 });
828 }
829
830 Self::validate_passenger_spawning(&config.passenger_spawning)?;
831
832 Ok(())
833 }
834
835 fn validate_passenger_spawning(
840 spawn: &crate::config::PassengerSpawnConfig,
841 ) -> Result<(), SimError> {
842 let (lo, hi) = spawn.weight_range;
843 if !lo.is_finite() || !hi.is_finite() {
844 return Err(SimError::InvalidConfig {
845 field: "passenger_spawning.weight_range",
846 reason: format!("both endpoints must be finite, got ({lo}, {hi})"),
847 });
848 }
849 if lo < 0.0 || hi < 0.0 {
850 return Err(SimError::InvalidConfig {
851 field: "passenger_spawning.weight_range",
852 reason: format!("both endpoints must be non-negative, got ({lo}, {hi})"),
853 });
854 }
855 if lo > hi {
856 return Err(SimError::InvalidConfig {
857 field: "passenger_spawning.weight_range",
858 reason: format!("min must be <= max, got ({lo}, {hi})"),
859 });
860 }
861 if spawn.mean_interval_ticks == 0 {
862 return Err(SimError::InvalidConfig {
863 field: "passenger_spawning.mean_interval_ticks",
864 reason: "must be > 0; mean_interval_ticks=0 burst-fires \
865 every catch-up tick"
866 .into(),
867 });
868 }
869 Ok(())
870 }
871
872 fn validate_legacy_elevators(
874 elevators: &[crate::config::ElevatorConfig],
875 building: &crate::config::BuildingConfig,
876 ) -> Result<(), SimError> {
877 if elevators.is_empty() {
878 return Err(SimError::InvalidConfig {
879 field: "elevators",
880 reason: "at least one elevator is required".into(),
881 });
882 }
883
884 for elev in elevators {
885 Self::validate_elevator_config(elev, building)?;
886 }
887
888 Ok(())
889 }
890
891 fn validate_elevator_config(
893 elev: &crate::config::ElevatorConfig,
894 building: &crate::config::BuildingConfig,
895 ) -> Result<(), SimError> {
896 validate_elevator_physics(
897 elev.max_speed.value(),
898 elev.acceleration.value(),
899 elev.deceleration.value(),
900 elev.weight_capacity.value(),
901 elev.inspection_speed_factor,
902 elev.door_transition_ticks,
903 elev.door_open_ticks,
904 elev.bypass_load_up_pct,
905 elev.bypass_load_down_pct,
906 )?;
907 if !building.stops.iter().any(|s| s.id == elev.starting_stop) {
908 return Err(SimError::InvalidConfig {
909 field: "elevators.starting_stop",
910 reason: format!("references non-existent {}", elev.starting_stop),
911 });
912 }
913 Ok(())
914 }
915
916 #[allow(
918 clippy::too_many_lines,
919 reason = "validation reads top-to-bottom; extracting helpers would scatter related rejections across files"
920 )]
921 fn validate_explicit_topology(
922 line_configs: &[crate::config::LineConfig],
923 stop_ids: &HashSet<StopId>,
924 building: &crate::config::BuildingConfig,
925 ) -> Result<(), SimError> {
926 let mut seen_line_ids = HashSet::new();
928 for lc in line_configs {
929 if !seen_line_ids.insert(lc.id) {
930 return Err(SimError::InvalidConfig {
931 field: "building.lines",
932 reason: format!("duplicate line id {}", lc.id),
933 });
934 }
935 }
936
937 for lc in line_configs {
939 if lc.serves.is_empty() {
940 return Err(SimError::InvalidConfig {
941 field: "building.lines.serves",
942 reason: format!("line {} has no stops", lc.id),
943 });
944 }
945 for sid in &lc.serves {
946 if !stop_ids.contains(sid) {
947 return Err(SimError::InvalidConfig {
948 field: "building.lines.serves",
949 reason: format!("line {} references non-existent {}", lc.id, sid),
950 });
951 }
952 }
953 for ec in &lc.elevators {
955 Self::validate_elevator_config(ec, building)?;
956 }
957
958 if let Some(max) = lc.max_cars
960 && lc.elevators.len() > max
961 {
962 return Err(SimError::InvalidConfig {
963 field: "building.lines.max_cars",
964 reason: format!(
965 "line {} has {} elevators but max_cars is {max}",
966 lc.id,
967 lc.elevators.len()
968 ),
969 });
970 }
971
972 if let Some(kind) = lc.kind
976 && let Err((field, reason)) = kind.validate()
977 {
978 return Err(SimError::InvalidConfig { field, reason });
979 }
980
981 #[cfg(feature = "loop_lines")]
988 if let Some(crate::components::LineKind::Loop {
989 circumference,
990 min_headway,
991 }) = lc.kind
992 {
993 let car_count = lc
994 .max_cars
995 .map_or_else(|| lc.elevators.len(), |max| max.max(lc.elevators.len()));
996 if car_count > 0 {
997 #[allow(
998 clippy::cast_precision_loss,
999 reason = "car_count is bounded by usize and the comparison is against a finite f64"
1000 )]
1001 let required = (car_count as f64) * min_headway;
1002 if required > circumference {
1003 return Err(SimError::InvalidConfig {
1004 field: "building.lines.kind",
1005 reason: format!(
1006 "loop line {}: {car_count} cars × min_headway {min_headway} = {required} \
1007 exceeds circumference {circumference}",
1008 lc.id,
1009 ),
1010 });
1011 }
1012 }
1013 }
1014 }
1015
1016 let has_elevator = line_configs.iter().any(|lc| !lc.elevators.is_empty());
1018 if !has_elevator {
1019 return Err(SimError::InvalidConfig {
1020 field: "building.lines",
1021 reason: "at least one line must have at least one elevator".into(),
1022 });
1023 }
1024
1025 let served: HashSet<StopId> = line_configs
1027 .iter()
1028 .flat_map(|lc| lc.serves.iter().copied())
1029 .collect();
1030 for sid in stop_ids {
1031 if !served.contains(sid) {
1032 return Err(SimError::InvalidConfig {
1033 field: "building.lines",
1034 reason: format!("orphaned stop {sid} not served by any line"),
1035 });
1036 }
1037 }
1038
1039 if let Some(group_configs) = &building.groups {
1041 let line_id_set: HashSet<u32> = line_configs.iter().map(|lc| lc.id).collect();
1042
1043 let mut seen_group_ids = HashSet::new();
1044 for gc in group_configs {
1045 if !seen_group_ids.insert(gc.id) {
1046 return Err(SimError::InvalidConfig {
1047 field: "building.groups",
1048 reason: format!("duplicate group id {}", gc.id),
1049 });
1050 }
1051 for &lid in &gc.lines {
1052 if !line_id_set.contains(&lid) {
1053 return Err(SimError::InvalidConfig {
1054 field: "building.groups.lines",
1055 reason: format!(
1056 "group {} references non-existent line id {}",
1057 gc.id, lid
1058 ),
1059 });
1060 }
1061 }
1062 }
1063
1064 let referenced_line_ids: HashSet<u32> = group_configs
1066 .iter()
1067 .flat_map(|g| g.lines.iter().copied())
1068 .collect();
1069 for lc in line_configs {
1070 if !referenced_line_ids.contains(&lc.id) {
1071 return Err(SimError::InvalidConfig {
1072 field: "building.lines",
1073 reason: format!("line {} is not assigned to any group", lc.id),
1074 });
1075 }
1076 }
1077
1078 #[cfg(feature = "loop_lines")]
1084 for gc in group_configs {
1085 let lines: Vec<&crate::config::LineConfig> = gc
1086 .lines
1087 .iter()
1088 .filter_map(|lid| line_configs.iter().find(|lc| lc.id == *lid))
1089 .collect();
1090 let any_loop = lines
1091 .iter()
1092 .any(|lc| matches!(lc.kind, Some(crate::components::LineKind::Loop { .. })));
1093 let any_linear = lines
1101 .iter()
1102 .any(|lc| lc.kind.as_ref().is_none_or(LineKind::is_linear));
1103 if any_loop && any_linear {
1108 return Err(SimError::InvalidConfig {
1109 field: "building.groups",
1110 reason: format!(
1111 "group {} mixes Loop and Linear lines; groups must be homogeneous",
1112 gc.id,
1113 ),
1114 });
1115 }
1116 if any_loop && gc.reposition.is_some() {
1122 return Err(SimError::InvalidConfig {
1123 field: "building.groups.reposition",
1124 reason: format!(
1125 "group {} contains Loop lines; reposition strategies are unsupported on Loop",
1126 gc.id,
1127 ),
1128 });
1129 }
1130 if any_loop
1138 && !matches!(
1139 gc.dispatch,
1140 BuiltinStrategy::LoopSweep | BuiltinStrategy::LoopSchedule,
1141 )
1142 {
1143 return Err(SimError::InvalidConfig {
1144 field: "building.groups.dispatch",
1145 reason: format!(
1146 "group {} contains Loop lines but uses {} dispatch; \
1147 only LoopSweep or LoopSchedule is supported for Loop groups",
1148 gc.id, gc.dispatch,
1149 ),
1150 });
1151 }
1152 }
1153 }
1154
1155 #[cfg(feature = "loop_lines")]
1158 for lc in line_configs {
1159 let Some(crate::components::LineKind::Loop {
1160 circumference,
1161 min_headway,
1162 }) = lc.kind
1163 else {
1164 continue;
1165 };
1166
1167 let stop_positions: Vec<f64> = lc
1172 .serves
1173 .iter()
1174 .filter_map(|sid| {
1175 building
1176 .stops
1177 .iter()
1178 .find(|s| s.id == *sid)
1179 .map(|s| s.position)
1180 })
1181 .collect();
1182 for (i, &pi) in stop_positions.iter().enumerate() {
1183 for (j, &pj) in stop_positions.iter().enumerate().skip(i + 1) {
1184 if (pi - pj).abs() < 1e-9 {
1185 return Err(SimError::InvalidConfig {
1186 field: "building.lines.serves",
1187 reason: format!(
1188 "loop line {} has duplicate stop positions at indices {i} and {j} (both at {pi})",
1189 lc.id,
1190 ),
1191 });
1192 }
1193 }
1194 }
1195
1196 let car_starts: Vec<f64> = lc
1202 .elevators
1203 .iter()
1204 .filter_map(|ec| {
1205 building
1206 .stops
1207 .iter()
1208 .find(|s| s.id == ec.starting_stop)
1209 .map(|s| s.position)
1210 })
1211 .collect();
1212 for (i, &a) in car_starts.iter().enumerate() {
1213 for (j, &b) in car_starts.iter().enumerate().skip(i + 1) {
1214 let d = crate::components::cyclic::cyclic_distance(a, b, circumference);
1215 if d < min_headway - 1e-9 {
1216 return Err(SimError::InvalidConfig {
1217 field: "building.lines.elevators.starting_stop",
1218 reason: format!(
1219 "loop line {}: cars at indices {i} ({a}) and {j} ({b}) are {d} apart \
1220 — below min_headway {min_headway}",
1221 lc.id,
1222 ),
1223 });
1224 }
1225 }
1226 }
1227 }
1228
1229 Ok(())
1230 }
1231
1232 pub fn set_dispatch(
1248 &mut self,
1249 group: GroupId,
1250 strategy: Box<dyn DispatchStrategy>,
1251 id: crate::dispatch::BuiltinStrategy,
1252 ) {
1253 let resolved_id = strategy.builtin_id().unwrap_or(id);
1254 if let Some(mode) = canonical_hall_call_mode(&resolved_id)
1255 && let Some(g) = self.groups.iter_mut().find(|g| g.id() == group)
1256 {
1257 g.set_hall_call_mode(mode);
1258 }
1259 self.dispatcher_set.insert(group, strategy, resolved_id);
1260 }
1261
1262 pub fn set_reposition(
1293 &mut self,
1294 group: GroupId,
1295 strategy: Box<dyn RepositionStrategy>,
1296 id: BuiltinReposition,
1297 ) {
1298 let resolved_id = strategy.builtin_id().unwrap_or(id);
1299 let needed_window = strategy.min_arrival_log_window();
1300 self.repositioner_set.insert(group, strategy, resolved_id);
1301 if needed_window > 0
1307 && let Some(retention) = self
1308 .world
1309 .resource_mut::<crate::arrival_log::ArrivalLogRetention>()
1310 && needed_window > retention.0
1311 {
1312 retention.0 = needed_window;
1313 }
1314 }
1315
1316 pub fn remove_reposition(&mut self, group: GroupId) {
1327 self.repositioner_set.remove(group);
1328 }
1329
1330 #[must_use]
1332 pub fn reposition_id(&self, group: GroupId) -> Option<&BuiltinReposition> {
1333 self.repositioner_set.id_for(group)
1334 }
1335
1336 pub fn add_before_hook(
1343 &mut self,
1344 phase: Phase,
1345 hook: impl Fn(&mut World) + Send + Sync + 'static,
1346 ) {
1347 self.hooks.add_before(phase, Box::new(hook));
1348 }
1349
1350 pub fn add_after_hook(
1355 &mut self,
1356 phase: Phase,
1357 hook: impl Fn(&mut World) + Send + Sync + 'static,
1358 ) {
1359 self.hooks.add_after(phase, Box::new(hook));
1360 }
1361
1362 pub fn add_before_group_hook(
1364 &mut self,
1365 phase: Phase,
1366 group: GroupId,
1367 hook: impl Fn(&mut World) + Send + Sync + 'static,
1368 ) {
1369 self.hooks.add_before_group(phase, group, Box::new(hook));
1370 }
1371
1372 pub fn add_after_group_hook(
1374 &mut self,
1375 phase: Phase,
1376 group: GroupId,
1377 hook: impl Fn(&mut World) + Send + Sync + 'static,
1378 ) {
1379 self.hooks.add_after_group(phase, group, Box::new(hook));
1380 }
1381}