Skip to main content

elevator_core/
world.rs

1//! Central entity/component storage (struct-of-arrays ECS).
2
3use std::any::{Any, TypeId};
4use std::collections::HashMap;
5use std::marker::PhantomData;
6
7use slotmap::{SecondaryMap, SlotMap};
8
9use crate::components::{
10    AccessControl, CallDirection, CarCall, DestinationQueue, Elevator, HallCall, Line, Patience,
11    Position, Preferences, Rider, Route, ServiceMode, Stop, Velocity,
12};
13#[cfg(feature = "energy")]
14use crate::energy::{EnergyMetrics, EnergyProfile};
15use crate::entity::EntityId;
16use crate::query::storage::AnyExtMap;
17
18/// Typed handle for extension component storage.
19///
20/// Constructed via [`ExtKey::new`] with an explicit name, or
21/// [`ExtKey::from_type_name`] which uses `std::any::type_name::<T>()`.
22#[derive(Debug)]
23pub struct ExtKey<T> {
24    /// Human-readable storage name, used for serialization roundtrips.
25    name: &'static str,
26    /// Binds this key to the extension component type `T`.
27    _marker: PhantomData<T>,
28}
29
30impl<T> Clone for ExtKey<T> {
31    fn clone(&self) -> Self {
32        *self
33    }
34}
35impl<T> Copy for ExtKey<T> {}
36
37impl<T> ExtKey<T> {
38    /// Create a key with an explicit storage name.
39    #[must_use]
40    pub const fn new(name: &'static str) -> Self {
41        Self {
42            name,
43            _marker: PhantomData,
44        }
45    }
46
47    /// Create a key using `std::any::type_name::<T>()` as the storage name.
48    #[must_use]
49    pub fn from_type_name() -> Self {
50        Self {
51            name: std::any::type_name::<T>(),
52            _marker: PhantomData,
53        }
54    }
55
56    /// The storage name for this key.
57    #[must_use]
58    pub const fn name(&self) -> &'static str {
59        self.name
60    }
61}
62
63impl<T> Default for ExtKey<T> {
64    fn default() -> Self {
65        Self::from_type_name()
66    }
67}
68
69/// Central storage for all simulation entities and their components.
70///
71/// Uses separate `SecondaryMap` per component type (struct-of-arrays pattern)
72/// to enable independent mutable borrows of different component storages
73/// within the same system function.
74///
75/// Built-in components are accessed via typed methods. Games can attach
76/// custom data via the extension storage (`insert_ext` / `ext`).
77/// The query builder (`world.query::<...>()`) provides ECS-style iteration.
78pub struct World {
79    /// Primary key storage. An entity exists iff its key is here.
80    pub(crate) alive: SlotMap<EntityId, ()>,
81
82    // -- Built-in component storages (crate-internal) --
83    /// Shaft-axis positions.
84    pub(crate) positions: SecondaryMap<EntityId, Position>,
85    /// Snapshot of `positions` taken at the start of the current tick.
86    /// Enables sub-tick interpolation for smooth rendering between steps.
87    pub(crate) prev_positions: SecondaryMap<EntityId, Position>,
88    /// Shaft-axis velocities.
89    pub(crate) velocities: SecondaryMap<EntityId, Velocity>,
90    /// Elevator components.
91    pub(crate) elevators: SecondaryMap<EntityId, Elevator>,
92    /// Stop (floor/station) data.
93    pub(crate) stops: SecondaryMap<EntityId, Stop>,
94    /// Rider core data.
95    pub(crate) riders: SecondaryMap<EntityId, Rider>,
96    /// Multi-leg routes.
97    pub(crate) routes: SecondaryMap<EntityId, Route>,
98    /// Line (physical path) components.
99    pub(crate) lines: SecondaryMap<EntityId, Line>,
100    /// Patience tracking.
101    pub(crate) patience: SecondaryMap<EntityId, Patience>,
102    /// Boarding preferences.
103    pub(crate) preferences: SecondaryMap<EntityId, Preferences>,
104    /// Per-rider access control (allowed stops).
105    pub(crate) access_controls: SecondaryMap<EntityId, AccessControl>,
106
107    /// Per-elevator energy cost profiles.
108    #[cfg(feature = "energy")]
109    pub(crate) energy_profiles: SecondaryMap<EntityId, EnergyProfile>,
110    /// Per-elevator accumulated energy metrics.
111    #[cfg(feature = "energy")]
112    pub(crate) energy_metrics: SecondaryMap<EntityId, EnergyMetrics>,
113    /// Elevator service modes.
114    pub(crate) service_modes: SecondaryMap<EntityId, ServiceMode>,
115    /// Per-elevator destination queues.
116    pub(crate) destination_queues: SecondaryMap<EntityId, DestinationQueue>,
117    /// Up/down hall call buttons per stop. At most two per stop.
118    pub(crate) hall_calls: SecondaryMap<EntityId, StopCalls>,
119    /// Floor buttons pressed inside each car (Classic mode).
120    pub(crate) car_calls: SecondaryMap<EntityId, Vec<CarCall>>,
121
122    /// Disabled marker (entities skipped by all systems).
123    pub(crate) disabled: SecondaryMap<EntityId, ()>,
124
125    // -- Extension storage for game-specific components --
126    /// Type-erased per-entity maps for custom components.
127    extensions: HashMap<TypeId, Box<dyn AnyExtMap>>,
128    /// `TypeId` → name mapping for extension serialization.
129    ext_names: HashMap<TypeId, String>,
130
131    // -- Global resources (singletons not attached to any entity) --
132    /// Type-erased global resources for game-specific state.
133    resources: HashMap<TypeId, Box<dyn Any + Send + Sync>>,
134}
135
136impl World {
137    /// Create an empty world with no entities.
138    #[must_use]
139    pub fn new() -> Self {
140        Self {
141            alive: SlotMap::with_key(),
142            positions: SecondaryMap::new(),
143            prev_positions: SecondaryMap::new(),
144            velocities: SecondaryMap::new(),
145            elevators: SecondaryMap::new(),
146            stops: SecondaryMap::new(),
147            riders: SecondaryMap::new(),
148            routes: SecondaryMap::new(),
149            lines: SecondaryMap::new(),
150            patience: SecondaryMap::new(),
151            preferences: SecondaryMap::new(),
152            access_controls: SecondaryMap::new(),
153            #[cfg(feature = "energy")]
154            energy_profiles: SecondaryMap::new(),
155            #[cfg(feature = "energy")]
156            energy_metrics: SecondaryMap::new(),
157            service_modes: SecondaryMap::new(),
158            destination_queues: SecondaryMap::new(),
159            hall_calls: SecondaryMap::new(),
160            car_calls: SecondaryMap::new(),
161            disabled: SecondaryMap::new(),
162            extensions: HashMap::new(),
163            ext_names: HashMap::new(),
164            resources: HashMap::new(),
165        }
166    }
167
168    /// Allocate a new entity. Returns its id. No components attached yet.
169    pub fn spawn(&mut self) -> EntityId {
170        self.alive.insert(())
171    }
172
173    /// Remove an entity and all its components (built-in and extensions).
174    ///
175    /// Cross-references are cleaned up automatically:
176    /// - If the entity is a rider aboard an elevator, it is removed from the
177    ///   elevator's rider list and `current_load` is adjusted.
178    /// - If the entity is an elevator, its riders' phases are reset to `Waiting`.
179    pub fn despawn(&mut self, id: EntityId) {
180        // Clean up rider → elevator cross-references.
181        if let Some(rider) = self.riders.get(id) {
182            let weight = rider.weight;
183            // If this rider is aboard an elevator, remove from its riders list.
184            match rider.phase {
185                crate::components::RiderPhase::Boarding(elev)
186                | crate::components::RiderPhase::Riding(elev)
187                | crate::components::RiderPhase::Exiting(elev) => {
188                    if let Some(car) = self.elevators.get_mut(elev) {
189                        car.riders.retain(|r| *r != id);
190                        car.current_load -= weight;
191                    }
192                }
193                _ => {}
194            }
195        }
196
197        // Clean up elevator → rider cross-references.
198        if let Some(car) = self.elevators.get(id) {
199            let rider_ids: Vec<EntityId> = car.riders.clone();
200            let elev_pos = self.positions.get(id).map(|p| p.value);
201            let nearest_stop = elev_pos.and_then(|p| self.find_nearest_stop(p));
202            for rid in rider_ids {
203                if let Some(rider) = self.riders.get_mut(rid) {
204                    rider.phase = crate::components::RiderPhase::Waiting;
205                    rider.current_stop = nearest_stop;
206                }
207            }
208        }
209
210        self.alive.remove(id);
211        self.positions.remove(id);
212        self.prev_positions.remove(id);
213        self.velocities.remove(id);
214        self.elevators.remove(id);
215        self.stops.remove(id);
216        self.riders.remove(id);
217        self.routes.remove(id);
218        self.lines.remove(id);
219        self.patience.remove(id);
220        self.preferences.remove(id);
221        self.access_controls.remove(id);
222        #[cfg(feature = "energy")]
223        self.energy_profiles.remove(id);
224        #[cfg(feature = "energy")]
225        self.energy_metrics.remove(id);
226        self.service_modes.remove(id);
227        self.destination_queues.remove(id);
228        self.disabled.remove(id);
229        self.hall_calls.remove(id);
230        self.car_calls.remove(id);
231
232        for ext in self.extensions.values_mut() {
233            ext.remove(id);
234        }
235    }
236
237    /// Check if an entity is alive.
238    #[must_use]
239    pub fn is_alive(&self, id: EntityId) -> bool {
240        self.alive.contains_key(id)
241    }
242
243    /// Number of live entities.
244    #[must_use]
245    pub fn entity_count(&self) -> usize {
246        self.alive.len()
247    }
248
249    /// Iterate all alive entity keys (used by the query builder).
250    pub(crate) fn alive_keys(&self) -> slotmap::basic::Keys<'_, EntityId, ()> {
251        self.alive.keys()
252    }
253
254    // ── Position accessors ───────────────────────────────────────────
255
256    /// Get an entity's position.
257    #[must_use]
258    pub fn position(&self, id: EntityId) -> Option<&Position> {
259        self.positions.get(id)
260    }
261
262    /// Get an entity's position mutably.
263    pub fn position_mut(&mut self, id: EntityId) -> Option<&mut Position> {
264        self.positions.get_mut(id)
265    }
266
267    /// Set an entity's position.
268    pub fn set_position(&mut self, id: EntityId, pos: Position) {
269        self.positions.insert(id, pos);
270    }
271
272    /// Snapshot of an entity's position at the start of the current tick.
273    ///
274    /// Pairs with [`position`](Self::position) to support sub-tick interpolation
275    /// (see [`Simulation::position_at`](crate::sim::Simulation::position_at)).
276    #[must_use]
277    pub fn prev_position(&self, id: EntityId) -> Option<&Position> {
278        self.prev_positions.get(id)
279    }
280
281    /// Snapshot all current positions into `prev_positions`.
282    ///
283    /// Called at the start of each tick by
284    /// [`Simulation::step`](crate::sim::Simulation::step) before any phase
285    /// mutates positions.
286    pub(crate) fn snapshot_prev_positions(&mut self) {
287        self.prev_positions.clear();
288        for (id, pos) in &self.positions {
289            self.prev_positions.insert(id, *pos);
290        }
291    }
292
293    // ── Velocity accessors ───────────────────────────────────────────
294
295    /// Get an entity's velocity.
296    #[must_use]
297    pub fn velocity(&self, id: EntityId) -> Option<&Velocity> {
298        self.velocities.get(id)
299    }
300
301    /// Get an entity's velocity mutably.
302    pub fn velocity_mut(&mut self, id: EntityId) -> Option<&mut Velocity> {
303        self.velocities.get_mut(id)
304    }
305
306    /// Set an entity's velocity.
307    pub fn set_velocity(&mut self, id: EntityId, vel: Velocity) {
308        self.velocities.insert(id, vel);
309    }
310
311    // ── Elevator accessors ───────────────────────────────────────────
312
313    /// Get an entity's elevator component.
314    #[must_use]
315    pub fn elevator(&self, id: EntityId) -> Option<&Elevator> {
316        self.elevators.get(id)
317    }
318
319    /// Get an entity's elevator component mutably.
320    pub fn elevator_mut(&mut self, id: EntityId) -> Option<&mut Elevator> {
321        self.elevators.get_mut(id)
322    }
323
324    /// Set an entity's elevator component.
325    pub fn set_elevator(&mut self, id: EntityId, elev: Elevator) {
326        self.elevators.insert(id, elev);
327    }
328
329    // ── Rider accessors ──────────────────────────────────────────────
330
331    /// Get an entity's rider component.
332    #[must_use]
333    pub fn rider(&self, id: EntityId) -> Option<&Rider> {
334        self.riders.get(id)
335    }
336
337    /// Get an entity's rider component mutably.
338    pub fn rider_mut(&mut self, id: EntityId) -> Option<&mut Rider> {
339        self.riders.get_mut(id)
340    }
341
342    /// Set an entity's rider component.
343    pub fn set_rider(&mut self, id: EntityId, rider: Rider) {
344        self.riders.insert(id, rider);
345    }
346
347    // ── Stop accessors ───────────────────────────────────────────────
348
349    /// Get an entity's stop component.
350    #[must_use]
351    pub fn stop(&self, id: EntityId) -> Option<&Stop> {
352        self.stops.get(id)
353    }
354
355    /// Get an entity's stop component mutably.
356    pub fn stop_mut(&mut self, id: EntityId) -> Option<&mut Stop> {
357        self.stops.get_mut(id)
358    }
359
360    /// Set an entity's stop component.
361    pub fn set_stop(&mut self, id: EntityId, stop: Stop) {
362        self.stops.insert(id, stop);
363    }
364
365    // ── Route accessors ──────────────────────────────────────────────
366
367    /// Get an entity's route.
368    #[must_use]
369    pub fn route(&self, id: EntityId) -> Option<&Route> {
370        self.routes.get(id)
371    }
372
373    /// Get an entity's route mutably.
374    pub fn route_mut(&mut self, id: EntityId) -> Option<&mut Route> {
375        self.routes.get_mut(id)
376    }
377
378    /// Set an entity's route.
379    pub fn set_route(&mut self, id: EntityId, route: Route) {
380        self.routes.insert(id, route);
381    }
382
383    // ── Line accessors ─────────────────────────────────────────────��──
384
385    /// Get an entity's line component.
386    #[must_use]
387    pub fn line(&self, id: EntityId) -> Option<&Line> {
388        self.lines.get(id)
389    }
390
391    /// Get an entity's line component mutably.
392    pub fn line_mut(&mut self, id: EntityId) -> Option<&mut Line> {
393        self.lines.get_mut(id)
394    }
395
396    /// Set an entity's line component.
397    pub fn set_line(&mut self, id: EntityId, line: Line) {
398        self.lines.insert(id, line);
399    }
400
401    /// Remove an entity's line component.
402    pub fn remove_line(&mut self, id: EntityId) -> Option<Line> {
403        self.lines.remove(id)
404    }
405
406    /// Iterate all line entities.
407    pub fn iter_lines(&self) -> impl Iterator<Item = (EntityId, &Line)> {
408        self.lines.iter()
409    }
410
411    // ── Patience accessors ───────────────────────────────────────────
412
413    /// Get an entity's patience.
414    #[must_use]
415    pub fn patience(&self, id: EntityId) -> Option<&Patience> {
416        self.patience.get(id)
417    }
418
419    /// Get an entity's patience mutably.
420    pub fn patience_mut(&mut self, id: EntityId) -> Option<&mut Patience> {
421        self.patience.get_mut(id)
422    }
423
424    /// Set an entity's patience.
425    pub fn set_patience(&mut self, id: EntityId, patience: Patience) {
426        self.patience.insert(id, patience);
427    }
428
429    // ── Preferences accessors ────────────────────────────────────────
430
431    /// Get an entity's preferences.
432    #[must_use]
433    pub fn preferences(&self, id: EntityId) -> Option<&Preferences> {
434        self.preferences.get(id)
435    }
436
437    /// Set an entity's preferences.
438    pub fn set_preferences(&mut self, id: EntityId, prefs: Preferences) {
439        self.preferences.insert(id, prefs);
440    }
441
442    // ── Access control accessors ────────────────────────────────────
443
444    /// Get an entity's access control.
445    #[must_use]
446    pub fn access_control(&self, id: EntityId) -> Option<&AccessControl> {
447        self.access_controls.get(id)
448    }
449
450    /// Get an entity's access control mutably.
451    pub fn access_control_mut(&mut self, id: EntityId) -> Option<&mut AccessControl> {
452        self.access_controls.get_mut(id)
453    }
454
455    /// Set an entity's access control.
456    pub fn set_access_control(&mut self, id: EntityId, ac: AccessControl) {
457        self.access_controls.insert(id, ac);
458    }
459
460    // ── Energy accessors (feature-gated) ────────────────────────────
461
462    #[cfg(feature = "energy")]
463    /// Get an entity's energy profile.
464    #[must_use]
465    pub fn energy_profile(&self, id: EntityId) -> Option<&EnergyProfile> {
466        self.energy_profiles.get(id)
467    }
468
469    #[cfg(feature = "energy")]
470    /// Get an entity's energy metrics.
471    #[must_use]
472    pub fn energy_metrics(&self, id: EntityId) -> Option<&EnergyMetrics> {
473        self.energy_metrics.get(id)
474    }
475
476    #[cfg(feature = "energy")]
477    /// Get an entity's energy metrics mutably.
478    pub fn energy_metrics_mut(&mut self, id: EntityId) -> Option<&mut EnergyMetrics> {
479        self.energy_metrics.get_mut(id)
480    }
481
482    #[cfg(feature = "energy")]
483    /// Set an entity's energy profile.
484    pub fn set_energy_profile(&mut self, id: EntityId, profile: EnergyProfile) {
485        self.energy_profiles.insert(id, profile);
486    }
487
488    #[cfg(feature = "energy")]
489    /// Set an entity's energy metrics.
490    pub fn set_energy_metrics(&mut self, id: EntityId, metrics: EnergyMetrics) {
491        self.energy_metrics.insert(id, metrics);
492    }
493
494    // ── Service mode accessors ──────────────────────────────────────
495
496    /// Get an entity's service mode.
497    #[must_use]
498    pub fn service_mode(&self, id: EntityId) -> Option<&ServiceMode> {
499        self.service_modes.get(id)
500    }
501
502    /// Set an entity's service mode.
503    pub fn set_service_mode(&mut self, id: EntityId, mode: ServiceMode) {
504        self.service_modes.insert(id, mode);
505    }
506
507    // ── Destination queue accessors ─────────────────────────────────
508
509    /// Get an entity's destination queue.
510    #[must_use]
511    pub fn destination_queue(&self, id: EntityId) -> Option<&DestinationQueue> {
512        self.destination_queues.get(id)
513    }
514
515    /// Get an entity's destination queue mutably (crate-internal — games
516    /// mutate via the [`Simulation`](crate::sim::Simulation) helpers).
517    pub(crate) fn destination_queue_mut(&mut self, id: EntityId) -> Option<&mut DestinationQueue> {
518        self.destination_queues.get_mut(id)
519    }
520
521    /// Set an entity's destination queue.
522    pub fn set_destination_queue(&mut self, id: EntityId, queue: DestinationQueue) {
523        self.destination_queues.insert(id, queue);
524    }
525
526    // ── Hall call / car call accessors ──────────────────────────────
527    //
528    // Phase wiring in follow-up commits consumes the mutators. Until
529    // that lands, `#[allow(dead_code)]` suppresses warnings that would
530    // otherwise block the build under the workspace's `deny(warnings)`.
531
532    /// Get the `(up, down)` hall call pair at a stop, if any exist.
533    #[must_use]
534    pub fn stop_calls(&self, stop: EntityId) -> Option<&StopCalls> {
535        self.hall_calls.get(stop)
536    }
537
538    /// Get a specific directional hall call at a stop.
539    #[must_use]
540    pub fn hall_call(&self, stop: EntityId, direction: CallDirection) -> Option<&HallCall> {
541        self.hall_calls.get(stop).and_then(|c| c.get(direction))
542    }
543
544    /// Mutable access to a directional hall call (crate-internal).
545    #[allow(dead_code)]
546    pub(crate) fn hall_call_mut(
547        &mut self,
548        stop: EntityId,
549        direction: CallDirection,
550    ) -> Option<&mut HallCall> {
551        self.hall_calls
552            .get_mut(stop)
553            .and_then(|c| c.get_mut(direction))
554    }
555
556    /// Insert (or replace) a hall call at `stop` in `direction`.
557    /// Returns `false` if the stop entity no longer exists in the world.
558    #[allow(dead_code)]
559    pub(crate) fn set_hall_call(&mut self, call: HallCall) -> bool {
560        let Some(entry) = self.hall_calls.entry(call.stop) else {
561            return false;
562        };
563        let slot = entry.or_default();
564        match call.direction {
565            CallDirection::Up => slot.up = Some(call),
566            CallDirection::Down => slot.down = Some(call),
567        }
568        true
569    }
570
571    /// Remove and return the hall call at `(stop, direction)`, if any.
572    #[allow(dead_code)]
573    pub(crate) fn remove_hall_call(
574        &mut self,
575        stop: EntityId,
576        direction: CallDirection,
577    ) -> Option<HallCall> {
578        let entry = self.hall_calls.get_mut(stop)?;
579        match direction {
580            CallDirection::Up => entry.up.take(),
581            CallDirection::Down => entry.down.take(),
582        }
583    }
584
585    /// Iterate every active hall call across the world.
586    pub fn iter_hall_calls(&self) -> impl Iterator<Item = &HallCall> {
587        self.hall_calls.values().flat_map(StopCalls::iter)
588    }
589
590    /// Mutable iteration over every active hall call (crate-internal).
591    #[allow(dead_code)]
592    pub(crate) fn iter_hall_calls_mut(&mut self) -> impl Iterator<Item = &mut HallCall> {
593        self.hall_calls.values_mut().flat_map(StopCalls::iter_mut)
594    }
595
596    /// Car calls currently registered inside `car`.
597    #[must_use]
598    pub fn car_calls(&self, car: EntityId) -> &[CarCall] {
599        self.car_calls.get(car).map_or(&[], Vec::as_slice)
600    }
601
602    /// Mutable access to the car-call list (crate-internal). Returns
603    /// `None` if the car entity no longer exists.
604    #[allow(dead_code)]
605    pub(crate) fn car_calls_mut(&mut self, car: EntityId) -> Option<&mut Vec<CarCall>> {
606        Some(self.car_calls.entry(car)?.or_default())
607    }
608
609    // ── Typed query helpers ──────────────────────────────────────────
610
611    /// Iterate all elevator entities (have `Elevator` + `Position`).
612    pub fn iter_elevators(&self) -> impl Iterator<Item = (EntityId, &Position, &Elevator)> {
613        self.elevators
614            .iter()
615            .filter_map(|(id, car)| self.positions.get(id).map(|pos| (id, pos, car)))
616    }
617
618    /// Iterate all elevator entity IDs (allocates).
619    #[must_use]
620    pub fn elevator_ids(&self) -> Vec<EntityId> {
621        self.elevators.keys().collect()
622    }
623
624    /// Fill the buffer with all elevator entity IDs, clearing it first.
625    pub fn elevator_ids_into(&self, buf: &mut Vec<EntityId>) {
626        buf.clear();
627        buf.extend(self.elevators.keys());
628    }
629
630    /// Iterate all rider entities.
631    pub fn iter_riders(&self) -> impl Iterator<Item = (EntityId, &Rider)> {
632        self.riders.iter()
633    }
634
635    /// Iterate all rider entities mutably.
636    pub fn iter_riders_mut(&mut self) -> impl Iterator<Item = (EntityId, &mut Rider)> {
637        self.riders.iter_mut()
638    }
639
640    /// Iterate all rider entity IDs (allocates).
641    #[must_use]
642    pub fn rider_ids(&self) -> Vec<EntityId> {
643        self.riders.keys().collect()
644    }
645
646    /// Iterate all stop entities.
647    pub fn iter_stops(&self) -> impl Iterator<Item = (EntityId, &Stop)> {
648        self.stops.iter()
649    }
650
651    /// Iterate all stop entity IDs (allocates).
652    #[must_use]
653    pub fn stop_ids(&self) -> Vec<EntityId> {
654        self.stops.keys().collect()
655    }
656
657    /// Iterate elevators in `Idle` phase (not disabled).
658    pub fn iter_idle_elevators(&self) -> impl Iterator<Item = (EntityId, &Position, &Elevator)> {
659        use crate::components::ElevatorPhase;
660        self.iter_elevators()
661            .filter(|(id, _, car)| car.phase == ElevatorPhase::Idle && !self.is_disabled(*id))
662    }
663
664    /// Iterate elevators that are currently moving — either on a dispatched
665    /// trip (`MovingToStop`) or a repositioning trip (`Repositioning`).
666    /// Excludes disabled elevators.
667    pub fn iter_moving_elevators(&self) -> impl Iterator<Item = (EntityId, &Position, &Elevator)> {
668        self.iter_elevators()
669            .filter(|(id, _, car)| car.phase.is_moving() && !self.is_disabled(*id))
670    }
671
672    /// Iterate riders in `Waiting` phase (not disabled).
673    pub fn iter_waiting_riders(&self) -> impl Iterator<Item = (EntityId, &Rider)> {
674        use crate::components::RiderPhase;
675        self.iter_riders()
676            .filter(|(id, r)| r.phase == RiderPhase::Waiting && !self.is_disabled(*id))
677    }
678
679    /// Find the stop entity at a given position (within epsilon).
680    #[must_use]
681    pub fn find_stop_at_position(&self, position: f64) -> Option<EntityId> {
682        const EPSILON: f64 = 1e-6;
683        self.stops.iter().find_map(|(id, stop)| {
684            if (stop.position - position).abs() < EPSILON {
685                Some(id)
686            } else {
687                None
688            }
689        })
690    }
691
692    /// Find the stop entity nearest to a given position.
693    ///
694    /// Unlike [`find_stop_at_position`](Self::find_stop_at_position), this finds
695    /// the closest stop by minimum distance rather than requiring an exact match.
696    /// Used when ejecting riders from a disabled/despawned elevator mid-transit.
697    #[must_use]
698    pub fn find_nearest_stop(&self, position: f64) -> Option<EntityId> {
699        self.stops
700            .iter()
701            .min_by(|(_, a), (_, b)| {
702                (a.position - position)
703                    .abs()
704                    .total_cmp(&(b.position - position).abs())
705            })
706            .map(|(id, _)| id)
707    }
708
709    /// Get a stop's position by entity id.
710    #[must_use]
711    pub fn stop_position(&self, id: EntityId) -> Option<f64> {
712        self.stops.get(id).map(|s| s.position)
713    }
714
715    // ── Extension (custom component) storage ─────────────────────────
716
717    /// Insert a custom component for an entity.
718    ///
719    /// Games use this to attach their own typed data to simulation entities.
720    /// Extension components must be `Serialize + DeserializeOwned` to support
721    /// snapshot save/load. An [`ExtKey`] is required for serialization roundtrips.
722    /// Extension components are automatically cleaned up on `despawn()`.
723    ///
724    /// ```
725    /// use elevator_core::world::{ExtKey, World};
726    /// use serde::{Serialize, Deserialize};
727    ///
728    /// #[derive(Debug, Clone, Serialize, Deserialize)]
729    /// struct VipTag { level: u32 }
730    ///
731    /// let mut world = World::new();
732    /// let entity = world.spawn();
733    /// world.insert_ext(entity, VipTag { level: 3 }, ExtKey::from_type_name());
734    /// ```
735    pub fn insert_ext<T: 'static + Send + Sync + serde::Serialize + serde::de::DeserializeOwned>(
736        &mut self,
737        id: EntityId,
738        value: T,
739        key: ExtKey<T>,
740    ) {
741        let type_id = TypeId::of::<T>();
742        let map = self
743            .extensions
744            .entry(type_id)
745            .or_insert_with(|| Box::new(SecondaryMap::<EntityId, T>::new()));
746        if let Some(m) = map.as_any_mut().downcast_mut::<SecondaryMap<EntityId, T>>() {
747            m.insert(id, value);
748        }
749        self.ext_names.insert(type_id, key.name().to_owned());
750    }
751
752    /// Get a clone of a custom component for an entity.
753    #[must_use]
754    pub fn ext<T: 'static + Send + Sync + Clone>(&self, id: EntityId) -> Option<T> {
755        self.ext_map::<T>()?.get(id).cloned()
756    }
757
758    /// Shared reference to a custom component for an entity.
759    ///
760    /// Zero-copy alternative to [`ext`](Self::ext): prefer this when
761    /// `T` is large or expensive to clone, or when the caller only needs a
762    /// borrow. Unlike `ext`, `T` does not need to implement `Clone`.
763    #[must_use]
764    pub fn ext_ref<T: 'static + Send + Sync>(&self, id: EntityId) -> Option<&T> {
765        self.ext_map::<T>()?.get(id)
766    }
767
768    /// Mutable reference to a custom component for an entity.
769    pub fn ext_mut<T: 'static + Send + Sync>(&mut self, id: EntityId) -> Option<&mut T> {
770        self.ext_map_mut::<T>()?.get_mut(id)
771    }
772
773    /// Remove a custom component for an entity.
774    pub fn remove_ext<T: 'static + Send + Sync>(&mut self, id: EntityId) -> Option<T> {
775        self.ext_map_mut::<T>()?.remove(id)
776    }
777
778    /// Downcast extension storage to a typed `SecondaryMap` (shared).
779    pub(crate) fn ext_map<T: 'static + Send + Sync>(&self) -> Option<&SecondaryMap<EntityId, T>> {
780        self.extensions
781            .get(&TypeId::of::<T>())?
782            .as_any()
783            .downcast_ref::<SecondaryMap<EntityId, T>>()
784    }
785
786    /// Downcast extension storage to a typed `SecondaryMap` (mutable).
787    fn ext_map_mut<T: 'static + Send + Sync>(&mut self) -> Option<&mut SecondaryMap<EntityId, T>> {
788        self.extensions
789            .get_mut(&TypeId::of::<T>())?
790            .as_any_mut()
791            .downcast_mut::<SecondaryMap<EntityId, T>>()
792    }
793
794    /// Serialize all extension component data for snapshot.
795    /// Returns name → (`EntityId` → RON string) mapping.
796    pub(crate) fn serialize_extensions(&self) -> HashMap<String, HashMap<EntityId, String>> {
797        let mut result = HashMap::new();
798        for (type_id, map) in &self.extensions {
799            if let Some(name) = self.ext_names.get(type_id) {
800                result.insert(name.clone(), map.serialize_entries());
801            }
802        }
803        result
804    }
805
806    /// Deserialize extension data from snapshot. Requires that extension types
807    /// have been registered (via `register_ext_deserializer`) before calling.
808    pub(crate) fn deserialize_extensions(
809        &mut self,
810        data: &HashMap<String, HashMap<EntityId, String>>,
811    ) {
812        for (name, entries) in data {
813            // Find the TypeId by name.
814            if let Some((&type_id, _)) = self.ext_names.iter().find(|(_, n)| *n == name)
815                && let Some(map) = self.extensions.get_mut(&type_id)
816            {
817                map.deserialize_entries(entries);
818            }
819        }
820    }
821
822    /// Return names from `snapshot_names` that have no registered extension type.
823    pub(crate) fn unregistered_ext_names<'a>(
824        &self,
825        snapshot_names: impl Iterator<Item = &'a String>,
826    ) -> Vec<String> {
827        let registered: std::collections::HashSet<&str> =
828            self.ext_names.values().map(String::as_str).collect();
829        snapshot_names
830            .filter(|name| !registered.contains(name.as_str()))
831            .cloned()
832            .collect()
833    }
834
835    /// Register an extension type for deserialization (creates empty storage).
836    ///
837    /// Must be called before `restore()` for each extension type that was
838    /// present in the original simulation. Returns the key for convenience.
839    pub fn register_ext<
840        T: 'static + Send + Sync + serde::Serialize + serde::de::DeserializeOwned,
841    >(
842        &mut self,
843        key: ExtKey<T>,
844    ) -> ExtKey<T> {
845        let type_id = TypeId::of::<T>();
846        self.extensions
847            .entry(type_id)
848            .or_insert_with(|| Box::new(SecondaryMap::<EntityId, T>::new()));
849        self.ext_names.insert(type_id, key.name().to_owned());
850        key
851    }
852
853    // ── Disabled entity management ──────────────────────────────────
854
855    /// Mark an entity as disabled. Disabled entities are skipped by all systems.
856    pub fn disable(&mut self, id: EntityId) {
857        self.disabled.insert(id, ());
858    }
859
860    /// Re-enable a disabled entity.
861    pub fn enable(&mut self, id: EntityId) {
862        self.disabled.remove(id);
863    }
864
865    /// Check if an entity is disabled.
866    #[must_use]
867    pub fn is_disabled(&self, id: EntityId) -> bool {
868        self.disabled.contains_key(id)
869    }
870
871    // ── Global resources (singletons) ───────────────────────────────
872
873    /// Insert a global resource. Replaces any existing resource of the same type.
874    ///
875    /// Resources are singletons not attached to any entity. Games use them
876    /// for event channels, score trackers, or any global state.
877    ///
878    /// ```
879    /// use elevator_core::world::World;
880    /// use elevator_core::events::EventChannel;
881    ///
882    /// #[derive(Debug)]
883    /// enum MyEvent { Score(u32) }
884    ///
885    /// let mut world = World::new();
886    /// world.insert_resource(EventChannel::<MyEvent>::new());
887    /// ```
888    pub fn insert_resource<T: 'static + Send + Sync>(&mut self, value: T) {
889        self.resources.insert(TypeId::of::<T>(), Box::new(value));
890    }
891
892    /// Get a shared reference to a global resource.
893    #[must_use]
894    pub fn resource<T: 'static + Send + Sync>(&self) -> Option<&T> {
895        self.resources.get(&TypeId::of::<T>())?.downcast_ref()
896    }
897
898    /// Get a mutable reference to a global resource.
899    pub fn resource_mut<T: 'static + Send + Sync>(&mut self) -> Option<&mut T> {
900        self.resources.get_mut(&TypeId::of::<T>())?.downcast_mut()
901    }
902
903    /// Remove a global resource, returning it if it existed.
904    pub fn remove_resource<T: 'static + Send + Sync>(&mut self) -> Option<T> {
905        self.resources
906            .remove(&TypeId::of::<T>())
907            .and_then(|b| b.downcast().ok())
908            .map(|b| *b)
909    }
910
911    // ── Query builder ───────────────────────────────────────────────
912
913    /// Create a query builder for iterating entities by component composition.
914    ///
915    /// ```
916    /// use elevator_core::prelude::*;
917    ///
918    /// let mut sim = SimulationBuilder::demo().build().unwrap();
919    /// sim.spawn_rider(StopId(0), StopId(1), 75.0).unwrap();
920    ///
921    /// let world = sim.world();
922    /// for (id, rider, pos) in world.query::<(EntityId, &Rider, &Position)>().iter() {
923    ///     println!("{id:?}: {:?} at {}", rider.phase(), pos.value());
924    /// }
925    /// ```
926    #[must_use]
927    pub const fn query<Q: crate::query::WorldQuery>(&self) -> crate::query::QueryBuilder<'_, Q> {
928        crate::query::QueryBuilder::new(self)
929    }
930
931    /// Create a mutable extension query builder.
932    ///
933    /// Uses the keys-snapshot pattern: collects matching entity IDs upfront
934    /// into an owned `Vec`, then iterates with mutable access via
935    /// [`for_each_mut`](crate::query::ExtQueryMut::for_each_mut).
936    ///
937    /// # Example
938    ///
939    /// ```ignore
940    /// world.query_ext_mut::<VipTag>().for_each_mut(|id, tag| {
941    ///     tag.level += 1;
942    /// });
943    /// ```
944    pub fn query_ext_mut<T: 'static + Send + Sync>(&mut self) -> crate::query::ExtQueryMut<'_, T> {
945        crate::query::ExtQueryMut::new(self)
946    }
947}
948
949impl Default for World {
950    fn default() -> Self {
951        Self::new()
952    }
953}
954
955/// Stops sorted by position for efficient range queries (binary search).
956///
957/// Used by the movement system to detect `PassingFloor` events in O(log n)
958/// instead of O(n) per moving elevator per tick.
959pub(crate) struct SortedStops(pub(crate) Vec<(f64, EntityId)>);
960
961/// The up/down hall call pair at a single stop.
962///
963/// At most two calls coexist at a stop (one per [`CallDirection`]);
964/// this struct owns the slots. Stored in `World::hall_calls` keyed by
965/// the stop's entity id.
966#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)]
967pub struct StopCalls {
968    /// Pending upward call, if the up button is pressed.
969    pub up: Option<HallCall>,
970    /// Pending downward call, if the down button is pressed.
971    pub down: Option<HallCall>,
972}
973
974impl StopCalls {
975    /// Borrow the call for a specific direction.
976    #[must_use]
977    pub const fn get(&self, direction: CallDirection) -> Option<&HallCall> {
978        match direction {
979            CallDirection::Up => self.up.as_ref(),
980            CallDirection::Down => self.down.as_ref(),
981        }
982    }
983
984    /// Mutable borrow of the call for a direction.
985    pub const fn get_mut(&mut self, direction: CallDirection) -> Option<&mut HallCall> {
986        match direction {
987            CallDirection::Up => self.up.as_mut(),
988            CallDirection::Down => self.down.as_mut(),
989        }
990    }
991
992    /// Iterate both calls in (Up, Down) order, skipping empty slots.
993    pub fn iter(&self) -> impl Iterator<Item = &HallCall> {
994        self.up.iter().chain(self.down.iter())
995    }
996
997    /// Mutable iteration over both calls.
998    pub fn iter_mut(&mut self) -> impl Iterator<Item = &mut HallCall> {
999        self.up.iter_mut().chain(self.down.iter_mut())
1000    }
1001}