1use crate::components::Route;
8use crate::components::{Elevator, ElevatorPhase, Line, LineKind, Position, Stop, Velocity};
9use crate::dispatch::{BuiltinStrategy, DispatchStrategy, ElevatorGroup, LineInfo};
10use crate::door::DoorState;
11use crate::entity::EntityId;
12use crate::error::SimError;
13use crate::events::Event;
14use crate::ids::GroupId;
15use crate::topology::TopologyGraph;
16
17use super::{ElevatorParams, LineParams, Simulation};
18
19impl Simulation {
20 fn mark_topo_dirty(&self) {
24 if let Ok(mut g) = self.topo_graph.lock() {
25 g.mark_dirty();
26 }
27 }
28
29 fn find_line(&self, line: EntityId) -> Result<(usize, usize), SimError> {
31 self.groups
32 .iter()
33 .enumerate()
34 .find_map(|(gi, g)| {
35 g.lines()
36 .iter()
37 .position(|li| li.entity() == line)
38 .map(|li_idx| (gi, li_idx))
39 })
40 .ok_or(SimError::LineNotFound(line))
41 }
42
43 pub fn add_stop(
53 &mut self,
54 name: String,
55 position: f64,
56 line: EntityId,
57 ) -> Result<EntityId, SimError> {
58 if !position.is_finite() {
59 return Err(SimError::InvalidConfig {
60 field: "position",
61 reason: format!(
62 "stop position must be finite (got {position}); NaN/±inf \
63 corrupt SortedStops ordering and find_stop_at_position lookup"
64 ),
65 });
66 }
67
68 let group_id = self
69 .world
70 .line(line)
71 .map(|l| l.group)
72 .ok_or(SimError::LineNotFound(line))?;
73
74 let (group_idx, line_idx) = self.find_line(line)?;
75
76 let eid = self.world.spawn();
77 self.world.set_stop(eid, Stop { name, position });
78 self.world.set_position(eid, Position { value: position });
79
80 self.groups[group_idx].lines_mut()[line_idx].add_stop(eid);
82
83 self.groups[group_idx].push_stop(eid);
85
86 if let Some(sorted) = self.world.resource_mut::<crate::world::SortedStops>() {
88 let idx = sorted.0.partition_point(|&(p, _)| p < position);
89 sorted.0.insert(idx, (position, eid));
90 }
91
92 self.mark_topo_dirty();
93 self.events.emit(Event::StopAdded {
94 stop: eid,
95 line,
96 group: group_id,
97 tick: self.tick,
98 });
99 Ok(eid)
100 }
101
102 pub fn add_elevator(
108 &mut self,
109 params: &ElevatorParams,
110 line: EntityId,
111 starting_position: f64,
112 ) -> Result<EntityId, SimError> {
113 super::construction::validate_elevator_physics(
116 params.max_speed.value(),
117 params.acceleration.value(),
118 params.deceleration.value(),
119 params.weight_capacity.value(),
120 params.inspection_speed_factor,
121 params.door_transition_ticks,
122 params.door_open_ticks,
123 params.bypass_load_up_pct,
124 params.bypass_load_down_pct,
125 )?;
126 if !starting_position.is_finite() {
127 return Err(SimError::InvalidConfig {
128 field: "starting_position",
129 reason: format!(
130 "must be finite (got {starting_position}); NaN/±inf corrupt \
131 SortedStops ordering and find_stop_at_position lookup"
132 ),
133 });
134 }
135
136 let group_id = self
137 .world
138 .line(line)
139 .map(|l| l.group)
140 .ok_or(SimError::LineNotFound(line))?;
141
142 let (group_idx, line_idx) = self.find_line(line)?;
143
144 if let Some(max) = self.world.line(line).and_then(Line::max_cars) {
146 let current_count = self.groups[group_idx].lines()[line_idx].elevators().len();
147 if current_count >= max {
148 return Err(SimError::InvalidConfig {
149 field: "line.max_cars",
150 reason: format!("line already has {current_count} cars (max {max})"),
151 });
152 }
153 }
154
155 let eid = self.world.spawn();
156 self.world.set_position(
157 eid,
158 Position {
159 value: starting_position,
160 },
161 );
162 self.world.set_velocity(eid, Velocity { value: 0.0 });
163 self.world.set_elevator(
164 eid,
165 Elevator {
166 phase: ElevatorPhase::Idle,
167 door: DoorState::Closed,
168 max_speed: params.max_speed,
169 acceleration: params.acceleration,
170 deceleration: params.deceleration,
171 weight_capacity: params.weight_capacity,
172 current_load: crate::components::Weight::ZERO,
173 riders: Vec::new(),
174 target_stop: None,
175 door_transition_ticks: params.door_transition_ticks,
176 door_open_ticks: params.door_open_ticks,
177 line,
178 repositioning: false,
179 restricted_stops: params.restricted_stops.clone(),
180 inspection_speed_factor: params.inspection_speed_factor,
181 going_up: true,
182 going_down: true,
183 going_forward: false,
184 move_count: 0,
185 door_command_queue: Vec::new(),
186 manual_target_velocity: None,
187 bypass_load_up_pct: params.bypass_load_up_pct,
188 bypass_load_down_pct: params.bypass_load_down_pct,
189 home_stop: None,
190 },
191 );
192 self.world
193 .set_destination_queue(eid, crate::components::DestinationQueue::new());
194 self.groups[group_idx].lines_mut()[line_idx].add_elevator(eid);
195 self.groups[group_idx].push_elevator(eid);
196
197 let line_name = self.world.line(line).map(|l| l.name.clone());
199 if let Some(name) = line_name
200 && let Some(tags) = self
201 .world
202 .resource_mut::<crate::tagged_metrics::MetricTags>()
203 {
204 tags.tag(eid, format!("line:{name}"));
205 }
206
207 self.mark_topo_dirty();
208 self.events.emit(Event::ElevatorAdded {
209 elevator: eid,
210 line,
211 group: group_id,
212 tick: self.tick,
213 });
214 Ok(eid)
215 }
216
217 pub fn add_line(&mut self, params: &LineParams) -> Result<EntityId, SimError> {
231 let kind = params.kind.unwrap_or(LineKind::Linear {
236 min: params.min_position,
237 max: params.max_position,
238 });
239 kind.validate()
240 .map_err(|(field, reason)| SimError::InvalidConfig { field, reason })?;
241
242 #[cfg(feature = "loop_lines")]
254 if let LineKind::Loop {
255 circumference,
256 min_headway,
257 } = kind
258 && let Some(max_cars) = params.max_cars
259 && max_cars > 0
260 {
261 #[allow(
262 clippy::cast_precision_loss,
263 reason = "max_cars is bounded by usize; the comparison is against a finite f64"
264 )]
265 let required = (max_cars as f64) * min_headway;
266 if required > circumference {
267 return Err(SimError::InvalidConfig {
268 field: "line.kind",
269 reason: format!(
270 "loop line: {max_cars} cars × min_headway {min_headway} = {required} \
271 exceeds circumference {circumference}",
272 ),
273 });
274 }
275 }
276
277 let group_id = params.group;
278 let group = self
279 .groups
280 .iter_mut()
281 .find(|g| g.id() == group_id)
282 .ok_or(SimError::GroupNotFound(group_id))?;
283
284 let line_tag = format!("line:{}", params.name);
285
286 let eid = self.world.spawn();
287 self.world.set_line(
288 eid,
289 Line {
290 name: params.name.clone(),
291 group: group_id,
292 orientation: params.orientation,
293 position: params.position,
294 kind,
295 max_cars: params.max_cars,
296 },
297 );
298
299 group
300 .lines_mut()
301 .push(LineInfo::new(eid, Vec::new(), Vec::new()));
302
303 if let Some(tags) = self
305 .world
306 .resource_mut::<crate::tagged_metrics::MetricTags>()
307 {
308 tags.tag(eid, line_tag);
309 }
310
311 self.mark_topo_dirty();
312 self.events.emit(Event::LineAdded {
313 line: eid,
314 group: group_id,
315 tick: self.tick,
316 });
317 Ok(eid)
318 }
319
320 pub fn set_line_range(&mut self, line: EntityId, min: f64, max: f64) -> Result<(), SimError> {
333 if !min.is_finite() || !max.is_finite() {
334 return Err(SimError::InvalidConfig {
335 field: "line.range",
336 reason: format!("min/max must be finite (got min={min}, max={max})"),
337 });
338 }
339 if min > max {
340 return Err(SimError::InvalidConfig {
341 field: "line.range",
342 reason: format!("min ({min}) must be <= max ({max})"),
343 });
344 }
345 let line_ref = self
346 .world
347 .line_mut(line)
348 .ok_or(SimError::LineNotFound(line))?;
349 match &mut line_ref.kind {
353 LineKind::Linear {
354 min: kmin,
355 max: kmax,
356 } => {
357 *kmin = min;
358 *kmax = max;
359 }
360 #[cfg(feature = "loop_lines")]
361 LineKind::Loop { .. } => {
362 return Err(SimError::InvalidConfig {
363 field: "line.range",
364 reason: "set_line_range is not valid on a Loop line; \
365 change circumference via a future API instead"
366 .to_string(),
367 });
368 }
369 }
370
371 let car_ids: Vec<EntityId> = self
373 .world
374 .iter_elevators()
375 .filter_map(|(eid, _, car)| (car.line == line).then_some(eid))
376 .collect();
377 for eid in car_ids {
378 let Some(pos) = self.world.position(eid).map(|p| p.value) else {
382 continue;
383 };
384 if pos < min || pos > max {
385 let clamped = pos.clamp(min, max);
386 if let Some(p) = self.world.position_mut(eid) {
387 p.value = clamped;
388 }
389 if let Some(v) = self.world.velocity_mut(eid) {
390 v.value = 0.0;
391 }
392 }
393 }
394
395 self.mark_topo_dirty();
396 Ok(())
397 }
398
399 pub fn remove_line(&mut self, line: EntityId) -> Result<(), SimError> {
409 let (group_idx, line_idx) = self.find_line(line)?;
410
411 let group_id = self.groups[group_idx].id();
412
413 let elevator_ids: Vec<EntityId> = self.groups[group_idx].lines()[line_idx]
415 .elevators()
416 .to_vec();
417
418 for eid in &elevator_ids {
420 let _ = self.disable(*eid);
422 }
423
424 self.groups[group_idx].lines_mut().remove(line_idx);
426
427 self.groups[group_idx].rebuild_caches();
429
430 self.world.remove_line(line);
432
433 self.mark_topo_dirty();
434 self.events.emit(Event::LineRemoved {
435 line,
436 group: group_id,
437 tick: self.tick,
438 });
439 Ok(())
440 }
441
442 pub fn remove_elevator(&mut self, elevator: EntityId) -> Result<(), SimError> {
451 let line = self
452 .world
453 .elevator(elevator)
454 .ok_or(SimError::EntityNotFound(elevator))?
455 .line();
456
457 let _ = self.disable(elevator);
459
460 let resolved_group: Option<GroupId> = match self.find_line(line) {
471 Ok((group_idx, line_idx)) => {
472 self.groups[group_idx].lines_mut()[line_idx].remove_elevator(elevator);
473 self.groups[group_idx].rebuild_caches();
474 Some(self.groups[group_idx].id())
475 }
476 Err(_) => None,
477 };
478
479 if let Some(group_id) = resolved_group {
483 self.events.emit(Event::ElevatorRemoved {
484 elevator,
485 line,
486 group: group_id,
487 tick: self.tick,
488 });
489 }
490
491 self.world.despawn(elevator);
493
494 self.mark_topo_dirty();
495 Ok(())
496 }
497
498 pub fn remove_stop(&mut self, stop: EntityId) -> Result<(), SimError> {
507 if self.world.stop(stop).is_none() {
508 return Err(SimError::EntityNotFound(stop));
509 }
510
511 let residents: Vec<EntityId> = self
514 .rider_index
515 .residents_at(stop)
516 .iter()
517 .copied()
518 .collect();
519 if !residents.is_empty() {
520 self.events
521 .emit(Event::ResidentsAtRemovedStop { stop, residents });
522 }
523
524 self.disable_stop_inner(stop, true);
528 self.world.disable(stop);
529 self.events.emit(Event::EntityDisabled {
530 entity: stop,
531 tick: self.tick,
532 });
533
534 let elevator_ids: Vec<EntityId> =
538 self.world.iter_elevators().map(|(eid, _, _)| eid).collect();
539 for eid in elevator_ids {
540 if let Some(car) = self.world.elevator_mut(eid) {
541 if car.target_stop == Some(stop) {
542 car.target_stop = None;
543 }
544 car.restricted_stops.remove(&stop);
545 }
546 if let Some(q) = self.world.destination_queue_mut(eid) {
547 q.retain(|s| s != stop);
548 }
549 if let Some(calls) = self.world.car_calls_mut(eid) {
554 calls.retain(|c| c.floor != stop);
555 }
556 }
557
558 for group in &mut self.groups {
560 for line_info in group.lines_mut() {
561 line_info.remove_stop(stop);
562 }
563 group.rebuild_caches();
564 }
565
566 if let Some(sorted) = self.world.resource_mut::<crate::world::SortedStops>() {
568 sorted.0.retain(|&(_, s)| s != stop);
569 }
570
571 self.stop_lookup.retain(|_, &mut eid| eid != stop);
573
574 self.events.emit(Event::StopRemoved {
575 stop,
576 tick: self.tick,
577 });
578
579 self.world.despawn(stop);
581
582 self.rider_index.rebuild(&self.world);
586
587 self.mark_topo_dirty();
588 Ok(())
589 }
590
591 pub fn add_group(
593 &mut self,
594 name: impl Into<String>,
595 dispatch: impl DispatchStrategy + 'static,
596 ) -> GroupId {
597 let next_id = self
598 .groups
599 .iter()
600 .map(|g| g.id().0)
601 .max()
602 .map_or(0, |m| m + 1);
603 let group_id = GroupId(next_id);
604
605 self.groups
606 .push(ElevatorGroup::new(group_id, name.into(), Vec::new()));
607
608 self.dispatcher_set
609 .insert(group_id, Box::new(dispatch), BuiltinStrategy::Scan);
610 self.mark_topo_dirty();
611 group_id
612 }
613
614 pub fn assign_line_to_group(
621 &mut self,
622 line: EntityId,
623 new_group: GroupId,
624 ) -> Result<GroupId, SimError> {
625 let (old_group_idx, line_idx) = self.find_line(line)?;
626
627 if !self.groups.iter().any(|g| g.id() == new_group) {
629 return Err(SimError::GroupNotFound(new_group));
630 }
631
632 let old_group_id = self.groups[old_group_idx].id();
633
634 if old_group_id == new_group {
639 return Ok(old_group_id);
640 }
641
642 let elevators_to_notify: Vec<EntityId> = self.groups[old_group_idx].lines()[line_idx]
647 .elevators()
648 .to_vec();
649 if let Some(dispatcher) = self.dispatcher_set.strategies_mut().get_mut(&old_group_id) {
650 for eid in &elevators_to_notify {
651 dispatcher.notify_removed(*eid);
652 }
653 }
654
655 let line_info = self.groups[old_group_idx].lines_mut().remove(line_idx);
657 self.groups[old_group_idx].rebuild_caches();
658
659 let new_group_idx = self
664 .groups
665 .iter()
666 .position(|g| g.id() == new_group)
667 .ok_or(SimError::GroupNotFound(new_group))?;
668 self.groups[new_group_idx].lines_mut().push(line_info);
669 self.groups[new_group_idx].rebuild_caches();
670
671 if let Some(line_comp) = self.world.line_mut(line) {
673 line_comp.group = new_group;
674 }
675
676 self.mark_topo_dirty();
677 self.events.emit(Event::LineReassigned {
678 line,
679 old_group: old_group_id,
680 new_group,
681 tick: self.tick,
682 });
683
684 Ok(old_group_id)
685 }
686
687 pub fn reassign_elevator_to_line(
698 &mut self,
699 elevator: EntityId,
700 new_line: EntityId,
701 ) -> Result<(), SimError> {
702 let old_line = self
703 .world
704 .elevator(elevator)
705 .ok_or(SimError::EntityNotFound(elevator))?
706 .line();
707
708 if old_line == new_line {
709 return Ok(());
710 }
711
712 let (old_group_idx, old_line_idx) = self.find_line(old_line)?;
714 let (new_group_idx, new_line_idx) = self.find_line(new_line)?;
715
716 if let Some(max) = self.world.line(new_line).and_then(Line::max_cars) {
718 let current_count = self.groups[new_group_idx].lines()[new_line_idx]
719 .elevators()
720 .len();
721 if current_count >= max {
722 return Err(SimError::InvalidConfig {
723 field: "line.max_cars",
724 reason: format!("target line already has {current_count} cars (max {max})"),
725 });
726 }
727 }
728
729 let old_group_id = self.groups[old_group_idx].id();
730 let new_group_id = self.groups[new_group_idx].id();
731
732 self.groups[old_group_idx].lines_mut()[old_line_idx].remove_elevator(elevator);
733 self.groups[new_group_idx].lines_mut()[new_line_idx].add_elevator(elevator);
734
735 if let Some(car) = self.world.elevator_mut(elevator) {
736 car.line = new_line;
737 }
738
739 self.groups[old_group_idx].rebuild_caches();
740 if new_group_idx != old_group_idx {
741 self.groups[new_group_idx].rebuild_caches();
742
743 if let Some(old_dispatcher) =
747 self.dispatcher_set.strategies_mut().get_mut(&old_group_id)
748 {
749 old_dispatcher.notify_removed(elevator);
750 }
751 }
752
753 self.mark_topo_dirty();
754
755 let _ = new_group_id; self.events.emit(Event::ElevatorReassigned {
757 elevator,
758 old_line,
759 new_line,
760 tick: self.tick,
761 });
762
763 Ok(())
764 }
765
766 pub fn add_stop_to_line(&mut self, stop: EntityId, line: EntityId) -> Result<(), SimError> {
773 if self.world.stop(stop).is_none() {
775 return Err(SimError::EntityNotFound(stop));
776 }
777
778 let (group_idx, line_idx) = self.find_line(line)?;
779
780 let li = &mut self.groups[group_idx].lines_mut()[line_idx];
781 li.add_stop(stop);
782
783 self.groups[group_idx].push_stop(stop);
784
785 self.mark_topo_dirty();
786 Ok(())
787 }
788
789 pub fn remove_stop_from_line(
795 &mut self,
796 stop: EntityId,
797 line: EntityId,
798 ) -> Result<(), SimError> {
799 let (group_idx, line_idx) = self.find_line(line)?;
800
801 self.groups[group_idx].lines_mut()[line_idx].remove_stop(stop);
802
803 self.groups[group_idx].rebuild_caches();
805
806 self.mark_topo_dirty();
807 Ok(())
808 }
809
810 #[must_use]
814 pub fn all_lines(&self) -> Vec<EntityId> {
815 self.groups
816 .iter()
817 .flat_map(|g| g.lines().iter().map(LineInfo::entity))
818 .collect()
819 }
820
821 #[must_use]
823 pub fn line_count(&self) -> usize {
824 self.groups.iter().map(|g| g.lines().len()).sum()
825 }
826
827 #[must_use]
829 pub fn lines_in_group(&self, group: GroupId) -> Vec<EntityId> {
830 self.groups
831 .iter()
832 .find(|g| g.id() == group)
833 .map_or_else(Vec::new, |g| {
834 g.lines().iter().map(LineInfo::entity).collect()
835 })
836 }
837
838 #[must_use]
840 pub fn elevators_on_line(&self, line: EntityId) -> Vec<EntityId> {
841 self.groups
842 .iter()
843 .flat_map(ElevatorGroup::lines)
844 .find(|li| li.entity() == line)
845 .map_or_else(Vec::new, |li| li.elevators().to_vec())
846 }
847
848 #[must_use]
850 pub fn stops_served_by_line(&self, line: EntityId) -> Vec<EntityId> {
851 self.groups
852 .iter()
853 .flat_map(ElevatorGroup::lines)
854 .find(|li| li.entity() == line)
855 .map_or_else(Vec::new, |li| li.serves().to_vec())
856 }
857
858 #[must_use]
871 pub fn find_stop_at_position_on_line(&self, position: f64, line: EntityId) -> Option<EntityId> {
872 let line_info = self
873 .groups
874 .iter()
875 .flat_map(ElevatorGroup::lines)
876 .find(|li| li.entity() == line)?;
877 self.world
878 .find_stop_at_position_in(position, line_info.serves())
879 }
880
881 #[must_use]
883 pub fn line_for_elevator(&self, elevator: EntityId) -> Option<EntityId> {
884 self.groups
885 .iter()
886 .flat_map(ElevatorGroup::lines)
887 .find(|li| li.elevators().contains(&elevator))
888 .map(LineInfo::entity)
889 }
890
891 pub fn iter_repositioning_elevators(&self) -> impl Iterator<Item = EntityId> + '_ {
893 self.world
894 .iter_elevators()
895 .filter_map(|(id, _pos, car)| if car.repositioning() { Some(id) } else { None })
896 }
897
898 #[must_use]
900 pub fn lines_serving_stop(&self, stop: EntityId) -> Vec<EntityId> {
901 self.groups
902 .iter()
903 .flat_map(ElevatorGroup::lines)
904 .filter(|li| li.serves().contains(&stop))
905 .map(LineInfo::entity)
906 .collect()
907 }
908
909 #[must_use]
911 pub fn groups_serving_stop(&self, stop: EntityId) -> Vec<GroupId> {
912 self.groups
913 .iter()
914 .filter(|g| g.stop_entities().contains(&stop))
915 .map(ElevatorGroup::id)
916 .collect()
917 }
918
919 fn ensure_graph_built(&self) {
923 if let Ok(mut graph) = self.topo_graph.lock()
924 && graph.is_dirty()
925 {
926 graph.rebuild(&self.groups);
927 }
928 }
929
930 pub fn reachable_stops_from(&self, stop: EntityId) -> Vec<EntityId> {
932 self.ensure_graph_built();
933 self.topo_graph
934 .lock()
935 .map_or_else(|_| Vec::new(), |g| g.reachable_stops_from(stop))
936 }
937
938 pub fn transfer_points(&self) -> Vec<EntityId> {
940 self.ensure_graph_built();
941 TopologyGraph::transfer_points(&self.groups)
942 }
943
944 pub fn shortest_route(&self, from: EntityId, to: EntityId) -> Option<Route> {
946 self.ensure_graph_built();
947 self.topo_graph
948 .lock()
949 .ok()
950 .and_then(|g| g.shortest_route(from, to))
951 }
952}