elevator_core/dispatch/destination.rs
1//! Hall-call destination dispatch ("DCS").
2//!
3//! Destination dispatch assigns each rider to a specific car at hall-call
4//! time (when their destination is first known) and the assignment is
5//! **sticky** — it never changes for the rider's lifetime, and no other car
6//! will pick them up. The controller minimizes each rider's own travel time,
7//! using a simple cost model:
8//!
9//! ```text
10//! J(C) = pickup_time(C, origin)
11//! + ride_time(origin, dest)
12//! + stop_penalty * new_stops_added(C, origin, dest)
13//! ```
14//!
15//! Assignments are recorded as an [`AssignedCar`] extension component on the
16//! rider; the loading filter in [`crate::systems::loading`] consults this to
17//! enforce the stickiness invariant.
18//!
19//! This is a sim — not a faithful reproduction of any vendor's controller.
20//! Each assigned car's [`DestinationQueue`](crate::components::DestinationQueue)
21//! is rebuilt every dispatch tick from the set of live sticky commitments
22//! (waiting riders contribute origin + dest; riding riders contribute dest)
23//! and arranged into a direction-aware two-run (plus fallback third-run)
24//! monotone sequence so the car visits stops in sweep order rather than
25//! in the order assignments arrived.
26
27use serde::{Deserialize, Serialize};
28
29use crate::components::{DestinationQueue, Direction, ElevatorPhase, TransportMode};
30use crate::entity::EntityId;
31use crate::world::World;
32
33use super::{DispatchManifest, DispatchStrategy, ElevatorGroup};
34
35/// Sticky rider → car assignment produced by [`DestinationDispatch`].
36///
37/// Stored as an extension component on the rider entity under the key
38/// `"assigned_car"`. Once set, the assignment is never mutated; the
39/// loading phase uses it to enforce that only the assigned car may board
40/// the rider.
41#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
42pub struct AssignedCar(pub EntityId);
43
44/// Extension component name used when inserting [`AssignedCar`] into the
45/// world's extension storage.
46pub const ASSIGNED_CAR_EXT_NAME: &str = "assigned_car";
47
48/// Hall-call destination dispatch (DCS).
49///
50/// ## API shape
51///
52/// Uses [`DispatchStrategy::pre_dispatch`] to write sticky
53/// [`AssignedCar`] extensions and rebuild each car's committed stop
54/// queue during a `&mut World` phase. [`DispatchStrategy::rank`] then
55/// routes each car to its own queue front and returns `None` for every
56/// other stop, so the group-wide Hungarian assignment trivially pairs
57/// each car with the stop it has already committed to.
58pub struct DestinationDispatch {
59 /// Weight for per-stop door overhead in the cost function. A positive
60 /// value biases assignments toward cars whose route change adds no
61 /// fresh stops; set via [`with_stop_penalty`](Self::with_stop_penalty).
62 ///
63 /// Units: ticks per newly-added stop. `None` ⇒ derive from the car's
64 /// own door timings (~`open + 2 * transition`).
65 stop_penalty: Option<f64>,
66}
67
68impl DestinationDispatch {
69 /// Create a new `DestinationDispatch` with defaults.
70 #[must_use]
71 pub const fn new() -> Self {
72 Self { stop_penalty: None }
73 }
74
75 /// Override the fresh-stop penalty (ticks per new stop added to a
76 /// car's committed route when it picks this rider up).
77 #[must_use]
78 pub const fn with_stop_penalty(mut self, penalty: f64) -> Self {
79 self.stop_penalty = Some(penalty);
80 self
81 }
82}
83
84impl Default for DestinationDispatch {
85 fn default() -> Self {
86 Self::new()
87 }
88}
89
90impl DispatchStrategy for DestinationDispatch {
91 fn pre_dispatch(
92 &mut self,
93 group: &ElevatorGroup,
94 manifest: &DispatchManifest,
95 world: &mut World,
96 ) {
97 // DCS requires the group to be in `HallCallMode::Destination` — that
98 // mode is what makes the kiosk-style "rider announces destination
99 // at press time" assumption hold. In Classic collective-control
100 // mode destinations aren't known until riders board, so running
101 // DCS there would commit assignments based on information a real
102 // controller wouldn't have. Early-return makes DCS a no-op for
103 // misconfigured groups; pair it with the right mode to activate.
104 if group.hall_call_mode() != super::HallCallMode::Destination {
105 return;
106 }
107
108 // Candidate cars in this group that are operable for dispatch.
109 let candidate_cars: Vec<EntityId> = group
110 .elevator_entities()
111 .iter()
112 .copied()
113 .filter(|eid| !world.is_disabled(*eid))
114 .filter(|eid| {
115 !world
116 .service_mode(*eid)
117 .is_some_and(|m| m.is_dispatch_excluded())
118 })
119 .filter(|eid| world.elevator(*eid).is_some())
120 .collect();
121
122 if candidate_cars.is_empty() {
123 return;
124 }
125
126 // Collect unassigned waiting riders in this group.
127 let mut pending: Vec<(EntityId, EntityId, EntityId, f64)> = Vec::new();
128 for riders in manifest.waiting_at_stop.values() {
129 for info in riders {
130 if world.get_ext::<AssignedCar>(info.id).is_some() {
131 continue; // sticky
132 }
133 let Some(dest) = info.destination else {
134 continue;
135 };
136 let Some(route) = world.route(info.id) else {
137 continue;
138 };
139 let Some(leg) = route.current() else {
140 continue;
141 };
142 let group_ok = match leg.via {
143 TransportMode::Group(g) => g == group.id(),
144 TransportMode::Line(l) => group.lines().iter().any(|li| li.entity() == l),
145 TransportMode::Walk => false,
146 };
147 if !group_ok {
148 continue;
149 }
150 pending.push((info.id, leg.from, dest, info.weight));
151 }
152 }
153 pending.sort_by_key(|(rid, ..)| *rid);
154
155 // Pre-compute committed-load per car (riders aboard + already-
156 // assigned waiting riders not yet boarded). Used by cost function
157 // to discourage piling more riders onto an already-full car.
158 let mut committed_load: std::collections::BTreeMap<EntityId, f64> =
159 std::collections::BTreeMap::new();
160 for (rid, rider) in world.iter_riders() {
161 use crate::components::RiderPhase;
162 // Count riders whose weight is "committed" to a specific car:
163 // actively aboard (Boarding/Riding) or still-Waiting with a
164 // sticky assignment. Terminal phases (Exiting, Arrived,
165 // Abandoned, Resident, Walking) must not contribute — AssignedCar
166 // is sticky and never cleared, so including them would permanently
167 // inflate the former car's committed load over long runs.
168 let car = match rider.phase() {
169 RiderPhase::Riding(c) | RiderPhase::Boarding(c) => Some(c),
170 RiderPhase::Waiting => world.get_ext::<AssignedCar>(rid).map(|AssignedCar(c)| c),
171 _ => None,
172 };
173 if let Some(c) = car {
174 *committed_load.entry(c).or_insert(0.0) += rider.weight;
175 }
176 }
177
178 for (rid, origin, dest, weight) in pending {
179 let best = candidate_cars
180 .iter()
181 .filter_map(|&eid| {
182 let car = world.elevator(eid)?;
183 if car.restricted_stops().contains(&dest)
184 || car.restricted_stops().contains(&origin)
185 {
186 return None;
187 }
188 if car.weight_capacity() > 0.0 && weight > car.weight_capacity() {
189 return None;
190 }
191 let com = committed_load.get(&eid).copied().unwrap_or(0.0);
192 let cost = self.compute_cost(eid, origin, dest, world, com);
193 if cost.is_finite() {
194 Some((eid, cost))
195 } else {
196 None
197 }
198 })
199 .min_by(|a, b| a.1.total_cmp(&b.1))
200 .map(|(eid, _)| eid);
201
202 let Some(car_eid) = best else {
203 continue;
204 };
205 world.insert_ext(rid, AssignedCar(car_eid), ASSIGNED_CAR_EXT_NAME);
206 *committed_load.entry(car_eid).or_insert(0.0) += weight;
207 }
208
209 // Rebuild each candidate car's destination queue from the current
210 // set of sticky commitments, arranged in direction-aware two-run
211 // monotone order. This is the source of truth per tick and avoids
212 // incremental-insertion drift (duplicates, orphaned entries).
213 for &car_eid in &candidate_cars {
214 rebuild_car_queue(world, car_eid);
215 }
216 }
217
218 fn rank(
219 &mut self,
220 car: EntityId,
221 _car_position: f64,
222 stop: EntityId,
223 _stop_position: f64,
224 _group: &ElevatorGroup,
225 _manifest: &DispatchManifest,
226 world: &World,
227 ) -> Option<f64> {
228 // The queue is the source of truth — route each car strictly to
229 // its own queue front. Every other stop is unavailable for this
230 // car, so the Hungarian assignment reduces to the identity match
231 // between each car and the stop it has already committed to.
232 let front = world
233 .destination_queue(car)
234 .and_then(DestinationQueue::front)?;
235 if front == stop { Some(0.0) } else { None }
236 }
237}
238
239impl DestinationDispatch {
240 /// Compute the assignment cost of sending car `eid` to pick up a rider
241 /// whose route is `origin → dest`.
242 fn compute_cost(
243 &self,
244 eid: EntityId,
245 origin: EntityId,
246 dest: EntityId,
247 world: &World,
248 committed_load: f64,
249 ) -> f64 {
250 let Some(car) = world.elevator(eid) else {
251 return f64::INFINITY;
252 };
253 if car.max_speed() <= 0.0 {
254 return f64::INFINITY;
255 }
256
257 let Some(car_pos) = world.position(eid).map(|p| p.value) else {
258 return f64::INFINITY;
259 };
260 let Some(origin_pos) = world.stop_position(origin) else {
261 return f64::INFINITY;
262 };
263 let Some(dest_pos) = world.stop_position(dest) else {
264 return f64::INFINITY;
265 };
266
267 let door_overhead = f64::from(car.door_transition_ticks() * 2 + car.door_open_ticks());
268 let penalty = self.stop_penalty.unwrap_or_else(|| door_overhead.max(1.0));
269
270 // Pickup time: direct distance + per-stop door overhead for each
271 // committed stop that lies between the car and the origin.
272 let pickup_dist = (car_pos - origin_pos).abs();
273 let pickup_travel = pickup_dist / car.max_speed();
274 let intervening_committed = world.destination_queue(eid).map_or(0usize, |q| {
275 let (lo, hi) = if car_pos < origin_pos {
276 (car_pos, origin_pos)
277 } else {
278 (origin_pos, car_pos)
279 };
280 q.queue()
281 .iter()
282 .filter_map(|s| world.stop_position(*s))
283 .filter(|p| *p > lo + 1e-9 && *p < hi - 1e-9)
284 .count()
285 });
286 let pickup_time = (intervening_committed as f64).mul_add(door_overhead, pickup_travel);
287
288 // Ride time: origin → dest travel + door overhead at origin pickup.
289 let ride_dist = (origin_pos - dest_pos).abs();
290 let ride_time = ride_dist / car.max_speed() + door_overhead;
291
292 // Fresh stops added: 0, 1, or 2 depending on whether origin/dest
293 // are already queued for this car.
294 let existing: Vec<EntityId> = world
295 .destination_queue(eid)
296 .map_or_else(Vec::new, |q| q.queue().to_vec());
297 let mut new_stops = 0f64;
298 if !existing.contains(&origin) {
299 new_stops += 1.0;
300 }
301 if !existing.contains(&dest) && dest != origin {
302 new_stops += 1.0;
303 }
304
305 // Idle bias: empty cars get a small bonus so the load spreads.
306 let idle_bonus = if car.phase() == ElevatorPhase::Idle && car.riders().is_empty() {
307 -0.1 * pickup_travel
308 } else {
309 0.0
310 };
311
312 // Load bias: include both aboard and already-assigned-but-waiting
313 // riders so dispatch spreads load even before any boarding happens.
314 let load_penalty = if car.weight_capacity() > 0.0 {
315 let effective = car.current_load().max(committed_load);
316 let ratio = (effective / car.weight_capacity()).min(2.0);
317 ratio * door_overhead * 4.0
318 } else {
319 0.0
320 };
321
322 pickup_time + ride_time + penalty * new_stops + idle_bonus + load_penalty
323 }
324}
325
326/// Rebuild `car_eid`'s destination queue from all live sticky commitments.
327///
328/// Scans all riders assigned to this car and collects the set of stops it
329/// must visit:
330/// - waiting riders contribute both their origin and destination,
331/// - riding/boarding riders contribute just their destination (origin
332/// already visited).
333///
334/// The stops are then arranged into a two-run monotone sequence: the
335/// current sweep (in the car's current direction) followed by the reverse
336/// sweep. A third run is appended when a rider's trip reverses the sweep
337/// twice (origin behind, dest ahead of origin in the original sweep).
338#[allow(clippy::too_many_lines)]
339fn rebuild_car_queue(world: &mut crate::world::World, car_eid: EntityId) {
340 use crate::components::RiderPhase;
341
342 // Local type for gathered (origin?, dest) trips.
343 struct Trip {
344 origin: Option<EntityId>,
345 dest: EntityId,
346 }
347
348 let Some(car) = world.elevator(car_eid) else {
349 return;
350 };
351 let car_pos = world.position(car_eid).map_or(0.0, |p| p.value);
352 let sweep_up = match car.direction() {
353 Direction::Up | Direction::Either => true,
354 Direction::Down => false,
355 };
356
357 // Skip inserting a stop the car is currently parked at and loading.
358 let at_stop_loading: Option<EntityId> = {
359 let stopped_here = !matches!(
360 car.phase(),
361 ElevatorPhase::MovingToStop(_) | ElevatorPhase::Repositioning(_)
362 );
363 if stopped_here {
364 world.find_stop_at_position(car_pos)
365 } else {
366 None
367 }
368 };
369
370 // Gather (origin?, dest) pairs from all sticky-assigned riders for this car.
371 let mut trips: Vec<Trip> = Vec::new();
372 for (rid, rider) in world.iter_riders() {
373 let Some(AssignedCar(assigned)) = world.get_ext::<AssignedCar>(rid) else {
374 continue;
375 };
376 if assigned != car_eid {
377 continue;
378 }
379 let Some(dest) = world
380 .route(rid)
381 .and_then(crate::components::Route::current_destination)
382 else {
383 continue;
384 };
385 match rider.phase() {
386 RiderPhase::Waiting => {
387 let origin = world
388 .route(rid)
389 .and_then(|r| r.current().map(|leg| leg.from));
390 // Strip origin if car is parked at it right now.
391 let origin = origin.filter(|o| Some(*o) != at_stop_loading);
392 trips.push(Trip { origin, dest });
393 }
394 RiderPhase::Boarding(_) | RiderPhase::Riding(_) => {
395 trips.push(Trip { origin: None, dest });
396 }
397 _ => {}
398 }
399 }
400
401 if trips.is_empty() {
402 if let Some(q) = world.destination_queue_mut(car_eid) {
403 q.clear();
404 }
405 return;
406 }
407
408 // Bucket each stop into up to three runs based on the car's direction:
409 // run1 = current sweep (same direction as car)
410 // run2 = reverse sweep
411 // run3 = second sweep in the original direction (for trips whose
412 // origin is behind the sweep but dest is further in it)
413 let mut run1: Vec<(EntityId, f64)> = Vec::new();
414 let mut run2: Vec<(EntityId, f64)> = Vec::new();
415 let mut run3: Vec<(EntityId, f64)> = Vec::new();
416
417 let in_run1 = |sp: f64| -> bool {
418 if sweep_up {
419 sp >= car_pos - 1e-9
420 } else {
421 sp <= car_pos + 1e-9
422 }
423 };
424
425 let push_unique = |v: &mut Vec<(EntityId, f64)>, s: EntityId, p: f64| {
426 if !v.iter().any(|(e, _)| *e == s) {
427 v.push((s, p));
428 }
429 };
430
431 for trip in &trips {
432 let dp = world.stop_position(trip.dest).unwrap_or(car_pos);
433 if let Some(o) = trip.origin {
434 let op = world.stop_position(o).unwrap_or(car_pos);
435 let o_in_run1 = in_run1(op);
436 let d_in_run1 = in_run1(dp);
437 if o_in_run1 {
438 push_unique(&mut run1, o, op);
439 if d_in_run1 {
440 // Both in run1: dest must be further in sweep than origin.
441 let d_fits = if sweep_up {
442 dp >= op - 1e-9
443 } else {
444 dp <= op + 1e-9
445 };
446 if d_fits {
447 push_unique(&mut run1, trip.dest, dp);
448 } else {
449 // Dest is behind origin in sweep: needs reverse run.
450 push_unique(&mut run2, trip.dest, dp);
451 }
452 } else {
453 push_unique(&mut run2, trip.dest, dp);
454 }
455 } else {
456 // Origin is behind sweep: both go in reverse/second run.
457 push_unique(&mut run2, o, op);
458 if d_in_run1 {
459 // Origin behind, dest ahead: need a third sweep.
460 push_unique(&mut run3, trip.dest, dp);
461 } else {
462 // Both behind sweep. Within reverse run, order dest
463 // after origin (dest further into reverse direction).
464 let d_further = if sweep_up {
465 dp <= op + 1e-9
466 } else {
467 dp >= op - 1e-9
468 };
469 if d_further {
470 push_unique(&mut run2, trip.dest, dp);
471 } else {
472 push_unique(&mut run3, trip.dest, dp);
473 }
474 }
475 }
476 } else {
477 // No origin: just drop off. Place dest in whichever run contains it.
478 if in_run1(dp) {
479 push_unique(&mut run1, trip.dest, dp);
480 } else {
481 push_unique(&mut run2, trip.dest, dp);
482 }
483 }
484 }
485
486 // Sort each run monotonically.
487 if sweep_up {
488 run1.sort_by(|a, b| a.1.total_cmp(&b.1));
489 run2.sort_by(|a, b| b.1.total_cmp(&a.1));
490 run3.sort_by(|a, b| a.1.total_cmp(&b.1));
491 } else {
492 run1.sort_by(|a, b| b.1.total_cmp(&a.1));
493 run2.sort_by(|a, b| a.1.total_cmp(&b.1));
494 run3.sort_by(|a, b| b.1.total_cmp(&a.1));
495 }
496
497 let mut out: Vec<EntityId> = Vec::with_capacity(run1.len() + run2.len() + run3.len());
498 out.extend(run1.into_iter().map(|(e, _)| e));
499 out.extend(run2.into_iter().map(|(e, _)| e));
500 out.extend(run3.into_iter().map(|(e, _)| e));
501 out.dedup();
502
503 if let Some(q) = world.destination_queue_mut(car_eid) {
504 q.replace(out);
505 }
506}