Expand description
Statecharts for Bevy, built out of ordinary entities.
A machine is an entity hierarchy: the root carries StateMachine, every
state is an entity linked to its parent by SubstateOf / Substates,
and every transition is an entity linked to its source by Source /
Transitions with a Target. Author a whole chart as one bsn! scene:
use bevy::prelude::*;
use bevy::scene::prelude::{bsn, CommandsSceneExt};
use bevy_gearbox::prelude::*;
#[derive(Message, Clone, Reflect, GearboxMessage)]
struct Fire {
#[gearbox(target)]
machine: Entity,
}
fn spawn(mut commands: Commands) {
commands.spawn_scene(bsn! {
StateMachine InitialState(#Ready)
Substates [
#Ready Transitions [ (Target(#Cooldown) MessageEdge::<Fire>) ],
#Cooldown Transitions [ (Target(#Ready) AlwaysEdge Delay::from_secs_f32(0.8)) ],
]
});
}
App::new()
.add_plugins((DefaultPlugins, GearboxPlugin::default()))
.add_systems(Startup, spawn)
.run();Transitions fire in response to Bevy messages (GearboxMessage), on entry
(AlwaysEdge), after a Delay, or when a TerminalState finishes.
Guards are marker components on edges plus systems in
GearboxPhase::BlockerPhase (InState and NotInState are built
in); several edges for one trigger are tried in Transitions order and
the first survivor wins. React to state changes
with Added<Active> queries, EnterState / ExitState observers, or a
StateComponent that mirrors a state onto the machine root.
Resolution runs in GearboxSchedule, looped each frame until no work
remains, so message-driven cascades settle within the frame they start.
The guide
walks through every feature with a worked example. The server feature
adds [server::ServerPlugin], which lets the visual editor connect to a
running game; it is off by default because it pulls in an HTTP server.
Modules§
- __bevy
- Bevy Logo
- commands
- components
- core
- The core crate, re-exported whole for paths that want to be explicit.
- delay
- guards
- Built-in guards. A guard is a component on an edge plus a system in
BlockerPhasethat vetoes the candidates carrying it; seeTransitionMessage. - helpers
- history
- inventory
- github crates-io docs-rs
- messages
- prelude
- Common imports: the core prelude plus the gearbox derive/attribute macros.
- registration
- resolve
- state_
component
Structs§
- Accept
All - Default validator that accepts all messages.
- Active
- Marker inserted on state entities that are currently active.
- Always
Edge - Marker: this edge fires automatically when its source is active.
- Blocked
Edges - Set of edge entities whose
TransitionMessageended this iterationblocked, either vetoed by a blocker system or beaten by a better-ranked candidate in the same group. Populated by [select_transitions] afterBlockerPhase. Side-effect systems check this to skip theMatchedmessages of transitions that will not be applied. - Candidate
Groups - Hands out
TransitionMessage::groupids to edge-detection systems. - Delay
- Delayed transition: fire after
durationelapses while the source is active. - Done
- Emitted when a state finishes: a
TerminalStatewas entered, so its parent is done, or every region of a parallel state is in a final state. Addressed to the finished state, so only aMessageEdge<Done>on that state (or below it) can fire. - Edge
Timer - Active timer for a delayed edge. Created when the source state is entered
(or, for a delayed
MessageEdge, when its message first matches) and removed when the source is exited. Ticked once per frame before the schedule loop; elapsed timers are proposed as transition candidates in the first iteration’s edge detection. - Enter
State - Triggered on a state entity when it is entered, inside the schedule loop
in
EntryPhase. Ancestors are entered before their descendants. UseOn<EnterState>observers on state entities to react. - Exit
State - Triggered on a state entity when it is exited, inside the schedule loop in
ExitPhase. Descendants are exited before their ancestors. UseOn<ExitState>observers on state entities to react. - Gearbox
Plugin - State machine plugin. By default the driver systems (machine init,
delay timers, schedule runner) are added to
Update. Usescheduleto run them in a different schedule (e.g.FixedPreUpdatefor deterministic simulation). - Gearbox
Schedule - The schedule that resolves state machine transitions. Runs N times per
frame inside [
run_gearbox_schedule]. - Gearbox
Set - System set in
Updatethat contains the gearbox schedule runner. Use this for ordering user systems relative to gearbox resolution: - History
State - Stores the previously active states for history restoration.
Automatically managed by
resolve_transitions. - InState
- Guard: the edge is taken only while the named state is active (the XState
stateInguard). Coordinates parallel regions, e.g. an edge in the weapon region that requiresInState(#Standing)in the posture region. Vetoed bycheck_state_guardsinBlockerPhase. - Initial
State - Which child state to enter by default when a parent state is entered.
- Installed
State Bridges - Deduplication resource for registered Bevy
Statesbridges. - Installed
State Components - Deduplication resource for registered state components.
- Installed
Transitions - Deduplication resource for registered message types.
- Iteration
Cap - Maximum number of iterations the schedule will run per frame. If hit, a warning is logged — this likely indicates a transition loop.
- Matched
- Written by
message_edge_listenerfor every edge that matches a message of typeMand is proposed as aTransitionMessagecandidate. Carries the original message along with the transition context. - Message
Edge - Attach to a transition edge to make it react to messages of type
M. - NotIn
State - Guard: the edge is taken only while the named state is inactive. The
complement of
InState. - Reset
Edge - Marker to request reset of subtree(s) when an edge fires.
- Source
- Source state of a transition edge.
- State
Component - When added to a state entity, inserts
Ton the machine root when this state is entered and removes it when this state is exited. - State
Inactive Component - When added to a state entity, removes
Tfrom the machine root when this state is entered and restores the stored clone when this state is exited. - State
Machine - Marks an entity as a state machine root and tracks active states.
- State
Machine Id - Stable, human-chosen identifier for a state machine.
- Substate
Of - Relationship: this state is a substate of another.
- Substates
- Relationship target: children substates, in authored order.
- Target
- Target state of a transition edge.
- Terminal
State - Marks a state as terminal (XState “final state”). When entered, a
Donemessage is emitted targeting the parent state (viaSubstateOf). The parent can then transition out via aMessageEdge<Done>. - Transition
Builder Deprecated - Builder for always-transitions with deferred component inserts.
- Transition
Message - A pending transition, proposed by edge detection (or by machine init and
elapsed delays) and applied by [
resolve_transitions]. - Transitions
- Outbound edges from a state, in priority order.
Enums§
- Edge
Kind - Whether a transition is External (default, exits/re-enters the LCA) or Internal (stays within the source state, no exit/re-enter of the LCA).
- Gearbox
Phase - System sets within
GearboxSchedule, declared in the order they run each iteration. - History
- Enables history behavior for a state. When a state with this component is
exited and later re-entered, it restores previously active substates
instead of following
InitialState. - Reset
Scope - Which side of the transition to reset.
Traits§
- Build
Entity Event - Helper trait to build and trigger an event given a root entity.
- Build
Transition Deprecated - Extension trait for building guarded always-transitions.
- Gearbox
Commands Ext - Commands helper to interact with a state machine found by a marker component.
- Gearbox
Message - Trait implemented by user message types that can trigger state machine transitions.
- Init
State Machine Deprecated - Extension for initializing a state machine on an existing entity.
- Message
Validator - Per-edge filter that accepts or rejects a message for a specific edge.
- Registration
AppExt - Extension trait for registering message-driven transitions, state components, and bridges with the gearbox schedule.
- Spawn
Substate Deprecated - Extension trait for spawning substates with less boilerplate.
- Spawn
Transition Deprecated - Extension trait for spawning transitions.
- Transition
Ext Deprecated - Extension methods for transition entities.
Functions§
- bridge_
to_ bevy_ state - Sync gearbox state into Bevy’s
NextState<S>when a state with componentSis entered. Runs inUpdateafterGearboxSet. - check_
state_ guards - Vetoes candidates whose edge carries an
InStatenaming an inactive state, or aNotInStatenaming an active one. The configuration checked is the one the transition would leave, as with XState’sstateIn. - emit_
terminal_ done - Emits
Donewhen aTerminalStategainsActive: once for its parent, then for each parallel ancestor in turn whose every region is now in a final state (the SCXML completion rule). The cascade stops at the first ancestor that is not a completed parallel state; a sequential state finishes only through a terminal child of its own. - message_
edge_ listener - System that reads incoming messages of type
Mand proposes every matching edge on the active configuration as aTransitionMessagecandidate, plus aMatched<M>for each. - state_
component_ enter - Insert
Ton the machine root when a state withStateComponent<T>is entered. - state_
component_ exit - Remove
Tfrom the machine root when a state withStateComponent<T>is exited. - state_
inactive_ component_ enter - Remove
Tfrom the machine root when a state withStateInactiveComponent<T>is entered. - state_
inactive_ component_ exit - Restore
Ton the machine root when a state withStateInactiveComponent<T>is exited.
Attribute Macros§
- state_
bridge - Attribute macro that registers a Bevy
Statestype to be driven by a gearbox state carrying it as a component, viainventory. - state_
component - Attribute macro that registers a type for use in
StateComponent<T>/StateInactiveComponent<T>viainventory.
Derive Macros§
- Gearbox
Message - Derive macro that implements
GearboxMessagefor a message struct and registers it withGearboxPluginviainventory.