1use crate::components::Route;
8use crate::components::{Elevator, ElevatorPhase, Line, 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]
82 .serves_mut()
83 .push(eid);
84
85 self.groups[group_idx].push_stop(eid);
87
88 if let Some(sorted) = self.world.resource_mut::<crate::world::SortedStops>() {
90 let idx = sorted.0.partition_point(|&(p, _)| p < position);
91 sorted.0.insert(idx, (position, eid));
92 }
93
94 self.mark_topo_dirty();
95 self.events.emit(Event::StopAdded {
96 stop: eid,
97 line,
98 group: group_id,
99 tick: self.tick,
100 });
101 Ok(eid)
102 }
103
104 pub fn add_elevator(
110 &mut self,
111 params: &ElevatorParams,
112 line: EntityId,
113 starting_position: f64,
114 ) -> Result<EntityId, SimError> {
115 super::construction::validate_elevator_physics(
118 params.max_speed.value(),
119 params.acceleration.value(),
120 params.deceleration.value(),
121 params.weight_capacity.value(),
122 params.inspection_speed_factor,
123 params.door_transition_ticks,
124 params.door_open_ticks,
125 params.bypass_load_up_pct,
126 params.bypass_load_down_pct,
127 )?;
128 if !starting_position.is_finite() {
129 return Err(SimError::InvalidConfig {
130 field: "starting_position",
131 reason: format!(
132 "must be finite (got {starting_position}); NaN/±inf corrupt \
133 SortedStops ordering and find_stop_at_position lookup"
134 ),
135 });
136 }
137
138 let group_id = self
139 .world
140 .line(line)
141 .map(|l| l.group)
142 .ok_or(SimError::LineNotFound(line))?;
143
144 let (group_idx, line_idx) = self.find_line(line)?;
145
146 if let Some(max) = self.world.line(line).and_then(Line::max_cars) {
148 let current_count = self.groups[group_idx].lines()[line_idx].elevators().len();
149 if current_count >= max {
150 return Err(SimError::InvalidConfig {
151 field: "line.max_cars",
152 reason: format!("line already has {current_count} cars (max {max})"),
153 });
154 }
155 }
156
157 let eid = self.world.spawn();
158 self.world.set_position(
159 eid,
160 Position {
161 value: starting_position,
162 },
163 );
164 self.world.set_velocity(eid, Velocity { value: 0.0 });
165 self.world.set_elevator(
166 eid,
167 Elevator {
168 phase: ElevatorPhase::Idle,
169 door: DoorState::Closed,
170 max_speed: params.max_speed,
171 acceleration: params.acceleration,
172 deceleration: params.deceleration,
173 weight_capacity: params.weight_capacity,
174 current_load: crate::components::Weight::ZERO,
175 riders: Vec::new(),
176 target_stop: None,
177 door_transition_ticks: params.door_transition_ticks,
178 door_open_ticks: params.door_open_ticks,
179 line,
180 repositioning: false,
181 restricted_stops: params.restricted_stops.clone(),
182 inspection_speed_factor: params.inspection_speed_factor,
183 going_up: true,
184 going_down: true,
185 move_count: 0,
186 door_command_queue: Vec::new(),
187 manual_target_velocity: None,
188 bypass_load_up_pct: params.bypass_load_up_pct,
189 bypass_load_down_pct: params.bypass_load_down_pct,
190 },
191 );
192 self.world
193 .set_destination_queue(eid, crate::components::DestinationQueue::new());
194 self.groups[group_idx].lines_mut()[line_idx]
195 .elevators_mut()
196 .push(eid);
197 self.groups[group_idx].push_elevator(eid);
198
199 let line_name = self.world.line(line).map(|l| l.name.clone());
201 if let Some(name) = line_name
202 && let Some(tags) = self
203 .world
204 .resource_mut::<crate::tagged_metrics::MetricTags>()
205 {
206 tags.tag(eid, format!("line:{name}"));
207 }
208
209 self.mark_topo_dirty();
210 self.events.emit(Event::ElevatorAdded {
211 elevator: eid,
212 line,
213 group: group_id,
214 tick: self.tick,
215 });
216 Ok(eid)
217 }
218
219 pub fn add_line(&mut self, params: &LineParams) -> Result<EntityId, SimError> {
227 let group_id = params.group;
228 let group = self
229 .groups
230 .iter_mut()
231 .find(|g| g.id() == group_id)
232 .ok_or(SimError::GroupNotFound(group_id))?;
233
234 let line_tag = format!("line:{}", params.name);
235
236 let eid = self.world.spawn();
237 self.world.set_line(
238 eid,
239 Line {
240 name: params.name.clone(),
241 group: group_id,
242 orientation: params.orientation,
243 position: params.position,
244 min_position: params.min_position,
245 max_position: params.max_position,
246 max_cars: params.max_cars,
247 },
248 );
249
250 group
251 .lines_mut()
252 .push(LineInfo::new(eid, Vec::new(), Vec::new()));
253
254 if let Some(tags) = self
256 .world
257 .resource_mut::<crate::tagged_metrics::MetricTags>()
258 {
259 tags.tag(eid, line_tag);
260 }
261
262 self.mark_topo_dirty();
263 self.events.emit(Event::LineAdded {
264 line: eid,
265 group: group_id,
266 tick: self.tick,
267 });
268 Ok(eid)
269 }
270
271 pub fn remove_line(&mut self, line: EntityId) -> Result<(), SimError> {
281 let (group_idx, line_idx) = self.find_line(line)?;
282
283 let group_id = self.groups[group_idx].id();
284
285 let elevator_ids: Vec<EntityId> = self.groups[group_idx].lines()[line_idx]
287 .elevators()
288 .to_vec();
289
290 for eid in &elevator_ids {
292 let _ = self.disable(*eid);
294 }
295
296 self.groups[group_idx].lines_mut().remove(line_idx);
298
299 self.groups[group_idx].rebuild_caches();
301
302 self.world.remove_line(line);
304
305 self.mark_topo_dirty();
306 self.events.emit(Event::LineRemoved {
307 line,
308 group: group_id,
309 tick: self.tick,
310 });
311 Ok(())
312 }
313
314 pub fn remove_elevator(&mut self, elevator: EntityId) -> Result<(), SimError> {
323 let line = self
324 .world
325 .elevator(elevator)
326 .ok_or(SimError::EntityNotFound(elevator))?
327 .line();
328
329 let _ = self.disable(elevator);
331
332 let resolved_group: Option<GroupId> = match self.find_line(line) {
336 Ok((group_idx, line_idx)) => {
337 self.groups[group_idx].lines_mut()[line_idx]
338 .elevators_mut()
339 .retain(|&e| e != elevator);
340 self.groups[group_idx].rebuild_caches();
341
342 let gid = self.groups[group_idx].id();
343 if let Some(dispatcher) = self.dispatchers.get_mut(&gid) {
345 dispatcher.notify_removed(elevator);
346 }
347 Some(gid)
348 }
349 Err(_) => None,
350 };
351
352 if let Some(group_id) = resolved_group {
356 self.events.emit(Event::ElevatorRemoved {
357 elevator,
358 line,
359 group: group_id,
360 tick: self.tick,
361 });
362 }
363
364 self.world.despawn(elevator);
366
367 self.mark_topo_dirty();
368 Ok(())
369 }
370
371 pub fn remove_stop(&mut self, stop: EntityId) -> Result<(), SimError> {
380 if self.world.stop(stop).is_none() {
381 return Err(SimError::EntityNotFound(stop));
382 }
383
384 let residents: Vec<EntityId> = self
387 .rider_index
388 .residents_at(stop)
389 .iter()
390 .copied()
391 .collect();
392 if !residents.is_empty() {
393 self.events
394 .emit(Event::ResidentsAtRemovedStop { stop, residents });
395 }
396
397 let _ = self.disable(stop);
399
400 let elevator_ids: Vec<EntityId> =
404 self.world.iter_elevators().map(|(eid, _, _)| eid).collect();
405 for eid in elevator_ids {
406 if let Some(car) = self.world.elevator_mut(eid) {
407 if car.target_stop == Some(stop) {
408 car.target_stop = None;
409 }
410 car.restricted_stops.remove(&stop);
411 }
412 if let Some(q) = self.world.destination_queue_mut(eid) {
413 q.retain(|s| s != stop);
414 }
415 if let Some(calls) = self.world.car_calls_mut(eid) {
420 calls.retain(|c| c.floor != stop);
421 }
422 }
423
424 for group in &mut self.groups {
426 for line_info in group.lines_mut() {
427 line_info.serves_mut().retain(|&s| s != stop);
428 }
429 group.rebuild_caches();
430 }
431
432 if let Some(sorted) = self.world.resource_mut::<crate::world::SortedStops>() {
434 sorted.0.retain(|&(_, s)| s != stop);
435 }
436
437 self.stop_lookup.retain(|_, &mut eid| eid != stop);
439
440 self.events.emit(Event::StopRemoved {
441 stop,
442 tick: self.tick,
443 });
444
445 self.world.despawn(stop);
447
448 self.mark_topo_dirty();
449 Ok(())
450 }
451
452 pub fn add_group(
454 &mut self,
455 name: impl Into<String>,
456 dispatch: impl DispatchStrategy + 'static,
457 ) -> GroupId {
458 let next_id = self
459 .groups
460 .iter()
461 .map(|g| g.id().0)
462 .max()
463 .map_or(0, |m| m + 1);
464 let group_id = GroupId(next_id);
465
466 self.groups
467 .push(ElevatorGroup::new(group_id, name.into(), Vec::new()));
468
469 self.dispatchers.insert(group_id, Box::new(dispatch));
470 self.strategy_ids.insert(group_id, BuiltinStrategy::Scan);
471 self.mark_topo_dirty();
472 group_id
473 }
474
475 pub fn assign_line_to_group(
482 &mut self,
483 line: EntityId,
484 new_group: GroupId,
485 ) -> Result<GroupId, SimError> {
486 let (old_group_idx, line_idx) = self.find_line(line)?;
487
488 if !self.groups.iter().any(|g| g.id() == new_group) {
490 return Err(SimError::GroupNotFound(new_group));
491 }
492
493 let old_group_id = self.groups[old_group_idx].id();
494
495 if old_group_id == new_group {
500 return Ok(old_group_id);
501 }
502
503 let elevators_to_notify: Vec<EntityId> = self.groups[old_group_idx].lines()[line_idx]
508 .elevators()
509 .to_vec();
510 if let Some(dispatcher) = self.dispatchers.get_mut(&old_group_id) {
511 for eid in &elevators_to_notify {
512 dispatcher.notify_removed(*eid);
513 }
514 }
515
516 let line_info = self.groups[old_group_idx].lines_mut().remove(line_idx);
518 self.groups[old_group_idx].rebuild_caches();
519
520 let new_group_idx = self
525 .groups
526 .iter()
527 .position(|g| g.id() == new_group)
528 .ok_or(SimError::GroupNotFound(new_group))?;
529 self.groups[new_group_idx].lines_mut().push(line_info);
530 self.groups[new_group_idx].rebuild_caches();
531
532 if let Some(line_comp) = self.world.line_mut(line) {
534 line_comp.group = new_group;
535 }
536
537 self.mark_topo_dirty();
538 self.events.emit(Event::LineReassigned {
539 line,
540 old_group: old_group_id,
541 new_group,
542 tick: self.tick,
543 });
544
545 Ok(old_group_id)
546 }
547
548 pub fn reassign_elevator_to_line(
559 &mut self,
560 elevator: EntityId,
561 new_line: EntityId,
562 ) -> Result<(), SimError> {
563 let old_line = self
564 .world
565 .elevator(elevator)
566 .ok_or(SimError::EntityNotFound(elevator))?
567 .line();
568
569 if old_line == new_line {
570 return Ok(());
571 }
572
573 let (old_group_idx, old_line_idx) = self.find_line(old_line)?;
575 let (new_group_idx, new_line_idx) = self.find_line(new_line)?;
576
577 if let Some(max) = self.world.line(new_line).and_then(Line::max_cars) {
579 let current_count = self.groups[new_group_idx].lines()[new_line_idx]
580 .elevators()
581 .len();
582 if current_count >= max {
583 return Err(SimError::InvalidConfig {
584 field: "line.max_cars",
585 reason: format!("target line already has {current_count} cars (max {max})"),
586 });
587 }
588 }
589
590 let old_group_id = self.groups[old_group_idx].id();
591 let new_group_id = self.groups[new_group_idx].id();
592
593 self.groups[old_group_idx].lines_mut()[old_line_idx]
594 .elevators_mut()
595 .retain(|&e| e != elevator);
596 self.groups[new_group_idx].lines_mut()[new_line_idx]
597 .elevators_mut()
598 .push(elevator);
599
600 if let Some(car) = self.world.elevator_mut(elevator) {
601 car.line = new_line;
602 }
603
604 self.groups[old_group_idx].rebuild_caches();
605 if new_group_idx != old_group_idx {
606 self.groups[new_group_idx].rebuild_caches();
607
608 if let Some(old_dispatcher) = self.dispatchers.get_mut(&old_group_id) {
612 old_dispatcher.notify_removed(elevator);
613 }
614 }
615
616 self.mark_topo_dirty();
617
618 let _ = new_group_id; self.events.emit(Event::ElevatorReassigned {
620 elevator,
621 old_line,
622 new_line,
623 tick: self.tick,
624 });
625
626 Ok(())
627 }
628
629 pub fn add_stop_to_line(&mut self, stop: EntityId, line: EntityId) -> Result<(), SimError> {
636 if self.world.stop(stop).is_none() {
638 return Err(SimError::EntityNotFound(stop));
639 }
640
641 let (group_idx, line_idx) = self.find_line(line)?;
642
643 let li = &mut self.groups[group_idx].lines_mut()[line_idx];
644 if !li.serves().contains(&stop) {
645 li.serves_mut().push(stop);
646 }
647
648 self.groups[group_idx].push_stop(stop);
649
650 self.mark_topo_dirty();
651 Ok(())
652 }
653
654 pub fn remove_stop_from_line(
660 &mut self,
661 stop: EntityId,
662 line: EntityId,
663 ) -> Result<(), SimError> {
664 let (group_idx, line_idx) = self.find_line(line)?;
665
666 self.groups[group_idx].lines_mut()[line_idx]
667 .serves_mut()
668 .retain(|&s| s != stop);
669
670 self.groups[group_idx].rebuild_caches();
672
673 self.mark_topo_dirty();
674 Ok(())
675 }
676
677 #[must_use]
681 pub fn all_lines(&self) -> Vec<EntityId> {
682 self.groups
683 .iter()
684 .flat_map(|g| g.lines().iter().map(LineInfo::entity))
685 .collect()
686 }
687
688 #[must_use]
690 pub fn line_count(&self) -> usize {
691 self.groups.iter().map(|g| g.lines().len()).sum()
692 }
693
694 #[must_use]
696 pub fn lines_in_group(&self, group: GroupId) -> Vec<EntityId> {
697 self.groups
698 .iter()
699 .find(|g| g.id() == group)
700 .map_or_else(Vec::new, |g| {
701 g.lines().iter().map(LineInfo::entity).collect()
702 })
703 }
704
705 #[must_use]
707 pub fn elevators_on_line(&self, line: EntityId) -> Vec<EntityId> {
708 self.groups
709 .iter()
710 .flat_map(ElevatorGroup::lines)
711 .find(|li| li.entity() == line)
712 .map_or_else(Vec::new, |li| li.elevators().to_vec())
713 }
714
715 #[must_use]
717 pub fn stops_served_by_line(&self, line: EntityId) -> Vec<EntityId> {
718 self.groups
719 .iter()
720 .flat_map(ElevatorGroup::lines)
721 .find(|li| li.entity() == line)
722 .map_or_else(Vec::new, |li| li.serves().to_vec())
723 }
724
725 #[must_use]
727 pub fn line_for_elevator(&self, elevator: EntityId) -> Option<EntityId> {
728 self.groups
729 .iter()
730 .flat_map(ElevatorGroup::lines)
731 .find(|li| li.elevators().contains(&elevator))
732 .map(LineInfo::entity)
733 }
734
735 pub fn iter_repositioning_elevators(&self) -> impl Iterator<Item = EntityId> + '_ {
737 self.world
738 .iter_elevators()
739 .filter_map(|(id, _pos, car)| if car.repositioning() { Some(id) } else { None })
740 }
741
742 #[must_use]
744 pub fn lines_serving_stop(&self, stop: EntityId) -> Vec<EntityId> {
745 self.groups
746 .iter()
747 .flat_map(ElevatorGroup::lines)
748 .filter(|li| li.serves().contains(&stop))
749 .map(LineInfo::entity)
750 .collect()
751 }
752
753 #[must_use]
755 pub fn groups_serving_stop(&self, stop: EntityId) -> Vec<GroupId> {
756 self.groups
757 .iter()
758 .filter(|g| g.stop_entities().contains(&stop))
759 .map(ElevatorGroup::id)
760 .collect()
761 }
762
763 fn ensure_graph_built(&self) {
767 if let Ok(mut graph) = self.topo_graph.lock()
768 && graph.is_dirty()
769 {
770 graph.rebuild(&self.groups);
771 }
772 }
773
774 pub fn reachable_stops_from(&self, stop: EntityId) -> Vec<EntityId> {
776 self.ensure_graph_built();
777 self.topo_graph
778 .lock()
779 .map_or_else(|_| Vec::new(), |g| g.reachable_stops_from(stop))
780 }
781
782 pub fn transfer_points(&self) -> Vec<EntityId> {
784 self.ensure_graph_built();
785 TopologyGraph::transfer_points(&self.groups)
786 }
787
788 pub fn shortest_route(&self, from: EntityId, to: EntityId) -> Option<Route> {
790 self.ensure_graph_built();
791 self.topo_graph
792 .lock()
793 .ok()
794 .and_then(|g| g.shortest_route(from, to))
795 }
796}