Skip to main content

elevator_core/
events.rs

1//! Simulation event bus and typed event channels.
2
3use crate::components::CallDirection;
4use crate::entity::EntityId;
5use crate::error::{RejectionContext, RejectionReason};
6use crate::ids::GroupId;
7use ordered_float::OrderedFloat;
8use serde::{Deserialize, Serialize};
9
10/// Events emitted by the simulation during ticks.
11///
12/// All entity references use `EntityId`. Games can look up additional
13/// component data on the referenced entity if needed.
14#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
15#[non_exhaustive]
16pub enum Event {
17    // -- Elevator events --
18    /// An elevator departed from a stop.
19    ElevatorDeparted {
20        /// The elevator that departed.
21        elevator: EntityId,
22        /// The stop it departed from.
23        from_stop: EntityId,
24        /// The tick when departure occurred.
25        tick: u64,
26    },
27    /// An elevator arrived at a stop.
28    ElevatorArrived {
29        /// The elevator that arrived.
30        elevator: EntityId,
31        /// The stop it arrived at.
32        at_stop: EntityId,
33        /// The tick when arrival occurred.
34        tick: u64,
35    },
36    /// An elevator's doors finished opening.
37    DoorOpened {
38        /// The elevator whose doors opened.
39        elevator: EntityId,
40        /// The tick when the doors opened.
41        tick: u64,
42    },
43    /// An elevator's doors finished closing.
44    DoorClosed {
45        /// The elevator whose doors closed.
46        elevator: EntityId,
47        /// The tick when the doors closed.
48        tick: u64,
49    },
50    /// Emitted when an elevator passes a stop without stopping.
51    /// Games/dispatch can use this to decide whether to add stops mid-travel.
52    PassingFloor {
53        /// The elevator passing by.
54        elevator: EntityId,
55        /// The stop being passed.
56        stop: EntityId,
57        /// Direction: true = moving up, false = moving down.
58        moving_up: bool,
59        /// The tick when the pass occurred.
60        tick: u64,
61    },
62    /// An in-flight movement was aborted by
63    /// [`Simulation::abort_movement`](crate::sim::Simulation::abort_movement).
64    ///
65    /// The car brakes along its normal deceleration profile, re-targets to
66    /// the nearest reachable stop, and arrives there without opening doors
67    /// (onboard riders stay aboard). The pending destination queue is also
68    /// cleared as part of the abort.
69    ///
70    /// Emitted at abort time — the car is still in flight, decelerating
71    /// toward `brake_target`. A normal [`Event::ElevatorArrived`] fires
72    /// once the car actually reaches the stop.
73    MovementAborted {
74        /// The elevator whose trip was aborted.
75        elevator: EntityId,
76        /// The stop the car will brake to and park at.
77        brake_target: EntityId,
78        /// The tick when the abort was requested.
79        tick: u64,
80    },
81
82    // -- Rider events (unified: passengers, cargo, any rideable entity) --
83    /// A new rider appeared at a stop and wants to travel.
84    RiderSpawned {
85        /// The spawned rider entity.
86        rider: EntityId,
87        /// The stop where the rider appeared.
88        origin: EntityId,
89        /// The stop the rider wants to reach.
90        destination: EntityId,
91        /// The tick when the rider spawned.
92        tick: u64,
93    },
94    /// A rider boarded an elevator.
95    RiderBoarded {
96        /// The rider that boarded.
97        rider: EntityId,
98        /// The elevator the rider boarded.
99        elevator: EntityId,
100        /// The tick when boarding occurred.
101        tick: u64,
102    },
103    /// A rider exited an elevator at a stop.
104    #[serde(alias = "RiderAlighted")]
105    RiderExited {
106        /// The rider that exited.
107        rider: EntityId,
108        /// The elevator the rider exited.
109        elevator: EntityId,
110        /// The stop where the rider exited.
111        stop: EntityId,
112        /// The tick when exiting occurred.
113        tick: u64,
114    },
115    /// A rider was rejected from boarding (e.g., over capacity).
116    RiderRejected {
117        /// The rider that was rejected.
118        rider: EntityId,
119        /// The elevator that rejected the rider.
120        elevator: EntityId,
121        /// The reason for rejection.
122        reason: RejectionReason,
123        /// Additional numeric context for the rejection.
124        context: Option<RejectionContext>,
125        /// The tick when rejection occurred.
126        tick: u64,
127    },
128    /// A rider gave up waiting and left the stop.
129    RiderAbandoned {
130        /// The rider that abandoned.
131        rider: EntityId,
132        /// The stop the rider left.
133        stop: EntityId,
134        /// The tick when abandonment occurred.
135        tick: u64,
136    },
137
138    /// A rider was ejected from an elevator (due to disable or despawn).
139    ///
140    /// The rider is moved to `Waiting` phase at the nearest stop.
141    RiderEjected {
142        /// The rider that was ejected.
143        rider: EntityId,
144        /// The elevator the rider was ejected from.
145        elevator: EntityId,
146        /// The stop the rider was placed at.
147        stop: EntityId,
148        /// The tick when ejection occurred.
149        tick: u64,
150    },
151
152    // -- Dispatch events --
153    /// An elevator was assigned to serve a stop by the dispatcher.
154    ElevatorAssigned {
155        /// The elevator that was assigned.
156        elevator: EntityId,
157        /// The stop it was assigned to serve.
158        stop: EntityId,
159        /// The tick when the assignment occurred.
160        tick: u64,
161    },
162
163    // -- Topology lifecycle events --
164    /// A new stop was added to the simulation.
165    StopAdded {
166        /// The new stop entity.
167        stop: EntityId,
168        /// The line the stop was added to.
169        line: EntityId,
170        /// The group the stop was added to.
171        group: GroupId,
172        /// The tick when the stop was added.
173        tick: u64,
174    },
175    /// A new elevator was added to the simulation.
176    ElevatorAdded {
177        /// The new elevator entity.
178        elevator: EntityId,
179        /// The line the elevator was added to.
180        line: EntityId,
181        /// The group the elevator was added to.
182        group: GroupId,
183        /// The tick when the elevator was added.
184        tick: u64,
185    },
186    /// An entity was disabled.
187    EntityDisabled {
188        /// The entity that was disabled.
189        entity: EntityId,
190        /// The tick when it was disabled.
191        tick: u64,
192    },
193    /// An entity was re-enabled.
194    EntityEnabled {
195        /// The entity that was re-enabled.
196        entity: EntityId,
197        /// The tick when it was enabled.
198        tick: u64,
199    },
200    /// A rider's route was invalidated due to topology change.
201    ///
202    /// Emitted when a stop on a rider's route is disabled or removed.
203    /// If no alternative is found, the rider will abandon after a grace period.
204    RouteInvalidated {
205        /// The affected rider.
206        rider: EntityId,
207        /// The stop that caused the invalidation.
208        affected_stop: EntityId,
209        /// Why the route was invalidated.
210        reason: RouteInvalidReason,
211        /// The tick when invalidation occurred.
212        tick: u64,
213    },
214    /// A rider was manually rerouted via `sim.reroute()` or `sim.reroute_rider()`.
215    RiderRerouted {
216        /// The rerouted rider.
217        rider: EntityId,
218        /// The new destination stop.
219        new_destination: EntityId,
220        /// The tick when rerouting occurred.
221        tick: u64,
222    },
223
224    /// A rider settled at a stop, becoming a resident.
225    RiderSettled {
226        /// The rider that settled.
227        rider: EntityId,
228        /// The stop where the rider settled.
229        stop: EntityId,
230        /// The tick when settlement occurred.
231        tick: u64,
232    },
233    /// A rider was removed from the simulation.
234    RiderDespawned {
235        /// The rider that was removed.
236        rider: EntityId,
237        /// The tick when despawn occurred.
238        tick: u64,
239    },
240
241    // -- Line lifecycle events --
242    /// A line was added to the simulation.
243    LineAdded {
244        /// The new line entity.
245        line: EntityId,
246        /// The group the line was added to.
247        group: GroupId,
248        /// The tick when the line was added.
249        tick: u64,
250    },
251    /// A line was removed from the simulation.
252    LineRemoved {
253        /// The removed line entity.
254        line: EntityId,
255        /// The group the line belonged to.
256        group: GroupId,
257        /// The tick when the line was removed.
258        tick: u64,
259    },
260    /// A line was reassigned to a different group.
261    LineReassigned {
262        /// The line entity that was reassigned.
263        line: EntityId,
264        /// The group the line was previously in.
265        old_group: GroupId,
266        /// The group the line was moved to.
267        new_group: GroupId,
268        /// The tick when reassignment occurred.
269        tick: u64,
270    },
271    /// An elevator was reassigned to a different line.
272    ElevatorReassigned {
273        /// The elevator that was reassigned.
274        elevator: EntityId,
275        /// The line the elevator was previously on.
276        old_line: EntityId,
277        /// The line the elevator was moved to.
278        new_line: EntityId,
279        /// The tick when reassignment occurred.
280        tick: u64,
281    },
282
283    // -- Repositioning events --
284    /// An elevator is being repositioned to improve coverage.
285    ///
286    /// Emitted when an idle elevator begins moving to a new position
287    /// as decided by the [`RepositionStrategy`](crate::dispatch::RepositionStrategy).
288    ElevatorRepositioning {
289        /// The elevator being repositioned.
290        elevator: EntityId,
291        /// The stop it is being sent to.
292        to_stop: EntityId,
293        /// The tick when repositioning began.
294        tick: u64,
295    },
296    /// An elevator completed repositioning and arrived at its target.
297    ///
298    /// Note: this is detected by the movement system — the elevator
299    /// arrives just like any other movement. Games can distinguish
300    /// repositioning arrivals from dispatch arrivals by tracking
301    /// which elevators received `ElevatorRepositioning` events.
302    ElevatorRepositioned {
303        /// The elevator that completed repositioning.
304        elevator: EntityId,
305        /// The stop it arrived at.
306        at_stop: EntityId,
307        /// The tick when it arrived.
308        tick: u64,
309    },
310
311    /// An elevator's service mode was changed.
312    ServiceModeChanged {
313        /// The elevator whose mode changed.
314        elevator: EntityId,
315        /// The previous service mode.
316        from: crate::components::ServiceMode,
317        /// The new service mode.
318        to: crate::components::ServiceMode,
319        /// The tick when the change occurred.
320        tick: u64,
321    },
322
323    // -- Observability events --
324    /// Energy consumed/regenerated by an elevator this tick.
325    ///
326    /// Requires the `energy` feature.
327    #[cfg(feature = "energy")]
328    EnergyConsumed {
329        /// The elevator that consumed energy.
330        elevator: EntityId,
331        /// Energy consumed this tick.
332        consumed: OrderedFloat<f64>,
333        /// Energy regenerated this tick.
334        regenerated: OrderedFloat<f64>,
335        /// The tick when energy was recorded.
336        tick: u64,
337    },
338
339    /// An elevator's load changed (rider boarded or exited).
340    ///
341    /// Emitted immediately after [`RiderBoarded`](Self::RiderBoarded) or
342    /// [`RiderExited`](Self::RiderExited). Useful for real-time capacity
343    /// bar displays in game UIs.
344    ///
345    /// Load values use [`OrderedFloat`] for
346    /// `Eq` compatibility. Dereference to get the inner `f64`:
347    ///
348    /// ```rust,ignore
349    /// use elevator_core::events::Event;
350    ///
351    /// if let Event::CapacityChanged { current_load, capacity, .. } = event {
352    ///     let pct = *current_load / *capacity * 100.0;
353    ///     println!("Elevator at {pct:.0}% capacity");
354    /// }
355    /// ```
356    CapacityChanged {
357        /// The elevator whose load changed.
358        elevator: EntityId,
359        /// Current total weight aboard after the change.
360        current_load: OrderedFloat<f64>,
361        /// Maximum weight capacity of the elevator.
362        capacity: OrderedFloat<f64>,
363        /// The tick when the change occurred.
364        tick: u64,
365    },
366
367    /// An elevator became idle (no more assignments or repositioning).
368    ElevatorIdle {
369        /// The elevator that became idle.
370        elevator: EntityId,
371        /// The stop where it became idle (if at a stop).
372        at_stop: Option<EntityId>,
373        /// The tick when it became idle.
374        tick: u64,
375    },
376
377    /// An elevator's direction indicator lamps changed.
378    ///
379    /// Emitted by the dispatch phase when the pair
380    /// `(going_up, going_down)` transitions to a new value — e.g. when
381    /// a car is assigned a target above it (up-only), below it (down-only),
382    /// or returns to idle (both lamps lit).
383    ///
384    /// Games can use this for UI (lighting up-arrow / down-arrow indicators
385    /// on a car) without polling the elevator each tick.
386    DirectionIndicatorChanged {
387        /// The elevator whose indicator lamps changed.
388        elevator: EntityId,
389        /// New state of the up-direction lamp.
390        going_up: bool,
391        /// New state of the down-direction lamp.
392        going_down: bool,
393        /// The tick when the change occurred.
394        tick: u64,
395    },
396
397    /// An elevator was permanently removed from the simulation.
398    ///
399    /// Distinct from [`Event::EntityDisabled`] — a disabled elevator can be
400    /// re-enabled, but a removed elevator is despawned.
401    ElevatorRemoved {
402        /// The elevator that was removed.
403        elevator: EntityId,
404        /// The line it belonged to.
405        line: EntityId,
406        /// The group it belonged to.
407        group: GroupId,
408        /// The tick when removal occurred.
409        tick: u64,
410    },
411
412    /// A stop was queued as a destination for an elevator.
413    ///
414    /// Emitted by [`Simulation::push_destination`](crate::sim::Simulation::push_destination),
415    /// [`Simulation::push_destination_front`](crate::sim::Simulation::push_destination_front),
416    /// and the built-in dispatch phase whenever it actually appends a stop
417    /// to an elevator's [`DestinationQueue`](crate::components::DestinationQueue).
418    /// Adjacent-duplicate pushes (that are deduplicated) do not emit.
419    DestinationQueued {
420        /// The elevator whose queue was updated.
421        elevator: EntityId,
422        /// The stop that was queued.
423        stop: EntityId,
424        /// The tick when the push occurred.
425        tick: u64,
426    },
427
428    /// A stop was permanently removed from the simulation.
429    ///
430    /// Distinct from [`Event::EntityDisabled`] — a disabled stop can be
431    /// re-enabled, but a removed stop is despawned.
432    StopRemoved {
433        /// The stop that was removed.
434        stop: EntityId,
435        /// The tick when removal occurred.
436        tick: u64,
437    },
438
439    /// A manual door-control command was received and either applied
440    /// immediately or stored for later.
441    ///
442    /// Emitted by
443    /// [`Simulation::open_door`](crate::sim::Simulation::open_door),
444    /// [`Simulation::close_door`](crate::sim::Simulation::close_door),
445    /// [`Simulation::hold_door`](crate::sim::Simulation::hold_door),
446    /// and [`Simulation::cancel_door_hold`](crate::sim::Simulation::cancel_door_hold)
447    /// when the command is accepted. Paired with
448    /// [`Event::DoorCommandApplied`] when the command eventually takes effect.
449    DoorCommandQueued {
450        /// The elevator targeted by the command.
451        elevator: EntityId,
452        /// The command that was queued.
453        command: crate::door::DoorCommand,
454        /// The tick when the command was submitted.
455        tick: u64,
456    },
457    /// A queued door-control command actually took effect — doors began
458    /// opening/closing or a hold was applied.
459    DoorCommandApplied {
460        /// The elevator the command applied to.
461        elevator: EntityId,
462        /// The command that was applied.
463        command: crate::door::DoorCommand,
464        /// The tick when the command was applied.
465        tick: u64,
466    },
467
468    /// An elevator parameter was mutated at runtime via one of the
469    /// `Simulation::set_*` upgrade setters (e.g. buying a speed upgrade
470    /// in an RPG, or a scripted event changing capacity mid-game).
471    ///
472    /// Emitted immediately when the setter succeeds. Games can use this
473    /// to trigger score popups, SFX, or UI updates.
474    ElevatorUpgraded {
475        /// The elevator whose parameter changed.
476        elevator: EntityId,
477        /// Which field was changed.
478        field: UpgradeField,
479        /// Previous value of the field.
480        old: UpgradeValue,
481        /// New value of the field.
482        new: UpgradeValue,
483        /// The tick when the upgrade was applied.
484        tick: u64,
485    },
486
487    /// A velocity command was submitted to an elevator running in
488    /// [`ServiceMode::Manual`](crate::components::ServiceMode::Manual).
489    ///
490    /// Emitted by
491    /// [`Simulation::set_target_velocity`](crate::sim::Simulation::set_target_velocity)
492    /// and [`Simulation::emergency_stop`](crate::sim::Simulation::emergency_stop).
493    ManualVelocityCommanded {
494        /// The elevator targeted by the command.
495        elevator: EntityId,
496        /// The new target velocity (clamped to `[-max_speed, max_speed]`),
497        /// or `None` when the command clears the target.
498        target_velocity: Option<ordered_float::OrderedFloat<f64>>,
499        /// The tick when the command was submitted.
500        tick: u64,
501    },
502
503    // -- Hall & car call events --
504    /// A hall button was pressed. Fires immediately, before any ack
505    /// latency delay. Games use this for button-light animations or SFX.
506    HallButtonPressed {
507        /// Stop where the press occurred.
508        stop: EntityId,
509        /// Direction the button requests service in.
510        direction: CallDirection,
511        /// Tick of the press.
512        tick: u64,
513    },
514    /// A hall call has elapsed its ack latency and is now visible to
515    /// dispatch. Useful for UI confirmations ("your call has been
516    /// received"). In groups with `ack_latency_ticks = 0` this fires on
517    /// the same tick as `HallButtonPressed`.
518    HallCallAcknowledged {
519        /// Stop the call was placed at.
520        stop: EntityId,
521        /// Direction of the call.
522        direction: CallDirection,
523        /// Tick acknowledgement completed.
524        tick: u64,
525    },
526    /// A hall call was cleared when an assigned car arrived at the stop
527    /// with matching direction indicators. Corresponds to the real-world
528    /// button-light turning off.
529    HallCallCleared {
530        /// Stop whose call was cleared.
531        stop: EntityId,
532        /// Direction of the cleared call.
533        direction: CallDirection,
534        /// Car that cleared the call by arriving.
535        car: EntityId,
536        /// Tick the call was cleared.
537        tick: u64,
538    },
539    /// A rider inside a car pressed a floor button (Classic mode only).
540    /// In Destination mode riders reveal destinations at the hall
541    /// kiosk, so no car buttons are pressed.
542    CarButtonPressed {
543        /// Elevator the button was pressed inside.
544        car: EntityId,
545        /// Floor the rider requested.
546        floor: EntityId,
547        /// Rider who pressed the button. `None` when the press is
548        /// synthetic — e.g. issued via
549        /// [`Simulation::press_car_button`](crate::sim::Simulation::press_car_button)
550        /// for scripted events, player input, or cutscene cues with no
551        /// associated rider entity.
552        rider: Option<EntityId>,
553        /// Tick of the press.
554        tick: u64,
555    },
556    /// A rider skipped boarding a car they considered too crowded
557    /// (their preferences filtered the car out). The rider remains
558    /// Waiting and may board a later car.
559    #[serde(alias = "RiderBalked")]
560    RiderSkipped {
561        /// Rider who skipped.
562        rider: EntityId,
563        /// Elevator they declined to board.
564        elevator: EntityId,
565        /// Stop where the skip happened.
566        at_stop: EntityId,
567        /// Tick of the skip.
568        tick: u64,
569    },
570    /// A snapshot restore encountered an entity reference that could not
571    /// be remapped. The original (now-invalid) ID was kept. This signals
572    /// a corrupted or hand-edited snapshot.
573    SnapshotDanglingReference {
574        /// The entity ID from the snapshot that had no mapping.
575        stale_id: EntityId,
576        /// Tick from the snapshot at restore time.
577        tick: u64,
578    },
579    /// A snapshot restore could not re-instantiate the reposition strategy
580    /// for a group (e.g. custom strategy not registered). Idle elevator
581    /// positioning will not work for this group until the game calls
582    /// [`Simulation::set_reposition`](crate::sim::Simulation::set_reposition).
583    RepositionStrategyNotRestored {
584        /// The group whose strategy was lost.
585        group: GroupId,
586    },
587    /// A stop was removed while resident riders were present.
588    /// The game must relocate or despawn these riders.
589    ResidentsAtRemovedStop {
590        /// The removed stop.
591        stop: EntityId,
592        /// Riders that were resident at the stop.
593        residents: Vec<EntityId>,
594    },
595}
596
597/// Identifies which elevator parameter was changed in an
598/// [`Event::ElevatorUpgraded`].
599#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
600#[non_exhaustive]
601pub enum UpgradeField {
602    /// Maximum travel speed (distance/tick).
603    MaxSpeed,
604    /// Acceleration rate (distance/tick^2).
605    Acceleration,
606    /// Deceleration rate (distance/tick^2).
607    Deceleration,
608    /// Maximum weight the car can carry.
609    WeightCapacity,
610    /// Ticks for a door open/close transition.
611    DoorTransitionTicks,
612    /// Ticks the door stays fully open.
613    DoorOpenTicks,
614}
615
616impl std::fmt::Display for UpgradeField {
617    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
618        match self {
619            Self::MaxSpeed => write!(f, "max_speed"),
620            Self::Acceleration => write!(f, "acceleration"),
621            Self::Deceleration => write!(f, "deceleration"),
622            Self::WeightCapacity => write!(f, "weight_capacity"),
623            Self::DoorTransitionTicks => write!(f, "door_transition_ticks"),
624            Self::DoorOpenTicks => write!(f, "door_open_ticks"),
625        }
626    }
627}
628
629/// Old-or-new value carried by [`Event::ElevatorUpgraded`].
630///
631/// Uses [`OrderedFloat`] for the float variant so the event enum
632/// remains `Eq`-comparable alongside the other observability events.
633#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
634#[non_exhaustive]
635pub enum UpgradeValue {
636    /// A floating-point parameter value (speed, accel, decel, capacity).
637    Float(OrderedFloat<f64>),
638    /// An integral tick-count parameter value (door timings).
639    Ticks(u32),
640}
641
642impl UpgradeValue {
643    /// Construct a float-valued upgrade payload.
644    #[must_use]
645    pub const fn float(v: f64) -> Self {
646        Self::Float(OrderedFloat(v))
647    }
648
649    /// Construct a tick-valued upgrade payload.
650    #[must_use]
651    pub const fn ticks(v: u32) -> Self {
652        Self::Ticks(v)
653    }
654}
655
656impl std::fmt::Display for UpgradeValue {
657    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
658        match self {
659            Self::Float(v) => write!(f, "{}", **v),
660            Self::Ticks(v) => write!(f, "{v}"),
661        }
662    }
663}
664
665/// Reason a rider's route was invalidated.
666#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
667#[non_exhaustive]
668pub enum RouteInvalidReason {
669    /// A stop on the route was disabled.
670    StopDisabled,
671    /// No alternative stop is available in the same group.
672    NoAlternative,
673}
674
675/// Coarse-grained classification of an [`Event`].
676///
677/// Exposes the same grouping that the `Event` variants are already
678/// commented under, so consumers can filter a drained event stream with
679/// one match arm per category rather than enumerating ~25 variants.
680#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
681#[non_exhaustive]
682pub enum EventCategory {
683    /// Elevator motion, arrival/departure, and door state.
684    Elevator,
685    /// Rider lifecycle: spawn, board, exit, reject, abandon, despawn, settle, reroute.
686    Rider,
687    /// Dispatch decisions and bookkeeping.
688    Dispatch,
689    /// Runtime topology mutations (entities/lines/groups added, removed, reassigned).
690    Topology,
691    /// Idle-elevator repositioning activity.
692    Reposition,
693    /// Direction indicator lamp state changes.
694    Direction,
695    /// Observability and misc signals (capacity, service mode, energy, etc.).
696    Observability,
697}
698
699impl Event {
700    /// Classify this event into a coarse-grained [`EventCategory`].
701    ///
702    /// Useful when a consumer only cares about, say, rider activity and
703    /// wants to skip elevator-motion and topology chatter without
704    /// enumerating every variant. The exhaustive match inside guarantees
705    /// the method stays in sync when new variants are added.
706    #[must_use]
707    pub const fn category(&self) -> EventCategory {
708        match self {
709            Self::ElevatorDeparted { .. }
710            | Self::ElevatorArrived { .. }
711            | Self::DoorOpened { .. }
712            | Self::DoorClosed { .. }
713            | Self::DoorCommandQueued { .. }
714            | Self::DoorCommandApplied { .. }
715            | Self::PassingFloor { .. }
716            | Self::MovementAborted { .. }
717            | Self::ElevatorIdle { .. } => EventCategory::Elevator,
718            Self::RiderSpawned { .. }
719            | Self::RiderBoarded { .. }
720            | Self::RiderExited { .. }
721            | Self::RiderRejected { .. }
722            | Self::RiderAbandoned { .. }
723            | Self::RiderEjected { .. }
724            | Self::RouteInvalidated { .. }
725            | Self::RiderRerouted { .. }
726            | Self::RiderSettled { .. }
727            | Self::RiderDespawned { .. } => EventCategory::Rider,
728            Self::ElevatorAssigned { .. } | Self::DestinationQueued { .. } => {
729                EventCategory::Dispatch
730            }
731            Self::StopAdded { .. }
732            | Self::StopRemoved { .. }
733            | Self::ElevatorAdded { .. }
734            | Self::ElevatorRemoved { .. }
735            | Self::EntityDisabled { .. }
736            | Self::EntityEnabled { .. }
737            | Self::LineAdded { .. }
738            | Self::LineRemoved { .. }
739            | Self::LineReassigned { .. }
740            | Self::ElevatorReassigned { .. } => EventCategory::Topology,
741            Self::ElevatorRepositioning { .. } | Self::ElevatorRepositioned { .. } => {
742                EventCategory::Reposition
743            }
744            Self::DirectionIndicatorChanged { .. } => EventCategory::Direction,
745            Self::ServiceModeChanged { .. }
746            | Self::CapacityChanged { .. }
747            | Self::ElevatorUpgraded { .. }
748            | Self::ManualVelocityCommanded { .. } => EventCategory::Observability,
749            #[cfg(feature = "energy")]
750            Self::EnergyConsumed { .. } => EventCategory::Observability,
751            Self::HallButtonPressed { .. }
752            | Self::HallCallAcknowledged { .. }
753            | Self::HallCallCleared { .. }
754            | Self::CarButtonPressed { .. } => EventCategory::Dispatch,
755            Self::RiderSkipped { .. } => EventCategory::Rider,
756            Self::SnapshotDanglingReference { .. } | Self::RepositionStrategyNotRestored { .. } => {
757                EventCategory::Observability
758            }
759            Self::ResidentsAtRemovedStop { .. } => EventCategory::Topology,
760        }
761    }
762}
763
764/// Collects simulation events for consumers to drain.
765#[derive(Debug, Default)]
766pub struct EventBus {
767    /// The pending events not yet consumed.
768    events: Vec<Event>,
769}
770
771impl EventBus {
772    /// Pushes a new event onto the bus.
773    pub fn emit(&mut self, event: Event) {
774        self.events.push(event);
775    }
776
777    /// Returns and clears all pending events.
778    pub fn drain(&mut self) -> Vec<Event> {
779        std::mem::take(&mut self.events)
780    }
781
782    /// Returns a slice of all pending events without clearing them.
783    #[must_use]
784    pub fn peek(&self) -> &[Event] {
785        &self.events
786    }
787}
788
789/// A typed event channel for game-specific events.
790///
791/// Games insert this as a global resource on `World`:
792///
793/// ```
794/// use elevator_core::world::World;
795/// use elevator_core::events::EventChannel;
796///
797/// #[derive(Debug)]
798/// enum MyGameEvent { Foo, Bar }
799///
800/// let mut world = World::new();
801/// world.insert_resource(EventChannel::<MyGameEvent>::new());
802/// // Later:
803/// world.resource_mut::<EventChannel<MyGameEvent>>().unwrap().emit(MyGameEvent::Foo);
804/// ```
805#[derive(Debug)]
806pub struct EventChannel<T> {
807    /// Pending events not yet consumed.
808    events: Vec<T>,
809}
810
811impl<T> EventChannel<T> {
812    /// Create an empty event channel.
813    #[must_use]
814    pub const fn new() -> Self {
815        Self { events: Vec::new() }
816    }
817
818    /// Emit an event into the channel.
819    pub fn emit(&mut self, event: T) {
820        self.events.push(event);
821    }
822
823    /// Drain and return all pending events.
824    pub fn drain(&mut self) -> Vec<T> {
825        std::mem::take(&mut self.events)
826    }
827
828    /// Peek at pending events without clearing.
829    #[must_use]
830    pub fn peek(&self) -> &[T] {
831        &self.events
832    }
833
834    /// Check if the channel has no pending events.
835    #[must_use]
836    pub const fn is_empty(&self) -> bool {
837        self.events.is_empty()
838    }
839
840    /// Number of pending events.
841    #[must_use]
842    pub const fn len(&self) -> usize {
843        self.events.len()
844    }
845}
846
847impl<T> Default for EventChannel<T> {
848    fn default() -> Self {
849        Self::new()
850    }
851}