Skip to main content

Crate bevy_gearbox

Crate bevy_gearbox 

Source
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 BlockerPhase that vetoes the candidates carrying it; see TransitionMessage.
helpers
history
inventory
githubcrates-iodocs-rs
messages
prelude
Common imports: the core prelude plus the gearbox derive/attribute macros.
registration
resolve
state_component

Structs§

AcceptAll
Default validator that accepts all messages.
Active
Marker inserted on state entities that are currently active.
AlwaysEdge
Marker: this edge fires automatically when its source is active.
BlockedEdges
Set of edge entities whose TransitionMessage ended this iteration blocked, either vetoed by a blocker system or beaten by a better-ranked candidate in the same group. Populated by [select_transitions] after BlockerPhase. Side-effect systems check this to skip the Matched messages of transitions that will not be applied.
CandidateGroups
Hands out TransitionMessage::group ids to edge-detection systems.
Delay
Delayed transition: fire after duration elapses while the source is active.
Done
Emitted when a state finishes: a TerminalState was 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 a MessageEdge<Done> on that state (or below it) can fire.
EdgeTimer
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.
EnterState
Triggered on a state entity when it is entered, inside the schedule loop in EntryPhase. Ancestors are entered before their descendants. Use On<EnterState> observers on state entities to react.
ExitState
Triggered on a state entity when it is exited, inside the schedule loop in ExitPhase. Descendants are exited before their ancestors. Use On<ExitState> observers on state entities to react.
GearboxPlugin
State machine plugin. By default the driver systems (machine init, delay timers, schedule runner) are added to Update. Use schedule to run them in a different schedule (e.g. FixedPreUpdate for deterministic simulation).
GearboxSchedule
The schedule that resolves state machine transitions. Runs N times per frame inside [run_gearbox_schedule].
GearboxSet
System set in Update that contains the gearbox schedule runner. Use this for ordering user systems relative to gearbox resolution:
HistoryState
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 stateIn guard). Coordinates parallel regions, e.g. an edge in the weapon region that requires InState(#Standing) in the posture region. Vetoed by check_state_guards in BlockerPhase.
InitialState
Which child state to enter by default when a parent state is entered.
InstalledStateBridges
Deduplication resource for registered Bevy States bridges.
InstalledStateComponents
Deduplication resource for registered state components.
InstalledTransitions
Deduplication resource for registered message types.
IterationCap
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_listener for every edge that matches a message of type M and is proposed as a TransitionMessage candidate. Carries the original message along with the transition context.
MessageEdge
Attach to a transition edge to make it react to messages of type M.
NotInState
Guard: the edge is taken only while the named state is inactive. The complement of InState.
ResetEdge
Marker to request reset of subtree(s) when an edge fires.
Source
Source state of a transition edge.
StateComponent
When added to a state entity, inserts T on the machine root when this state is entered and removes it when this state is exited.
StateInactiveComponent
When added to a state entity, removes T from the machine root when this state is entered and restores the stored clone when this state is exited.
StateMachine
Marks an entity as a state machine root and tracks active states.
StateMachineId
Stable, human-chosen identifier for a state machine.
SubstateOf
Relationship: this state is a substate of another.
Substates
Relationship target: children substates, in authored order.
Target
Target state of a transition edge.
TerminalState
Marks a state as terminal (XState “final state”). When entered, a Done message is emitted targeting the parent state (via SubstateOf). The parent can then transition out via a MessageEdge<Done>.
TransitionBuilderDeprecated
Builder for always-transitions with deferred component inserts.
TransitionMessage
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§

EdgeKind
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).
GearboxPhase
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.
ResetScope
Which side of the transition to reset.

Traits§

BuildEntityEvent
Helper trait to build and trigger an event given a root entity.
BuildTransitionDeprecated
Extension trait for building guarded always-transitions.
GearboxCommandsExt
Commands helper to interact with a state machine found by a marker component.
GearboxMessage
Trait implemented by user message types that can trigger state machine transitions.
InitStateMachineDeprecated
Extension for initializing a state machine on an existing entity.
MessageValidator
Per-edge filter that accepts or rejects a message for a specific edge.
RegistrationAppExt
Extension trait for registering message-driven transitions, state components, and bridges with the gearbox schedule.
SpawnSubstateDeprecated
Extension trait for spawning substates with less boilerplate.
SpawnTransitionDeprecated
Extension trait for spawning transitions.
TransitionExtDeprecated
Extension methods for transition entities.

Functions§

bridge_to_bevy_state
Sync gearbox state into Bevy’s NextState<S> when a state with component S is entered. Runs in Update after GearboxSet.
check_state_guards
Vetoes candidates whose edge carries an InState naming an inactive state, or a NotInState naming an active one. The configuration checked is the one the transition would leave, as with XState’s stateIn.
emit_terminal_done
Emits Done when a TerminalState gains Active: 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 M and proposes every matching edge on the active configuration as a TransitionMessage candidate, plus a Matched<M> for each.
state_component_enter
Insert T on the machine root when a state with StateComponent<T> is entered.
state_component_exit
Remove T from the machine root when a state with StateComponent<T> is exited.
state_inactive_component_enter
Remove T from the machine root when a state with StateInactiveComponent<T> is entered.
state_inactive_component_exit
Restore T on the machine root when a state with StateInactiveComponent<T> is exited.

Attribute Macros§

state_bridge
Attribute macro that registers a Bevy States type to be driven by a gearbox state carrying it as a component, via inventory.
state_component
Attribute macro that registers a type for use in StateComponent<T> / StateInactiveComponent<T> via inventory.

Derive Macros§

GearboxMessage
Derive macro that implements GearboxMessage for a message struct and registers it with GearboxPlugin via inventory.