1use 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
38type TopologyResult = (
40 Vec<ElevatorGroup>,
41 BTreeMap<GroupId, Box<dyn DispatchStrategy>>,
42 BTreeMap<GroupId, BuiltinStrategy>,
43);
44
45fn 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#[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
128fn 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 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 #[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 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 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 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 world.insert_resource(crate::traffic_detector::TrafficDetector::default());
214 world.insert_resource(crate::dispatch::reposition::RepositionCooldowns::default());
220 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 world.register_ext::<crate::dispatch::destination::AssignedCar>(
254 crate::dispatch::destination::ASSIGNED_CAR_KEY,
255 );
256
257 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 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 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 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 },
369 );
370 #[cfg(feature = "energy")]
371 if let Some(ref profile) = ec.energy_profile {
372 world.set_energy_profile(eid, profile.clone());
373 world.set_energy_metrics(eid, crate::energy::EnergyMetrics::default());
374 }
375 if let Some(mode) = ec.service_mode {
376 world.set_service_mode(eid, mode);
377 }
378 world.set_destination_queue(eid, crate::components::DestinationQueue::new());
379 eid
380 }
381
382 fn build_legacy_topology(
384 world: &mut World,
385 config: &SimConfig,
386 stop_lookup: &HashMap<StopId, EntityId>,
387 builder_dispatchers: BTreeMap<GroupId, Box<dyn DispatchStrategy>>,
388 ) -> TopologyResult {
389 let all_stop_entities: Vec<EntityId> = stop_lookup.values().copied().collect();
390 let stop_positions: Vec<f64> = config.building.stops.iter().map(|s| s.position).collect();
391 let min_pos = stop_positions.iter().copied().fold(f64::INFINITY, f64::min);
392 let max_pos = stop_positions
393 .iter()
394 .copied()
395 .fold(f64::NEG_INFINITY, f64::max);
396
397 let default_line_eid = world.spawn();
398 world.set_line(
399 default_line_eid,
400 Line {
401 name: "Default".into(),
402 group: GroupId(0),
403 orientation: Orientation::Vertical,
404 position: None,
405 min_position: min_pos,
406 max_position: max_pos,
407 max_cars: None,
408 },
409 );
410
411 let mut elevator_entities = Vec::new();
412 for ec in &config.elevators {
413 let eid = Self::spawn_elevator_entity(
414 world,
415 ec,
416 default_line_eid,
417 stop_lookup,
418 &config.building.stops,
419 );
420 elevator_entities.push(eid);
421 }
422
423 let default_line_info =
424 LineInfo::new(default_line_eid, elevator_entities, all_stop_entities);
425
426 let group = ElevatorGroup::new(GroupId(0), "Default".into(), vec![default_line_info]);
427
428 let mut dispatchers = BTreeMap::new();
435 let mut strategy_ids = BTreeMap::new();
436 let user_dispatcher = builder_dispatchers
437 .into_iter()
438 .find_map(|(gid, d)| if gid == GroupId(0) { Some(d) } else { None });
439 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 #[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 let mut line_map: HashMap<u32, (EntityId, LineInfo)> = HashMap::new();
479
480 for lc in line_configs {
481 let served_entities: Vec<EntityId> = lc
483 .serves
484 .iter()
485 .filter_map(|sid| stop_lookup.get(sid).copied())
486 .collect();
487
488 let stop_positions: Vec<f64> = lc
490 .serves
491 .iter()
492 .filter_map(|sid| {
493 config
494 .building
495 .stops
496 .iter()
497 .find(|s| s.id == *sid)
498 .map(|s| s.position)
499 })
500 .collect();
501 let auto_min = stop_positions.iter().copied().fold(f64::INFINITY, f64::min);
502 let auto_max = stop_positions
503 .iter()
504 .copied()
505 .fold(f64::NEG_INFINITY, f64::max);
506
507 let min_pos = lc.min_position.unwrap_or(auto_min);
508 let max_pos = lc.max_position.unwrap_or(auto_max);
509
510 let line_eid = world.spawn();
511 world.set_line(
514 line_eid,
515 Line {
516 name: lc.name.clone(),
517 group: GroupId(0),
518 orientation: lc.orientation,
519 position: lc.position,
520 min_position: min_pos,
521 max_position: max_pos,
522 max_cars: lc.max_cars,
523 },
524 );
525
526 let mut elevator_entities = Vec::new();
528 for ec in &lc.elevators {
529 let eid = Self::spawn_elevator_entity(
530 world,
531 ec,
532 line_eid,
533 stop_lookup,
534 &config.building.stops,
535 );
536 elevator_entities.push(eid);
537 }
538
539 let line_info = LineInfo::new(line_eid, elevator_entities, served_entities);
540 line_map.insert(lc.id, (line_eid, line_info));
541 }
542
543 let group_configs = config.building.groups.as_deref();
545 let mut groups = Vec::new();
546 let mut dispatchers = BTreeMap::new();
547 let mut strategy_ids = BTreeMap::new();
548
549 if let Some(gcs) = group_configs {
550 for gc in gcs {
551 let group_id = GroupId(gc.id);
552
553 let mut group_lines = Vec::new();
554
555 for &lid in &gc.lines {
556 if let Some((line_eid, li)) = line_map.get(&lid) {
557 if let Some(line_comp) = world.line_mut(*line_eid) {
559 line_comp.group = group_id;
560 }
561 group_lines.push(li.clone());
562 }
563 }
564
565 let mut group = ElevatorGroup::new(group_id, gc.name.clone(), group_lines);
566 if let Some(mode) = gc.hall_call_mode {
567 group.set_hall_call_mode(mode);
568 }
569 if let Some(ticks) = gc.ack_latency_ticks {
570 group.set_ack_latency_ticks(ticks);
571 }
572 groups.push(group);
573
574 let dispatch: Box<dyn DispatchStrategy> = gc
576 .dispatch
577 .instantiate()
578 .unwrap_or_else(|| Box::new(crate::dispatch::scan::ScanDispatch::new()));
579 dispatchers.insert(group_id, dispatch);
580 strategy_ids.insert(group_id, gc.dispatch.clone());
581 }
582 } else {
583 let group_id = GroupId(0);
585 let mut group_lines = Vec::new();
586
587 for (line_eid, li) in line_map.values() {
588 if let Some(line_comp) = world.line_mut(*line_eid) {
589 line_comp.group = group_id;
590 }
591 group_lines.push(li.clone());
592 }
593
594 let group = ElevatorGroup::new(group_id, "Default".into(), group_lines);
595 groups.push(group);
596
597 let dispatch: Box<dyn DispatchStrategy> =
598 Box::new(crate::dispatch::scan::ScanDispatch::new());
599 dispatchers.insert(group_id, dispatch);
600 strategy_ids.insert(group_id, BuiltinStrategy::Scan);
601 }
602
603 for (gid, d) in builder_dispatchers {
613 let inferred_id = d.builtin_id();
614 dispatchers.insert(gid, d);
615 match inferred_id {
616 Some(id) => {
617 strategy_ids.insert(gid, id);
618 }
619 None => {
620 strategy_ids
621 .entry(gid)
622 .or_insert_with(|| BuiltinStrategy::Custom("user-supplied".into()));
623 }
624 }
625 }
626
627 (groups, dispatchers, strategy_ids)
628 }
629
630 #[allow(clippy::too_many_arguments)]
632 pub(crate) fn from_parts(
633 world: World,
634 tick: u64,
635 dt: f64,
636 groups: Vec<ElevatorGroup>,
637 stop_lookup: HashMap<StopId, EntityId>,
638 dispatchers: BTreeMap<GroupId, Box<dyn DispatchStrategy>>,
639 strategy_ids: BTreeMap<GroupId, crate::dispatch::BuiltinStrategy>,
640 metrics: Metrics,
641 ticks_per_second: f64,
642 ) -> Self {
643 let mut rider_index = RiderIndex::default();
644 rider_index.rebuild(&world);
645 let mut world = world;
651 world.insert_resource(crate::time::TickRate(ticks_per_second));
652 if world
660 .resource::<crate::traffic_detector::TrafficDetector>()
661 .is_none()
662 {
663 world.insert_resource(crate::traffic_detector::TrafficDetector::default());
664 }
665 if world
670 .resource::<crate::arrival_log::DestinationLog>()
671 .is_none()
672 {
673 world.insert_resource(crate::arrival_log::DestinationLog::default());
674 }
675 world.register_ext::<crate::dispatch::destination::AssignedCar>(
690 crate::dispatch::destination::ASSIGNED_CAR_KEY,
691 );
692 if let Some(pending) = world.resource::<crate::snapshot::PendingExtensions>() {
693 let data = pending.0.clone();
694 world.deserialize_extensions(&data);
695 }
696 Self {
697 world,
698 events: EventBus::default(),
699 pending_output: Vec::new(),
700 tick,
701 dt,
702 groups,
703 stop_lookup,
704 dispatchers,
705 strategy_ids,
706 repositioners: BTreeMap::new(),
707 reposition_ids: BTreeMap::new(),
708 metrics,
709 time: TimeAdapter::new(ticks_per_second),
710 hooks: PhaseHooks::default(),
711 elevator_ids_buf: Vec::new(),
712 reposition_buf: Vec::new(),
713 dispatch_scratch: crate::dispatch::DispatchScratch::default(),
714 topo_graph: Mutex::new(TopologyGraph::new()),
715 rider_index,
716 tick_in_progress: false,
717 }
718 }
719
720 pub(crate) fn validate_config(config: &SimConfig) -> Result<(), SimError> {
722 if config.building.stops.is_empty() {
723 return Err(SimError::InvalidConfig {
724 field: "building.stops",
725 reason: "at least one stop is required".into(),
726 });
727 }
728
729 let mut seen_ids = HashSet::new();
731 for stop in &config.building.stops {
732 if !seen_ids.insert(stop.id) {
733 return Err(SimError::InvalidConfig {
734 field: "building.stops",
735 reason: format!("duplicate {}", stop.id),
736 });
737 }
738 if !stop.position.is_finite() {
739 return Err(SimError::InvalidConfig {
740 field: "building.stops.position",
741 reason: format!("{} has non-finite position {}", stop.id, stop.position),
742 });
743 }
744 }
745
746 let stop_ids: HashSet<StopId> = config.building.stops.iter().map(|s| s.id).collect();
747
748 if let Some(line_configs) = &config.building.lines {
749 Self::validate_explicit_topology(line_configs, &stop_ids, &config.building)?;
751 } else {
752 Self::validate_legacy_elevators(&config.elevators, &config.building)?;
754 }
755
756 if !config.simulation.ticks_per_second.is_finite()
757 || config.simulation.ticks_per_second <= 0.0
758 {
759 return Err(SimError::InvalidConfig {
760 field: "simulation.ticks_per_second",
761 reason: format!(
762 "must be finite and positive, got {}",
763 config.simulation.ticks_per_second
764 ),
765 });
766 }
767
768 Self::validate_passenger_spawning(&config.passenger_spawning)?;
769
770 Ok(())
771 }
772
773 fn validate_passenger_spawning(
778 spawn: &crate::config::PassengerSpawnConfig,
779 ) -> Result<(), SimError> {
780 let (lo, hi) = spawn.weight_range;
781 if !lo.is_finite() || !hi.is_finite() {
782 return Err(SimError::InvalidConfig {
783 field: "passenger_spawning.weight_range",
784 reason: format!("both endpoints must be finite, got ({lo}, {hi})"),
785 });
786 }
787 if lo < 0.0 || hi < 0.0 {
788 return Err(SimError::InvalidConfig {
789 field: "passenger_spawning.weight_range",
790 reason: format!("both endpoints must be non-negative, got ({lo}, {hi})"),
791 });
792 }
793 if lo > hi {
794 return Err(SimError::InvalidConfig {
795 field: "passenger_spawning.weight_range",
796 reason: format!("min must be <= max, got ({lo}, {hi})"),
797 });
798 }
799 if spawn.mean_interval_ticks == 0 {
800 return Err(SimError::InvalidConfig {
801 field: "passenger_spawning.mean_interval_ticks",
802 reason: "must be > 0; mean_interval_ticks=0 burst-fires \
803 every catch-up tick"
804 .into(),
805 });
806 }
807 Ok(())
808 }
809
810 fn validate_legacy_elevators(
812 elevators: &[crate::config::ElevatorConfig],
813 building: &crate::config::BuildingConfig,
814 ) -> Result<(), SimError> {
815 if elevators.is_empty() {
816 return Err(SimError::InvalidConfig {
817 field: "elevators",
818 reason: "at least one elevator is required".into(),
819 });
820 }
821
822 for elev in elevators {
823 Self::validate_elevator_config(elev, building)?;
824 }
825
826 Ok(())
827 }
828
829 fn validate_elevator_config(
831 elev: &crate::config::ElevatorConfig,
832 building: &crate::config::BuildingConfig,
833 ) -> Result<(), SimError> {
834 validate_elevator_physics(
835 elev.max_speed.value(),
836 elev.acceleration.value(),
837 elev.deceleration.value(),
838 elev.weight_capacity.value(),
839 elev.inspection_speed_factor,
840 elev.door_transition_ticks,
841 elev.door_open_ticks,
842 elev.bypass_load_up_pct,
843 elev.bypass_load_down_pct,
844 )?;
845 if !building.stops.iter().any(|s| s.id == elev.starting_stop) {
846 return Err(SimError::InvalidConfig {
847 field: "elevators.starting_stop",
848 reason: format!("references non-existent {}", elev.starting_stop),
849 });
850 }
851 Ok(())
852 }
853
854 fn validate_explicit_topology(
856 line_configs: &[crate::config::LineConfig],
857 stop_ids: &HashSet<StopId>,
858 building: &crate::config::BuildingConfig,
859 ) -> Result<(), SimError> {
860 let mut seen_line_ids = HashSet::new();
862 for lc in line_configs {
863 if !seen_line_ids.insert(lc.id) {
864 return Err(SimError::InvalidConfig {
865 field: "building.lines",
866 reason: format!("duplicate line id {}", lc.id),
867 });
868 }
869 }
870
871 for lc in line_configs {
873 if lc.serves.is_empty() {
874 return Err(SimError::InvalidConfig {
875 field: "building.lines.serves",
876 reason: format!("line {} has no stops", lc.id),
877 });
878 }
879 for sid in &lc.serves {
880 if !stop_ids.contains(sid) {
881 return Err(SimError::InvalidConfig {
882 field: "building.lines.serves",
883 reason: format!("line {} references non-existent {}", lc.id, sid),
884 });
885 }
886 }
887 for ec in &lc.elevators {
889 Self::validate_elevator_config(ec, building)?;
890 }
891
892 if let Some(max) = lc.max_cars
894 && lc.elevators.len() > max
895 {
896 return Err(SimError::InvalidConfig {
897 field: "building.lines.max_cars",
898 reason: format!(
899 "line {} has {} elevators but max_cars is {max}",
900 lc.id,
901 lc.elevators.len()
902 ),
903 });
904 }
905 }
906
907 let has_elevator = line_configs.iter().any(|lc| !lc.elevators.is_empty());
909 if !has_elevator {
910 return Err(SimError::InvalidConfig {
911 field: "building.lines",
912 reason: "at least one line must have at least one elevator".into(),
913 });
914 }
915
916 let served: HashSet<StopId> = line_configs
918 .iter()
919 .flat_map(|lc| lc.serves.iter().copied())
920 .collect();
921 for sid in stop_ids {
922 if !served.contains(sid) {
923 return Err(SimError::InvalidConfig {
924 field: "building.lines",
925 reason: format!("orphaned stop {sid} not served by any line"),
926 });
927 }
928 }
929
930 if let Some(group_configs) = &building.groups {
932 let line_id_set: HashSet<u32> = line_configs.iter().map(|lc| lc.id).collect();
933
934 let mut seen_group_ids = HashSet::new();
935 for gc in group_configs {
936 if !seen_group_ids.insert(gc.id) {
937 return Err(SimError::InvalidConfig {
938 field: "building.groups",
939 reason: format!("duplicate group id {}", gc.id),
940 });
941 }
942 for &lid in &gc.lines {
943 if !line_id_set.contains(&lid) {
944 return Err(SimError::InvalidConfig {
945 field: "building.groups.lines",
946 reason: format!(
947 "group {} references non-existent line id {}",
948 gc.id, lid
949 ),
950 });
951 }
952 }
953 }
954
955 let referenced_line_ids: HashSet<u32> = group_configs
957 .iter()
958 .flat_map(|g| g.lines.iter().copied())
959 .collect();
960 for lc in line_configs {
961 if !referenced_line_ids.contains(&lc.id) {
962 return Err(SimError::InvalidConfig {
963 field: "building.lines",
964 reason: format!("line {} is not assigned to any group", lc.id),
965 });
966 }
967 }
968 }
969
970 Ok(())
971 }
972
973 pub fn set_dispatch(
989 &mut self,
990 group: GroupId,
991 strategy: Box<dyn DispatchStrategy>,
992 id: crate::dispatch::BuiltinStrategy,
993 ) {
994 let resolved_id = strategy.builtin_id().unwrap_or(id);
995 let mode = match &resolved_id {
996 BuiltinStrategy::Destination => Some(crate::dispatch::HallCallMode::Destination),
997 BuiltinStrategy::Custom(_) => None,
998 BuiltinStrategy::Scan
999 | BuiltinStrategy::Look
1000 | BuiltinStrategy::NearestCar
1001 | BuiltinStrategy::Etd
1002 | BuiltinStrategy::Rsr => Some(crate::dispatch::HallCallMode::Classic),
1003 };
1004 if let Some(mode) = mode
1005 && let Some(g) = self.groups.iter_mut().find(|g| g.id() == group)
1006 {
1007 g.set_hall_call_mode(mode);
1008 }
1009 self.dispatchers.insert(group, strategy);
1010 self.strategy_ids.insert(group, resolved_id);
1011 }
1012
1013 pub fn set_reposition(
1028 &mut self,
1029 group: GroupId,
1030 strategy: Box<dyn RepositionStrategy>,
1031 id: BuiltinReposition,
1032 ) {
1033 let resolved_id = strategy.builtin_id().unwrap_or(id);
1034 self.repositioners.insert(group, strategy);
1035 self.reposition_ids.insert(group, resolved_id);
1036 }
1037
1038 pub fn remove_reposition(&mut self, group: GroupId) {
1040 self.repositioners.remove(&group);
1041 self.reposition_ids.remove(&group);
1042 }
1043
1044 #[must_use]
1046 pub fn reposition_id(&self, group: GroupId) -> Option<&BuiltinReposition> {
1047 self.reposition_ids.get(&group)
1048 }
1049
1050 pub fn add_before_hook(
1057 &mut self,
1058 phase: Phase,
1059 hook: impl Fn(&mut World) + Send + Sync + 'static,
1060 ) {
1061 self.hooks.add_before(phase, Box::new(hook));
1062 }
1063
1064 pub fn add_after_hook(
1069 &mut self,
1070 phase: Phase,
1071 hook: impl Fn(&mut World) + Send + Sync + 'static,
1072 ) {
1073 self.hooks.add_after(phase, Box::new(hook));
1074 }
1075
1076 pub fn add_before_group_hook(
1078 &mut self,
1079 phase: Phase,
1080 group: GroupId,
1081 hook: impl Fn(&mut World) + Send + Sync + 'static,
1082 ) {
1083 self.hooks.add_before_group(phase, group, Box::new(hook));
1084 }
1085
1086 pub fn add_after_group_hook(
1088 &mut self,
1089 phase: Phase,
1090 group: GroupId,
1091 hook: impl Fn(&mut World) + Send + Sync + 'static,
1092 ) {
1093 self.hooks.add_after_group(phase, group, Box::new(hook));
1094 }
1095}