elevator-core 15.26.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
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
use crate::components::{Accel, Speed, Weight};
use std::collections::HashSet;

use crate::entity::EntityId;
use crate::events::Event;
use crate::ids::GroupId;
use crate::sim::ElevatorParams;
use crate::stop::StopId;

use super::helpers::{default_config, scan};

#[test]
fn add_stop_at_runtime() {
    let config = default_config();
    let mut sim = crate::sim::Simulation::new(&config, scan()).unwrap();
    let line = sim.lines_in_group(GroupId(0))[0];

    let stop = sim.add_stop("Penthouse".into(), 12.0, line).unwrap();

    // Stop entity is alive and has correct data.
    assert!(sim.world().is_alive(stop));
    assert_eq!(sim.world().stop(stop).unwrap().name, "Penthouse");
    assert!((sim.world().stop(stop).unwrap().position - 12.0).abs() < 1e-9);

    // Stop was added to the group.
    let group = &sim.groups()[0];
    assert!(group.stop_entities().contains(&stop));

    // StopAdded event was emitted.
    let events = sim.drain_events();
    assert!(events.iter().any(|e| matches!(e,
        Event::StopAdded { stop: s, group: GroupId(0), .. } if *s == stop
    )));
}

#[test]
fn add_elevator_at_runtime() {
    let config = default_config();
    let mut sim = crate::sim::Simulation::new(&config, scan()).unwrap();
    let line = sim.lines_in_group(GroupId(0))[0];

    let params = ElevatorParams {
        max_speed: Speed::from(3.0),
        acceleration: Accel::from(2.0),
        deceleration: Accel::from(2.5),
        weight_capacity: Weight::from(1000.0),
        door_transition_ticks: 3,
        door_open_ticks: 8,
        restricted_stops: HashSet::new(),
        inspection_speed_factor: 0.25,

        bypass_load_up_pct: None,

        bypass_load_down_pct: None,
    };

    let elev = sim.add_elevator(&params, line, 4.0).unwrap();

    // Elevator entity is alive and positioned correctly.
    assert!(sim.world().is_alive(elev));
    assert!((sim.world().position(elev).unwrap().value - 4.0).abs() < 1e-9);
    assert!((sim.world().elevator(elev).unwrap().max_speed.value() - 3.0).abs() < 1e-9);

    // Elevator was added to the group.
    let group = &sim.groups()[0];
    assert!(group.elevator_entities().contains(&elev));

    // ElevatorAdded event was emitted.
    let events = sim.drain_events();
    assert!(events.iter().any(|e| matches!(e,
        Event::ElevatorAdded { elevator: e, group: GroupId(0), .. } if *e == elev
    )));
}

/// `add_elevator` runtime path must validate physics & door params (#247).
/// Construction-time validation rejects these; the runtime path was
/// previously silent, letting zero/negative speed or zero door ticks
/// reach the world and crash later phases.
#[test]
fn add_elevator_rejects_invalid_params() {
    use crate::error::SimError;

    let config = default_config();
    let mut sim = crate::sim::Simulation::new(&config, scan()).unwrap();
    let line = sim.lines_in_group(GroupId(0))[0];

    let valid = || ElevatorParams {
        max_speed: Speed::from(2.0),
        acceleration: Accel::from(1.5),
        deceleration: Accel::from(2.0),
        weight_capacity: Weight::from(800.0),
        door_transition_ticks: 5,
        door_open_ticks: 10,
        restricted_stops: HashSet::new(),
        inspection_speed_factor: 0.25,

        bypass_load_up_pct: None,

        bypass_load_down_pct: None,
    };

    // Note: Speed/Weight/Accel constructors panic on NaN/Inf/negative, so
    // those cases can't reach `add_elevator` through the public API. Cover
    // the values that *can* — zeroes for unit-typed fields, plus NaN/Inf
    // for the raw f64 inspection_speed_factor.
    let cases: Vec<(&'static str, ElevatorParams)> = vec![
        (
            "max_speed=0",
            ElevatorParams {
                max_speed: Speed::from(0.0),
                ..valid()
            },
        ),
        (
            "acceleration=0",
            ElevatorParams {
                acceleration: Accel::from(0.0),
                ..valid()
            },
        ),
        (
            "deceleration=0",
            ElevatorParams {
                deceleration: Accel::from(0.0),
                ..valid()
            },
        ),
        (
            "weight_capacity=0",
            ElevatorParams {
                weight_capacity: Weight::from(0.0),
                ..valid()
            },
        ),
        (
            "door_transition_ticks=0",
            ElevatorParams {
                door_transition_ticks: 0,
                ..valid()
            },
        ),
        (
            "door_open_ticks=0",
            ElevatorParams {
                door_open_ticks: 0,
                ..valid()
            },
        ),
        (
            "inspection_speed_factor=0",
            ElevatorParams {
                inspection_speed_factor: 0.0,
                ..valid()
            },
        ),
        (
            "inspection_speed_factor=NaN",
            ElevatorParams {
                inspection_speed_factor: f64::NAN,
                ..valid()
            },
        ),
        (
            "inspection_speed_factor=-1",
            ElevatorParams {
                inspection_speed_factor: -1.0,
                ..valid()
            },
        ),
    ];

    for (label, params) in cases {
        let elev_count_before = sim.world().elevator_ids().len();
        let result = sim.add_elevator(&params, line, 0.0);
        assert!(
            matches!(result, Err(SimError::InvalidConfig { .. })),
            "expected InvalidConfig for {label}, got {result:?}"
        );
        assert_eq!(
            sim.world().elevator_ids().len(),
            elev_count_before,
            "{label} must not add an elevator"
        );
    }

    // Sanity: a valid params set still succeeds afterwards.
    sim.add_elevator(&valid(), line, 0.0).unwrap();
}

/// Non-finite `starting_position` corrupts `SortedStops` and movement-phase
/// distance math. Reject it the same way `add_stop` does for stop position.
#[test]
fn add_elevator_rejects_non_finite_starting_position() {
    use crate::error::SimError;

    let config = default_config();
    let mut sim = crate::sim::Simulation::new(&config, scan()).unwrap();
    let line = sim.lines_in_group(GroupId(0))[0];

    let params = ElevatorParams {
        max_speed: Speed::from(2.0),
        acceleration: Accel::from(1.5),
        deceleration: Accel::from(2.0),
        weight_capacity: Weight::from(800.0),
        door_transition_ticks: 5,
        door_open_ticks: 10,
        restricted_stops: HashSet::new(),
        inspection_speed_factor: 0.25,

        bypass_load_up_pct: None,

        bypass_load_down_pct: None,
    };

    for (label, value) in [
        ("NaN", f64::NAN),
        ("+inf", f64::INFINITY),
        ("-inf", f64::NEG_INFINITY),
    ] {
        let elev_count_before = sim.world().elevator_ids().len();
        let result = sim.add_elevator(&params, line, value);
        assert!(
            matches!(
                result,
                Err(SimError::InvalidConfig {
                    field: "starting_position",
                    ..
                })
            ),
            "expected InvalidConfig{{field=starting_position}} for {label}, got {result:?}"
        );
        assert_eq!(
            sim.world().elevator_ids().len(),
            elev_count_before,
            "{label} must not add an elevator"
        );
    }
}

/// `add_stop` must reject non-finite positions instead of silently
/// inserting them into `SortedStops` (where `partition_point` on NaN
/// is undefined behavior for ordering) and the position map (where
/// `find_stop_at_position` with `f64::NAN` returns nondeterministic
/// results).
#[test]
fn add_stop_rejects_non_finite_position() {
    let config = default_config();
    let mut sim = crate::sim::Simulation::new(&config, scan()).unwrap();
    let line = sim.lines_in_group(GroupId(0))[0];

    for (label, value) in [
        ("NaN", f64::NAN),
        ("+inf", f64::INFINITY),
        ("-inf", f64::NEG_INFINITY),
    ] {
        let result = sim.add_stop(label.into(), value, line);
        assert!(
            matches!(result, Err(crate::error::SimError::InvalidConfig { .. })),
            "add_stop with {label} position must return InvalidConfig, got {result:?}"
        );
    }
}

#[test]
fn add_to_nonexistent_line_returns_error() {
    let config = default_config();
    let mut sim = crate::sim::Simulation::new(&config, scan()).unwrap();

    let bogus = EntityId::default();
    let result = sim.add_stop("X".into(), 0.0, bogus);
    assert!(result.is_err());

    let params = ElevatorParams {
        max_speed: Speed::from(1.0),
        acceleration: Accel::from(1.0),
        deceleration: Accel::from(1.0),
        weight_capacity: Weight::from(100.0),
        door_transition_ticks: 1,
        door_open_ticks: 1,
        restricted_stops: HashSet::new(),
        inspection_speed_factor: 0.25,

        bypass_load_up_pct: None,

        bypass_load_down_pct: None,
    };
    let result = sim.add_elevator(&params, bogus, 0.0);
    assert!(result.is_err());
}

#[test]
fn disable_and_enable_entities() {
    let config = default_config();
    let mut sim = crate::sim::Simulation::new(&config, scan()).unwrap();

    let stop = sim.stop_entity(StopId(0)).unwrap();

    assert!(!sim.is_disabled(stop));
    sim.disable(stop).unwrap();
    assert!(sim.is_disabled(stop));

    // EntityDisabled event emitted.
    let events = sim.drain_events();
    assert!(
        events
            .iter()
            .any(|e| matches!(e, Event::EntityDisabled { entity, .. } if *entity == stop))
    );

    sim.enable(stop).unwrap();
    assert!(!sim.is_disabled(stop));

    let events = sim.drain_events();
    assert!(
        events
            .iter()
            .any(|e| matches!(e, Event::EntityEnabled { entity, .. } if *entity == stop))
    );
}

#[test]
fn disabled_elevator_not_dispatched() {
    let config = default_config();
    let mut sim = crate::sim::Simulation::new(&config, scan()).unwrap();

    // Get the only elevator and disable it.
    let elev = sim.world().elevator_ids()[0];
    sim.disable(elev).unwrap();
    sim.drain_events();

    // Spawn a rider — should trigger dispatch, but elevator is disabled.
    sim.spawn_rider(StopId(0), StopId(2), 70.0).unwrap();
    sim.step();

    let events = sim.drain_events();
    // No ElevatorAssigned because the elevator is disabled.
    assert!(
        !events
            .iter()
            .any(|e| matches!(e, Event::ElevatorAssigned { .. }))
    );
}

#[test]
fn add_line_rejects_invalid_bounds() {
    use crate::components::Orientation;
    use crate::sim::LineParams;

    let config = default_config();
    let mut sim = crate::sim::Simulation::new(&config, scan()).unwrap();

    let mut bad = LineParams::new("bad", GroupId(0));
    bad.orientation = Orientation::default();

    bad.min_position = f64::NAN;
    bad.max_position = 10.0;
    assert!(sim.add_line(&bad).is_err(), "NaN min should be rejected");

    bad.min_position = 0.0;
    bad.max_position = f64::INFINITY;
    assert!(
        sim.add_line(&bad).is_err(),
        "infinite max should be rejected"
    );

    bad.min_position = 10.0;
    bad.max_position = 5.0;
    assert!(
        sim.add_line(&bad).is_err(),
        "inverted bounds should be rejected"
    );
}

#[test]
fn set_line_range_clamps_out_of_range_car() {
    let config = default_config();
    let mut sim = crate::sim::Simulation::new(&config, scan()).unwrap();
    let line = sim.lines_in_group(GroupId(0))[0];
    let elevators = sim.groups()[0].lines()[0].elevators().to_vec();
    assert!(!elevators.is_empty(), "default config should have a car");
    let car = elevators[0];

    // Move the car well above the building, then shrink the line below it.
    if let Some(p) = sim.world_mut().position_mut(car) {
        p.value = 100.0;
    }

    sim.set_line_range(line, 0.0, 10.0).unwrap();

    let pos = sim.world().position(car).unwrap().value;
    assert!(
        (pos - 10.0).abs() < 1e-9,
        "car should be clamped to new max (got {pos})"
    );
    let vel = sim.world().velocity(car).unwrap().value;
    assert!(vel.abs() < 1e-9, "velocity should be zeroed on clamp");
}

#[test]
fn set_line_range_rejects_inverted_bounds() {
    let config = default_config();
    let mut sim = crate::sim::Simulation::new(&config, scan()).unwrap();
    let line = sim.lines_in_group(GroupId(0))[0];

    assert!(sim.set_line_range(line, 10.0, 5.0).is_err());
}

#[test]
fn set_line_range_rejects_nonfinite_bounds() {
    let config = default_config();
    let mut sim = crate::sim::Simulation::new(&config, scan()).unwrap();
    let line = sim.lines_in_group(GroupId(0))[0];

    assert!(sim.set_line_range(line, f64::NAN, 10.0).is_err());
    assert!(sim.set_line_range(line, 0.0, f64::INFINITY).is_err());
}

#[test]
fn set_line_range_unknown_line_is_error() {
    let config = default_config();
    let mut sim = crate::sim::Simulation::new(&config, scan()).unwrap();

    let bogus = sim.world_mut().spawn();
    assert!(sim.set_line_range(bogus, 0.0, 10.0).is_err());
}

#[test]
fn runtime_stop_has_no_stop_id() {
    let config = default_config();
    let mut sim = crate::sim::Simulation::new(&config, scan()).unwrap();
    let line = sim.lines_in_group(GroupId(0))[0];

    let _stop = sim.add_stop("Runtime".into(), 20.0, line).unwrap();

    // Config stop lookup should not contain runtime stops.
    assert_eq!(
        sim.stop_entity(StopId(0)),
        Some(sim.stop_entity(StopId(0)).unwrap())
    );
    // There's no StopId for the runtime stop — only EntityId.
}

#[test]
fn find_stop_at_position_on_line_walks_group_topology() {
    let config = default_config();
    let mut sim = crate::sim::Simulation::new(&config, scan()).unwrap();
    let line = sim.lines_in_group(GroupId(0))[0];

    let stop = sim.add_stop("Roof".into(), 20.0, line).unwrap();

    // Happy path: line exists, stop position matches.
    assert_eq!(
        sim.find_stop_at_position_on_line(20.0, line),
        Some(stop),
        "lookup should find the stop on the line"
    );

    // None case 1: position has no stop on this line.
    assert_eq!(
        sim.find_stop_at_position_on_line(99.0, line),
        None,
        "no stop at position 99.0"
    );

    // None case 2: line entity doesn't exist.
    let bogus = sim.world_mut().spawn();
    assert_eq!(
        sim.find_stop_at_position_on_line(20.0, bogus),
        None,
        "unknown line should resolve to None"
    );
}