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
45impl Simulation {
46 pub fn new(
57 config: &SimConfig,
58 dispatch: impl DispatchStrategy + 'static,
59 ) -> Result<Self, SimError> {
60 let mut dispatchers = BTreeMap::new();
61 dispatchers.insert(GroupId(0), Box::new(dispatch) as Box<dyn DispatchStrategy>);
62 Self::new_with_hooks(config, dispatchers, PhaseHooks::default())
63 }
64
65 #[allow(clippy::too_many_lines)]
69 pub(crate) fn new_with_hooks(
70 config: &SimConfig,
71 builder_dispatchers: BTreeMap<GroupId, Box<dyn DispatchStrategy>>,
72 hooks: PhaseHooks,
73 ) -> Result<Self, SimError> {
74 Self::validate_config(config)?;
75
76 let mut world = World::new();
77
78 let mut stop_lookup: HashMap<StopId, EntityId> = HashMap::new();
80 for sc in &config.building.stops {
81 let eid = world.spawn();
82 world.set_stop(
83 eid,
84 Stop {
85 name: sc.name.clone(),
86 position: sc.position,
87 },
88 );
89 world.set_position(eid, Position { value: sc.position });
90 stop_lookup.insert(sc.id, eid);
91 }
92
93 let mut sorted: Vec<(f64, EntityId)> = world
95 .iter_stops()
96 .map(|(eid, stop)| (stop.position, eid))
97 .collect();
98 sorted.sort_by(|a, b| a.0.total_cmp(&b.0));
99 world.insert_resource(crate::world::SortedStops(sorted));
100
101 let (groups, dispatchers, strategy_ids) = if let Some(line_configs) = &config.building.lines
102 {
103 Self::build_explicit_topology(
104 &mut world,
105 config,
106 line_configs,
107 &stop_lookup,
108 builder_dispatchers,
109 )
110 } else {
111 Self::build_legacy_topology(&mut world, config, &stop_lookup, builder_dispatchers)
112 };
113
114 let dt = 1.0 / config.simulation.ticks_per_second;
115
116 world.insert_resource(crate::tagged_metrics::MetricTags::default());
117
118 let line_tag_info: Vec<(EntityId, String, Vec<EntityId>)> = groups
121 .iter()
122 .flat_map(|group| {
123 group.lines().iter().filter_map(|li| {
124 let line_comp = world.line(li.entity())?;
125 Some((li.entity(), line_comp.name.clone(), li.elevators().to_vec()))
126 })
127 })
128 .collect();
129
130 if let Some(tags) = world.resource_mut::<crate::tagged_metrics::MetricTags>() {
132 for (line_eid, name, elevators) in &line_tag_info {
133 let tag = format!("line:{name}");
134 tags.tag(*line_eid, tag.clone());
135 for elev_eid in elevators {
136 tags.tag(*elev_eid, tag.clone());
137 }
138 }
139 }
140
141 let mut repositioners: BTreeMap<GroupId, Box<dyn RepositionStrategy>> = BTreeMap::new();
143 let mut reposition_ids: BTreeMap<GroupId, BuiltinReposition> = BTreeMap::new();
144 if let Some(group_configs) = &config.building.groups {
145 for gc in group_configs {
146 if let Some(ref repo_id) = gc.reposition
147 && let Some(strategy) = repo_id.instantiate()
148 {
149 let gid = GroupId(gc.id);
150 repositioners.insert(gid, strategy);
151 reposition_ids.insert(gid, repo_id.clone());
152 }
153 }
154 }
155
156 Ok(Self {
157 world,
158 events: EventBus::default(),
159 pending_output: Vec::new(),
160 tick: 0,
161 dt,
162 groups,
163 stop_lookup,
164 dispatchers,
165 strategy_ids,
166 repositioners,
167 reposition_ids,
168 metrics: Metrics::new(),
169 time: TimeAdapter::new(config.simulation.ticks_per_second),
170 hooks,
171 elevator_ids_buf: Vec::new(),
172 topo_graph: Mutex::new(TopologyGraph::new()),
173 rider_index: RiderIndex::default(),
174 })
175 }
176
177 fn spawn_elevator_entity(
183 world: &mut World,
184 ec: &crate::config::ElevatorConfig,
185 line: EntityId,
186 stop_lookup: &HashMap<StopId, EntityId>,
187 start_pos_lookup: &[crate::stop::StopConfig],
188 ) -> EntityId {
189 let eid = world.spawn();
190 let start_pos = start_pos_lookup
191 .iter()
192 .find(|s| s.id == ec.starting_stop)
193 .map_or(0.0, |s| s.position);
194 world.set_position(eid, Position { value: start_pos });
195 world.set_velocity(eid, Velocity { value: 0.0 });
196 let restricted: HashSet<EntityId> = ec
197 .restricted_stops
198 .iter()
199 .filter_map(|sid| stop_lookup.get(sid).copied())
200 .collect();
201 world.set_elevator(
202 eid,
203 Elevator {
204 phase: ElevatorPhase::Idle,
205 door: DoorState::Closed,
206 max_speed: ec.max_speed,
207 acceleration: ec.acceleration,
208 deceleration: ec.deceleration,
209 weight_capacity: ec.weight_capacity,
210 current_load: 0.0,
211 riders: Vec::new(),
212 target_stop: None,
213 door_transition_ticks: ec.door_transition_ticks,
214 door_open_ticks: ec.door_open_ticks,
215 line,
216 repositioning: false,
217 restricted_stops: restricted,
218 inspection_speed_factor: ec.inspection_speed_factor,
219 going_up: true,
220 going_down: true,
221 move_count: 0,
222 door_command_queue: Vec::new(),
223 manual_target_velocity: None,
224 },
225 );
226 #[cfg(feature = "energy")]
227 if let Some(ref profile) = ec.energy_profile {
228 world.set_energy_profile(eid, profile.clone());
229 world.set_energy_metrics(eid, crate::energy::EnergyMetrics::default());
230 }
231 if let Some(mode) = ec.service_mode {
232 world.set_service_mode(eid, mode);
233 }
234 world.set_destination_queue(eid, crate::components::DestinationQueue::new());
235 eid
236 }
237
238 fn build_legacy_topology(
240 world: &mut World,
241 config: &SimConfig,
242 stop_lookup: &HashMap<StopId, EntityId>,
243 builder_dispatchers: BTreeMap<GroupId, Box<dyn DispatchStrategy>>,
244 ) -> TopologyResult {
245 let all_stop_entities: Vec<EntityId> = stop_lookup.values().copied().collect();
246 let stop_positions: Vec<f64> = config.building.stops.iter().map(|s| s.position).collect();
247 let min_pos = stop_positions.iter().copied().fold(f64::INFINITY, f64::min);
248 let max_pos = stop_positions
249 .iter()
250 .copied()
251 .fold(f64::NEG_INFINITY, f64::max);
252
253 let default_line_eid = world.spawn();
254 world.set_line(
255 default_line_eid,
256 Line {
257 name: "Default".into(),
258 group: GroupId(0),
259 orientation: Orientation::Vertical,
260 position: None,
261 min_position: min_pos,
262 max_position: max_pos,
263 max_cars: None,
264 },
265 );
266
267 let mut elevator_entities = Vec::new();
268 for ec in &config.elevators {
269 let eid = Self::spawn_elevator_entity(
270 world,
271 ec,
272 default_line_eid,
273 stop_lookup,
274 &config.building.stops,
275 );
276 elevator_entities.push(eid);
277 }
278
279 let default_line_info =
280 LineInfo::new(default_line_eid, elevator_entities, all_stop_entities);
281
282 let group = ElevatorGroup::new(GroupId(0), "Default".into(), vec![default_line_info]);
283
284 let mut dispatchers = BTreeMap::new();
286 let dispatch = builder_dispatchers.into_iter().next().map_or_else(
287 || Box::new(crate::dispatch::scan::ScanDispatch::new()) as Box<dyn DispatchStrategy>,
288 |(_, d)| d,
289 );
290 dispatchers.insert(GroupId(0), dispatch);
291
292 let mut strategy_ids = BTreeMap::new();
293 strategy_ids.insert(GroupId(0), BuiltinStrategy::Scan);
294
295 (vec![group], dispatchers, strategy_ids)
296 }
297
298 #[allow(clippy::too_many_lines)]
300 fn build_explicit_topology(
301 world: &mut World,
302 config: &SimConfig,
303 line_configs: &[crate::config::LineConfig],
304 stop_lookup: &HashMap<StopId, EntityId>,
305 builder_dispatchers: BTreeMap<GroupId, Box<dyn DispatchStrategy>>,
306 ) -> TopologyResult {
307 let mut line_map: HashMap<u32, (EntityId, LineInfo)> = HashMap::new();
309
310 for lc in line_configs {
311 let served_entities: Vec<EntityId> = lc
313 .serves
314 .iter()
315 .filter_map(|sid| stop_lookup.get(sid).copied())
316 .collect();
317
318 let stop_positions: Vec<f64> = lc
320 .serves
321 .iter()
322 .filter_map(|sid| {
323 config
324 .building
325 .stops
326 .iter()
327 .find(|s| s.id == *sid)
328 .map(|s| s.position)
329 })
330 .collect();
331 let auto_min = stop_positions.iter().copied().fold(f64::INFINITY, f64::min);
332 let auto_max = stop_positions
333 .iter()
334 .copied()
335 .fold(f64::NEG_INFINITY, f64::max);
336
337 let min_pos = lc.min_position.unwrap_or(auto_min);
338 let max_pos = lc.max_position.unwrap_or(auto_max);
339
340 let line_eid = world.spawn();
341 world.set_line(
344 line_eid,
345 Line {
346 name: lc.name.clone(),
347 group: GroupId(0),
348 orientation: lc.orientation,
349 position: lc.position,
350 min_position: min_pos,
351 max_position: max_pos,
352 max_cars: lc.max_cars,
353 },
354 );
355
356 let mut elevator_entities = Vec::new();
358 for ec in &lc.elevators {
359 let eid = Self::spawn_elevator_entity(
360 world,
361 ec,
362 line_eid,
363 stop_lookup,
364 &config.building.stops,
365 );
366 elevator_entities.push(eid);
367 }
368
369 let line_info = LineInfo::new(line_eid, elevator_entities, served_entities);
370 line_map.insert(lc.id, (line_eid, line_info));
371 }
372
373 let group_configs = config.building.groups.as_deref();
375 let mut groups = Vec::new();
376 let mut dispatchers = BTreeMap::new();
377 let mut strategy_ids = BTreeMap::new();
378
379 if let Some(gcs) = group_configs {
380 for gc in gcs {
381 let group_id = GroupId(gc.id);
382
383 let mut group_lines = Vec::new();
384
385 for &lid in &gc.lines {
386 if let Some((line_eid, li)) = line_map.get(&lid) {
387 if let Some(line_comp) = world.line_mut(*line_eid) {
389 line_comp.group = group_id;
390 }
391 group_lines.push(li.clone());
392 }
393 }
394
395 let group = ElevatorGroup::new(group_id, gc.name.clone(), group_lines);
396 groups.push(group);
397
398 let dispatch: Box<dyn DispatchStrategy> = gc
400 .dispatch
401 .instantiate()
402 .unwrap_or_else(|| Box::new(crate::dispatch::scan::ScanDispatch::new()));
403 dispatchers.insert(group_id, dispatch);
404 strategy_ids.insert(group_id, gc.dispatch.clone());
405 }
406 } else {
407 let group_id = GroupId(0);
409 let mut group_lines = Vec::new();
410
411 for (line_eid, li) in line_map.values() {
412 if let Some(line_comp) = world.line_mut(*line_eid) {
413 line_comp.group = group_id;
414 }
415 group_lines.push(li.clone());
416 }
417
418 let group = ElevatorGroup::new(group_id, "Default".into(), group_lines);
419 groups.push(group);
420
421 let dispatch: Box<dyn DispatchStrategy> =
422 Box::new(crate::dispatch::scan::ScanDispatch::new());
423 dispatchers.insert(group_id, dispatch);
424 strategy_ids.insert(group_id, BuiltinStrategy::Scan);
425 }
426
427 for (gid, d) in builder_dispatchers {
429 dispatchers.insert(gid, d);
430 }
431
432 (groups, dispatchers, strategy_ids)
433 }
434
435 #[allow(clippy::too_many_arguments)]
437 pub(crate) fn from_parts(
438 world: World,
439 tick: u64,
440 dt: f64,
441 groups: Vec<ElevatorGroup>,
442 stop_lookup: HashMap<StopId, EntityId>,
443 dispatchers: BTreeMap<GroupId, Box<dyn DispatchStrategy>>,
444 strategy_ids: BTreeMap<GroupId, crate::dispatch::BuiltinStrategy>,
445 metrics: Metrics,
446 ticks_per_second: f64,
447 ) -> Self {
448 let mut rider_index = RiderIndex::default();
449 rider_index.rebuild(&world);
450 Self {
451 world,
452 events: EventBus::default(),
453 pending_output: Vec::new(),
454 tick,
455 dt,
456 groups,
457 stop_lookup,
458 dispatchers,
459 strategy_ids,
460 repositioners: BTreeMap::new(),
461 reposition_ids: BTreeMap::new(),
462 metrics,
463 time: TimeAdapter::new(ticks_per_second),
464 hooks: PhaseHooks::default(),
465 elevator_ids_buf: Vec::new(),
466 topo_graph: Mutex::new(TopologyGraph::new()),
467 rider_index,
468 }
469 }
470
471 pub(crate) fn validate_config(config: &SimConfig) -> Result<(), SimError> {
473 if config.building.stops.is_empty() {
474 return Err(SimError::InvalidConfig {
475 field: "building.stops",
476 reason: "at least one stop is required".into(),
477 });
478 }
479
480 let mut seen_ids = HashSet::new();
482 for stop in &config.building.stops {
483 if !seen_ids.insert(stop.id) {
484 return Err(SimError::InvalidConfig {
485 field: "building.stops",
486 reason: format!("duplicate {}", stop.id),
487 });
488 }
489 }
490
491 let stop_ids: HashSet<StopId> = config.building.stops.iter().map(|s| s.id).collect();
492
493 if let Some(line_configs) = &config.building.lines {
494 Self::validate_explicit_topology(line_configs, &stop_ids, &config.building)?;
496 } else {
497 Self::validate_legacy_elevators(&config.elevators, &config.building)?;
499 }
500
501 if config.simulation.ticks_per_second <= 0.0 {
502 return Err(SimError::InvalidConfig {
503 field: "simulation.ticks_per_second",
504 reason: format!(
505 "must be positive, got {}",
506 config.simulation.ticks_per_second
507 ),
508 });
509 }
510
511 Ok(())
512 }
513
514 fn validate_legacy_elevators(
516 elevators: &[crate::config::ElevatorConfig],
517 building: &crate::config::BuildingConfig,
518 ) -> Result<(), SimError> {
519 if elevators.is_empty() {
520 return Err(SimError::InvalidConfig {
521 field: "elevators",
522 reason: "at least one elevator is required".into(),
523 });
524 }
525
526 for elev in elevators {
527 Self::validate_elevator_config(elev, building)?;
528 }
529
530 Ok(())
531 }
532
533 fn validate_elevator_config(
535 elev: &crate::config::ElevatorConfig,
536 building: &crate::config::BuildingConfig,
537 ) -> Result<(), SimError> {
538 if elev.max_speed <= 0.0 {
539 return Err(SimError::InvalidConfig {
540 field: "elevators.max_speed",
541 reason: format!("must be positive, got {}", elev.max_speed),
542 });
543 }
544 if elev.acceleration <= 0.0 {
545 return Err(SimError::InvalidConfig {
546 field: "elevators.acceleration",
547 reason: format!("must be positive, got {}", elev.acceleration),
548 });
549 }
550 if elev.deceleration <= 0.0 {
551 return Err(SimError::InvalidConfig {
552 field: "elevators.deceleration",
553 reason: format!("must be positive, got {}", elev.deceleration),
554 });
555 }
556 if elev.weight_capacity <= 0.0 {
557 return Err(SimError::InvalidConfig {
558 field: "elevators.weight_capacity",
559 reason: format!("must be positive, got {}", elev.weight_capacity),
560 });
561 }
562 if elev.inspection_speed_factor <= 0.0 {
563 return Err(SimError::InvalidConfig {
564 field: "elevators.inspection_speed_factor",
565 reason: format!("must be positive, got {}", elev.inspection_speed_factor),
566 });
567 }
568 if !building.stops.iter().any(|s| s.id == elev.starting_stop) {
569 return Err(SimError::InvalidConfig {
570 field: "elevators.starting_stop",
571 reason: format!("references non-existent {}", elev.starting_stop),
572 });
573 }
574 Ok(())
575 }
576
577 fn validate_explicit_topology(
579 line_configs: &[crate::config::LineConfig],
580 stop_ids: &HashSet<StopId>,
581 building: &crate::config::BuildingConfig,
582 ) -> Result<(), SimError> {
583 let mut seen_line_ids = HashSet::new();
585 for lc in line_configs {
586 if !seen_line_ids.insert(lc.id) {
587 return Err(SimError::InvalidConfig {
588 field: "building.lines",
589 reason: format!("duplicate line id {}", lc.id),
590 });
591 }
592 }
593
594 for lc in line_configs {
596 for sid in &lc.serves {
597 if !stop_ids.contains(sid) {
598 return Err(SimError::InvalidConfig {
599 field: "building.lines.serves",
600 reason: format!("line {} references non-existent {}", lc.id, sid),
601 });
602 }
603 }
604 for ec in &lc.elevators {
606 Self::validate_elevator_config(ec, building)?;
607 }
608
609 if let Some(max) = lc.max_cars
611 && lc.elevators.len() > max
612 {
613 return Err(SimError::InvalidConfig {
614 field: "building.lines.max_cars",
615 reason: format!(
616 "line {} has {} elevators but max_cars is {max}",
617 lc.id,
618 lc.elevators.len()
619 ),
620 });
621 }
622 }
623
624 let has_elevator = line_configs.iter().any(|lc| !lc.elevators.is_empty());
626 if !has_elevator {
627 return Err(SimError::InvalidConfig {
628 field: "building.lines",
629 reason: "at least one line must have at least one elevator".into(),
630 });
631 }
632
633 let served: HashSet<StopId> = line_configs
635 .iter()
636 .flat_map(|lc| lc.serves.iter().copied())
637 .collect();
638 for sid in stop_ids {
639 if !served.contains(sid) {
640 return Err(SimError::InvalidConfig {
641 field: "building.lines",
642 reason: format!("orphaned stop {sid} not served by any line"),
643 });
644 }
645 }
646
647 if let Some(group_configs) = &building.groups {
649 let line_id_set: HashSet<u32> = line_configs.iter().map(|lc| lc.id).collect();
650
651 let mut seen_group_ids = HashSet::new();
652 for gc in group_configs {
653 if !seen_group_ids.insert(gc.id) {
654 return Err(SimError::InvalidConfig {
655 field: "building.groups",
656 reason: format!("duplicate group id {}", gc.id),
657 });
658 }
659 for &lid in &gc.lines {
660 if !line_id_set.contains(&lid) {
661 return Err(SimError::InvalidConfig {
662 field: "building.groups.lines",
663 reason: format!(
664 "group {} references non-existent line id {}",
665 gc.id, lid
666 ),
667 });
668 }
669 }
670 }
671
672 let referenced_line_ids: HashSet<u32> = group_configs
674 .iter()
675 .flat_map(|g| g.lines.iter().copied())
676 .collect();
677 for lc in line_configs {
678 if !referenced_line_ids.contains(&lc.id) {
679 return Err(SimError::InvalidConfig {
680 field: "building.lines",
681 reason: format!("line {} is not assigned to any group", lc.id),
682 });
683 }
684 }
685 }
686
687 Ok(())
688 }
689
690 pub fn set_dispatch(
697 &mut self,
698 group: GroupId,
699 strategy: Box<dyn DispatchStrategy>,
700 id: crate::dispatch::BuiltinStrategy,
701 ) {
702 self.dispatchers.insert(group, strategy);
703 self.strategy_ids.insert(group, id);
704 }
705
706 pub fn set_reposition(
713 &mut self,
714 group: GroupId,
715 strategy: Box<dyn RepositionStrategy>,
716 id: BuiltinReposition,
717 ) {
718 self.repositioners.insert(group, strategy);
719 self.reposition_ids.insert(group, id);
720 }
721
722 pub fn remove_reposition(&mut self, group: GroupId) {
724 self.repositioners.remove(&group);
725 self.reposition_ids.remove(&group);
726 }
727
728 #[must_use]
730 pub fn reposition_id(&self, group: GroupId) -> Option<&BuiltinReposition> {
731 self.reposition_ids.get(&group)
732 }
733
734 pub fn add_before_hook(
741 &mut self,
742 phase: Phase,
743 hook: impl Fn(&mut World) + Send + Sync + 'static,
744 ) {
745 self.hooks.add_before(phase, Box::new(hook));
746 }
747
748 pub fn add_after_hook(
753 &mut self,
754 phase: Phase,
755 hook: impl Fn(&mut World) + Send + Sync + 'static,
756 ) {
757 self.hooks.add_after(phase, Box::new(hook));
758 }
759
760 pub fn add_before_group_hook(
762 &mut self,
763 phase: Phase,
764 group: GroupId,
765 hook: impl Fn(&mut World) + Send + Sync + 'static,
766 ) {
767 self.hooks.add_before_group(phase, group, Box::new(hook));
768 }
769
770 pub fn add_after_group_hook(
772 &mut self,
773 phase: Phase,
774 group: GroupId,
775 hook: impl Fn(&mut World) + Send + Sync + 'static,
776 ) {
777 self.hooks.add_after_group(phase, group, Box::new(hook));
778 }
779}