Skip to main content

sim_logic/application/
app.rs

1//! Application configuration and immutable registry construction.
2
3use std::{error::Error, fmt, sync::Arc};
4
5use bevy_ecs::{component::Component, entity_disabling::Disabled, system::SystemParamFunction};
6
7use crate::{
8    assets::{ImageAssetError, ImageAssetId, ImageAssetLimits, ImageAssetRegistry},
9    collision::{CircleCollider2d, RectangleCollider2d},
10    component::{ComponentApprovalError, ComponentRegistry, ComponentTuple},
11    events::EventRegistry,
12    headless::{HeadlessRunner, RunnerBuildError},
13    identity::{ApplicationId, IdentityExhausted, WorldFactoryId},
14    input::{
15        Action, ActionBindings, DigitalAxis2d, DuplicateKeyBinding, DuplicateMouseBinding,
16        MouseButton, PhysicalKeyCode,
17    },
18    motion::{
19        CameraFollowTarget2d, DigitalMovement2d, LinearAcceleration2d, LinearVelocity2d,
20        follow_camera_target2d, integrate_digital_movement2d, integrate_linear_acceleration2d,
21        integrate_linear_velocity2d,
22    },
23    render::RenderLimits,
24    resources::{ApplicationResourceError, ApplicationResourceRegistry},
25    screen::{ScreenImageVisual, ScreenRectangleVisual},
26    system::{
27        Stage, StageFactories, SupportedSystemParamTuple, register_system_application_resources,
28        register_system_events,
29    },
30    three_d::{CuboidVisual3d, ThreeDRenderLimits},
31    time::TimeConfig,
32    transition::replace_world_on_press,
33    visual::{ActiveCamera2d, CircleVisual, LineVisual, RectangleVisual, Transform2d},
34    world::{WorldBuildError, WorldBuilder},
35};
36
37/// Default maximum number of managed entities in one active World.
38pub const DEFAULT_ENTITY_LIMIT: usize = 100_000;
39
40/// Default maximum structural, transition, and application-control commands
41/// in one stage.
42pub const DEFAULT_COMMAND_LIMIT: usize = 4_096;
43
44/// Default maximum number of events of one type in one stage invocation.
45pub const DEFAULT_EVENT_LIMIT: usize = 1_024;
46
47/// Default maximum retained WorldEnter/WorldExit diagnostic records.
48pub const DEFAULT_LIFECYCLE_TRACE_LIMIT: usize = 1_024;
49
50/// Default maximum number of distinct Application Resource types.
51pub const DEFAULT_APPLICATION_RESOURCE_LIMIT: usize = 256;
52
53/// Complete frozen configuration for one Sim;Logic application.
54#[derive(Debug, Clone, Copy, PartialEq)]
55pub struct AppConfig {
56    time: TimeConfig,
57    entity_limit: usize,
58    command_limit: usize,
59    event_limit: usize,
60    input_event_limit: usize,
61    lifecycle_trace_limit: usize,
62    application_resource_limit: usize,
63    render: RenderLimits,
64    images: ImageAssetLimits,
65    #[cfg(feature = "headless-text")]
66    text: crate::text::TextLimits,
67}
68
69impl Default for AppConfig {
70    fn default() -> Self {
71        Self {
72            time: TimeConfig::default(),
73            entity_limit: DEFAULT_ENTITY_LIMIT,
74            command_limit: DEFAULT_COMMAND_LIMIT,
75            event_limit: DEFAULT_EVENT_LIMIT,
76            input_event_limit: crate::input::DEFAULT_INPUT_EVENT_LIMIT,
77            lifecycle_trace_limit: DEFAULT_LIFECYCLE_TRACE_LIMIT,
78            application_resource_limit: DEFAULT_APPLICATION_RESOURCE_LIMIT,
79            render: RenderLimits::default(),
80            images: ImageAssetLimits::default(),
81            #[cfg(feature = "headless-text")]
82            text: crate::text::TextLimits::default(),
83        }
84    }
85}
86
87impl AppConfig {
88    /// Replaces the fixed-step time configuration.
89    pub fn set_time(&mut self, time: TimeConfig) -> &mut Self {
90        self.time = time;
91        self
92    }
93
94    /// Replaces the maximum managed entity count.
95    pub fn set_entity_limit(&mut self, limit: usize) -> Result<&mut Self, AppConfigError> {
96        if limit == 0 {
97            return Err(AppConfigError::ZeroEntityLimit);
98        }
99        self.entity_limit = limit;
100        Ok(self)
101    }
102
103    /// Replaces the maximum combined command count for one stage.
104    pub fn set_command_limit(&mut self, limit: usize) -> Result<&mut Self, AppConfigError> {
105        if limit == 0 {
106            return Err(AppConfigError::ZeroCommandLimit);
107        }
108        self.command_limit = limit;
109        Ok(self)
110    }
111
112    /// Replaces the maximum event count for each type in one stage invocation.
113    pub fn set_event_limit(&mut self, limit: usize) -> Result<&mut Self, AppConfigError> {
114        if limit == 0 {
115            return Err(AppConfigError::ZeroEventLimit);
116        }
117        self.event_limit = limit;
118        Ok(self)
119    }
120
121    /// Replaces the maximum physical events per frame, generated logical edges
122    /// per frame, and retained logical edges for a later FixedUpdate delivery.
123    ///
124    /// A frame exceeding any bound is rejected before input state changes.
125    /// Generated edges include synthetic mouse releases on pointer leave;
126    /// their frame bound still applies while fixed updates are paused.
127    pub fn set_input_event_limit(&mut self, limit: usize) -> Result<&mut Self, AppConfigError> {
128        if limit == 0 {
129            return Err(AppConfigError::ZeroInputEventLimit);
130        }
131        self.input_event_limit = limit;
132        Ok(self)
133    }
134
135    /// Replaces the maximum retained WorldEnter/WorldExit diagnostic records.
136    ///
137    /// Once full, the trace evicts its oldest record before retaining a new
138    /// one. This affects diagnostics only, never World lifecycle execution.
139    pub fn set_lifecycle_trace_limit(&mut self, limit: usize) -> Result<&mut Self, AppConfigError> {
140        if limit == 0 {
141            return Err(AppConfigError::ZeroLifecycleTraceLimit);
142        }
143        self.lifecycle_trace_limit = limit;
144        Ok(self)
145    }
146
147    /// Replaces the maximum number of distinct Application Resource types.
148    ///
149    /// This bounds registry entries, not heap memory retained inside arbitrary
150    /// user values.
151    pub fn set_application_resource_limit(
152        &mut self,
153        limit: usize,
154    ) -> Result<&mut Self, AppConfigError> {
155        if limit == 0 {
156            return Err(AppConfigError::ZeroApplicationResourceLimit);
157        }
158        self.application_resource_limit = limit;
159        Ok(self)
160    }
161
162    /// Replaces renderer-independent extraction and presentation limits.
163    pub fn set_render_limits(&mut self, limits: RenderLimits) -> &mut Self {
164        self.render = limits;
165        self
166    }
167
168    /// Replaces opt-in cuboid, triangle, and physical depth-target limits.
169    ///
170    /// All other rendering limits are preserved. Final composition still
171    /// requires a target pass and color texture space in FrameLimits.
172    pub fn set_three_d_render_limits(&mut self, limits: ThreeDRenderLimits) -> &mut Self {
173        self.render = self.render.with_three_d_render_limits(limits);
174        self
175    }
176
177    /// Replaces setup-time image count, dimension, and retained-pixel limits.
178    ///
179    /// Zero limits are valid and disable the corresponding allowance. This
180    /// does not enable screen-image extraction or raise presentation budgets.
181    pub fn set_image_asset_limits(&mut self, limits: ImageAssetLimits) -> &mut Self {
182        self.images = limits;
183        self
184    }
185
186    /// Replaces setup-time font count and retained font-byte limits.
187    ///
188    /// Does not raise render limits or initialize a window/device. Use
189    /// `headless-text` without defaults to exclude GPU/window dependencies;
190    /// `text` additionally compiles Engine's retained GPU text bridge.
191    #[cfg(feature = "headless-text")]
192    pub fn set_text_limits(&mut self, limits: crate::text::TextLimits) -> &mut Self {
193        self.text = limits;
194        self
195    }
196
197    pub(crate) const fn time(self) -> TimeConfig {
198        self.time
199    }
200
201    pub(crate) const fn entity_limit(self) -> usize {
202        self.entity_limit
203    }
204
205    pub(crate) const fn command_limit(self) -> usize {
206        self.command_limit
207    }
208
209    pub(crate) const fn event_limit(self) -> usize {
210        self.event_limit
211    }
212
213    pub(crate) const fn input_event_limit(self) -> usize {
214        self.input_event_limit
215    }
216
217    pub(crate) const fn lifecycle_trace_limit(self) -> usize {
218        self.lifecycle_trace_limit
219    }
220
221    pub(crate) const fn application_resource_limit(self) -> usize {
222        self.application_resource_limit
223    }
224
225    pub(crate) const fn render(self) -> RenderLimits {
226        self.render
227    }
228}
229
230/// Invalid finite application limit.
231#[derive(Debug, Clone, Copy, PartialEq, Eq)]
232pub enum AppConfigError {
233    /// An active World must permit at least one entity.
234    ZeroEntityLimit,
235    /// A stage must permit at least one command.
236    ZeroCommandLimit,
237    /// A stage must permit at least one event of each registered type.
238    ZeroEventLimit,
239    /// A frame must permit at least one physical input event.
240    ZeroInputEventLimit,
241    /// A lifecycle trace must retain at least its newest record.
242    ZeroLifecycleTraceLimit,
243    /// An Application must permit at least one persistent resource type.
244    ZeroApplicationResourceLimit,
245}
246
247impl fmt::Display for AppConfigError {
248    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
249        match self {
250            Self::ZeroEntityLimit => formatter.write_str("entity limit must be positive"),
251            Self::ZeroCommandLimit => formatter.write_str("command limit must be positive"),
252            Self::ZeroEventLimit => formatter.write_str("event limit must be positive"),
253            Self::ZeroInputEventLimit => formatter.write_str("input event limit must be positive"),
254            Self::ZeroLifecycleTraceLimit => {
255                formatter.write_str("lifecycle trace limit must be positive")
256            }
257            Self::ZeroApplicationResourceLimit => {
258                formatter.write_str("Application Resource limit must be positive")
259            }
260        }
261    }
262}
263
264impl Error for AppConfigError {}
265
266/// Failure to create an application runtime identity or its standard registry.
267#[derive(Debug)]
268pub enum ApplicationCreationError {
269    /// The process-wide application identity counter is exhausted.
270    Identity(IdentityExhausted),
271    /// A built-in component unexpectedly violates the managed component rules.
272    StandardComponent(ComponentApprovalError),
273}
274
275impl fmt::Display for ApplicationCreationError {
276    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
277        match self {
278            Self::Identity(error) => error.fmt(formatter),
279            Self::StandardComponent(error) => {
280                write!(formatter, "standard component approval failed: {error}")
281            }
282        }
283    }
284}
285
286impl Error for ApplicationCreationError {
287    fn source(&self) -> Option<&(dyn Error + 'static)> {
288        match self {
289            Self::Identity(error) => Some(error),
290            Self::StandardComponent(error) => Some(error),
291        }
292    }
293}
294
295/// Failure to register a no-payload World factory.
296#[derive(Debug, Clone, PartialEq, Eq)]
297pub enum WorldRegistrationError {
298    /// Diagnostic route names must contain a non-whitespace character.
299    EmptyName,
300    /// Diagnostic route names are bounded to 128 UTF-8 bytes.
301    NameTooLong,
302    /// Another factory already uses this exact diagnostic route name.
303    DuplicateName {
304        /// Rejected duplicate name.
305        name: String,
306    },
307    /// The runtime registry cannot represent another factory slot.
308    RegistryExhausted,
309}
310
311impl fmt::Display for WorldRegistrationError {
312    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
313        match self {
314            Self::EmptyName => formatter.write_str("World factory name must not be empty"),
315            Self::NameTooLong => formatter.write_str("World factory name exceeds 128 UTF-8 bytes"),
316            Self::DuplicateName { name } => {
317                write!(
318                    formatter,
319                    "World factory name `{name}` is already registered"
320                )
321            }
322            Self::RegistryExhausted => formatter.write_str("World factory registry is exhausted"),
323        }
324    }
325}
326
327impl Error for WorldRegistrationError {}
328
329pub(crate) type WorldFactory =
330    dyn Fn(&mut WorldBuilder) -> Result<(), WorldBuildError> + Send + Sync + 'static;
331
332pub(crate) struct RegisteredWorldFactory {
333    pub(crate) id: WorldFactoryId,
334    pub(crate) diagnostic_name: String,
335    pub(crate) factory: Arc<WorldFactory>,
336}
337
338/// Mutable pre-startup builder for one typed Sim;Logic application.
339pub struct Application<A: Action> {
340    pub(crate) application: ApplicationId,
341    pub(crate) config: AppConfig,
342    pub(crate) components: ComponentRegistry,
343    pub(crate) events: EventRegistry,
344    pub(crate) application_resources: ApplicationResourceRegistry,
345    pub(crate) images: ImageAssetRegistry,
346    #[cfg(feature = "headless-text")]
347    pub(crate) texts: crate::text::TextRegistry,
348    #[cfg(feature = "easter-eggs")]
349    pub(crate) crab_image: Option<ImageAssetId>,
350    pub(crate) bindings: ActionBindings<A>,
351    pub(crate) factories: Vec<RegisteredWorldFactory>,
352    pub(crate) startup: StageFactories,
353    pub(crate) fixed: StageFactories,
354    pub(crate) frame: StageFactories,
355}
356
357impl<A: Action> Application<A> {
358    /// Creates an application builder and approves Sim;Logic's standard
359    /// world and screen visual, collision, motion, and disabled components,
360    /// including their complete required-component closure.
361    pub fn new(config: AppConfig) -> Result<Self, ApplicationCreationError> {
362        let application = ApplicationId::issue().map_err(ApplicationCreationError::Identity)?;
363        let mut components = ComponentRegistry::default();
364        components
365            .approve::<Transform2d>()
366            .map_err(ApplicationCreationError::StandardComponent)?;
367        components
368            .approve::<Disabled>()
369            .map_err(ApplicationCreationError::StandardComponent)?;
370        components
371            .approve::<CircleVisual>()
372            .map_err(ApplicationCreationError::StandardComponent)?;
373        components
374            .approve::<RectangleVisual>()
375            .map_err(ApplicationCreationError::StandardComponent)?;
376        components
377            .approve::<LineVisual>()
378            .map_err(ApplicationCreationError::StandardComponent)?;
379        components
380            .approve::<ScreenRectangleVisual>()
381            .map_err(ApplicationCreationError::StandardComponent)?;
382        components
383            .approve::<crate::screen::ScreenLineVisual>()
384            .map_err(ApplicationCreationError::StandardComponent)?;
385        components
386            .approve::<crate::screen::ScreenCircleVisual>()
387            .map_err(ApplicationCreationError::StandardComponent)?;
388        components
389            .approve::<crate::screen::ScreenPolylineVisual>()
390            .map_err(ApplicationCreationError::StandardComponent)?;
391        components
392            .approve::<ScreenImageVisual>()
393            .map_err(ApplicationCreationError::StandardComponent)?;
394        #[cfg(feature = "headless-text")]
395        components
396            .approve::<crate::text::ScreenTextVisual>()
397            .map_err(ApplicationCreationError::StandardComponent)?;
398        components
399            .approve::<CuboidVisual3d>()
400            .map_err(ApplicationCreationError::StandardComponent)?;
401        components
402            .approve::<crate::three_d::MeshVisual3d>()
403            .map_err(ApplicationCreationError::StandardComponent)?;
404        components
405            .approve::<ActiveCamera2d>()
406            .map_err(ApplicationCreationError::StandardComponent)?;
407        components
408            .approve::<CircleCollider2d>()
409            .map_err(ApplicationCreationError::StandardComponent)?;
410        components
411            .approve::<RectangleCollider2d>()
412            .map_err(ApplicationCreationError::StandardComponent)?;
413        components
414            .approve::<LinearVelocity2d>()
415            .map_err(ApplicationCreationError::StandardComponent)?;
416        components
417            .approve::<LinearAcceleration2d>()
418            .map_err(ApplicationCreationError::StandardComponent)?;
419        components
420            .approve::<DigitalMovement2d<A>>()
421            .map_err(ApplicationCreationError::StandardComponent)?;
422        components
423            .approve::<CameraFollowTarget2d>()
424            .map_err(ApplicationCreationError::StandardComponent)?;
425
426        Ok(Self {
427            application,
428            config,
429            components,
430            events: EventRegistry::default(),
431            application_resources: ApplicationResourceRegistry::default(),
432            images: ImageAssetRegistry::new(application, config.images),
433            #[cfg(feature = "headless-text")]
434            texts: crate::text::TextRegistry::new(application, config.text),
435            #[cfg(feature = "easter-eggs")]
436            crab_image: None,
437            bindings: ActionBindings::new(),
438            factories: Vec::new(),
439            startup: StageFactories::default(),
440            fixed: StageFactories::default(),
441            frame: StageFactories::default(),
442        })
443    }
444
445    /// Approves one hook-free component type for candidate and command bundles.
446    pub fn approve_component<T: Component>(&mut self) -> Result<&mut Self, ComponentApprovalError> {
447        self.components.approve::<T>()?;
448        Ok(self)
449    }
450
451    /// Registers immutable straight-alpha sRGB RGBA8 pixels before startup.
452    ///
453    /// Copies exactly one row-major image after validating dimensions, byte
454    /// length, and configured asset limits. A failed registration publishes no
455    /// handle or pixel entry. Handles belong only to this Application, survive
456    /// World replacement, and are not persistent file identifiers. Registering
457    /// identical pixels twice creates two distinct resources. No GPU or file
458    /// decoder is involved; normal frames never copy these pixels again on the
459    /// CPU side. GPU preparation retains its own recovery copy when needed.
460    pub fn register_image_rgba8(
461        &mut self,
462        width: u32,
463        height: u32,
464        pixels: &[u8],
465    ) -> Result<ImageAssetId, ImageAssetError> {
466        self.images.register(width, height, pixels)
467    }
468
469    /// Registers an owned trusted TTF/OTF asset and fixed logical text settings.
470    ///
471    /// Parsing and limits are checked before publishing an opaque font handle;
472    /// equal registrations remain distinct. Clones share font storage and the
473    /// handle survives World replacement. No window, GPU call, font discovery,
474    /// or download occurs. The caller supplies licensed, trusted font bytes.
475    #[cfg(feature = "headless-text")]
476    pub fn register_font(
477        &mut self,
478        bytes: Vec<u8>,
479        settings: crate::text::TextSettings,
480    ) -> Result<crate::text::TextFont, crate::text::TextError> {
481        self.texts.register(bytes, settings)
482    }
483
484    /// Registers another size/direction/layout configuration sharing an existing
485    /// font's parsed face and source bytes. No file copy, reparse, or GPU work occurs.
486    ///
487    /// The source must belong to this application. The new style has its own
488    /// registration/atlas identity, consumes one font-count slot, and charges zero
489    /// additional source bytes. Per-style atlas/run budgets remain independent.
490    /// Failure preserves the registry. A source style can also share its face onward.
491    #[cfg(feature = "headless-text")]
492    pub fn register_font_style(
493        &mut self,
494        source: &crate::text::TextFont,
495        settings: crate::text::TextSettings,
496    ) -> Result<crate::text::TextFont, crate::text::TextError> {
497        self.texts.register_style(source, settings)
498    }
499
500    /// Approves a flat tuple of one through fifteen hook-free component types.
501    ///
502    /// The registry update is atomic: if one tuple member is rejected, types
503    /// newly added by this call are removed again. Components that were
504    /// already approved before the call remain approved. Required components
505    /// must still be listed explicitly, in any order, and are checked when the
506    /// application creates a World candidate.
507    pub fn approve_components<T: ComponentTuple>(
508        &mut self,
509    ) -> Result<&mut Self, ComponentApprovalError> {
510        self.components.approve_tuple::<T>()?;
511        Ok(self)
512    }
513
514    /// Binds one portable physical key to a typed action.
515    pub fn bind_key(
516        &mut self,
517        key: PhysicalKeyCode,
518        action: A,
519    ) -> Result<&mut Self, DuplicateKeyBinding> {
520        self.bindings.bind(key, action)?;
521        Ok(self)
522    }
523
524    /// Binds one portable mouse button to a typed action without replacing an
525    /// existing binding. Bindings freeze when the application is started.
526    ///
527    /// Mouse buttons and keys may share an action: it remains held until all
528    /// bound physical controls release. Their individual edges remain distinct.
529    pub fn bind_mouse_button(
530        &mut self,
531        button: MouseButton,
532        action: A,
533    ) -> Result<&mut Self, DuplicateMouseBinding> {
534        self.bindings.bind_mouse_button(button, action)?;
535        Ok(self)
536    }
537
538    /// Atomically binds W/A/S/D to one typed two-dimensional action axis.
539    ///
540    /// W maps to positive y, A to negative x, S to negative y, and D to
541    /// positive x. All four physical keys are checked first in W/A/S/D order.
542    /// If any is already bound, that binding is reported and the complete
543    /// table remains unchanged. Repeating one logical action in several axis
544    /// slots is allowed, matching [`DigitalAxis2d`] sampling semantics.
545    pub fn bind_wasd(&mut self, axis: DigitalAxis2d<A>) -> Result<&mut Self, DuplicateKeyBinding> {
546        self.bindings.bind_wasd(axis)?;
547        Ok(self)
548    }
549
550    /// Atomically binds the physical arrow keys to one typed action axis.
551    ///
552    /// Left maps to negative x, Right to positive x, Down to negative y, and
553    /// Up to positive y. All four keys are checked first in that order. If any
554    /// is already bound, that binding is reported and the complete table
555    /// remains unchanged. The same axis may be bound to both arrows and W/A/S/D.
556    pub fn bind_arrows(
557        &mut self,
558        axis: DigitalAxis2d<A>,
559    ) -> Result<&mut Self, DuplicateKeyBinding> {
560        self.bindings.bind_arrows(axis)?;
561        Ok(self)
562    }
563
564    /// Atomically binds W/A/S/D and the arrow keys to one typed action axis.
565    ///
566    /// The mappings match [`Application::bind_wasd`] and
567    /// [`Application::bind_arrows`]. All eight keys are checked before any
568    /// binding is written, in W, A, S, D, Left, Right, Down, Up order. If any
569    /// key is already bound, that binding is reported and the complete table
570    /// remains unchanged. Calling this method again reports W as the first
571    /// conflict. Use the separate presets when only one key family should be
572    /// accepted.
573    pub fn bind_wasd_and_arrows(
574        &mut self,
575        axis: DigitalAxis2d<A>,
576    ) -> Result<&mut Self, DuplicateKeyBinding> {
577        self.bindings.bind_wasd_and_arrows(axis)?;
578        Ok(self)
579    }
580
581    /// Registers one typed value owned by the Application rather than a World.
582    ///
583    /// The value becomes available through [`crate::resources::AppRes`] and
584    /// [`crate::resources::AppResMut`] in FixedUpdate and FrameUpdate, and the
585    /// same value survives successful World replacement without cloning.
586    /// Candidate factories and Startup systems cannot access it.
587    ///
588    /// Registration is explicit, accepts at most one value of each concrete
589    /// type, and is bounded by [`AppConfig::set_application_resource_limit`].
590    /// A duplicate returns [`ApplicationResourceError::Duplicate`] and keeps
591    /// the first value; registration never means replacement. `T` needs no
592    /// Bevy `Resource` derive.
593    ///
594    /// ```no_run
595    /// use sim_logic::prelude::*;
596    ///
597    /// #[derive(Clone, Copy, PartialEq, Eq, Hash)]
598    /// enum Action {}
599    ///
600    /// #[derive(Default)]
601    /// struct SessionScore(u32);
602    ///
603    /// fn award(mut score: AppResMut<SessionScore>) {
604    ///     score.0 = score.0.saturating_add(1);
605    /// }
606    ///
607    /// # fn main() -> LogicResult {
608    /// let mut app = Application::<Action>::new(AppConfig::default())?;
609    /// app.register_app_resource(SessionScore::default())?;
610    /// app.add_system(Stage::FixedUpdate, award);
611    /// # Ok(())
612    /// # }
613    /// ```
614    pub fn register_app_resource<T: Send + Sync + 'static>(
615        &mut self,
616        resource: T,
617    ) -> Result<&mut Self, ApplicationResourceError> {
618        self.application_resources
619            .insert(resource, self.config.application_resource_limit())?;
620        Ok(self)
621    }
622
623    /// Registers one repeatable synchronous no-payload World factory.
624    ///
625    /// A factory is a restricted construction recipe, not an effect callback.
626    /// It must derive the same candidate from its immutable captures, mutate
627    /// only the supplied [`WorldBuilder`], and finish before returning. It must
628    /// not perform I/O, start background work, or mutate shared external state.
629    /// The runtime can discard an isolated candidate, but it cannot roll back
630    /// effects performed outside that candidate.
631    pub fn register_world(
632        &mut self,
633        diagnostic_name: impl Into<String>,
634        factory: impl Fn(&mut WorldBuilder) -> Result<(), WorldBuildError> + Send + Sync + 'static,
635    ) -> Result<WorldFactoryId, WorldRegistrationError> {
636        let diagnostic_name = diagnostic_name.into();
637        if diagnostic_name.trim().is_empty() {
638            return Err(WorldRegistrationError::EmptyName);
639        }
640        if diagnostic_name.len() > 128 {
641            return Err(WorldRegistrationError::NameTooLong);
642        }
643        if self
644            .factories
645            .iter()
646            .any(|registered| registered.diagnostic_name == diagnostic_name)
647        {
648            return Err(WorldRegistrationError::DuplicateName {
649                name: diagnostic_name,
650            });
651        }
652        let slot = u32::try_from(self.factories.len())
653            .map_err(|_| WorldRegistrationError::RegistryExhausted)?;
654        let id = WorldFactoryId::new(self.application, slot, 1);
655        self.factories.push(RegisteredWorldFactory {
656            id,
657            diagnostic_name,
658            factory: Arc::new(factory),
659        });
660        Ok(id)
661    }
662
663    /// Registers an infallible System in the FixedUpdate stage.
664    ///
665    /// This is the short form of `add_system(Stage::FixedUpdate, system)`.
666    /// Both forms append to the same ordered stage list.
667    pub fn add_fixed_system<FunctionMarker: 'static, S>(&mut self, system: S) -> &mut Self
668    where
669        S: SystemParamFunction<FunctionMarker, In = (), Out = ()> + Clone + Send + Sync + 'static,
670        S::Param: SupportedSystemParamTuple,
671    {
672        self.add_system(Stage::FixedUpdate, system)
673    }
674
675    /// Registers a fallible System in the FixedUpdate stage.
676    ///
677    /// This is the short form of
678    /// `add_fallible_system(Stage::FixedUpdate, system)`. Both forms append to
679    /// the same ordered stage list and use the same failure semantics.
680    pub fn add_fallible_fixed_system<FunctionMarker: 'static, S, E>(
681        &mut self,
682        system: S,
683    ) -> &mut Self
684    where
685        S: SystemParamFunction<FunctionMarker, In = (), Out = Result<(), E>>
686            + Clone
687            + Send
688            + Sync
689            + 'static,
690        S::Param: SupportedSystemParamTuple,
691        E: fmt::Display + 'static,
692    {
693        self.add_fallible_system(Stage::FixedUpdate, system)
694    }
695
696    /// Appends the standard fixed-press World-replacement System.
697    ///
698    /// In a World containing
699    /// [`WorldReplacementOnPress<A>`](crate::transition::WorldReplacementOnPress), every matching
700    /// press occurrence queues one ordinary deferred replacement request with
701    /// that edge's original causal token. A World without the Resource, or a
702    /// fixed tick without a matching press, is a successful no-op. Physical
703    /// key bindings remain explicit and the Resource is inert until this
704    /// method is called. Presses received while fixed simulation is paused are
705    /// frame-only input and are not replayed through this adapter on unpause.
706    ///
707    /// The adapter runs at this exact point in FixedUpdate registration order.
708    /// Later Systems in the same tick still run before the stage barrier. An
709    /// accepted replacement then follows the existing arbitration, candidate
710    /// preparation, lifecycle, catch-up stopping, input consumption, and
711    /// same-frame extraction rules. Every occurrence consumes one command
712    /// slot. Each duplicate registration runs at its own position and consumes
713    /// another slot. If no intervening System changes the route, the repeated
714    /// token and target coalesce idempotently; otherwise ordinary arbitration
715    /// decides the differently routed requests.
716    ///
717    /// This helper provides one unconditional route per World. It does not bind
718    /// a key, observe held or release state, request application exit, build a
719    /// route table, attach a payload, or add a FrameUpdate counterpart.
720    pub fn add_world_replacement_on_press_system(&mut self) -> &mut Self {
721        self.add_fallible_fixed_system(replace_world_on_press::<A>)
722    }
723
724    /// Appends the standard fixed-step linear-acceleration System.
725    ///
726    /// Each enabled managed entity with [`LinearAcceleration2d`] changes its
727    /// [`LinearVelocity2d`] by `acceleration * fixed_delta` at this exact point
728    /// in registration order. The component is inert until this method is
729    /// called. Exact zero acceleration is a no-op before arithmetic. Calling
730    /// this method twice applies acceleration twice per fixed tick.
731    ///
732    /// Register this before [`Self::add_linear_velocity2d_system`] for
733    /// semi-implicit Euler motion. Reversing the calls deliberately moves with
734    /// the old velocity before updating it for the next step. Direct component
735    /// writes by earlier Systems are visible; deferred spawn or insert Commands
736    /// first accelerate on a later fixed tick. Arithmetic overflow leaves the
737    /// failing entity's velocity unchanged; entities processed earlier by the
738    /// same System may already have changed under ordinary non-transactional
739    /// fallible-System semantics.
740    ///
741    /// This adapter does not represent force or mass, move a Transform itself,
742    /// or apply gravity, drag, collision response, rotation, or world bounds.
743    pub fn add_linear_acceleration2d_system(&mut self) -> &mut Self {
744        self.add_fallible_fixed_system(integrate_linear_acceleration2d)
745    }
746
747    /// Appends the standard fixed-step linear-velocity System.
748    ///
749    /// Each enabled managed entity with [`LinearVelocity2d`] moves by
750    /// `velocity * fixed_delta` at this exact point in registration order.
751    /// The component itself is inert until this method is called. Calling the
752    /// method twice appends two Systems and therefore integrates twice per
753    /// fixed tick, just like registering an ordinary System twice.
754    ///
755    /// Direct component writes by earlier Systems are visible to this System,
756    /// and later Systems observe the integrated translation. Deferred spawn or
757    /// insert Commands become visible only after the stage barrier, so newly
758    /// moving entities first integrate on a later fixed tick. Arithmetic
759    /// overflow follows normal fallible-System semantics and may leave earlier
760    /// entities in the same query already moved.
761    ///
762    /// This adapter does not apply acceleration, forces, collision response,
763    /// rotation, drag, or world bounds.
764    pub fn add_linear_velocity2d_system(&mut self) -> &mut Self {
765        self.add_fallible_fixed_system(integrate_linear_velocity2d)
766    }
767
768    /// Appends the standard fixed-step digital-movement System.
769    ///
770    /// Each enabled managed entity with [`DigitalMovement2d<A>`] samples its
771    /// typed axis, normalizes the direction, and moves by `speed * fixed_delta`
772    /// at this exact point in registration order. The component is inert until
773    /// this method is called, and physical keys must be bound separately.
774    /// Calling the method twice appends two Systems and moves twice per tick.
775    ///
776    /// Direct component writes by earlier Systems are visible here; later
777    /// Systems observe the integrated translation. Deferred spawn or insert
778    /// Commands become visible only after the stage barrier. If this and the
779    /// linear-velocity adapter are both registered, their Transform writes
780    /// compose in explicit registration order. Idle or exactly opposed input
781    /// is a no-op before speed/time multiplication; active arithmetic overflow
782    /// follows ordinary fallible-System semantics.
783    ///
784    /// This adapter does not apply collision response, acceleration, facing,
785    /// analog input, smoothing, or world bounds.
786    pub fn add_digital_movement2d_system(&mut self) -> &mut Self {
787        self.add_fallible_fixed_system(integrate_digital_movement2d::<A>)
788    }
789
790    /// Appends the standard fixed-step camera-follow System.
791    ///
792    /// With no enabled [`CameraFollowTarget2d`], this System is a successful
793    /// no-op so other Worlds in the application need no follow target. With
794    /// exactly one target and one enabled [`ActiveCamera2d`], it replaces the
795    /// canonical camera center with `target translation + camera offset` at
796    /// this exact point in registration order. More than one target fails the
797    /// stage before changing a camera. Missing or duplicate active cameras are
798    /// left unchanged for the extraction validator and its repair path.
799    ///
800    /// Register this after target movement for same-tick following, or before
801    /// movement to deliberately use the previous target position. Deferred
802    /// spawn or insert Commands first affect following on a later fixed tick;
803    /// Disabled targets are ignored. Arithmetic overflow leaves the camera
804    /// unchanged. Duplicate registration performs another ordinary assignment
805    /// and can observe writes placed between the two adapters.
806    ///
807    /// The adapter does not run during World preparation, create or initially
808    /// align a camera, infer teleports, smooth motion, clamp bounds, change zoom
809    /// or rotation, or choose among multiple targets.
810    pub fn add_camera_follow2d_system(&mut self) -> &mut Self {
811        self.add_fallible_fixed_system(follow_camera_target2d)
812    }
813
814    /// Registers an infallible System in the FrameUpdate stage.
815    ///
816    /// This is the short form of `add_system(Stage::FrameUpdate, system)`.
817    /// Both forms append to the same ordered stage list.
818    pub fn add_frame_system<FunctionMarker: 'static, S>(&mut self, system: S) -> &mut Self
819    where
820        S: SystemParamFunction<FunctionMarker, In = (), Out = ()> + Clone + Send + Sync + 'static,
821        S::Param: SupportedSystemParamTuple,
822    {
823        self.add_system(Stage::FrameUpdate, system)
824    }
825
826    /// Registers a fallible System in the FrameUpdate stage.
827    ///
828    /// This is the short form of
829    /// `add_fallible_system(Stage::FrameUpdate, system)`. Both forms append to
830    /// the same ordered stage list and use the same failure semantics.
831    pub fn add_fallible_frame_system<FunctionMarker: 'static, S, E>(
832        &mut self,
833        system: S,
834    ) -> &mut Self
835    where
836        S: SystemParamFunction<FunctionMarker, In = (), Out = Result<(), E>>
837            + Clone
838            + Send
839            + Sync
840            + 'static,
841        S::Param: SupportedSystemParamTuple,
842        E: fmt::Display + 'static,
843    {
844        self.add_fallible_system(Stage::FrameUpdate, system)
845    }
846
847    /// Registers a recreatable System in explicit execution order.
848    ///
849    /// The supplied function or closure must be cloneable because every World
850    /// generation receives a fresh Bevy System instance.
851    /// Captured values shared through interior mutability remain external to a
852    /// candidate and therefore are not rolled back when preparation fails.
853    ///
854    /// Only the managed parameter set documented by
855    /// [`SupportedSystemParamTuple`] is accepted. In particular, raw Bevy
856    /// `Query` or `Single`, raw `Entity`, Bevy `Commands`, raw World access,
857    /// `Local<T>`, and arbitrary custom SystemParams are rejected at compile
858    /// time instead of running their initialization code against a candidate.
859    pub fn add_system<FunctionMarker: 'static, S>(&mut self, stage: Stage, system: S) -> &mut Self
860    where
861        S: SystemParamFunction<FunctionMarker, In = (), Out = ()> + Clone + Send + Sync + 'static,
862        S::Param: SupportedSystemParamTuple,
863    {
864        register_system_events::<S::Param>(&mut self.events);
865        if stage != Stage::Startup {
866            register_system_application_resources::<S::Param>(
867                &mut self.application_resources,
868                stage,
869                std::any::type_name::<S>(),
870            );
871        }
872        match stage {
873            Stage::Startup => self.startup.add(system),
874            Stage::FixedUpdate => self.fixed.add(system),
875            Stage::FrameUpdate => self.frame.add(system),
876        }
877        self
878    }
879
880    /// Registers a recreatable System that can stop its stage with an error.
881    ///
882    /// Returning `Err` skips the remaining Systems in the current stage and
883    /// discards every [`crate::commands::LogicCommands`] operation queued by
884    /// that stage. It is not a transaction: direct component and Resource
885    /// mutations performed before the error remain in an active World. On a
886    /// failed fixed tick, the runtime restores only the previous interpolation
887    /// endpoints; current [`Transform2d`] and [`ActiveCamera2d`] values remain
888    /// mutated.
889    ///
890    /// A Startup error instead discards the complete isolated World candidate.
891    /// The error is formatted only on the failing path and is exposed through
892    /// [`crate::system::SystemRunFailure`]. Panics are outside this typed error
893    /// contract.
894    ///
895    /// The same parameter and recreation restrictions as [`Self::add_system`]
896    /// apply.
897    pub fn add_fallible_system<FunctionMarker: 'static, S, E>(
898        &mut self,
899        stage: Stage,
900        system: S,
901    ) -> &mut Self
902    where
903        S: SystemParamFunction<FunctionMarker, In = (), Out = Result<(), E>>
904            + Clone
905            + Send
906            + Sync
907            + 'static,
908        S::Param: SupportedSystemParamTuple,
909        E: fmt::Display + 'static,
910    {
911        register_system_events::<S::Param>(&mut self.events);
912        if stage != Stage::Startup {
913            register_system_application_resources::<S::Param>(
914                &mut self.application_resources,
915                stage,
916                std::any::type_name::<S>(),
917            );
918        }
919        match stage {
920            Stage::Startup => self.startup.add_fallible(system),
921            Stage::FixedUpdate => self.fixed.add_fallible(system),
922            Stage::FrameUpdate => self.frame.add_fallible(system),
923        }
924        self
925    }
926
927    /// Freezes the registries, prepares `initial`, and creates the shared
928    /// headless runtime core.
929    pub fn build_headless(
930        self,
931        initial: WorldFactoryId,
932    ) -> Result<HeadlessRunner<A>, RunnerBuildError> {
933        HeadlessRunner::from_application(self, initial)
934    }
935
936    /// Runs the one-window desktop adapter until the window closes or a System
937    /// commits [`crate::commands::LogicCommands::request_exit`].
938    ///
939    /// Call this on the process main thread. Platform event-loop rules may
940    /// permit creating only one event loop for the lifetime of the process.
941    #[cfg(feature = "desktop")]
942    pub fn run_desktop(
943        self,
944        initial: WorldFactoryId,
945        config: crate::desktop::DesktopConfig,
946    ) -> Result<crate::desktop::DesktopRunReport, crate::desktop::DesktopRunError> {
947        crate::desktop::run(self, initial, config)
948    }
949
950    /// Runs one desktop window with the default title, size, and VSync mode
951    /// until the window closes or a System requests exit.
952    ///
953    /// Call this on the process main thread. Platform event-loop rules may
954    /// permit creating only one event loop for the lifetime of the process.
955    #[cfg(feature = "desktop")]
956    pub fn run(
957        self,
958        initial: WorldFactoryId,
959    ) -> Result<crate::desktop::DesktopRunReport, crate::desktop::DesktopRunError> {
960        self.run_desktop(initial, crate::desktop::DesktopConfig::default())
961    }
962}
963
964#[cfg(test)]
965mod tests {
966    use super::{
967        AppConfig, AppConfigError, Application, DEFAULT_APPLICATION_RESOURCE_LIMIT,
968        DEFAULT_EVENT_LIMIT,
969    };
970    use crate::input::{DigitalAxis2d, PhysicalKeyCode};
971
972    #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
973    enum BindingAction {
974        Left,
975        Right,
976        Down,
977        Up,
978        Other,
979    }
980
981    #[test]
982    fn event_limit_is_positive_and_rejected_updates_are_atomic() {
983        let mut config = AppConfig::default();
984        assert_eq!(config.event_limit(), DEFAULT_EVENT_LIMIT);
985        assert!(matches!(
986            config.set_event_limit(0),
987            Err(AppConfigError::ZeroEventLimit)
988        ));
989        assert_eq!(config.event_limit(), DEFAULT_EVENT_LIMIT);
990        assert!(config.set_event_limit(7).is_ok());
991        assert_eq!(config.event_limit(), 7);
992    }
993
994    #[test]
995    fn application_resource_limit_is_positive_and_rejected_updates_are_atomic() {
996        let mut config = AppConfig::default();
997        assert_eq!(
998            config.application_resource_limit(),
999            DEFAULT_APPLICATION_RESOURCE_LIMIT
1000        );
1001        assert!(matches!(
1002            config.set_application_resource_limit(0),
1003            Err(AppConfigError::ZeroApplicationResourceLimit)
1004        ));
1005        assert_eq!(
1006            config.application_resource_limit(),
1007            DEFAULT_APPLICATION_RESOURCE_LIMIT
1008        );
1009        assert!(config.set_application_resource_limit(7).is_ok());
1010        assert_eq!(config.application_resource_limit(), 7);
1011    }
1012
1013    #[test]
1014    fn public_combined_binding_does_not_install_wasd_before_an_arrow_conflict() {
1015        let axis = DigitalAxis2d::new(
1016            BindingAction::Left,
1017            BindingAction::Right,
1018            BindingAction::Down,
1019            BindingAction::Up,
1020        );
1021        let mut application = Application::new(AppConfig::default()).unwrap();
1022        assert!(
1023            application
1024                .bind_key(PhysicalKeyCode::ArrowLeft, BindingAction::Other)
1025                .is_ok()
1026        );
1027        assert!(
1028            application
1029                .bind_key(PhysicalKeyCode::Escape, BindingAction::Other)
1030                .is_ok()
1031        );
1032
1033        let combined_error = match application.bind_wasd_and_arrows(axis) {
1034            Ok(_) => panic!("occupied arrow should reject the combined preset"),
1035            Err(error) => error,
1036        };
1037        assert_eq!(combined_error.key(), PhysicalKeyCode::ArrowLeft);
1038        assert!(
1039            application
1040                .bind_key(PhysicalKeyCode::KeyW, BindingAction::Up)
1041                .is_ok()
1042        );
1043        let escape_error = match application.bind_key(PhysicalKeyCode::Escape, BindingAction::Up) {
1044            Ok(_) => panic!("the unrelated Escape binding should remain installed"),
1045            Err(error) => error,
1046        };
1047        assert_eq!(escape_error.key(), PhysicalKeyCode::Escape);
1048    }
1049}