elevator-core 15.32.0

Engine-agnostic elevator simulation library with pluggable dispatch strategies
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
//! Elevator state and configuration component.

use serde::{Deserialize, Serialize};
use std::collections::HashSet;

use super::units::{Accel, Speed, Weight};
use crate::door::{DoorCommand, DoorState};
use crate::entity::EntityId;

/// Maximum number of manual door commands queued per elevator.
///
/// Beyond this cap, the oldest entry is dropped (after adjacent-duplicate
/// collapsing). Prevents runaway growth if a game submits commands faster
/// than the sim can apply them.
pub const DOOR_COMMAND_QUEUE_CAP: usize = 16;

/// Direction an elevator's indicator lamps are signalling.
///
/// Derived from the pair of `going_up` / `going_down` flags on [`Elevator`].
/// `Either` corresponds to both lamps lit — the car is idle and will accept
/// riders heading either way. `Up` / `Down` correspond to an actively
/// committed direction.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[non_exhaustive]
pub enum Direction {
    /// Car will serve upward trips only.
    Up,
    /// Car will serve downward trips only.
    Down,
    /// Car will serve either direction (idle).
    Either,
}

impl std::fmt::Display for Direction {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Up => write!(f, "Up"),
            Self::Down => write!(f, "Down"),
            Self::Either => write!(f, "Either"),
        }
    }
}

/// Operational phase of an elevator.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[non_exhaustive]
pub enum ElevatorPhase {
    /// Parked with no pending requests.
    Idle,
    /// Travelling toward a specific stop in response to a dispatch
    /// assignment (carrying or about to pick up riders).
    MovingToStop(EntityId),
    /// Travelling toward a stop for repositioning — no rider service
    /// obligation, will transition directly to [`Idle`] on arrival
    /// without opening doors. Distinct from [`MovingToStop`] so that
    /// downstream code (dispatch, UI, metrics) can treat opportunistic
    /// moves differently from scheduled trips.
    ///
    /// [`MovingToStop`]: Self::MovingToStop
    /// [`Idle`]: Self::Idle
    Repositioning(EntityId),
    /// Doors are currently opening.
    DoorOpening,
    /// Doors open; riders may board or exit.
    Loading,
    /// Doors are currently closing.
    DoorClosing,
    /// Stopped at a floor (doors closed, awaiting dispatch).
    Stopped,
}

impl ElevatorPhase {
    /// Whether the elevator is currently travelling (in either a dispatched
    /// or a repositioning move).
    #[must_use]
    pub const fn is_moving(&self) -> bool {
        matches!(self, Self::MovingToStop(_) | Self::Repositioning(_))
    }

    /// The target stop of a moving elevator, if any.
    ///
    /// Returns `Some(stop)` for both [`MovingToStop`] and [`Repositioning`]
    /// variants; `None` otherwise.
    ///
    /// [`MovingToStop`]: Self::MovingToStop
    /// [`Repositioning`]: Self::Repositioning
    #[must_use]
    pub const fn moving_target(&self) -> Option<EntityId> {
        match self {
            Self::MovingToStop(s) | Self::Repositioning(s) => Some(*s),
            _ => None,
        }
    }
}

impl std::fmt::Display for ElevatorPhase {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Idle => write!(f, "Idle"),
            Self::MovingToStop(id) => write!(f, "MovingToStop({id:?})"),
            Self::Repositioning(id) => write!(f, "Repositioning({id:?})"),
            Self::DoorOpening => write!(f, "DoorOpening"),
            Self::Loading => write!(f, "Loading"),
            Self::DoorClosing => write!(f, "DoorClosing"),
            Self::Stopped => write!(f, "Stopped"),
        }
    }
}

/// Component for an elevator entity.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Elevator {
    /// Current operational phase.
    pub(crate) phase: ElevatorPhase,
    /// Door finite-state machine.
    pub(crate) door: DoorState,
    /// Maximum travel speed (distance/tick).
    pub(crate) max_speed: Speed,
    /// Acceleration rate (distance/tick^2).
    pub(crate) acceleration: Accel,
    /// Deceleration rate (distance/tick^2).
    pub(crate) deceleration: Accel,
    /// Maximum weight the car can carry.
    pub(crate) weight_capacity: Weight,
    /// Total weight of riders currently aboard.
    pub(crate) current_load: Weight,
    /// Entity IDs of riders currently aboard.
    pub(crate) riders: Vec<EntityId>,
    /// Stop entity the car is heading toward, if any.
    pub(crate) target_stop: Option<EntityId>,
    /// Ticks for a door open/close transition.
    pub(crate) door_transition_ticks: u32,
    /// Ticks the door stays fully open.
    pub(crate) door_open_ticks: u32,
    /// Line entity this car belongs to.
    #[serde(alias = "group")]
    pub(crate) line: EntityId,
    /// Whether this elevator is currently repositioning (not serving a dispatch).
    #[serde(default)]
    pub(crate) repositioning: bool,
    /// Stop entity IDs this elevator cannot serve (access restriction).
    #[serde(default)]
    pub(crate) restricted_stops: HashSet<EntityId>,
    /// Speed multiplier for Inspection mode (0.0..1.0).
    #[serde(default = "default_inspection_speed_factor")]
    pub(crate) inspection_speed_factor: f64,
    /// Up-direction indicator lamp: whether this car will serve upward trips.
    ///
    /// Auto-managed by the dispatch phase: set true when heading up (or idle),
    /// false while actively committed to a downward trip. Affects boarding:
    /// a rider whose next leg goes up will not board a car with `going_up=false`.
    #[serde(default = "default_true")]
    pub(crate) going_up: bool,
    /// Down-direction indicator lamp: whether this car will serve downward trips.
    ///
    /// Auto-managed by the dispatch phase: set true when heading down (or idle),
    /// false while actively committed to an upward trip. Affects boarding:
    /// a rider whose next leg goes down will not board a car with `going_down=false`.
    #[serde(default = "default_true")]
    pub(crate) going_down: bool,
    /// Count of rounded-floor transitions (passing-floors + arrivals).
    /// Useful as a scoring axis for efficiency — fewer moves per delivery
    /// means less wasted travel.
    #[serde(default)]
    pub(crate) move_count: u64,
    /// Pending manual door-control commands. Processed at the start of the
    /// doors phase; commands that aren't yet valid remain queued.
    #[serde(default)]
    pub(crate) door_command_queue: Vec<DoorCommand>,
    /// Target velocity commanded by the game while in
    /// [`ServiceMode::Manual`](crate::components::ServiceMode::Manual).
    ///
    /// `None` means no command is active — the car coasts to a stop using
    /// `deceleration`. Read the current target via
    /// [`Elevator::manual_target_velocity`].
    #[serde(default)]
    pub(crate) manual_target_velocity: Option<f64>,
    /// Load-ratio threshold (0..=1) above which this car ignores new
    /// upward hall calls. Modeled on Otis Elevonic 411's full-load
    /// bypass (patent US5490580A). `None` disables the bypass — the
    /// default for backwards compatibility.
    ///
    /// Aboard riders still get delivered regardless; the threshold
    /// affects *pickup* decisions only.
    #[serde(default)]
    pub(crate) bypass_load_up_pct: Option<f64>,
    /// Load-ratio threshold for downward-direction pickups. Typically
    /// set lower than `bypass_load_up_pct` because down-peak riders
    /// accumulate more gradually and a half-full car has less incentive
    /// to skip the next stop. `None` disables the bypass.
    #[serde(default)]
    pub(crate) bypass_load_down_pct: Option<f64>,
    /// Per-elevator home stop. When `Some(stop)`, the reposition phase
    /// hard-pins this car to that stop: any time the car is idle and
    /// off-position, it is routed home regardless of the group's
    /// reposition strategy. Useful for express cars assigned to a
    /// dedicated lobby or service cars that should park in a
    /// loading bay between requests. `None` (the default) leaves
    /// reposition decisions entirely to the group strategy.
    #[serde(default)]
    pub(crate) home_stop: Option<EntityId>,
}

/// Default inspection speed factor (25% of normal speed).
const fn default_inspection_speed_factor() -> f64 {
    0.25
}

/// Default value for direction indicator fields (both lamps on = idle/either direction).
const fn default_true() -> bool {
    true
}

impl Elevator {
    /// Current operational phase.
    #[must_use]
    pub const fn phase(&self) -> ElevatorPhase {
        self.phase
    }

    /// Door finite-state machine.
    #[must_use]
    pub const fn door(&self) -> &DoorState {
        &self.door
    }

    /// Maximum travel speed (distance/tick).
    #[must_use]
    pub const fn max_speed(&self) -> Speed {
        self.max_speed
    }

    /// Acceleration rate (distance/tick^2).
    #[must_use]
    pub const fn acceleration(&self) -> Accel {
        self.acceleration
    }

    /// Deceleration rate (distance/tick^2).
    #[must_use]
    pub const fn deceleration(&self) -> Accel {
        self.deceleration
    }

    /// Maximum weight the car can carry.
    #[must_use]
    pub const fn weight_capacity(&self) -> Weight {
        self.weight_capacity
    }

    /// Total weight of riders currently aboard.
    #[must_use]
    pub const fn current_load(&self) -> Weight {
        self.current_load
    }

    /// Entity IDs of riders currently aboard.
    #[must_use]
    pub fn riders(&self) -> &[EntityId] {
        &self.riders
    }

    /// Stop entity the car is heading toward, if any.
    #[must_use]
    pub const fn target_stop(&self) -> Option<EntityId> {
        self.target_stop
    }

    /// Ticks for a door open/close transition.
    #[must_use]
    pub const fn door_transition_ticks(&self) -> u32 {
        self.door_transition_ticks
    }

    /// Ticks the door stays fully open.
    #[must_use]
    pub const fn door_open_ticks(&self) -> u32 {
        self.door_open_ticks
    }

    /// Line entity this car belongs to.
    #[must_use]
    pub const fn line(&self) -> EntityId {
        self.line
    }

    /// Whether this elevator is currently repositioning (not serving a dispatch).
    #[must_use]
    pub const fn repositioning(&self) -> bool {
        self.repositioning
    }

    /// Stop entity IDs this elevator cannot serve (access restriction).
    #[must_use]
    pub const fn restricted_stops(&self) -> &HashSet<EntityId> {
        &self.restricted_stops
    }

    /// Speed multiplier applied during Inspection mode.
    #[must_use]
    pub const fn inspection_speed_factor(&self) -> f64 {
        self.inspection_speed_factor
    }

    /// Load-ratio threshold above which upward-direction pickups are
    /// skipped (full-load bypass). `None` disables the bypass. See the
    /// field docs on [`Elevator`] for the underlying model.
    #[must_use]
    pub const fn bypass_load_up_pct(&self) -> Option<f64> {
        self.bypass_load_up_pct
    }

    /// Load-ratio threshold above which downward-direction pickups are
    /// skipped. `None` disables the bypass.
    #[must_use]
    pub const fn bypass_load_down_pct(&self) -> Option<f64> {
        self.bypass_load_down_pct
    }

    /// Mutator for the upward full-load bypass threshold.
    pub const fn set_bypass_load_up_pct(&mut self, pct: Option<f64>) {
        self.bypass_load_up_pct = pct;
    }

    /// Mutator for the downward full-load bypass threshold.
    pub const fn set_bypass_load_down_pct(&mut self, pct: Option<f64>) {
        self.bypass_load_down_pct = pct;
    }

    /// Per-elevator hard-pinned home stop. When `Some(stop)`, the
    /// reposition phase routes this car to `stop` whenever it is
    /// idle and off-position, regardless of the group's reposition
    /// strategy. `None` (the default) leaves reposition decisions
    /// entirely to the group strategy.
    #[must_use]
    pub const fn home_stop(&self) -> Option<EntityId> {
        self.home_stop
    }

    /// Whether this car's up-direction indicator lamp is lit.
    ///
    /// A lit up-lamp signals the car will serve upward-travelling riders.
    /// Both lamps lit means the car is idle and will accept either direction.
    #[must_use]
    pub const fn going_up(&self) -> bool {
        self.going_up
    }

    /// Whether this car's down-direction indicator lamp is lit.
    ///
    /// A lit down-lamp signals the car will serve downward-travelling riders.
    /// Both lamps lit means the car is idle and will accept either direction.
    #[must_use]
    pub const fn going_down(&self) -> bool {
        self.going_down
    }

    /// Direction this car is currently committed to, derived from the pair
    /// of indicator-lamp flags.
    ///
    /// - `Direction::Up` — only `going_up` is set
    /// - `Direction::Down` — only `going_down` is set
    /// - `Direction::Either` — both lamps lit (car is idle / accepting
    ///   either direction), or neither is set (treated as `Either` too,
    ///   though the dispatch phase normally keeps at least one lit)
    #[must_use]
    pub const fn direction(&self) -> Direction {
        match (self.going_up, self.going_down) {
            (true, false) => Direction::Up,
            (false, true) => Direction::Down,
            _ => Direction::Either,
        }
    }

    /// Count of rounded-floor transitions this elevator has made
    /// (both passing-floor crossings and arrivals).
    #[must_use]
    pub const fn move_count(&self) -> u64 {
        self.move_count
    }

    /// Pending manual door-control commands for this elevator.
    ///
    /// Populated by
    /// [`Simulation::open_door`](crate::sim::Simulation::open_door)
    /// and its siblings. Commands are drained at the start of each doors-phase
    /// tick; any that aren't yet valid remain queued.
    #[must_use]
    pub fn door_command_queue(&self) -> &[DoorCommand] {
        &self.door_command_queue
    }

    /// Currently commanded target velocity for
    /// [`ServiceMode::Manual`](crate::components::ServiceMode::Manual).
    ///
    /// Returns `None` if no target is set, meaning the car coasts to a
    /// stop using the configured deceleration. Positive values command
    /// upward travel, negative values command downward travel.
    #[must_use]
    pub const fn manual_target_velocity(&self) -> Option<f64> {
        self.manual_target_velocity
    }
}