elevator-core 20.0.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
use crate::components::{Accel, Speed, Weight};
use std::collections::HashSet;

use crate::components::*;
use crate::door::DoorState;
use crate::world::{ExtKey, World};

#[test]
fn spawn_and_check_alive() {
    let mut world = World::new();
    let id = world.spawn();
    assert!(world.is_alive(id));
    assert_eq!(world.entity_count(), 1);
}

#[test]
fn despawn_removes_entity_and_components() {
    let mut world = World::new();
    let id = world.spawn();
    world.set_position(id, Position { value: 42.0 });
    world.set_stop(
        id,
        Stop {
            name: "Test".into(),
            position: 42.0,
        },
    );

    assert!(world.position(id).is_some());
    assert!(world.stop(id).is_some());

    world.despawn(id);

    assert!(!world.is_alive(id));
    assert!(world.position(id).is_none());
    assert!(world.stop(id).is_none());
    assert_eq!(world.entity_count(), 0);
}

#[test]
fn elevator_query_returns_entities_with_both_components() {
    let mut world = World::new();

    // Entity with both Position + Elevator.
    let elev_id = world.spawn();
    world.set_position(elev_id, Position { value: 10.0 });
    world.set_elevator(
        elev_id,
        Elevator {
            phase: ElevatorPhase::Idle,
            door: DoorState::Closed,
            max_speed: Speed::from(2.0),
            acceleration: Accel::from(1.5),
            deceleration: Accel::from(2.0),
            weight_capacity: Weight::from(800.0),
            current_load: Weight::from(0.0),
            riders: vec![],
            target_stop: None,
            door_transition_ticks: 15,
            door_open_ticks: 60,
            line: crate::entity::EntityId::default(),
            repositioning: false,
            restricted_stops: HashSet::new(),
            inspection_speed_factor: 0.25,
            going_up: true,
            going_down: true,
            move_count: 0,
            door_command_queue: Vec::new(),
            manual_target_velocity: None,
            bypass_load_up_pct: None,
            bypass_load_down_pct: None,
            home_stop: None,
        },
    );

    // Entity with only Position (a stop, not an elevator).
    let stop_id = world.spawn();
    world.set_position(stop_id, Position { value: 0.0 });

    let elevators: Vec<_> = world.iter_elevators().collect();
    assert_eq!(elevators.len(), 1);
    assert_eq!(elevators[0].0, elev_id);
    assert!((elevators[0].1.value - 10.0).abs() < f64::EPSILON);
}

#[test]
fn rider_query() {
    let mut world = World::new();

    let p1 = world.spawn();
    let origin = world.spawn();
    world.set_rider(
        p1,
        Rider {
            weight: Weight::from(70.0),
            phase: RiderPhase::Waiting,
            current_stop: Some(origin),
            spawn_tick: 0,
            tag: 0,
            board_tick: None,
        },
    );

    let riders: Vec<_> = world.iter_riders().collect();
    assert_eq!(riders.len(), 1);
    assert!((riders[0].1.weight.value() - 70.0).abs() < f64::EPSILON);
}

#[test]
fn find_stop_at_position() {
    let mut world = World::new();

    let s0 = world.spawn();
    world.set_stop(
        s0,
        Stop {
            name: "Ground".into(),
            position: 0.0,
        },
    );

    let s1 = world.spawn();
    world.set_stop(
        s1,
        Stop {
            name: "Roof".into(),
            position: 100.0,
        },
    );

    assert_eq!(world.find_stop_at_position(0.0), Some(s0));
    assert_eq!(world.find_stop_at_position(100.0), Some(s1));
    assert_eq!(world.find_stop_at_position(50.0), None);
}

#[test]
fn find_stop_at_position_in_disambiguates_co_located_stops() {
    // Two stops at the same physical position — global lookup is
    // ambiguous; the per-line variant must respect the candidates
    // filter so callers get the stop they actually meant.
    let mut world = World::new();
    let s_low = world.spawn();
    world.set_stop(
        s_low,
        Stop {
            name: "Lobby (low bank)".into(),
            position: 0.0,
        },
    );
    let s_high = world.spawn();
    world.set_stop(
        s_high,
        Stop {
            name: "Lobby (high bank)".into(),
            position: 0.0,
        },
    );

    // Asking for stops on the "high bank" line returns s_high regardless
    // of which one wins the global linear scan.
    let high_bank_stops = [s_high];
    assert_eq!(
        world.find_stop_at_position_in(0.0, &high_bank_stops),
        Some(s_high)
    );

    let low_bank_stops = [s_low];
    assert_eq!(
        world.find_stop_at_position_in(0.0, &low_bank_stops),
        Some(s_low)
    );

    // No candidates → None even when stops exist at the position.
    assert_eq!(world.find_stop_at_position_in(0.0, &[]), None);

    // Candidates at a different position → None.
    let other_stops = [s_low];
    assert_eq!(world.find_stop_at_position_in(50.0, &other_stops), None);
}

#[test]
fn multiple_entities_independent() {
    let mut world = World::new();
    let a = world.spawn();
    let b = world.spawn();
    let c = world.spawn();

    world.set_position(a, Position { value: 1.0 });
    world.set_position(b, Position { value: 2.0 });
    world.set_position(c, Position { value: 3.0 });

    world.despawn(b);

    assert!(world.is_alive(a));
    assert!(!world.is_alive(b));
    assert!(world.is_alive(c));
    assert_eq!(world.entity_count(), 2);
}

#[test]
fn stop_position_helper() {
    let mut world = World::new();
    let s = world.spawn();
    world.set_stop(
        s,
        Stop {
            name: "Test".into(),
            position: 42.5,
        },
    );

    assert_eq!(world.stop_position(s), Some(42.5));

    let fake = world.spawn();
    assert_eq!(world.stop_position(fake), None);
}

#[test]
fn extension_components() {
    #[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
    struct VipTag {
        level: u32,
    }

    let mut world = World::new();
    let e = world.spawn();

    // Insert, get, mutate.
    world.insert_ext(e, VipTag { level: 3 }, ExtKey::from_type_name());
    assert_eq!(world.ext::<VipTag>(e), Some(VipTag { level: 3 }));

    world.ext_mut::<VipTag>(e).unwrap().level = 5;
    assert_eq!(world.ext::<VipTag>(e).unwrap().level, 5);

    // Despawn cleans up extensions.
    world.despawn(e);
    assert!(world.ext::<VipTag>(e).is_none());
}

/// `register_ext` panics if a different type already owns this name (#262).
/// Two extension types sharing one `ExtKey` name silently corrupts snapshot
/// serde — `serialize_extensions` collapses both into one slot, and
/// `deserialize_extensions` routes data via non-deterministic `HashMap::iter`.
#[test]
#[should_panic(expected = "already registered")]
fn register_ext_panics_on_name_collision_via_register() {
    #[derive(serde::Serialize, serde::Deserialize)]
    struct A;
    #[derive(serde::Serialize, serde::Deserialize)]
    struct B;

    let mut world = World::new();
    world.register_ext::<A>(ExtKey::new("foo"));
    world.register_ext::<B>(ExtKey::new("foo")); // same name, different type → panic
}

#[test]
#[should_panic(expected = "already registered")]
fn register_ext_panics_on_name_collision_via_insert() {
    #[derive(serde::Serialize, serde::Deserialize)]
    struct A;
    #[derive(serde::Serialize, serde::Deserialize)]
    struct B;

    let mut world = World::new();
    let e = world.spawn();
    world.insert_ext(e, A, ExtKey::new("foo"));
    world.insert_ext(e, B, ExtKey::new("foo")); // panic
}

#[test]
fn register_ext_same_type_same_name_idempotent() {
    // Re-registering the SAME type with the SAME name is a no-op (used for
    // snapshot restore where `register_ext` is called per-type before
    // `deserialize_extensions`).
    #[derive(serde::Serialize, serde::Deserialize)]
    struct A;

    let mut world = World::new();
    world.register_ext::<A>(ExtKey::new("foo"));
    world.register_ext::<A>(ExtKey::new("foo")); // idempotent — no panic
}

/// Verify that despawn cleans up `hall_calls` and `car_calls`.
#[test]
fn despawn_cleans_up_hall_and_car_calls() {
    let mut world = World::new();
    let stop_eid = world.spawn();
    world.set_stop(
        stop_eid,
        Stop {
            name: "S".into(),
            position: 0.0,
        },
    );

    let car_eid = world.spawn();
    world.set_elevator(
        car_eid,
        Elevator {
            phase: ElevatorPhase::Idle,
            door: DoorState::Closed,
            max_speed: Speed::from(2.0),
            acceleration: Accel::from(1.5),
            deceleration: Accel::from(2.0),
            weight_capacity: Weight::from(800.0),
            current_load: Weight::from(0.0),
            riders: vec![],
            target_stop: None,
            door_transition_ticks: 15,
            door_open_ticks: 60,
            line: crate::entity::EntityId::default(),
            repositioning: false,
            restricted_stops: HashSet::new(),
            inspection_speed_factor: 0.25,
            going_up: true,
            going_down: true,
            move_count: 0,
            door_command_queue: Vec::new(),
            manual_target_velocity: None,
            bypass_load_up_pct: None,
            bypass_load_down_pct: None,
            home_stop: None,
        },
    );

    // Populate car_calls for the elevator.
    if let Some(cc) = world.car_calls_mut(car_eid) {
        cc.push(crate::components::CarCall::new(car_eid, stop_eid, 0));
    }
    assert!(!world.car_calls(car_eid).is_empty());

    world.despawn(car_eid);
    assert!(
        world.car_calls(car_eid).is_empty(),
        "car_calls should be cleaned up after despawn"
    );
}

fn make_elevator(
    world: &mut World,
    position: f64,
    capacity: f64,
    load: f64,
) -> crate::entity::EntityId {
    let id = world.spawn();
    world.set_position(id, Position { value: position });
    world.set_elevator(
        id,
        Elevator {
            phase: ElevatorPhase::Idle,
            door: DoorState::Closed,
            max_speed: Speed::from(2.0),
            acceleration: Accel::from(1.5),
            deceleration: Accel::from(2.0),
            weight_capacity: Weight::from(capacity),
            current_load: Weight::from(load),
            riders: vec![],
            target_stop: None,
            door_transition_ticks: 15,
            door_open_ticks: 60,
            line: crate::entity::EntityId::default(),
            repositioning: false,
            restricted_stops: HashSet::new(),
            inspection_speed_factor: 0.25,
            going_up: true,
            going_down: true,
            move_count: 0,
            door_command_queue: Vec::new(),
            manual_target_velocity: None,
            bypass_load_up_pct: None,
            bypass_load_down_pct: None,
            home_stop: None,
        },
    );
    id
}

#[test]
fn elevator_load_ratio_clamps_and_handles_non_elevator() {
    let mut world = World::new();
    let elev = make_elevator(&mut world, 0.0, 800.0, 200.0);
    let non_elev = world.spawn();

    assert!((world.elevator_load_ratio(elev).unwrap() - 0.25).abs() < 1e-9);
    assert!(world.elevator_load_ratio(non_elev).is_none());

    let overloaded = make_elevator(&mut world, 0.0, 100.0, 999.0);
    assert!((world.elevator_load_ratio(overloaded).unwrap() - 1.0).abs() < 1e-9);
}

#[test]
fn elevator_occupants_returns_riders_slice() {
    let mut world = World::new();
    let elev = make_elevator(&mut world, 0.0, 800.0, 0.0);
    let bare = world.spawn();
    assert_eq!(world.elevator_occupants(elev).map(<[_]>::len), Some(0));
    assert!(world.elevator_occupants(bare).is_none());
}

#[test]
fn find_elevator_at_position_matches_within_epsilon() {
    let mut world = World::new();
    let elev = make_elevator(&mut world, 10.0, 800.0, 0.0);
    let _ = make_elevator(&mut world, 50.0, 800.0, 0.0);

    assert_eq!(world.find_elevator_at_position(10.0), Some(elev));
    assert_eq!(
        world.find_elevator_at_position(10.0 + World::STOP_POSITION_EPSILON / 2.0),
        Some(elev),
    );
    // Strict `<` epsilon: a query a few epsilons away must miss. Using
    // exactly `+ EPSILON` would be flaky under f64 rounding (the
    // computed delta lands on either side of EPSILON depending on the
    // bit pattern), so step out by 2× to make the boundary intent clear.
    assert!(
        world
            .find_elevator_at_position(2.0_f64.mul_add(World::STOP_POSITION_EPSILON, 10.0))
            .is_none()
    );
    assert!(world.find_elevator_at_position(20.0).is_none());
}