Skip to main content

elevator_core/
builder.rs

1//! Fluent builder for constructing a [`Simulation`](crate::sim::Simulation)
2//! programmatically.
3
4use serde::{Serialize, de::DeserializeOwned};
5
6use crate::components::{Accel, Speed, Weight};
7use crate::config::{
8    BuildingConfig, ElevatorConfig, GroupConfig, LineConfig, PassengerSpawnConfig, SimConfig,
9    SimulationParams,
10};
11use crate::dispatch::scan::ScanDispatch;
12use crate::dispatch::{BuiltinReposition, DispatchStrategy, RepositionStrategy};
13use crate::error::SimError;
14use crate::hooks::{Phase, PhaseHooks};
15use crate::ids::GroupId;
16use crate::sim::Simulation;
17use crate::stop::{StopConfig, StopId};
18use crate::world::World;
19use std::collections::BTreeMap;
20
21/// A deferred extension registration closure.
22type ExtRegistration = Box<dyn FnOnce(&mut World) + Send>;
23
24/// Fluent builder for constructing a [`Simulation`].
25///
26/// Builds a [`SimConfig`] internally and delegates to [`Simulation::new()`].
27/// Provides a more ergonomic API for programmatic construction compared to
28/// assembling a config struct manually.
29///
30/// # Constructors
31///
32/// - [`SimulationBuilder::new`] — empty builder. You must add at least one
33///   stop and at least one elevator before `.build()`, or it errors.
34///   `ScanDispatch` is the default strategy, 60 ticks/s the default rate.
35/// - [`SimulationBuilder::demo`] — pre-populated with two stops (Ground at
36///   0.0, Top at 10.0) and one elevator, for doctests and quick
37///   prototyping. Override any piece with the fluent methods.
38pub struct SimulationBuilder {
39    /// Simulation configuration (stops, elevators, timing).
40    config: SimConfig,
41    /// Per-group dispatch strategies.
42    dispatchers: BTreeMap<GroupId, Box<dyn DispatchStrategy>>,
43    /// Per-group reposition strategies.
44    repositioners: Vec<(GroupId, Box<dyn RepositionStrategy>, BuiltinReposition)>,
45    /// Lifecycle hooks for before/after each tick phase.
46    hooks: PhaseHooks,
47    /// Deferred extension registrations (applied after build).
48    ext_registrations: Vec<ExtRegistration>,
49}
50
51impl Default for SimulationBuilder {
52    fn default() -> Self {
53        Self::new()
54    }
55}
56
57impl SimulationBuilder {
58    /// Create an empty builder — no stops, no elevators, `ScanDispatch` as
59    /// the default strategy, and 60 ticks per second.
60    ///
61    /// You must add at least one stop and at least one elevator (via
62    /// [`stops`](Self::stops) / [`stop`](Self::stop) and
63    /// [`elevators`](Self::elevators) / [`elevator`](Self::elevator))
64    /// before [`build`](Self::build), or the build fails with
65    /// [`SimError::InvalidConfig`].
66    ///
67    /// If you want a quick, already-valid sim for prototyping or examples,
68    /// use [`demo`](Self::demo).
69    ///
70    /// ```
71    /// use elevator_core::prelude::*;
72    /// use elevator_core::components::{Speed, Accel, Weight};
73    /// use elevator_core::config::ElevatorConfig;
74    /// use elevator_core::stop::StopConfig;
75    ///
76    /// // An empty builder errors on build — you must configure it first.
77    /// assert!(SimulationBuilder::new().build().is_err());
78    ///
79    /// // Minimum valid configuration: at least one stop and one elevator.
80    /// let sim = SimulationBuilder::new()
81    ///     .stops(vec![
82    ///         StopConfig { id: StopId(0), name: "Ground".into(), position: 0.0 },
83    ///         StopConfig { id: StopId(1), name: "Top".into(), position: 10.0 },
84    ///     ])
85    ///     .elevator(ElevatorConfig {
86    ///         id: 0,
87    ///         name: "Main".into(),
88    ///         max_speed: Speed::from(2.0),
89    ///         acceleration: Accel::from(1.5),
90    ///         deceleration: Accel::from(2.0),
91    ///         weight_capacity: Weight::from(800.0),
92    ///         starting_stop: StopId(0),
93    ///         door_open_ticks: 10,
94    ///         door_transition_ticks: 5,
95    ///         restricted_stops: Vec::new(),
96    ///         # #[cfg(feature = "energy")]
97    ///         # energy_profile: None,
98    ///         service_mode: None,
99    ///         inspection_speed_factor: 0.25,
100    ///         bypass_load_up_pct: None,
101    ///         bypass_load_down_pct: None,
102    ///     })
103    ///     .build()
104    ///     .unwrap();
105    /// assert_eq!(sim.current_tick(), 0);
106    /// ```
107    #[must_use]
108    pub fn new() -> Self {
109        let config = SimConfig {
110            schema_version: crate::config::CURRENT_CONFIG_SCHEMA_VERSION,
111            building: BuildingConfig {
112                name: "Untitled".into(),
113                stops: Vec::new(),
114                lines: None,
115                groups: None,
116            },
117            elevators: Vec::new(),
118            simulation: SimulationParams {
119                ticks_per_second: 60.0,
120            },
121            passenger_spawning: PassengerSpawnConfig {
122                mean_interval_ticks: 120,
123                weight_range: (50.0, 100.0),
124            },
125        };
126
127        let mut dispatchers = BTreeMap::new();
128        dispatchers.insert(
129            GroupId(0),
130            Box::new(ScanDispatch::new()) as Box<dyn DispatchStrategy>,
131        );
132
133        Self {
134            config,
135            dispatchers,
136            repositioners: Vec::new(),
137            hooks: PhaseHooks::default(),
138            ext_registrations: Vec::new(),
139        }
140    }
141
142    /// Pre-populated builder for zero-config examples, doctests, and quick
143    /// prototyping where the building layout isn't the point.
144    ///
145    /// Provides two stops (Ground at 0.0, Top at 10.0) and one elevator
146    /// with SCAN dispatch. Use this when you want a working `Simulation`
147    /// in one call and don't care about the specific stops.
148    ///
149    /// ```
150    /// use elevator_core::prelude::*;
151    ///
152    /// let sim = SimulationBuilder::demo().build().unwrap();
153    /// assert_eq!(sim.current_tick(), 0);
154    /// ```
155    ///
156    /// If you need a specific stop layout or elevator physics, use
157    /// [`new`](Self::new) and configure every field explicitly — it reads
158    /// more clearly than threading overrides on top of `demo`'s defaults.
159    /// [`.stop()`](Self::stop) is a *push* onto the current stops list,
160    /// so calling it after `demo()` appends to the two defaults rather
161    /// than replacing them.
162    #[must_use]
163    pub fn demo() -> Self {
164        let mut b = Self::new();
165        b.config.building.name = "Demo".into();
166        b.config.building.stops = vec![
167            StopConfig {
168                id: StopId(0),
169                name: "Ground".into(),
170                position: 0.0,
171            },
172            StopConfig {
173                id: StopId(1),
174                name: "Top".into(),
175                position: 10.0,
176            },
177        ];
178        b.config.elevators = vec![ElevatorConfig {
179            id: 0,
180            name: "Elevator 1".into(),
181            max_speed: Speed::from(2.0),
182            acceleration: Accel::from(1.5),
183            deceleration: Accel::from(2.0),
184            weight_capacity: Weight::from(800.0),
185            starting_stop: StopId(0),
186            door_open_ticks: 10,
187            door_transition_ticks: 5,
188            restricted_stops: Vec::new(),
189            #[cfg(feature = "energy")]
190            energy_profile: None,
191            service_mode: None,
192            inspection_speed_factor: 0.25,
193            bypass_load_up_pct: None,
194            bypass_load_down_pct: None,
195        }];
196        b
197    }
198
199    /// Create a builder from an existing [`SimConfig`].
200    ///
201    /// Honours the `dispatch` field on each `GroupConfig` from the config —
202    /// no default is pre-seeded. Call [`.dispatch()`](Self::dispatch) or
203    /// [`.dispatch_for_group()`](Self::dispatch_for_group) to override the
204    /// per-group strategy from code; otherwise the config's choice (or
205    /// `ScanDispatch` if neither config nor builder specifies) is used.
206    #[must_use]
207    pub fn from_config(config: SimConfig) -> Self {
208        Self {
209            config,
210            dispatchers: BTreeMap::new(),
211            repositioners: Vec::new(),
212            hooks: PhaseHooks::default(),
213            ext_registrations: Vec::new(),
214        }
215    }
216
217    /// Replace all stops with the given list.
218    ///
219    /// Clears any previously added stops.
220    #[must_use]
221    pub fn stops(mut self, stops: Vec<StopConfig>) -> Self {
222        self.config.building.stops = stops;
223        self
224    }
225
226    /// Add a single stop to the building.
227    #[must_use]
228    pub fn stop(mut self, id: StopId, name: impl Into<String>, position: f64) -> Self {
229        self.config.building.stops.push(StopConfig {
230            id,
231            name: name.into(),
232            position,
233        });
234        self
235    }
236
237    /// Replace all elevators with the given list.
238    ///
239    /// Clears any previously added elevators.
240    #[must_use]
241    pub fn elevators(mut self, elevators: Vec<ElevatorConfig>) -> Self {
242        self.config.elevators = elevators;
243        self
244    }
245
246    /// Add a single elevator configuration.
247    #[must_use]
248    pub fn elevator(mut self, config: ElevatorConfig) -> Self {
249        self.config.elevators.push(config);
250        self
251    }
252
253    /// Add a single line configuration.
254    ///
255    /// Switches from legacy flat-elevator mode to explicit topology.
256    #[must_use]
257    pub fn line(mut self, config: LineConfig) -> Self {
258        self.config
259            .building
260            .lines
261            .get_or_insert_with(Vec::new)
262            .push(config);
263        self
264    }
265
266    /// Replace all lines with the given list.
267    ///
268    /// Switches from legacy flat-elevator mode to explicit topology.
269    #[must_use]
270    pub fn lines(mut self, lines: Vec<LineConfig>) -> Self {
271        self.config.building.lines = Some(lines);
272        self
273    }
274
275    /// Add a single group configuration.
276    #[must_use]
277    pub fn group(mut self, config: GroupConfig) -> Self {
278        self.config
279            .building
280            .groups
281            .get_or_insert_with(Vec::new)
282            .push(config);
283        self
284    }
285
286    /// Replace all groups with the given list.
287    #[must_use]
288    pub fn groups(mut self, groups: Vec<GroupConfig>) -> Self {
289        self.config.building.groups = Some(groups);
290        self
291    }
292
293    /// Set the simulation tick rate (ticks per second).
294    #[must_use]
295    pub const fn ticks_per_second(mut self, tps: f64) -> Self {
296        self.config.simulation.ticks_per_second = tps;
297        self
298    }
299
300    /// Set the building name.
301    #[must_use]
302    pub fn building_name(mut self, name: impl Into<String>) -> Self {
303        self.config.building.name = name.into();
304        self
305    }
306
307    /// Set the default dispatch strategy for the default group.
308    #[must_use]
309    pub fn dispatch(mut self, strategy: impl DispatchStrategy + 'static) -> Self {
310        self.dispatchers.insert(GroupId(0), Box::new(strategy));
311        self
312    }
313
314    /// Set a dispatch strategy for a specific group.
315    #[must_use]
316    pub fn dispatch_for_group(
317        mut self,
318        group: GroupId,
319        strategy: impl DispatchStrategy + 'static,
320    ) -> Self {
321        self.dispatchers.insert(group, Box::new(strategy));
322        self
323    }
324
325    /// Register a hook to run before a simulation phase.
326    #[must_use]
327    pub fn before(
328        mut self,
329        phase: Phase,
330        hook: impl Fn(&mut World) + Send + Sync + 'static,
331    ) -> Self {
332        self.hooks.add_before(phase, Box::new(hook));
333        self
334    }
335
336    /// Register a hook to run after a simulation phase.
337    #[must_use]
338    pub fn after(
339        mut self,
340        phase: Phase,
341        hook: impl Fn(&mut World) + Send + Sync + 'static,
342    ) -> Self {
343        self.hooks.add_after(phase, Box::new(hook));
344        self
345    }
346
347    /// Register a hook to run before a phase for a specific group.
348    #[must_use]
349    pub fn before_group(
350        mut self,
351        phase: Phase,
352        group: GroupId,
353        hook: impl Fn(&mut World) + Send + Sync + 'static,
354    ) -> Self {
355        self.hooks.add_before_group(phase, group, Box::new(hook));
356        self
357    }
358
359    /// Register a hook to run after a phase for a specific group.
360    #[must_use]
361    pub fn after_group(
362        mut self,
363        phase: Phase,
364        group: GroupId,
365        hook: impl Fn(&mut World) + Send + Sync + 'static,
366    ) -> Self {
367        self.hooks.add_after_group(phase, group, Box::new(hook));
368        self
369    }
370
371    /// Set a reposition strategy for the default group.
372    ///
373    /// Enables the reposition phase, which runs after dispatch to
374    /// move idle elevators for better coverage.
375    #[must_use]
376    pub fn reposition(
377        self,
378        strategy: impl RepositionStrategy + 'static,
379        id: BuiltinReposition,
380    ) -> Self {
381        self.reposition_for_group(GroupId(0), strategy, id)
382    }
383
384    /// Set a reposition strategy for a specific group.
385    #[must_use]
386    pub fn reposition_for_group(
387        mut self,
388        group: GroupId,
389        strategy: impl RepositionStrategy + 'static,
390        id: BuiltinReposition,
391    ) -> Self {
392        self.repositioners.push((group, Box::new(strategy), id));
393        self
394    }
395
396    /// Pre-register an extension type for snapshot deserialization.
397    ///
398    /// Extensions registered here will be available immediately after [`build()`](Self::build)
399    /// without needing to call `register_ext` manually.
400    #[must_use]
401    pub fn with_ext<T: 'static + Send + Sync + Serialize + DeserializeOwned>(mut self) -> Self {
402        self.ext_registrations
403            .push(Box::new(move |world: &mut World| {
404                world.register_ext::<T>(crate::world::ExtKey::from_type_name());
405            }));
406        self
407    }
408
409    /// Validate the configuration without building the simulation.
410    ///
411    /// Runs the same validation as [`build()`](Self::build) but does not
412    /// allocate entities or construct the simulation. Useful for CLI tools,
413    /// config editors, and dry-run checks.
414    ///
415    /// # Errors
416    ///
417    /// Returns [`SimError::InvalidConfig`] if the configuration is invalid.
418    pub fn validate(&self) -> Result<(), SimError> {
419        Simulation::validate_config(&self.config)
420    }
421
422    /// Build the simulation, validating the configuration.
423    ///
424    /// Returns `Err(SimError)` if the configuration is invalid.
425    ///
426    /// # Errors
427    ///
428    /// Returns [`SimError::InvalidConfig`] if the assembled configuration is invalid.
429    ///
430    /// # Examples
431    ///
432    /// ```
433    /// use elevator_core::prelude::*;
434    /// use elevator_core::stop::StopConfig;
435    ///
436    /// let mut sim = SimulationBuilder::demo()
437    ///     .stops(vec![
438    ///         StopConfig { id: StopId(0), name: "Lobby".into(), position: 0.0 },
439    ///         StopConfig { id: StopId(1), name: "Roof".into(), position: 20.0 },
440    ///     ])
441    ///     .build()
442    ///     .unwrap();
443    ///
444    /// sim.spawn_rider(StopId(0), StopId(1), 75.0).unwrap();
445    ///
446    /// for _ in 0..1000 {
447    ///     sim.step();
448    /// }
449    ///
450    /// assert!(sim.metrics().total_delivered() > 0);
451    /// ```
452    pub fn build(self) -> Result<Simulation, SimError> {
453        let mut sim = Simulation::new_with_hooks(&self.config, self.dispatchers, self.hooks)?;
454
455        for (group, strategy, id) in self.repositioners {
456            sim.set_reposition(group, strategy, id);
457        }
458
459        for register in self.ext_registrations {
460            register(sim.world_mut());
461        }
462
463        Ok(sim)
464    }
465}