Skip to main content

Application

Struct Application 

Source
pub struct Application<A: Action> { /* private fields */ }
Expand description

Mutable pre-startup builder for one typed Sim;Logic application.

Implementations§

Source§

impl<A: Action> Application<A>

Source

pub fn new(config: AppConfig) -> Result<Self, ApplicationCreationError>

Creates an application builder and approves Sim;Logic’s standard world and screen visual, collision, motion, and disabled components, including their complete required-component closure.

Source

pub fn approve_component<T: Component>( &mut self, ) -> Result<&mut Self, ComponentApprovalError>

Approves one hook-free component type for candidate and command bundles.

Source

pub fn register_image_rgba8( &mut self, width: u32, height: u32, pixels: &[u8], ) -> Result<ImageAssetId, ImageAssetError>

Registers immutable straight-alpha sRGB RGBA8 pixels before startup.

Copies exactly one row-major image after validating dimensions, byte length, and configured asset limits. A failed registration publishes no handle or pixel entry. Handles belong only to this Application, survive World replacement, and are not persistent file identifiers. Registering identical pixels twice creates two distinct resources. No GPU or file decoder is involved; normal frames never copy these pixels again on the CPU side. GPU preparation retains its own recovery copy when needed.

Source

pub fn register_font( &mut self, bytes: Vec<u8>, settings: TextSettings, ) -> Result<TextFont, TextError>

Registers an owned trusted TTF/OTF asset and fixed logical text settings.

Parsing and limits are checked before publishing an opaque font handle; equal registrations remain distinct. Clones share font storage and the handle survives World replacement. No window, GPU call, font discovery, or download occurs. The caller supplies licensed, trusted font bytes.

Source

pub fn register_font_style( &mut self, source: &TextFont, settings: TextSettings, ) -> Result<TextFont, TextError>

Registers another size/direction/layout configuration sharing an existing font’s parsed face and source bytes. No file copy, reparse, or GPU work occurs.

The source must belong to this application. The new style has its own registration/atlas identity, consumes one font-count slot, and charges zero additional source bytes. Per-style atlas/run budgets remain independent. Failure preserves the registry. A source style can also share its face onward.

Source

pub fn approve_components<T: ComponentTuple>( &mut self, ) -> Result<&mut Self, ComponentApprovalError>

Approves a flat tuple of one through fifteen hook-free component types.

The registry update is atomic: if one tuple member is rejected, types newly added by this call are removed again. Components that were already approved before the call remain approved. Required components must still be listed explicitly, in any order, and are checked when the application creates a World candidate.

Source

pub fn bind_key( &mut self, key: PhysicalKeyCode, action: A, ) -> Result<&mut Self, DuplicateKeyBinding>

Binds one portable physical key to a typed action.

Source

pub fn bind_mouse_button( &mut self, button: MouseButton, action: A, ) -> Result<&mut Self, DuplicateMouseBinding>

Binds one portable mouse button to a typed action without replacing an existing binding. Bindings freeze when the application is started.

Mouse buttons and keys may share an action: it remains held until all bound physical controls release. Their individual edges remain distinct.

Source

pub fn bind_wasd( &mut self, axis: DigitalAxis2d<A>, ) -> Result<&mut Self, DuplicateKeyBinding>

Atomically binds W/A/S/D to one typed two-dimensional action axis.

W maps to positive y, A to negative x, S to negative y, and D to positive x. All four physical keys are checked first in W/A/S/D order. If any is already bound, that binding is reported and the complete table remains unchanged. Repeating one logical action in several axis slots is allowed, matching DigitalAxis2d sampling semantics.

Source

pub fn bind_arrows( &mut self, axis: DigitalAxis2d<A>, ) -> Result<&mut Self, DuplicateKeyBinding>

Atomically binds the physical arrow keys to one typed action axis.

Left maps to negative x, Right to positive x, Down to negative y, and Up to positive y. All four keys are checked first in that order. If any is already bound, that binding is reported and the complete table remains unchanged. The same axis may be bound to both arrows and W/A/S/D.

Source

pub fn bind_wasd_and_arrows( &mut self, axis: DigitalAxis2d<A>, ) -> Result<&mut Self, DuplicateKeyBinding>

Atomically binds W/A/S/D and the arrow keys to one typed action axis.

The mappings match Application::bind_wasd and Application::bind_arrows. All eight keys are checked before any binding is written, in W, A, S, D, Left, Right, Down, Up order. If any key is already bound, that binding is reported and the complete table remains unchanged. Calling this method again reports W as the first conflict. Use the separate presets when only one key family should be accepted.

Source

pub fn register_app_resource<T: Send + Sync + 'static>( &mut self, resource: T, ) -> Result<&mut Self, ApplicationResourceError>

Registers one typed value owned by the Application rather than a World.

The value becomes available through crate::resources::AppRes and crate::resources::AppResMut in FixedUpdate and FrameUpdate, and the same value survives successful World replacement without cloning. Candidate factories and Startup systems cannot access it.

Registration is explicit, accepts at most one value of each concrete type, and is bounded by AppConfig::set_application_resource_limit. A duplicate returns ApplicationResourceError::Duplicate and keeps the first value; registration never means replacement. T needs no Bevy Resource derive.

use sim_logic::prelude::*;

#[derive(Clone, Copy, PartialEq, Eq, Hash)]
enum Action {}

#[derive(Default)]
struct SessionScore(u32);

fn award(mut score: AppResMut<SessionScore>) {
    score.0 = score.0.saturating_add(1);
}

let mut app = Application::<Action>::new(AppConfig::default())?;
app.register_app_resource(SessionScore::default())?;
app.add_system(Stage::FixedUpdate, award);
Source

pub fn register_world( &mut self, diagnostic_name: impl Into<String>, factory: impl Fn(&mut WorldBuilder) -> Result<(), WorldBuildError> + Send + Sync + 'static, ) -> Result<WorldFactoryId, WorldRegistrationError>

Registers one repeatable synchronous no-payload World factory.

A factory is a restricted construction recipe, not an effect callback. It must derive the same candidate from its immutable captures, mutate only the supplied WorldBuilder, and finish before returning. It must not perform I/O, start background work, or mutate shared external state. The runtime can discard an isolated candidate, but it cannot roll back effects performed outside that candidate.

Source

pub fn add_fixed_system<FunctionMarker: 'static, S>( &mut self, system: S, ) -> &mut Self
where S: SystemParamFunction<FunctionMarker, In = (), Out = ()> + Clone + Send + Sync + 'static, S::Param: SupportedSystemParamTuple,

Registers an infallible System in the FixedUpdate stage.

This is the short form of add_system(Stage::FixedUpdate, system). Both forms append to the same ordered stage list.

Source

pub fn add_fallible_fixed_system<FunctionMarker: 'static, S, E>( &mut self, system: S, ) -> &mut Self
where S: SystemParamFunction<FunctionMarker, In = (), Out = Result<(), E>> + Clone + Send + Sync + 'static, S::Param: SupportedSystemParamTuple, E: Display + 'static,

Registers a fallible System in the FixedUpdate stage.

This is the short form of add_fallible_system(Stage::FixedUpdate, system). Both forms append to the same ordered stage list and use the same failure semantics.

Source

pub fn add_world_replacement_on_press_system(&mut self) -> &mut Self

Appends the standard fixed-press World-replacement System.

In a World containing WorldReplacementOnPress<A>, every matching press occurrence queues one ordinary deferred replacement request with that edge’s original causal token. A World without the Resource, or a fixed tick without a matching press, is a successful no-op. Physical key bindings remain explicit and the Resource is inert until this method is called. Presses received while fixed simulation is paused are frame-only input and are not replayed through this adapter on unpause.

The adapter runs at this exact point in FixedUpdate registration order. Later Systems in the same tick still run before the stage barrier. An accepted replacement then follows the existing arbitration, candidate preparation, lifecycle, catch-up stopping, input consumption, and same-frame extraction rules. Every occurrence consumes one command slot. Each duplicate registration runs at its own position and consumes another slot. If no intervening System changes the route, the repeated token and target coalesce idempotently; otherwise ordinary arbitration decides the differently routed requests.

This helper provides one unconditional route per World. It does not bind a key, observe held or release state, request application exit, build a route table, attach a payload, or add a FrameUpdate counterpart.

Source

pub fn add_linear_acceleration2d_system(&mut self) -> &mut Self

Appends the standard fixed-step linear-acceleration System.

Each enabled managed entity with LinearAcceleration2d changes its LinearVelocity2d by acceleration * fixed_delta at this exact point in registration order. The component is inert until this method is called. Exact zero acceleration is a no-op before arithmetic. Calling this method twice applies acceleration twice per fixed tick.

Register this before Self::add_linear_velocity2d_system for semi-implicit Euler motion. Reversing the calls deliberately moves with the old velocity before updating it for the next step. Direct component writes by earlier Systems are visible; deferred spawn or insert Commands first accelerate on a later fixed tick. Arithmetic overflow leaves the failing entity’s velocity unchanged; entities processed earlier by the same System may already have changed under ordinary non-transactional fallible-System semantics.

This adapter does not represent force or mass, move a Transform itself, or apply gravity, drag, collision response, rotation, or world bounds.

Source

pub fn add_linear_velocity2d_system(&mut self) -> &mut Self

Appends the standard fixed-step linear-velocity System.

Each enabled managed entity with LinearVelocity2d moves by velocity * fixed_delta at this exact point in registration order. The component itself is inert until this method is called. Calling the method twice appends two Systems and therefore integrates twice per fixed tick, just like registering an ordinary System twice.

Direct component writes by earlier Systems are visible to this System, and later Systems observe the integrated translation. Deferred spawn or insert Commands become visible only after the stage barrier, so newly moving entities first integrate on a later fixed tick. Arithmetic overflow follows normal fallible-System semantics and may leave earlier entities in the same query already moved.

This adapter does not apply acceleration, forces, collision response, rotation, drag, or world bounds.

Source

pub fn add_digital_movement2d_system(&mut self) -> &mut Self

Appends the standard fixed-step digital-movement System.

Each enabled managed entity with DigitalMovement2d<A> samples its typed axis, normalizes the direction, and moves by speed * fixed_delta at this exact point in registration order. The component is inert until this method is called, and physical keys must be bound separately. Calling the method twice appends two Systems and moves twice per tick.

Direct component writes by earlier Systems are visible here; later Systems observe the integrated translation. Deferred spawn or insert Commands become visible only after the stage barrier. If this and the linear-velocity adapter are both registered, their Transform writes compose in explicit registration order. Idle or exactly opposed input is a no-op before speed/time multiplication; active arithmetic overflow follows ordinary fallible-System semantics.

This adapter does not apply collision response, acceleration, facing, analog input, smoothing, or world bounds.

Source

pub fn add_camera_follow2d_system(&mut self) -> &mut Self

Appends the standard fixed-step camera-follow System.

With no enabled CameraFollowTarget2d, this System is a successful no-op so other Worlds in the application need no follow target. With exactly one target and one enabled ActiveCamera2d, it replaces the canonical camera center with target translation + camera offset at this exact point in registration order. More than one target fails the stage before changing a camera. Missing or duplicate active cameras are left unchanged for the extraction validator and its repair path.

Register this after target movement for same-tick following, or before movement to deliberately use the previous target position. Deferred spawn or insert Commands first affect following on a later fixed tick; Disabled targets are ignored. Arithmetic overflow leaves the camera unchanged. Duplicate registration performs another ordinary assignment and can observe writes placed between the two adapters.

The adapter does not run during World preparation, create or initially align a camera, infer teleports, smooth motion, clamp bounds, change zoom or rotation, or choose among multiple targets.

Source

pub fn add_frame_system<FunctionMarker: 'static, S>( &mut self, system: S, ) -> &mut Self
where S: SystemParamFunction<FunctionMarker, In = (), Out = ()> + Clone + Send + Sync + 'static, S::Param: SupportedSystemParamTuple,

Registers an infallible System in the FrameUpdate stage.

This is the short form of add_system(Stage::FrameUpdate, system). Both forms append to the same ordered stage list.

Source

pub fn add_fallible_frame_system<FunctionMarker: 'static, S, E>( &mut self, system: S, ) -> &mut Self
where S: SystemParamFunction<FunctionMarker, In = (), Out = Result<(), E>> + Clone + Send + Sync + 'static, S::Param: SupportedSystemParamTuple, E: Display + 'static,

Registers a fallible System in the FrameUpdate stage.

This is the short form of add_fallible_system(Stage::FrameUpdate, system). Both forms append to the same ordered stage list and use the same failure semantics.

Source

pub fn add_system<FunctionMarker: 'static, S>( &mut self, stage: Stage, system: S, ) -> &mut Self
where S: SystemParamFunction<FunctionMarker, In = (), Out = ()> + Clone + Send + Sync + 'static, S::Param: SupportedSystemParamTuple,

Registers a recreatable System in explicit execution order.

The supplied function or closure must be cloneable because every World generation receives a fresh Bevy System instance. Captured values shared through interior mutability remain external to a candidate and therefore are not rolled back when preparation fails.

Only the managed parameter set documented by SupportedSystemParamTuple is accepted. In particular, raw Bevy Query or Single, raw Entity, Bevy Commands, raw World access, Local<T>, and arbitrary custom SystemParams are rejected at compile time instead of running their initialization code against a candidate.

Source

pub fn add_fallible_system<FunctionMarker: 'static, S, E>( &mut self, stage: Stage, system: S, ) -> &mut Self
where S: SystemParamFunction<FunctionMarker, In = (), Out = Result<(), E>> + Clone + Send + Sync + 'static, S::Param: SupportedSystemParamTuple, E: Display + 'static,

Registers a recreatable System that can stop its stage with an error.

Returning Err skips the remaining Systems in the current stage and discards every crate::commands::LogicCommands operation queued by that stage. It is not a transaction: direct component and Resource mutations performed before the error remain in an active World. On a failed fixed tick, the runtime restores only the previous interpolation endpoints; current Transform2d and ActiveCamera2d values remain mutated.

A Startup error instead discards the complete isolated World candidate. The error is formatted only on the failing path and is exposed through crate::system::SystemRunFailure. Panics are outside this typed error contract.

The same parameter and recreation restrictions as Self::add_system apply.

Source

pub fn build_headless( self, initial: WorldFactoryId, ) -> Result<HeadlessRunner<A>, RunnerBuildError>

Freezes the registries, prepares initial, and creates the shared headless runtime core.

Source

pub fn run_desktop( self, initial: WorldFactoryId, config: DesktopConfig, ) -> Result<DesktopRunReport, DesktopRunError>

Runs the one-window desktop adapter until the window closes or a System commits crate::commands::LogicCommands::request_exit.

Call this on the process main thread. Platform event-loop rules may permit creating only one event loop for the lifetime of the process.

Source

pub fn run( self, initial: WorldFactoryId, ) -> Result<DesktopRunReport, DesktopRunError>

Runs one desktop window with the default title, size, and VSync mode until the window closes or a System requests exit.

Call this on the process main thread. Platform event-loop rules may permit creating only one event loop for the lifetime of the process.

Auto Trait Implementations§

§

impl<A> !RefUnwindSafe for Application<A>

§

impl<A> !Sync for Application<A>

§

impl<A> !UnwindSafe for Application<A>

§

impl<A> Freeze for Application<A>
where ActionBindings<A>: Freeze,

§

impl<A> Send for Application<A>
where ActionBindings<A>: Send,

§

impl<A> Unpin for Application<A>
where ActionBindings<A>: Unpin,

§

impl<A> UnsafeUnpin for Application<A>
where ActionBindings<A>: UnsafeUnpin,

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<T> ConditionalSend for T
where T: Send,

Source§

impl<T> Downcast for T
where T: Any,

Source§

fn into_any(self: Box<T>) -> Box<dyn Any>

Convert Box<dyn Trait> (where Trait: Downcast) to Box<dyn Any>. Box<dyn Any> can then be further downcast into Box<ConcreteType> where ConcreteType implements Trait.
Source§

fn into_any_rc(self: Rc<T>) -> Rc<dyn Any>

Convert Rc<Trait> (where Trait: Downcast) to Rc<Any>. Rc<Any> can then be further downcast into Rc<ConcreteType> where ConcreteType implements Trait.
Source§

fn as_any(&self) -> &(dyn Any + 'static)

Convert &Trait (where Trait: Downcast) to &Any. This is needed since Rust cannot generate &Any’s vtable from &Trait’s.
Source§

fn as_any_mut(&mut self) -> &mut (dyn Any + 'static)

Convert &mut Trait (where Trait: Downcast) to &Any. This is needed since Rust cannot generate &mut Any’s vtable from &mut Trait’s.
Source§

impl<T> Downcast<T> for T

Source§

fn downcast(&self) -> &T

Source§

impl<S, T> Duplex<S> for T
where T: FromSample<S> + ToSample<S>,

Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<S> FromSample<S> for S

Source§

fn from_sample_(s: S) -> S

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self> ⓘ

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self> ⓘ

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoResult<T> for T

Source§

fn into_result(self) -> Result<T, RunSystemError>

Converts this type into the system output type.
Source§

impl<T> Read<Exclusive, BecauseExclusive> for T
where T: ?Sized,

Source§

impl<T, U> ToSample<U> for T
where U: FromSample<T>,

Source§

fn to_sample_(self) -> U

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> Upcast<T> for T

Source§

fn upcast(&self) -> Option<&T>

Source§

impl<T> WasmNotSend for T
where T: Send,

Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more