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 },
223 );
224 #[cfg(feature = "energy")]
225 if let Some(ref profile) = ec.energy_profile {
226 world.set_energy_profile(eid, profile.clone());
227 world.set_energy_metrics(eid, crate::energy::EnergyMetrics::default());
228 }
229 if let Some(mode) = ec.service_mode {
230 world.set_service_mode(eid, mode);
231 }
232 world.set_destination_queue(eid, crate::components::DestinationQueue::new());
233 eid
234 }
235
236 fn build_legacy_topology(
238 world: &mut World,
239 config: &SimConfig,
240 stop_lookup: &HashMap<StopId, EntityId>,
241 builder_dispatchers: BTreeMap<GroupId, Box<dyn DispatchStrategy>>,
242 ) -> TopologyResult {
243 let all_stop_entities: Vec<EntityId> = stop_lookup.values().copied().collect();
244 let stop_positions: Vec<f64> = config.building.stops.iter().map(|s| s.position).collect();
245 let min_pos = stop_positions.iter().copied().fold(f64::INFINITY, f64::min);
246 let max_pos = stop_positions
247 .iter()
248 .copied()
249 .fold(f64::NEG_INFINITY, f64::max);
250
251 let default_line_eid = world.spawn();
252 world.set_line(
253 default_line_eid,
254 Line {
255 name: "Default".into(),
256 group: GroupId(0),
257 orientation: Orientation::Vertical,
258 position: None,
259 min_position: min_pos,
260 max_position: max_pos,
261 max_cars: None,
262 },
263 );
264
265 let mut elevator_entities = Vec::new();
266 for ec in &config.elevators {
267 let eid = Self::spawn_elevator_entity(
268 world,
269 ec,
270 default_line_eid,
271 stop_lookup,
272 &config.building.stops,
273 );
274 elevator_entities.push(eid);
275 }
276
277 let default_line_info =
278 LineInfo::new(default_line_eid, elevator_entities, all_stop_entities);
279
280 let group = ElevatorGroup::new(GroupId(0), "Default".into(), vec![default_line_info]);
281
282 let mut dispatchers = BTreeMap::new();
284 let dispatch = builder_dispatchers.into_iter().next().map_or_else(
285 || Box::new(crate::dispatch::scan::ScanDispatch::new()) as Box<dyn DispatchStrategy>,
286 |(_, d)| d,
287 );
288 dispatchers.insert(GroupId(0), dispatch);
289
290 let mut strategy_ids = BTreeMap::new();
291 strategy_ids.insert(GroupId(0), BuiltinStrategy::Scan);
292
293 (vec![group], dispatchers, strategy_ids)
294 }
295
296 #[allow(clippy::too_many_lines)]
298 fn build_explicit_topology(
299 world: &mut World,
300 config: &SimConfig,
301 line_configs: &[crate::config::LineConfig],
302 stop_lookup: &HashMap<StopId, EntityId>,
303 builder_dispatchers: BTreeMap<GroupId, Box<dyn DispatchStrategy>>,
304 ) -> TopologyResult {
305 let mut line_map: HashMap<u32, (EntityId, LineInfo)> = HashMap::new();
307
308 for lc in line_configs {
309 let served_entities: Vec<EntityId> = lc
311 .serves
312 .iter()
313 .filter_map(|sid| stop_lookup.get(sid).copied())
314 .collect();
315
316 let stop_positions: Vec<f64> = lc
318 .serves
319 .iter()
320 .filter_map(|sid| {
321 config
322 .building
323 .stops
324 .iter()
325 .find(|s| s.id == *sid)
326 .map(|s| s.position)
327 })
328 .collect();
329 let auto_min = stop_positions.iter().copied().fold(f64::INFINITY, f64::min);
330 let auto_max = stop_positions
331 .iter()
332 .copied()
333 .fold(f64::NEG_INFINITY, f64::max);
334
335 let min_pos = lc.min_position.unwrap_or(auto_min);
336 let max_pos = lc.max_position.unwrap_or(auto_max);
337
338 let line_eid = world.spawn();
339 world.set_line(
342 line_eid,
343 Line {
344 name: lc.name.clone(),
345 group: GroupId(0),
346 orientation: lc.orientation,
347 position: lc.position,
348 min_position: min_pos,
349 max_position: max_pos,
350 max_cars: lc.max_cars,
351 },
352 );
353
354 let mut elevator_entities = Vec::new();
356 for ec in &lc.elevators {
357 let eid = Self::spawn_elevator_entity(
358 world,
359 ec,
360 line_eid,
361 stop_lookup,
362 &config.building.stops,
363 );
364 elevator_entities.push(eid);
365 }
366
367 let line_info = LineInfo::new(line_eid, elevator_entities, served_entities);
368 line_map.insert(lc.id, (line_eid, line_info));
369 }
370
371 let group_configs = config.building.groups.as_deref();
373 let mut groups = Vec::new();
374 let mut dispatchers = BTreeMap::new();
375 let mut strategy_ids = BTreeMap::new();
376
377 if let Some(gcs) = group_configs {
378 for gc in gcs {
379 let group_id = GroupId(gc.id);
380
381 let mut group_lines = Vec::new();
382
383 for &lid in &gc.lines {
384 if let Some((line_eid, li)) = line_map.get(&lid) {
385 if let Some(line_comp) = world.line_mut(*line_eid) {
387 line_comp.group = group_id;
388 }
389 group_lines.push(li.clone());
390 }
391 }
392
393 let group = ElevatorGroup::new(group_id, gc.name.clone(), group_lines);
394 groups.push(group);
395
396 let dispatch: Box<dyn DispatchStrategy> = gc
398 .dispatch
399 .instantiate()
400 .unwrap_or_else(|| Box::new(crate::dispatch::scan::ScanDispatch::new()));
401 dispatchers.insert(group_id, dispatch);
402 strategy_ids.insert(group_id, gc.dispatch.clone());
403 }
404 } else {
405 let group_id = GroupId(0);
407 let mut group_lines = Vec::new();
408
409 for (line_eid, li) in line_map.values() {
410 if let Some(line_comp) = world.line_mut(*line_eid) {
411 line_comp.group = group_id;
412 }
413 group_lines.push(li.clone());
414 }
415
416 let group = ElevatorGroup::new(group_id, "Default".into(), group_lines);
417 groups.push(group);
418
419 let dispatch: Box<dyn DispatchStrategy> =
420 Box::new(crate::dispatch::scan::ScanDispatch::new());
421 dispatchers.insert(group_id, dispatch);
422 strategy_ids.insert(group_id, BuiltinStrategy::Scan);
423 }
424
425 for (gid, d) in builder_dispatchers {
427 dispatchers.insert(gid, d);
428 }
429
430 (groups, dispatchers, strategy_ids)
431 }
432
433 #[allow(clippy::too_many_arguments)]
435 pub(crate) fn from_parts(
436 world: World,
437 tick: u64,
438 dt: f64,
439 groups: Vec<ElevatorGroup>,
440 stop_lookup: HashMap<StopId, EntityId>,
441 dispatchers: BTreeMap<GroupId, Box<dyn DispatchStrategy>>,
442 strategy_ids: BTreeMap<GroupId, crate::dispatch::BuiltinStrategy>,
443 metrics: Metrics,
444 ticks_per_second: f64,
445 ) -> Self {
446 let mut rider_index = RiderIndex::default();
447 rider_index.rebuild(&world);
448 Self {
449 world,
450 events: EventBus::default(),
451 pending_output: Vec::new(),
452 tick,
453 dt,
454 groups,
455 stop_lookup,
456 dispatchers,
457 strategy_ids,
458 repositioners: BTreeMap::new(),
459 reposition_ids: BTreeMap::new(),
460 metrics,
461 time: TimeAdapter::new(ticks_per_second),
462 hooks: PhaseHooks::default(),
463 elevator_ids_buf: Vec::new(),
464 topo_graph: Mutex::new(TopologyGraph::new()),
465 rider_index,
466 }
467 }
468
469 pub(crate) fn validate_config(config: &SimConfig) -> Result<(), SimError> {
471 if config.building.stops.is_empty() {
472 return Err(SimError::InvalidConfig {
473 field: "building.stops",
474 reason: "at least one stop is required".into(),
475 });
476 }
477
478 let mut seen_ids = HashSet::new();
480 for stop in &config.building.stops {
481 if !seen_ids.insert(stop.id) {
482 return Err(SimError::InvalidConfig {
483 field: "building.stops",
484 reason: format!("duplicate {}", stop.id),
485 });
486 }
487 }
488
489 let stop_ids: HashSet<StopId> = config.building.stops.iter().map(|s| s.id).collect();
490
491 if let Some(line_configs) = &config.building.lines {
492 Self::validate_explicit_topology(line_configs, &stop_ids, &config.building)?;
494 } else {
495 Self::validate_legacy_elevators(&config.elevators, &config.building)?;
497 }
498
499 if config.simulation.ticks_per_second <= 0.0 {
500 return Err(SimError::InvalidConfig {
501 field: "simulation.ticks_per_second",
502 reason: format!(
503 "must be positive, got {}",
504 config.simulation.ticks_per_second
505 ),
506 });
507 }
508
509 Ok(())
510 }
511
512 fn validate_legacy_elevators(
514 elevators: &[crate::config::ElevatorConfig],
515 building: &crate::config::BuildingConfig,
516 ) -> Result<(), SimError> {
517 if elevators.is_empty() {
518 return Err(SimError::InvalidConfig {
519 field: "elevators",
520 reason: "at least one elevator is required".into(),
521 });
522 }
523
524 for elev in elevators {
525 Self::validate_elevator_config(elev, building)?;
526 }
527
528 Ok(())
529 }
530
531 fn validate_elevator_config(
533 elev: &crate::config::ElevatorConfig,
534 building: &crate::config::BuildingConfig,
535 ) -> Result<(), SimError> {
536 if elev.max_speed <= 0.0 {
537 return Err(SimError::InvalidConfig {
538 field: "elevators.max_speed",
539 reason: format!("must be positive, got {}", elev.max_speed),
540 });
541 }
542 if elev.acceleration <= 0.0 {
543 return Err(SimError::InvalidConfig {
544 field: "elevators.acceleration",
545 reason: format!("must be positive, got {}", elev.acceleration),
546 });
547 }
548 if elev.deceleration <= 0.0 {
549 return Err(SimError::InvalidConfig {
550 field: "elevators.deceleration",
551 reason: format!("must be positive, got {}", elev.deceleration),
552 });
553 }
554 if elev.weight_capacity <= 0.0 {
555 return Err(SimError::InvalidConfig {
556 field: "elevators.weight_capacity",
557 reason: format!("must be positive, got {}", elev.weight_capacity),
558 });
559 }
560 if elev.inspection_speed_factor <= 0.0 {
561 return Err(SimError::InvalidConfig {
562 field: "elevators.inspection_speed_factor",
563 reason: format!("must be positive, got {}", elev.inspection_speed_factor),
564 });
565 }
566 if !building.stops.iter().any(|s| s.id == elev.starting_stop) {
567 return Err(SimError::InvalidConfig {
568 field: "elevators.starting_stop",
569 reason: format!("references non-existent {}", elev.starting_stop),
570 });
571 }
572 Ok(())
573 }
574
575 fn validate_explicit_topology(
577 line_configs: &[crate::config::LineConfig],
578 stop_ids: &HashSet<StopId>,
579 building: &crate::config::BuildingConfig,
580 ) -> Result<(), SimError> {
581 let mut seen_line_ids = HashSet::new();
583 for lc in line_configs {
584 if !seen_line_ids.insert(lc.id) {
585 return Err(SimError::InvalidConfig {
586 field: "building.lines",
587 reason: format!("duplicate line id {}", lc.id),
588 });
589 }
590 }
591
592 for lc in line_configs {
594 for sid in &lc.serves {
595 if !stop_ids.contains(sid) {
596 return Err(SimError::InvalidConfig {
597 field: "building.lines.serves",
598 reason: format!("line {} references non-existent {}", lc.id, sid),
599 });
600 }
601 }
602 for ec in &lc.elevators {
604 Self::validate_elevator_config(ec, building)?;
605 }
606
607 if let Some(max) = lc.max_cars
609 && lc.elevators.len() > max
610 {
611 return Err(SimError::InvalidConfig {
612 field: "building.lines.max_cars",
613 reason: format!(
614 "line {} has {} elevators but max_cars is {max}",
615 lc.id,
616 lc.elevators.len()
617 ),
618 });
619 }
620 }
621
622 let has_elevator = line_configs.iter().any(|lc| !lc.elevators.is_empty());
624 if !has_elevator {
625 return Err(SimError::InvalidConfig {
626 field: "building.lines",
627 reason: "at least one line must have at least one elevator".into(),
628 });
629 }
630
631 let served: HashSet<StopId> = line_configs
633 .iter()
634 .flat_map(|lc| lc.serves.iter().copied())
635 .collect();
636 for sid in stop_ids {
637 if !served.contains(sid) {
638 return Err(SimError::InvalidConfig {
639 field: "building.lines",
640 reason: format!("orphaned stop {sid} not served by any line"),
641 });
642 }
643 }
644
645 if let Some(group_configs) = &building.groups {
647 let line_id_set: HashSet<u32> = line_configs.iter().map(|lc| lc.id).collect();
648
649 let mut seen_group_ids = HashSet::new();
650 for gc in group_configs {
651 if !seen_group_ids.insert(gc.id) {
652 return Err(SimError::InvalidConfig {
653 field: "building.groups",
654 reason: format!("duplicate group id {}", gc.id),
655 });
656 }
657 for &lid in &gc.lines {
658 if !line_id_set.contains(&lid) {
659 return Err(SimError::InvalidConfig {
660 field: "building.groups.lines",
661 reason: format!(
662 "group {} references non-existent line id {}",
663 gc.id, lid
664 ),
665 });
666 }
667 }
668 }
669
670 let referenced_line_ids: HashSet<u32> = group_configs
672 .iter()
673 .flat_map(|g| g.lines.iter().copied())
674 .collect();
675 for lc in line_configs {
676 if !referenced_line_ids.contains(&lc.id) {
677 return Err(SimError::InvalidConfig {
678 field: "building.lines",
679 reason: format!("line {} is not assigned to any group", lc.id),
680 });
681 }
682 }
683 }
684
685 Ok(())
686 }
687
688 pub fn set_dispatch(
695 &mut self,
696 group: GroupId,
697 strategy: Box<dyn DispatchStrategy>,
698 id: crate::dispatch::BuiltinStrategy,
699 ) {
700 self.dispatchers.insert(group, strategy);
701 self.strategy_ids.insert(group, id);
702 }
703
704 pub fn set_reposition(
711 &mut self,
712 group: GroupId,
713 strategy: Box<dyn RepositionStrategy>,
714 id: BuiltinReposition,
715 ) {
716 self.repositioners.insert(group, strategy);
717 self.reposition_ids.insert(group, id);
718 }
719
720 pub fn remove_reposition(&mut self, group: GroupId) {
722 self.repositioners.remove(&group);
723 self.reposition_ids.remove(&group);
724 }
725
726 #[must_use]
728 pub fn reposition_id(&self, group: GroupId) -> Option<&BuiltinReposition> {
729 self.reposition_ids.get(&group)
730 }
731
732 pub fn add_before_hook(
739 &mut self,
740 phase: Phase,
741 hook: impl Fn(&mut World) + Send + Sync + 'static,
742 ) {
743 self.hooks.add_before(phase, Box::new(hook));
744 }
745
746 pub fn add_after_hook(
751 &mut self,
752 phase: Phase,
753 hook: impl Fn(&mut World) + Send + Sync + 'static,
754 ) {
755 self.hooks.add_after(phase, Box::new(hook));
756 }
757
758 pub fn add_before_group_hook(
760 &mut self,
761 phase: Phase,
762 group: GroupId,
763 hook: impl Fn(&mut World) + Send + Sync + 'static,
764 ) {
765 self.hooks.add_before_group(phase, group, Box::new(hook));
766 }
767
768 pub fn add_after_group_hook(
770 &mut self,
771 phase: Phase,
772 group: GroupId,
773 hook: impl Fn(&mut World) + Send + Sync + 'static,
774 ) {
775 self.hooks.add_after_group(phase, group, Box::new(hook));
776 }
777}