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 let line_tag_info: Vec<(EntityId, String, Vec<EntityId>)> = groups
248 .iter()
249 .flat_map(|group| {
250 group.lines().iter().filter_map(|li| {
251 let line_comp = world.line(li.entity())?;
252 Some((li.entity(), line_comp.name.clone(), li.elevators().to_vec()))
253 })
254 })
255 .collect();
256
257 if let Some(tags) = world.resource_mut::<crate::tagged_metrics::MetricTags>() {
259 for (line_eid, name, elevators) in &line_tag_info {
260 let tag = format!("line:{name}");
261 tags.tag(*line_eid, tag.clone());
262 for elev_eid in elevators {
263 tags.tag(*elev_eid, tag.clone());
264 }
265 }
266 }
267
268 let mut repositioners: BTreeMap<GroupId, Box<dyn RepositionStrategy>> = BTreeMap::new();
270 let mut reposition_ids: BTreeMap<GroupId, BuiltinReposition> = BTreeMap::new();
271 if let Some(group_configs) = &config.building.groups {
272 for gc in group_configs {
273 if let Some(ref repo_id) = gc.reposition
274 && let Some(strategy) = repo_id.instantiate()
275 {
276 let gid = GroupId(gc.id);
277 repositioners.insert(gid, strategy);
278 reposition_ids.insert(gid, repo_id.clone());
279 }
280 }
281 }
282
283 Ok(Self {
284 world,
285 events: EventBus::default(),
286 pending_output: Vec::new(),
287 tick: 0,
288 dt,
289 groups,
290 stop_lookup,
291 dispatchers,
292 strategy_ids,
293 repositioners,
294 reposition_ids,
295 metrics: Metrics::new(),
296 time: TimeAdapter::new(config.simulation.ticks_per_second),
297 hooks,
298 elevator_ids_buf: Vec::new(),
299 reposition_buf: Vec::new(),
300 dispatch_scratch: crate::dispatch::DispatchScratch::default(),
301 topo_graph: Mutex::new(TopologyGraph::new()),
302 rider_index: RiderIndex::default(),
303 tick_in_progress: false,
304 })
305 }
306
307 fn spawn_elevator_entity(
313 world: &mut World,
314 ec: &crate::config::ElevatorConfig,
315 line: EntityId,
316 stop_lookup: &HashMap<StopId, EntityId>,
317 start_pos_lookup: &[crate::stop::StopConfig],
318 ) -> EntityId {
319 let eid = world.spawn();
320 let start_pos = start_pos_lookup
321 .iter()
322 .find(|s| s.id == ec.starting_stop)
323 .map_or(0.0, |s| s.position);
324 world.set_position(eid, Position { value: start_pos });
325 world.set_velocity(eid, Velocity { value: 0.0 });
326 let restricted: HashSet<EntityId> = ec
327 .restricted_stops
328 .iter()
329 .filter_map(|sid| stop_lookup.get(sid).copied())
330 .collect();
331 world.set_elevator(
332 eid,
333 Elevator {
334 phase: ElevatorPhase::Idle,
335 door: DoorState::Closed,
336 max_speed: ec.max_speed,
337 acceleration: ec.acceleration,
338 deceleration: ec.deceleration,
339 weight_capacity: ec.weight_capacity,
340 current_load: crate::components::Weight::ZERO,
341 riders: Vec::new(),
342 target_stop: None,
343 door_transition_ticks: ec.door_transition_ticks,
344 door_open_ticks: ec.door_open_ticks,
345 line,
346 repositioning: false,
347 restricted_stops: restricted,
348 inspection_speed_factor: ec.inspection_speed_factor,
349 going_up: true,
350 going_down: true,
351 move_count: 0,
352 door_command_queue: Vec::new(),
353 manual_target_velocity: None,
354 bypass_load_up_pct: ec.bypass_load_up_pct,
355 bypass_load_down_pct: ec.bypass_load_down_pct,
356 },
357 );
358 #[cfg(feature = "energy")]
359 if let Some(ref profile) = ec.energy_profile {
360 world.set_energy_profile(eid, profile.clone());
361 world.set_energy_metrics(eid, crate::energy::EnergyMetrics::default());
362 }
363 if let Some(mode) = ec.service_mode {
364 world.set_service_mode(eid, mode);
365 }
366 world.set_destination_queue(eid, crate::components::DestinationQueue::new());
367 eid
368 }
369
370 fn build_legacy_topology(
372 world: &mut World,
373 config: &SimConfig,
374 stop_lookup: &HashMap<StopId, EntityId>,
375 builder_dispatchers: BTreeMap<GroupId, Box<dyn DispatchStrategy>>,
376 ) -> TopologyResult {
377 let all_stop_entities: Vec<EntityId> = stop_lookup.values().copied().collect();
378 let stop_positions: Vec<f64> = config.building.stops.iter().map(|s| s.position).collect();
379 let min_pos = stop_positions.iter().copied().fold(f64::INFINITY, f64::min);
380 let max_pos = stop_positions
381 .iter()
382 .copied()
383 .fold(f64::NEG_INFINITY, f64::max);
384
385 let default_line_eid = world.spawn();
386 world.set_line(
387 default_line_eid,
388 Line {
389 name: "Default".into(),
390 group: GroupId(0),
391 orientation: Orientation::Vertical,
392 position: None,
393 min_position: min_pos,
394 max_position: max_pos,
395 max_cars: None,
396 },
397 );
398
399 let mut elevator_entities = Vec::new();
400 for ec in &config.elevators {
401 let eid = Self::spawn_elevator_entity(
402 world,
403 ec,
404 default_line_eid,
405 stop_lookup,
406 &config.building.stops,
407 );
408 elevator_entities.push(eid);
409 }
410
411 let default_line_info =
412 LineInfo::new(default_line_eid, elevator_entities, all_stop_entities);
413
414 let group = ElevatorGroup::new(GroupId(0), "Default".into(), vec![default_line_info]);
415
416 let mut dispatchers = BTreeMap::new();
423 let mut strategy_ids = BTreeMap::new();
424 let user_dispatcher = builder_dispatchers
425 .into_iter()
426 .find_map(|(gid, d)| if gid == GroupId(0) { Some(d) } else { None });
427 let inferred_id = user_dispatcher
440 .as_ref()
441 .and_then(|d| d.builtin_id())
442 .unwrap_or(BuiltinStrategy::Scan);
443 if let Some(d) = user_dispatcher {
444 dispatchers.insert(GroupId(0), d);
445 } else {
446 dispatchers.insert(
447 GroupId(0),
448 Box::new(crate::dispatch::scan::ScanDispatch::new()) as Box<dyn DispatchStrategy>,
449 );
450 }
451 strategy_ids.insert(GroupId(0), inferred_id);
452
453 (vec![group], dispatchers, strategy_ids)
454 }
455
456 #[allow(clippy::too_many_lines)]
458 fn build_explicit_topology(
459 world: &mut World,
460 config: &SimConfig,
461 line_configs: &[crate::config::LineConfig],
462 stop_lookup: &HashMap<StopId, EntityId>,
463 builder_dispatchers: BTreeMap<GroupId, Box<dyn DispatchStrategy>>,
464 ) -> TopologyResult {
465 let mut line_map: HashMap<u32, (EntityId, LineInfo)> = HashMap::new();
467
468 for lc in line_configs {
469 let served_entities: Vec<EntityId> = lc
471 .serves
472 .iter()
473 .filter_map(|sid| stop_lookup.get(sid).copied())
474 .collect();
475
476 let stop_positions: Vec<f64> = lc
478 .serves
479 .iter()
480 .filter_map(|sid| {
481 config
482 .building
483 .stops
484 .iter()
485 .find(|s| s.id == *sid)
486 .map(|s| s.position)
487 })
488 .collect();
489 let auto_min = stop_positions.iter().copied().fold(f64::INFINITY, f64::min);
490 let auto_max = stop_positions
491 .iter()
492 .copied()
493 .fold(f64::NEG_INFINITY, f64::max);
494
495 let min_pos = lc.min_position.unwrap_or(auto_min);
496 let max_pos = lc.max_position.unwrap_or(auto_max);
497
498 let line_eid = world.spawn();
499 world.set_line(
502 line_eid,
503 Line {
504 name: lc.name.clone(),
505 group: GroupId(0),
506 orientation: lc.orientation,
507 position: lc.position,
508 min_position: min_pos,
509 max_position: max_pos,
510 max_cars: lc.max_cars,
511 },
512 );
513
514 let mut elevator_entities = Vec::new();
516 for ec in &lc.elevators {
517 let eid = Self::spawn_elevator_entity(
518 world,
519 ec,
520 line_eid,
521 stop_lookup,
522 &config.building.stops,
523 );
524 elevator_entities.push(eid);
525 }
526
527 let line_info = LineInfo::new(line_eid, elevator_entities, served_entities);
528 line_map.insert(lc.id, (line_eid, line_info));
529 }
530
531 let group_configs = config.building.groups.as_deref();
533 let mut groups = Vec::new();
534 let mut dispatchers = BTreeMap::new();
535 let mut strategy_ids = BTreeMap::new();
536
537 if let Some(gcs) = group_configs {
538 for gc in gcs {
539 let group_id = GroupId(gc.id);
540
541 let mut group_lines = Vec::new();
542
543 for &lid in &gc.lines {
544 if let Some((line_eid, li)) = line_map.get(&lid) {
545 if let Some(line_comp) = world.line_mut(*line_eid) {
547 line_comp.group = group_id;
548 }
549 group_lines.push(li.clone());
550 }
551 }
552
553 let mut group = ElevatorGroup::new(group_id, gc.name.clone(), group_lines);
554 if let Some(mode) = gc.hall_call_mode {
555 group.set_hall_call_mode(mode);
556 }
557 if let Some(ticks) = gc.ack_latency_ticks {
558 group.set_ack_latency_ticks(ticks);
559 }
560 groups.push(group);
561
562 let dispatch: Box<dyn DispatchStrategy> = gc
564 .dispatch
565 .instantiate()
566 .unwrap_or_else(|| Box::new(crate::dispatch::scan::ScanDispatch::new()));
567 dispatchers.insert(group_id, dispatch);
568 strategy_ids.insert(group_id, gc.dispatch.clone());
569 }
570 } else {
571 let group_id = GroupId(0);
573 let mut group_lines = Vec::new();
574
575 for (line_eid, li) in line_map.values() {
576 if let Some(line_comp) = world.line_mut(*line_eid) {
577 line_comp.group = group_id;
578 }
579 group_lines.push(li.clone());
580 }
581
582 let group = ElevatorGroup::new(group_id, "Default".into(), group_lines);
583 groups.push(group);
584
585 let dispatch: Box<dyn DispatchStrategy> =
586 Box::new(crate::dispatch::scan::ScanDispatch::new());
587 dispatchers.insert(group_id, dispatch);
588 strategy_ids.insert(group_id, BuiltinStrategy::Scan);
589 }
590
591 for (gid, d) in builder_dispatchers {
601 let inferred_id = d.builtin_id();
602 dispatchers.insert(gid, d);
603 match inferred_id {
604 Some(id) => {
605 strategy_ids.insert(gid, id);
606 }
607 None => {
608 strategy_ids
609 .entry(gid)
610 .or_insert_with(|| BuiltinStrategy::Custom("user-supplied".into()));
611 }
612 }
613 }
614
615 (groups, dispatchers, strategy_ids)
616 }
617
618 #[allow(clippy::too_many_arguments)]
620 pub(crate) fn from_parts(
621 world: World,
622 tick: u64,
623 dt: f64,
624 groups: Vec<ElevatorGroup>,
625 stop_lookup: HashMap<StopId, EntityId>,
626 dispatchers: BTreeMap<GroupId, Box<dyn DispatchStrategy>>,
627 strategy_ids: BTreeMap<GroupId, crate::dispatch::BuiltinStrategy>,
628 metrics: Metrics,
629 ticks_per_second: f64,
630 ) -> Self {
631 let mut rider_index = RiderIndex::default();
632 rider_index.rebuild(&world);
633 let mut world = world;
639 world.insert_resource(crate::time::TickRate(ticks_per_second));
640 if world
648 .resource::<crate::traffic_detector::TrafficDetector>()
649 .is_none()
650 {
651 world.insert_resource(crate::traffic_detector::TrafficDetector::default());
652 }
653 if world
658 .resource::<crate::arrival_log::DestinationLog>()
659 .is_none()
660 {
661 world.insert_resource(crate::arrival_log::DestinationLog::default());
662 }
663 world.register_ext::<crate::dispatch::destination::AssignedCar>(
678 crate::dispatch::destination::ASSIGNED_CAR_KEY,
679 );
680 if let Some(pending) = world.resource::<crate::snapshot::PendingExtensions>() {
681 let data = pending.0.clone();
682 world.deserialize_extensions(&data);
683 }
684 Self {
685 world,
686 events: EventBus::default(),
687 pending_output: Vec::new(),
688 tick,
689 dt,
690 groups,
691 stop_lookup,
692 dispatchers,
693 strategy_ids,
694 repositioners: BTreeMap::new(),
695 reposition_ids: BTreeMap::new(),
696 metrics,
697 time: TimeAdapter::new(ticks_per_second),
698 hooks: PhaseHooks::default(),
699 elevator_ids_buf: Vec::new(),
700 reposition_buf: Vec::new(),
701 dispatch_scratch: crate::dispatch::DispatchScratch::default(),
702 topo_graph: Mutex::new(TopologyGraph::new()),
703 rider_index,
704 tick_in_progress: false,
705 }
706 }
707
708 pub(crate) fn validate_config(config: &SimConfig) -> Result<(), SimError> {
710 if config.building.stops.is_empty() {
711 return Err(SimError::InvalidConfig {
712 field: "building.stops",
713 reason: "at least one stop is required".into(),
714 });
715 }
716
717 let mut seen_ids = HashSet::new();
719 for stop in &config.building.stops {
720 if !seen_ids.insert(stop.id) {
721 return Err(SimError::InvalidConfig {
722 field: "building.stops",
723 reason: format!("duplicate {}", stop.id),
724 });
725 }
726 if !stop.position.is_finite() {
727 return Err(SimError::InvalidConfig {
728 field: "building.stops.position",
729 reason: format!("{} has non-finite position {}", stop.id, stop.position),
730 });
731 }
732 }
733
734 let stop_ids: HashSet<StopId> = config.building.stops.iter().map(|s| s.id).collect();
735
736 if let Some(line_configs) = &config.building.lines {
737 Self::validate_explicit_topology(line_configs, &stop_ids, &config.building)?;
739 } else {
740 Self::validate_legacy_elevators(&config.elevators, &config.building)?;
742 }
743
744 if !config.simulation.ticks_per_second.is_finite()
745 || config.simulation.ticks_per_second <= 0.0
746 {
747 return Err(SimError::InvalidConfig {
748 field: "simulation.ticks_per_second",
749 reason: format!(
750 "must be finite and positive, got {}",
751 config.simulation.ticks_per_second
752 ),
753 });
754 }
755
756 Self::validate_passenger_spawning(&config.passenger_spawning)?;
757
758 Ok(())
759 }
760
761 fn validate_passenger_spawning(
766 spawn: &crate::config::PassengerSpawnConfig,
767 ) -> Result<(), SimError> {
768 let (lo, hi) = spawn.weight_range;
769 if !lo.is_finite() || !hi.is_finite() {
770 return Err(SimError::InvalidConfig {
771 field: "passenger_spawning.weight_range",
772 reason: format!("both endpoints must be finite, got ({lo}, {hi})"),
773 });
774 }
775 if lo < 0.0 || hi < 0.0 {
776 return Err(SimError::InvalidConfig {
777 field: "passenger_spawning.weight_range",
778 reason: format!("both endpoints must be non-negative, got ({lo}, {hi})"),
779 });
780 }
781 if lo > hi {
782 return Err(SimError::InvalidConfig {
783 field: "passenger_spawning.weight_range",
784 reason: format!("min must be <= max, got ({lo}, {hi})"),
785 });
786 }
787 if spawn.mean_interval_ticks == 0 {
788 return Err(SimError::InvalidConfig {
789 field: "passenger_spawning.mean_interval_ticks",
790 reason: "must be > 0; mean_interval_ticks=0 burst-fires \
791 every catch-up tick"
792 .into(),
793 });
794 }
795 Ok(())
796 }
797
798 fn validate_legacy_elevators(
800 elevators: &[crate::config::ElevatorConfig],
801 building: &crate::config::BuildingConfig,
802 ) -> Result<(), SimError> {
803 if elevators.is_empty() {
804 return Err(SimError::InvalidConfig {
805 field: "elevators",
806 reason: "at least one elevator is required".into(),
807 });
808 }
809
810 for elev in elevators {
811 Self::validate_elevator_config(elev, building)?;
812 }
813
814 Ok(())
815 }
816
817 fn validate_elevator_config(
819 elev: &crate::config::ElevatorConfig,
820 building: &crate::config::BuildingConfig,
821 ) -> Result<(), SimError> {
822 validate_elevator_physics(
823 elev.max_speed.value(),
824 elev.acceleration.value(),
825 elev.deceleration.value(),
826 elev.weight_capacity.value(),
827 elev.inspection_speed_factor,
828 elev.door_transition_ticks,
829 elev.door_open_ticks,
830 elev.bypass_load_up_pct,
831 elev.bypass_load_down_pct,
832 )?;
833 if !building.stops.iter().any(|s| s.id == elev.starting_stop) {
834 return Err(SimError::InvalidConfig {
835 field: "elevators.starting_stop",
836 reason: format!("references non-existent {}", elev.starting_stop),
837 });
838 }
839 Ok(())
840 }
841
842 fn validate_explicit_topology(
844 line_configs: &[crate::config::LineConfig],
845 stop_ids: &HashSet<StopId>,
846 building: &crate::config::BuildingConfig,
847 ) -> Result<(), SimError> {
848 let mut seen_line_ids = HashSet::new();
850 for lc in line_configs {
851 if !seen_line_ids.insert(lc.id) {
852 return Err(SimError::InvalidConfig {
853 field: "building.lines",
854 reason: format!("duplicate line id {}", lc.id),
855 });
856 }
857 }
858
859 for lc in line_configs {
861 if lc.serves.is_empty() {
862 return Err(SimError::InvalidConfig {
863 field: "building.lines.serves",
864 reason: format!("line {} has no stops", lc.id),
865 });
866 }
867 for sid in &lc.serves {
868 if !stop_ids.contains(sid) {
869 return Err(SimError::InvalidConfig {
870 field: "building.lines.serves",
871 reason: format!("line {} references non-existent {}", lc.id, sid),
872 });
873 }
874 }
875 for ec in &lc.elevators {
877 Self::validate_elevator_config(ec, building)?;
878 }
879
880 if let Some(max) = lc.max_cars
882 && lc.elevators.len() > max
883 {
884 return Err(SimError::InvalidConfig {
885 field: "building.lines.max_cars",
886 reason: format!(
887 "line {} has {} elevators but max_cars is {max}",
888 lc.id,
889 lc.elevators.len()
890 ),
891 });
892 }
893 }
894
895 let has_elevator = line_configs.iter().any(|lc| !lc.elevators.is_empty());
897 if !has_elevator {
898 return Err(SimError::InvalidConfig {
899 field: "building.lines",
900 reason: "at least one line must have at least one elevator".into(),
901 });
902 }
903
904 let served: HashSet<StopId> = line_configs
906 .iter()
907 .flat_map(|lc| lc.serves.iter().copied())
908 .collect();
909 for sid in stop_ids {
910 if !served.contains(sid) {
911 return Err(SimError::InvalidConfig {
912 field: "building.lines",
913 reason: format!("orphaned stop {sid} not served by any line"),
914 });
915 }
916 }
917
918 if let Some(group_configs) = &building.groups {
920 let line_id_set: HashSet<u32> = line_configs.iter().map(|lc| lc.id).collect();
921
922 let mut seen_group_ids = HashSet::new();
923 for gc in group_configs {
924 if !seen_group_ids.insert(gc.id) {
925 return Err(SimError::InvalidConfig {
926 field: "building.groups",
927 reason: format!("duplicate group id {}", gc.id),
928 });
929 }
930 for &lid in &gc.lines {
931 if !line_id_set.contains(&lid) {
932 return Err(SimError::InvalidConfig {
933 field: "building.groups.lines",
934 reason: format!(
935 "group {} references non-existent line id {}",
936 gc.id, lid
937 ),
938 });
939 }
940 }
941 }
942
943 let referenced_line_ids: HashSet<u32> = group_configs
945 .iter()
946 .flat_map(|g| g.lines.iter().copied())
947 .collect();
948 for lc in line_configs {
949 if !referenced_line_ids.contains(&lc.id) {
950 return Err(SimError::InvalidConfig {
951 field: "building.lines",
952 reason: format!("line {} is not assigned to any group", lc.id),
953 });
954 }
955 }
956 }
957
958 Ok(())
959 }
960
961 pub fn set_dispatch(
977 &mut self,
978 group: GroupId,
979 strategy: Box<dyn DispatchStrategy>,
980 id: crate::dispatch::BuiltinStrategy,
981 ) {
982 let resolved_id = strategy.builtin_id().unwrap_or(id);
983 let mode = match &resolved_id {
984 BuiltinStrategy::Destination => Some(crate::dispatch::HallCallMode::Destination),
985 BuiltinStrategy::Custom(_) => None,
986 BuiltinStrategy::Scan
987 | BuiltinStrategy::Look
988 | BuiltinStrategy::NearestCar
989 | BuiltinStrategy::Etd
990 | BuiltinStrategy::Rsr => Some(crate::dispatch::HallCallMode::Classic),
991 };
992 if let Some(mode) = mode
993 && let Some(g) = self.groups.iter_mut().find(|g| g.id() == group)
994 {
995 g.set_hall_call_mode(mode);
996 }
997 self.dispatchers.insert(group, strategy);
998 self.strategy_ids.insert(group, resolved_id);
999 }
1000
1001 pub fn set_reposition(
1016 &mut self,
1017 group: GroupId,
1018 strategy: Box<dyn RepositionStrategy>,
1019 id: BuiltinReposition,
1020 ) {
1021 let resolved_id = strategy.builtin_id().unwrap_or(id);
1022 self.repositioners.insert(group, strategy);
1023 self.reposition_ids.insert(group, resolved_id);
1024 }
1025
1026 pub fn remove_reposition(&mut self, group: GroupId) {
1028 self.repositioners.remove(&group);
1029 self.reposition_ids.remove(&group);
1030 }
1031
1032 #[must_use]
1034 pub fn reposition_id(&self, group: GroupId) -> Option<&BuiltinReposition> {
1035 self.reposition_ids.get(&group)
1036 }
1037
1038 pub fn add_before_hook(
1045 &mut self,
1046 phase: Phase,
1047 hook: impl Fn(&mut World) + Send + Sync + 'static,
1048 ) {
1049 self.hooks.add_before(phase, Box::new(hook));
1050 }
1051
1052 pub fn add_after_hook(
1057 &mut self,
1058 phase: Phase,
1059 hook: impl Fn(&mut World) + Send + Sync + 'static,
1060 ) {
1061 self.hooks.add_after(phase, Box::new(hook));
1062 }
1063
1064 pub fn add_before_group_hook(
1066 &mut self,
1067 phase: Phase,
1068 group: GroupId,
1069 hook: impl Fn(&mut World) + Send + Sync + 'static,
1070 ) {
1071 self.hooks.add_before_group(phase, group, Box::new(hook));
1072 }
1073
1074 pub fn add_after_group_hook(
1076 &mut self,
1077 phase: Phase,
1078 group: GroupId,
1079 hook: impl Fn(&mut World) + Send + Sync + 'static,
1080 ) {
1081 self.hooks.add_after_group(phase, group, Box::new(hook));
1082 }
1083}