Skip to main content

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 std::collections::HashSet;
28
29use serde::{Deserialize, Serialize};
30
31use crate::components::{DestinationQueue, Direction, ElevatorPhase, TransportMode};
32use crate::entity::EntityId;
33use crate::world::{ExtKey, World};
34
35use super::{DispatchManifest, DispatchStrategy, ElevatorGroup, RankContext, pair_can_do_work};
36
37/// Sticky rider → car assignment produced by [`DestinationDispatch`].
38///
39/// Stored as an extension component on the rider entity. Once set, the
40/// assignment is never mutated; the loading phase uses it to enforce
41/// that only the assigned car may board the rider.
42#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
43pub struct AssignedCar(pub EntityId);
44
45/// Typed extension key for [`AssignedCar`] storage.
46pub const ASSIGNED_CAR_KEY: ExtKey<AssignedCar> = ExtKey::new("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    /// Deferred-commitment window. When `Some(window)`, a rider's
67    /// sticky assignment is re-evaluated each pass until the assigned
68    /// car is within `window` ticks of the rider's origin — modelling
69    /// KONE Polaris's two-button reallocation regime (DCS calls fix on
70    /// press; two-button hall calls re-allocate continuously until
71    /// commitment). `None` ⇒ immediate sticky (the default), matching
72    /// fixed-on-press DCS behavior.
73    commitment_window_ticks: Option<u64>,
74}
75
76impl DestinationDispatch {
77    /// Create a new `DestinationDispatch` with defaults (immediate sticky,
78    /// no commitment window).
79    #[must_use]
80    pub const fn new() -> Self {
81        Self {
82            stop_penalty: None,
83            commitment_window_ticks: None,
84        }
85    }
86
87    /// Override the fresh-stop penalty (ticks per new stop added to a
88    /// car's committed route when it picks this rider up).
89    #[must_use]
90    pub const fn with_stop_penalty(mut self, penalty: f64) -> Self {
91        self.stop_penalty = Some(penalty);
92        self
93    }
94
95    /// Enable deferred commitment: riders' sticky assignments are
96    /// re-evaluated each pass until the currently-assigned car is
97    /// within `window` ticks of the rider's origin. At that point the
98    /// commitment latches and later ticks leave the assignment alone.
99    #[must_use]
100    pub const fn with_commitment_window_ticks(mut self, window: u64) -> Self {
101        self.commitment_window_ticks = Some(window);
102        self
103    }
104}
105
106impl Default for DestinationDispatch {
107    fn default() -> Self {
108        Self::new()
109    }
110}
111
112impl DispatchStrategy for DestinationDispatch {
113    #[allow(clippy::too_many_lines)]
114    fn pre_dispatch(
115        &mut self,
116        group: &ElevatorGroup,
117        manifest: &DispatchManifest,
118        world: &mut World,
119    ) {
120        // DCS requires the group to be in `HallCallMode::Destination` — that
121        // mode is what makes the kiosk-style "rider announces destination
122        // at press time" assumption hold. In Classic collective-control
123        // mode destinations aren't known until riders board, so running
124        // DCS there would commit assignments based on information a real
125        // controller wouldn't have. Early-return makes DCS a no-op for
126        // misconfigured groups; pair it with the right mode to activate.
127        if group.hall_call_mode() != super::HallCallMode::Destination {
128            return;
129        }
130
131        // Candidate cars in this group that are operable for dispatch.
132        let candidate_cars: Vec<EntityId> = group
133            .elevator_entities()
134            .iter()
135            .copied()
136            .filter(|eid| !world.is_disabled(*eid))
137            .filter(|eid| {
138                !world
139                    .service_mode(*eid)
140                    .is_some_and(|m| m.is_dispatch_excluded())
141            })
142            .filter(|eid| world.elevator(*eid).is_some())
143            .collect();
144
145        if candidate_cars.is_empty() {
146            return;
147        }
148
149        // Collect unassigned waiting riders in this group. A sticky
150        // assignment whose target car is dead or disabled is treated as
151        // void — re-assign rather than strand. (Lifecycle hooks in
152        // `disable`/`remove_elevator` normally clear these; this is the
153        // defense layer if cleanup is ever missed.)
154        let mut stale_assignments: Vec<EntityId> = Vec::new();
155        let mut pending: Vec<(EntityId, EntityId, EntityId, f64)> = Vec::new();
156        for (_, riders) in manifest.iter_waiting_stops() {
157            for info in riders {
158                if let Some(AssignedCar(c)) = world.ext::<AssignedCar>(info.id) {
159                    // An assignment stays sticky only when the target
160                    // car is still alive and (no commitment window is
161                    // configured, or the car is already inside the
162                    // latch window). Otherwise strip it so the rider
163                    // re-competes below.
164                    let alive = world.elevator(c).is_some() && !world.is_disabled(c);
165                    let latched = self
166                        .commitment_window_ticks
167                        .is_none_or(|w| assigned_car_within_window(world, info.id, c, w));
168                    if alive && latched {
169                        continue; // sticky and live
170                    }
171                    stale_assignments.push(info.id);
172                }
173                let Some(dest) = info.destination else {
174                    continue;
175                };
176                let Some(route) = world.route(info.id) else {
177                    continue;
178                };
179                let Some(leg) = route.current() else {
180                    continue;
181                };
182                let group_ok = match leg.via {
183                    TransportMode::Group(g) => g == group.id(),
184                    TransportMode::Line(l) => group.lines().iter().any(|li| li.entity() == l),
185                    TransportMode::Walk => false,
186                };
187                if !group_ok {
188                    continue;
189                }
190                pending.push((info.id, leg.from, dest, info.weight.value()));
191            }
192        }
193        pending.sort_by_key(|(rid, ..)| *rid);
194        // Drop stale extensions so subsequent ticks see them as unassigned.
195        for rid in stale_assignments {
196            world.remove_ext::<AssignedCar>(rid);
197        }
198
199        // Pre-compute committed-load per car (riders aboard + already-
200        // assigned waiting riders not yet boarded). Used by cost function
201        // to discourage piling more riders onto an already-full car.
202        let mut committed_load: std::collections::BTreeMap<EntityId, f64> =
203            std::collections::BTreeMap::new();
204        for (rid, rider) in world.iter_riders() {
205            use crate::components::RiderPhase;
206            // Count riders whose weight is "committed" to a specific car:
207            // actively aboard (Boarding/Riding) or still-Waiting with a
208            // sticky assignment. Terminal phases (Exiting, Arrived,
209            // Abandoned, Resident, Walking) must not contribute — they no
210            // longer need elevator service, and stale `AssignedCar`
211            // extensions on them would inflate the former car's committed
212            // load until cleared.
213            let car = match rider.phase() {
214                RiderPhase::Riding(c) | RiderPhase::Boarding(c) => Some(c),
215                RiderPhase::Waiting => world.ext::<AssignedCar>(rid).map(|AssignedCar(c)| c),
216                _ => None,
217            };
218            if let Some(c) = car {
219                *committed_load.entry(c).or_insert(0.0) += rider.weight.value();
220            }
221        }
222
223        for (rid, origin, dest, weight) in pending {
224            let best = candidate_cars
225                .iter()
226                .filter_map(|&eid| {
227                    let car = world.elevator(eid)?;
228                    if car.restricted_stops().contains(&dest)
229                        || car.restricted_stops().contains(&origin)
230                    {
231                        return None;
232                    }
233                    if car.weight_capacity().value() > 0.0 && weight > car.weight_capacity().value()
234                    {
235                        return None;
236                    }
237                    let com = committed_load.get(&eid).copied().unwrap_or(0.0);
238                    let cost = self.compute_cost(eid, origin, dest, world, com);
239                    if cost.is_finite() {
240                        Some((eid, cost))
241                    } else {
242                        None
243                    }
244                })
245                .min_by(|a, b| a.1.total_cmp(&b.1))
246                .map(|(eid, _)| eid);
247
248            let Some(car_eid) = best else {
249                continue;
250            };
251            world.insert_ext(rid, AssignedCar(car_eid), ASSIGNED_CAR_KEY);
252            *committed_load.entry(car_eid).or_insert(0.0) += weight;
253        }
254
255        // Rebuild each candidate car's destination queue from the current
256        // set of sticky commitments, arranged in direction-aware two-run
257        // monotone order. This is the source of truth per tick and avoids
258        // incremental-insertion drift (duplicates, orphaned entries).
259        for &car_eid in &candidate_cars {
260            rebuild_car_queue(world, car_eid);
261        }
262    }
263
264    fn rank(&mut self, ctx: &RankContext<'_>) -> Option<f64> {
265        // The queue is the source of truth — route each car strictly to
266        // its own queue front. Every other stop is unavailable for this
267        // car, so the Hungarian assignment reduces to the identity match
268        // between each car and the stop it has already committed to.
269        //
270        // The `pair_can_do_work` gate guards against the same full-car
271        // self-assign stall the other built-ins close: a sticky DCS
272        // assignment whose car has filled up with earlier riders and
273        // whose queue front is still the *pickup* for an un-boarded
274        // rider would otherwise rank 0.0, win the Hungarian every tick,
275        // and cycle doors forever.
276        let front = ctx
277            .world
278            .destination_queue(ctx.car)
279            .and_then(DestinationQueue::front)?;
280        if front == ctx.stop && pair_can_do_work(ctx) {
281            Some(0.0)
282        } else {
283            None
284        }
285    }
286}
287
288impl DestinationDispatch {
289    /// Compute the assignment cost of sending car `eid` to pick up a rider
290    /// whose route is `origin → dest`.
291    fn compute_cost(
292        &self,
293        eid: EntityId,
294        origin: EntityId,
295        dest: EntityId,
296        world: &World,
297        committed_load: f64,
298    ) -> f64 {
299        let Some(car) = world.elevator(eid) else {
300            return f64::INFINITY;
301        };
302        if car.max_speed().value() <= 0.0 {
303            return f64::INFINITY;
304        }
305
306        let Some(car_pos) = world.position(eid).map(|p| p.value) else {
307            return f64::INFINITY;
308        };
309        let Some(origin_pos) = world.stop_position(origin) else {
310            return f64::INFINITY;
311        };
312        let Some(dest_pos) = world.stop_position(dest) else {
313            return f64::INFINITY;
314        };
315
316        let door_overhead = f64::from(car.door_transition_ticks() * 2 + car.door_open_ticks());
317        let penalty = self.stop_penalty.unwrap_or_else(|| door_overhead.max(1.0));
318
319        // Pickup time: direct distance + per-stop door overhead for each
320        // committed stop that lies between the car and the origin.
321        let pickup_dist = (car_pos - origin_pos).abs();
322        let pickup_travel = pickup_dist / car.max_speed().value();
323        let intervening_committed = world.destination_queue(eid).map_or(0usize, |q| {
324            let (lo, hi) = if car_pos < origin_pos {
325                (car_pos, origin_pos)
326            } else {
327                (origin_pos, car_pos)
328            };
329            q.queue()
330                .iter()
331                .filter_map(|s| world.stop_position(*s))
332                .filter(|p| *p > lo + 1e-9 && *p < hi - 1e-9)
333                .count()
334        });
335        let pickup_time = (intervening_committed as f64).mul_add(door_overhead, pickup_travel);
336
337        // Ride time: origin → dest travel + door overhead at origin pickup.
338        let ride_dist = (origin_pos - dest_pos).abs();
339        let ride_time = ride_dist / car.max_speed().value() + door_overhead;
340
341        // Fresh stops added: 0, 1, or 2 depending on whether origin/dest
342        // are already queued for this car.
343        let existing: Vec<EntityId> = world
344            .destination_queue(eid)
345            .map_or_else(Vec::new, |q| q.queue().to_vec());
346        let mut new_stops = 0f64;
347        if !existing.contains(&origin) {
348            new_stops += 1.0;
349        }
350        if !existing.contains(&dest) && dest != origin {
351            new_stops += 1.0;
352        }
353
354        // Idle bias: empty cars get a small bonus so the load spreads.
355        let idle_bonus = if car.phase() == ElevatorPhase::Idle && car.riders().is_empty() {
356            -0.1 * pickup_travel
357        } else {
358            0.0
359        };
360
361        // Load bias: include both aboard and already-assigned-but-waiting
362        // riders so dispatch spreads load even before any boarding happens.
363        let load_penalty = if car.weight_capacity().value() > 0.0 {
364            let effective = car.current_load().value().max(committed_load);
365            let ratio = (effective / car.weight_capacity().value()).min(2.0);
366            ratio * door_overhead * 4.0
367        } else {
368            0.0
369        };
370
371        pickup_time + ride_time + penalty * new_stops + idle_bonus + load_penalty
372    }
373}
374
375/// True when the `car` assigned to `rider` is within `window` ticks of
376/// the rider's origin, measured by raw distance / `max_speed`. Used to
377/// decide whether a deferred commitment has latched.
378fn assigned_car_within_window(
379    world: &crate::world::World,
380    rider: EntityId,
381    car: EntityId,
382    window: u64,
383) -> bool {
384    let Some(leg) = world.route(rider).and_then(|r| r.current()) else {
385        return false;
386    };
387    let Some(origin_pos) = world.stop_position(leg.from) else {
388        return false;
389    };
390    let Some(car_pos) = world.position(car).map(|p| p.value) else {
391        return false;
392    };
393    let Some(car_data) = world.elevator(car) else {
394        return false;
395    };
396    let speed = car_data.max_speed().value();
397    if !speed.is_finite() || speed <= 0.0 {
398        return false;
399    }
400    let eta_ticks = (car_pos - origin_pos).abs() / speed;
401    // A non-finite ETA (NaN from corrupted position) would saturate
402    // the `as u64` cast to 0 and erroneously latch the commitment —
403    // refuse to latch instead.
404    if !eta_ticks.is_finite() {
405        return false;
406    }
407    eta_ticks.round() as u64 <= window
408}
409
410/// Drop every sticky [`AssignedCar`] assignment that points at `car_eid`.
411///
412/// Called by `Simulation::disable` and `Simulation::remove_elevator` when an
413/// elevator leaves service so DCS-routed riders are not stranded behind a
414/// dead reference. Assignments are sticky by design — if no one clears them,
415/// no other car will pick the rider up — so the lifecycle layer is responsible
416/// for invoking this helper at car-loss boundaries.
417pub fn clear_assignments_to(world: &mut crate::world::World, car_eid: EntityId) {
418    let stale: Vec<EntityId> = world
419        .iter_riders()
420        .filter_map(|(rid, _)| match world.ext::<AssignedCar>(rid) {
421            Some(AssignedCar(c)) if c == car_eid => Some(rid),
422            _ => None,
423        })
424        .collect();
425    for rid in stale {
426        world.remove_ext::<AssignedCar>(rid);
427    }
428}
429
430/// Rebuild `car_eid`'s destination queue from all live sticky commitments.
431///
432/// Scans all riders assigned to this car and collects the set of stops it
433/// must visit:
434///   - waiting riders contribute both their origin and destination,
435///   - riding/boarding riders contribute just their destination (origin
436///     already visited).
437///
438/// The stops are then arranged into a two-run monotone sequence: the
439/// current sweep (in the car's current direction) followed by the reverse
440/// sweep. A third run is appended when a rider's trip reverses the sweep
441/// twice (origin behind, dest ahead of origin in the original sweep).
442#[allow(clippy::too_many_lines)]
443fn rebuild_car_queue(world: &mut crate::world::World, car_eid: EntityId) {
444    use crate::components::RiderPhase;
445
446    // Local type for gathered (origin?, dest) trips.
447    struct Trip {
448        origin: Option<EntityId>,
449        dest: EntityId,
450    }
451
452    let Some(car) = world.elevator(car_eid) else {
453        return;
454    };
455    let car_pos = world.position(car_eid).map_or(0.0, |p| p.value);
456    let sweep_up = match car.direction() {
457        Direction::Up | Direction::Either => true,
458        Direction::Down => false,
459    };
460
461    // Skip inserting a stop the car is currently parked at and loading.
462    let at_stop_loading: Option<EntityId> = {
463        let stopped_here = !matches!(
464            car.phase(),
465            ElevatorPhase::MovingToStop(_) | ElevatorPhase::Repositioning(_)
466        );
467        if stopped_here {
468            world.find_stop_at_position(car_pos)
469        } else {
470            None
471        }
472    };
473
474    // Gather (origin?, dest) pairs from all sticky-assigned riders for this car.
475    let mut trips: Vec<Trip> = Vec::new();
476    for (rid, rider) in world.iter_riders() {
477        let Some(AssignedCar(assigned)) = world.ext::<AssignedCar>(rid) else {
478            continue;
479        };
480        if assigned != car_eid {
481            continue;
482        }
483        let Some(dest) = world
484            .route(rid)
485            .and_then(crate::components::Route::current_destination)
486        else {
487            continue;
488        };
489        match rider.phase() {
490            RiderPhase::Waiting => {
491                let origin = world
492                    .route(rid)
493                    .and_then(|r| r.current().map(|leg| leg.from));
494                // Strip origin if car is parked at it right now.
495                let origin = origin.filter(|o| Some(*o) != at_stop_loading);
496                trips.push(Trip { origin, dest });
497            }
498            RiderPhase::Boarding(_) | RiderPhase::Riding(_) => {
499                trips.push(Trip { origin: None, dest });
500            }
501            _ => {}
502        }
503    }
504
505    if trips.is_empty() {
506        if let Some(q) = world.destination_queue_mut(car_eid) {
507            q.clear();
508        }
509        return;
510    }
511
512    // Bucket each stop into up to three runs based on the car's direction:
513    //   run1 = current sweep (same direction as car)
514    //   run2 = reverse sweep
515    //   run3 = second sweep in the original direction (for trips whose
516    //          origin is behind the sweep but dest is further in it)
517    let mut run1: Vec<(EntityId, f64)> = Vec::new();
518    let mut run2: Vec<(EntityId, f64)> = Vec::new();
519    let mut run3: Vec<(EntityId, f64)> = Vec::new();
520
521    let in_run1 = |sp: f64| -> bool {
522        if sweep_up {
523            sp >= car_pos - 1e-9
524        } else {
525            sp <= car_pos + 1e-9
526        }
527    };
528
529    let push_unique = |v: &mut Vec<(EntityId, f64)>, s: EntityId, p: f64| {
530        if !v.iter().any(|(e, _)| *e == s) {
531            v.push((s, p));
532        }
533    };
534
535    for trip in &trips {
536        let dp = world.stop_position(trip.dest).unwrap_or(car_pos);
537        if let Some(o) = trip.origin {
538            let op = world.stop_position(o).unwrap_or(car_pos);
539            let o_in_run1 = in_run1(op);
540            let d_in_run1 = in_run1(dp);
541            if o_in_run1 {
542                push_unique(&mut run1, o, op);
543                if d_in_run1 {
544                    // Both in run1: dest must be further in sweep than origin.
545                    let d_fits = if sweep_up {
546                        dp >= op - 1e-9
547                    } else {
548                        dp <= op + 1e-9
549                    };
550                    if d_fits {
551                        push_unique(&mut run1, trip.dest, dp);
552                    } else {
553                        // Dest is behind origin in sweep: needs reverse run.
554                        push_unique(&mut run2, trip.dest, dp);
555                    }
556                } else {
557                    push_unique(&mut run2, trip.dest, dp);
558                }
559            } else {
560                // Origin is behind sweep: both go in reverse/second run.
561                push_unique(&mut run2, o, op);
562                if d_in_run1 {
563                    // Origin behind, dest ahead: need a third sweep.
564                    push_unique(&mut run3, trip.dest, dp);
565                } else {
566                    // Both behind sweep. Within reverse run, order dest
567                    // after origin (dest further into reverse direction).
568                    let d_further = if sweep_up {
569                        dp <= op + 1e-9
570                    } else {
571                        dp >= op - 1e-9
572                    };
573                    if d_further {
574                        push_unique(&mut run2, trip.dest, dp);
575                    } else {
576                        push_unique(&mut run3, trip.dest, dp);
577                    }
578                }
579            }
580        } else {
581            // No origin: just drop off. Place dest in whichever run contains it.
582            if in_run1(dp) {
583                push_unique(&mut run1, trip.dest, dp);
584            } else {
585                push_unique(&mut run2, trip.dest, dp);
586            }
587        }
588    }
589
590    // Sort each run monotonically.
591    if sweep_up {
592        run1.sort_by(|a, b| a.1.total_cmp(&b.1));
593        run2.sort_by(|a, b| b.1.total_cmp(&a.1));
594        run3.sort_by(|a, b| a.1.total_cmp(&b.1));
595    } else {
596        run1.sort_by(|a, b| b.1.total_cmp(&a.1));
597        run2.sort_by(|a, b| a.1.total_cmp(&b.1));
598        run3.sort_by(|a, b| b.1.total_cmp(&a.1));
599    }
600
601    let mut out: Vec<EntityId> = Vec::with_capacity(run1.len() + run2.len() + run3.len());
602    out.extend(run1.into_iter().map(|(e, _)| e));
603    out.extend(run2.into_iter().map(|(e, _)| e));
604    out.extend(run3.into_iter().map(|(e, _)| e));
605    let mut seen = HashSet::with_capacity(out.len());
606    out.retain(|e| seen.insert(*e));
607
608    if let Some(q) = world.destination_queue_mut(car_eid) {
609        q.replace(out);
610    }
611}