Introduction
Bevy Mod Scripting
Script your Bevy game: hot-reloadable Lua & Rune with full ECS access
BMS (bevy_mod_scripting) runs Lua and Rune scripts inside a Bevy app. Scripts reach the world through reflection, so any Reflect type, including ones from other crates, can be used from scripts without writing glue code.
- Update game logic without recompiling, with hot reloading of script assets
- Let modders add content through the same bindings your own scripts use
- Bindings are written once in Rust and work in every supported language
- Scripts can add their own systems, components and events
- Generated docs and Lua language server definitions for your bindings
How a script runs
Loading a script asset runs nothing. A script runs code when it is attached, reloaded or detached, which the script pipeline handles, and when one of its callbacks is invoked by name. The schedule each one runs in is in italics.
flowchart TB
COMP(["ScriptComponent added / removed"]) -- "<i>PreUpdate</i>" --> PIPE[["script pipeline"]]
CMDS(["AttachScript / DetachScript"]) -- "<i>immediately</i>" --> PIPE
PIPE --> LIVE((attached))
subgraph CALLBACKS ["callbacks, run by name"]
direction LR
EH["event_handler<br/><i>your schedule</i>"] ~~~ CMD["RunScriptCallback<br/><i>on command flush</i>"] ~~~ SYS["script systems<br/><i>their schedule</i>"]
OBS["observers<br/><i>on trigger</i>"] ~~~ OTHER["other scripts<br/><i>immediately or queued</i>"]
end
LIVE <--> CALLBACKS
LIVE -. "asset modified, <i>PreUpdate</i>" .-> PIPE
click PIPE href "#the-script-pipeline"
The script pipeline
flowchart LR
subgraph PRE ["script pipeline"]
direction LR
A(["attached"]) --> L["context initializers<br/>top level code<br/>on_script_loaded"]
M(["asset modified"]) --> R["on_script_unloaded<br/>top level code<br/>on_script_loaded<br/>on_script_reloaded"]
D(["detached"]) --> U["on_script_unloaded<br/>context removed<br/>with its last script"]
end
- The attachment (entity + script, or a static script) is the script’s identity, see Managing Scripts. Scripts sharing a context share globals.
- Callbacks run the function passed to
register_callback, else the top level function of that name, see Running Scripts and Calling Other Scripts. on_script_*are the core callbacks.on_script_unloadedcan return state, whichon_script_reloadedreceives.- Ordering and budgeting are covered in Script Pipeline.
Where to start
| You are | Read |
|---|---|
| Adding scripting to a Bevy game | Installation, then the User Guide |
| Writing scripts or mods | The Scripting Reference |
| Upgrading BMS | The Release Notes |
| Contributing to BMS | Developing BMS |
Glossary
The key concepts of BMS. Each entry’s first paragraph is shown when hovering over the term elsewhere in the book.
Attachment
Where a script lives: pinned to an entity, or “static”, pinned to nothing. A script file only runs once attached, and the same file attached twice runs twice, so the attachment, not the file, is what callbacks target.
In Rust it is a ScriptAttachment: EntityScript(entity, handle), made by adding a ScriptComponent, or StaticScript(handle), made with the AttachScript command. See Managing Scripts.
Binding
A Rust function or type made available to scripts. Written once in Rust, bindings work in every supported language, and are documented in the generated reference.
Functions are registered with #[script_bindings] or a NamespaceBuilder, on a type or a namespace. See Controlling Script Bindings and Core Bindings.
Callback
A function in a script that BMS calls by name, like an event listener. Everything a script does after loading happens inside a callback.
A callback is the function passed to register_callback, or else the top level function with that name. Callbacks are triggered by event_handler systems, RunScriptCallback commands, script systems, observers and other scripts. See Running Scripts and Callbacks.
Callback label
The name a callback is called by, as a Rust type, so Rust code can’t misspell it.
Defined with callback_labels!(OnEvent => "on_event") and used by event_handler::<OnEvent, _> and ScriptCallbackMessages. See Running Scripts.
Context
The sandbox a script runs in, holding its global variables and functions, like a separate Lua state. Scripts in different contexts can’t see each other’s globals.
Contexts are created when scripts are attached, and removed with their last script. While one of its callbacks runs, a context is busy. See Contexts.
Context policy
The rule deciding which scripts share a context: by default each entity-script pair gets its own, at the other end all scripts share one.
Set with set_context_policy on the scripting plugin. See Contexts.
Core callbacks
The callbacks BMS calls by itself around loading: on_script_loaded, on_script_unloaded and on_script_reloaded. Use them to set up a script and to carry state across hot reloads.
See Core Callbacks.
Event handler
A Bevy system which delivers ScriptCallbackMessages with one callback label to the scripts of one language, the usual way for Rust to call scripts every frame.
Added as event_handler::<Label, Plugin> in the schedule you want the callbacks to run in. See Running Scripts.
Hot reloading
Editing a script file while the game runs, and having the new code take effect without a restart. The script’s top level code runs again in its existing context.
Needs Bevy’s file_watcher feature. on_script_unloaded can return state which on_script_reloaded receives. See Managing Scripts.
Initializer
A Rust function run on a context, or runtime, to customize it, i.e. to set globals before the script’s code runs.
Context initializers run when a context is created or reloaded, pre handling initializers before every callback, runtime initializers once. See Customizing Contexts.
LAD file
A language agnostic JSON description of every type and function scripts can use. It drives the generated reference pages and the Lua language server definitions.
See Editor Support.
Namespace
A named group of types and functions which scripts import, i.e. import_namespace("math"). Types are not globals, so namespaces keep same named types apart.
Rust types live in the namespace of their crate or binding category, scripts register their own components and events into script.* namespaces. See Namespaces.
Reflect reference
A script’s pointer into the Bevy world: to a component, a resource, or a value BMS allocated. Reading or writing its fields reads or writes the real value, through reflection.
Its base is a component, a resource, an allocation or an asset. In Rust it is a ReflectReference, received as R<T>, M<T> or V<T> in binding signatures. See References.
Runtime
The engine state shared by all contexts of one language, if the language has one. Contexts are the sandboxes, the runtime is what they run on. Lua has no separate runtime, Rune does.
Customized with runtime initializers. See Customizing Contexts.
Script
A Lua or Rune source file, loaded as a Bevy asset (ScriptAsset). Loading it runs nothing: it runs once attached.
See Managing Scripts.
Script pipeline
The machinery which turns attachments, detachments and modified assets into loaded, reloaded or unloaded scripts, running the core callbacks along the way.
Runs in PreUpdate, and immediately for AttachScript / DetachScript. See Script Pipeline.
Script system
A Bevy system added by a script, which calls one of the script’s callbacks each time its schedule runs, with the queries and resources it asked for.
Built with bms.system_builder and added with world.add_system. See Script Systems.
Script value
The language neutral value passed between Rust and scripts: integers, strings, lists, functions, references and so on. Each language converts it to and from its own values.
In Rust it is ScriptValue, converted with FromScript and IntoScript. See Controlling Script Bindings.
Static script
A script attached to nothing rather than to an entity, i.e. game wide logic.
Attached and detached with the AttachScript and DetachScript commands. See Managing Scripts.
Installation
Cargo
Add BMS to your Cargo.toml with a language feature:
bevy_mod_scripting = { version = "0.24", features = ["lua54"] }
Each BMS release supports one Bevy version, see the compatibility table.
Language Features
| Language | Feature Flag |
|---|---|
| Lua 5.1 | lua51 |
| Lua 5.2 | lua52 |
| Lua 5.3 | lua53 |
| Lua 5.4 | lua54 |
| LuaJIT | luajit |
| LuaJIT 5.2 | luajit52 |
| Luau | luau |
| Rune | rune |
Only one Lua feature can be enabled at a time. Lua and Rune can be enabled together.
Bevy Plugin
Add the BMS plugin group to your app:
app.add_plugins(BMSPlugin);
Each plugin in the group can be replaced with a configured one using BMSPlugin.set(MySubPlugin).
Next, load and attach your first script.
Extra Features
The default features are core_functions and the ecs, input, math, time, transform, color and window bindings. Disable default features if you only need BMS for script lifecycle management and want to register the bindings yourself.
| Feature | Description |
|---|---|
core_functions | The core functions, i.e. world and the other ways to interact with Bevy via reflection |
bevy_<crate>_bindings | Bindings for a Bevy crate, i.e. bevy_math_bindings, bevy_transform_bindings. See the [features] of the Cargo manifest for the full list |
lua_language_server_files | Generates Lua language server definitions, see Editor Support |
mlua_async | Enables mlua/async |
mlua_serialize | Enables mlua/serialize |
mlua_macros | Enables mlua/macros |
unsafe_lua_modules | Allows loading native modules via require in Lua |
profile_with_tracy | Adds tracy profiling spans |
Mobile
CI type-checks bevy_mod_scripting for aarch64-linux-android and aarch64-apple-ios; nothing is run on a device. Both need the target’s C toolchain (Android NDK, Xcode) as the Lua runtimes are built from source, and Android needs a bevy activity feature in your app (e.g. bevy/android-native-activity).
| Language | Android | iOS |
|---|---|---|
| Lua 5.1, 5.2, 5.3 | yes | no: the Lua sources call system, which the iOS SDK marks unavailable (fixed upstream in Lua 5.4) |
| Lua 5.4 | yes | yes |
| LuaJIT, LuaJIT 5.2 | yes | no: luajit-src can’t build for iOS, which also forbids JIT |
| Luau | yes | yes |
| Rune | yes | yes |
unsafe_lua_modules loads native libraries at runtime, which iOS restricts.
Managing Scripts
Scripts are Bevy assets (ScriptAsset), loaded from the assets directory like any other asset. A loaded script does nothing until it is attached, which evaluates it:
- parsing the script body,
- creating or updating the script’s context, the environment holding its globals.
Script attachments
A ScriptAttachment says where a script “lives”, and is the identity scripts are addressed by:
ScriptAttachment::EntityScript(entity, handle): attached to an entity through itsScriptComponent,ScriptAttachment::StaticScript(handle): attached to nothing, activated through theAttachScriptcommand.
Inserting or removing a ScriptComponent sends ScriptLifecycleMessages (Attached / Detached), which the script pipeline processes. Static scripts are attached and detached with the AttachScript and DetachScript commands.
Loading
Load scripts with the AssetServer, or create them in memory:
let handle = asset_server.load::<ScriptAsset>("my_script.lua");
let mut script = ScriptAsset::from("x = 0".to_string());
script.language = Language::Lua;
let handle = script_assets.add(script);
Neither runs any code yet.
Note
Scripts are identified by their handle, not their path. The path is only used in logs and error messages, so scripts created in memory show up by asset id instead.
Attaching scripts to entities
Add a ScriptComponent to an entity:
fn load_script(asset_server: Res<AssetServer>, mut commands: Commands) {
let handle = asset_server.load::<ScriptAsset>("my_script.lua");
commands.spawn(ScriptComponent::new(vec![handle]));
}
In the script, import_namespace("bms").current_entity() returns the entity the script is attached to.
Static scripts
Scripts which don’t belong to an entity are attached as static scripts:
fn add_static_script(asset_server: Res<AssetServer>, mut commands: Commands) {
let handle = asset_server.load("scripts/my_script.lua");
commands.queue(AttachScript::<LuaScriptingPlugin>::new(
ScriptAttachment::StaticScript(handle),
));
}
fn remove_static_script(handle: Local<Handle<ScriptAsset>>, mut commands: Commands) {
commands.queue(DetachScript::<LuaScriptingPlugin>::new(
ScriptAttachment::StaticScript(handle.clone()),
));
}
The commands run the script pipeline until the attachment is processed. To avoid frame time spikes, write ScriptLifecycleMessages instead, and let the pipeline pick them up as normal.
Unloading
BMS keeps a handle to each attached script, so dropping your own handles does not unload it. To unload a script, and run its on_script_unloaded callback, remove it from its ScriptComponent or detach it with DetachScript. Once no handles are left, Bevy drops the asset.
A context is removed together with the last script in it.
Hot reloading
Enable Bevy’s file_watcher feature, and changes to script assets are picked up and the scripts reloaded. Use on_script_unloaded and on_script_reloaded to keep state across reloads.
File extensions
Each language plugin maps file extensions to its language, i.e. lua and luau for Lua. To add more:
app.add_plugins(LuaScriptingPlugin::default().add_supported_extension("pua"));
Next, run your scripts.
Running Scripts
Once attached, a script runs its top level code, then waits for callbacks: functions the script defines, which Rust (or other scripts) invoke by name.
print("hello from load time")
function on_event(arg1)
print("hello from event time", arg1)
end
This prints “hello from load time” when the script is loaded, and “hello from event time” whenever an on_event callback targets this script. Besides your own callbacks, BMS calls the core callbacks (on_script_loaded, …) on its own.
Sending callback messages
Define a label for the callback, then write a ScriptCallbackMessage with it:
#[derive(Reflect)]
pub struct MyReflectType;
// define as many labels as you like here
callback_labels!(OnEvent => "on_event");
fn send_event(mut writer: MessageWriter<ScriptCallbackMessage>) {
// allocated values live as long as references to them
let payload = ReflectReference::new_allocated(MyReflectType);
writer.write(ScriptCallbackMessage::new_for_all_scripts(
OnEvent,
vec![payload.into()],
));
}
The second argument is the list of arguments the callback receives. Any Reflect type can be sent as a ReflectReference, and the other ScriptValue variants carry plain data, i.e. ScriptValue::Integer(5).
Besides new_for_all_scripts, messages can target one script (new_for_static_script, new_for_script_entity) or each context once (new_for_all_contexts).
Event handlers
Messages are only delivered by an event_handler system for their label and language:
app.add_systems(
Update,
(
send_event,
event_handler::<OnEvent, LuaScriptingPlugin>.after(send_event),
),
);
The handler runs the on_event callback on every targeted script which defines it. Order the systems writing the messages before the handler, otherwise messages are only handled in the next frame.
Commands
To run a callback right away, queue a RunScriptCallback command for a single script:
commands.queue(RunScriptCallback::<LuaScriptingPlugin>::new(
ScriptAttachment::StaticScript(handle),
OnEvent.into_callback_label(),
vec![ScriptValue::Integer(5)],
false, // don't send a `ScriptCallbackResponseMessage`
));
To keep a callback’s logic across reloads, or share contexts between scripts, see Callbacks.
Callbacks
Callbacks are script functions which BMS calls by name, through an event handler or a RunScriptCallback command, from other scripts, or as one of the core callbacks.
They come in two variants:
- freestanding: top level functions,
- registered: functions passed to
register_callback, which are “frozen”.
Freestanding callbacks
function on_script_loaded()
print("doing things")
end
The callback is looked up by name each time it runs, so when the script is reloaded, the new version of the function runs.
Registered callbacks
local function my_registered_callback()
print("doing things")
end
register_callback("on_script_loaded", my_registered_callback)
Registered callbacks take priority over freestanding ones, and are “frozen”: once registered, reloading other scripts won’t change them.
This matters with shared contexts, where scripts overwrite each other’s top level functions when loaded. Register each script’s callbacks while it loads, and every callback will reach the right script.
Registered callbacks are implemented by each language plugin, Lua and Rune both support them.
Contexts
Each script runs in a context: the environment holding its global variables and functions. Which scripts share a context is decided by the context policy of the scripting plugin. By default each entity-script pair gets its own context, isolated from all other scripts.
Context policies
| Policy | Scripts sharing a context |
|---|---|
ContextPolicy::per_entity_and_script() (default) | None, the most isolated |
ContextPolicy::per_entity() | All scripts attached to the same entity |
ContextPolicy::per_script() | All attachments of the same script, i.e. one script on many entities |
ContextPolicy::shared() | All scripts, there is only one context |
Set the policy on the scripting plugin:
app.add_plugins(LuaScriptingPlugin::default().set_context_policy(
ContextPolicy::shared(),
));
Sharing a context makes it easy to share data between scripts, at the cost of scripts being able to interfere with each other.
Warning
In a shared context, scripts overwrite each other’s top level functions when loaded. Use registered callbacks so each callback reaches the right script.
A script’s context is busy while one of its callbacks runs, which limits which scripts it can call immediately.
Custom policies
A policy is a list of rules, tried in order until one applies. per_script() could be written as:
let policy = ContextPolicy {
priorities: vec![Arc::new(ContextRule::Script), Arc::new(ContextRule::Shared)],
};
Each rule maps the script’s attachment to a ContextKey, and scripts with the same key share a context:
pub struct ContextKey {
pub entity: Option<Entity>,
pub script: Option<AssetId<ScriptAsset>>,
}
So the policy reads: if there is a script, the key is just the script. Failing that, ContextRule::Shared always applies, returning the empty key.
For entirely custom rules, implement ContextKeySelector, or pass a closure Fn(&ScriptAttachment) -> Option<ContextKey>.
To change what is in a context, see Customizing Contexts.
Customizing Contexts
Most of the time, registering script functions is all you need: they work in every language, and show up in the generated docs. For anything else, scripting plugins take initializers which run on each context or runtime:
| Initializer | Runs |
|---|---|
add_context_initializer | Once a context is created, and when its script is reloaded, before any callbacks |
add_context_pre_handling_initializer | Before every callback, and on load and reload |
add_runtime_initializer | Once, on the runtime shared by all contexts |
Initializers are plain functions (fn pointers), so they can’t capture variables.
Context initializers
i.e. setting some globals for every Lua script:
let plugin = LuaScriptingPlugin::default().add_context_initializer(|_attachment, context| {
let globals = context.globals();
for i in 0..10 {
globals.set(i, i).map_err(IntoInteropError::to_bms_error)?;
}
Ok(())
});
app.add_plugins(plugin);
Pre handling initializers
These receive the attachment of the script about to run, i.e. to expose its name:
app.add_plugins(LuaScriptingPlugin::default().add_context_pre_handling_initializer(
|attachment, context| {
let name = attachment.script().path().map(|p| p.to_string());
context
.globals()
.set("script_name", name)
.map_err(IntoInteropError::to_bms_error)?;
Ok(())
},
));
Runtime initializers
Some languages have a runtime, shared by all contexts, which is customized with add_runtime_initializer(|runtime| { ... }). Lua’s runtime type is (), as mlua has no separate runtime.
Accessing the world
During initializers, the world is available through the ThreadWorldContainer thread local:
LuaScriptingPlugin::default().add_context_initializer(|_attachment, _context| {
let world = ThreadWorldContainer::try_get_context()?.world;
world.with_resource(|res: &MyResource| println!("My resource: {res:?}"))?;
Ok(())
});
Controlling Script Bindings
A binding is anything a script can access to communicate with your Rust code, i.e. binding script code to rust code. Bindings are written once in Rust, and work in every supported language.
Functions are registered on a type or a namespace, see where functions can live. Scripts reach them through namespaces.
Dynamic Functions
Everything callable by scripts must first be registered in the dynamic function registry. Notably we do not make use of the normal bevy function registry to improve performance and usability. This means you cannot call just any function.
In order for a function to be callable by a script it must adhere to a few requirements:
- Each argument must implement
FromScript. - Each return type must implement
IntoScript. - Each argument must also implement
GetTypeDependencies - Each return type must also implement
GetTypeDependencies
The into/from requirements allow us to convert these types to ScriptValue’s, and each supported scripting language can then marshall these into the script.
These traits are implemented for primitives, but if you want to interact with one of your Reflect implementing types, you will need to use one of R<T>, M<T> or V<T> wrappers in place of &T, &mut T and T respectively.
These wrappers enable us to safely interact with bevy, and claim any necessary mutex’es on Resources, Components or Allocations.
The GetTypeDependencies, trait is simply a local trait alias for GetTypeRegistration with less strict type requirements. It allows us to register all the types necessary for the function calls, so that you don’t have to register anything manually. If your type implements GetTypeRegistration you should not face any issues on this front.
Registering Script Functions
Registering functions can be done via the NamespaceBuilder like below:
NamespaceBuilder::<ReflectReference>::new(&mut world)
.register(
"hello_world",
|_self: ReflectReference, s: String| {
println!("{s}")
},
);
NamespaceBuilder::in_namespace(&mut world, "my_game")
.register(
"hello_world2",
|s: String| {
println!("{s}")
},
);
This will allow you to call this function within Lua like so:
some_value:hello_world("hi from method!")
import_namespace("my_game").hello_world2("hi from my_game!")
new also registers the type in the type registry. Functions on ReflectReference are available on every value, and receive it as their first argument, see where functions can live.
Macros
The above is a bit tedious, so instead you can use the script_bindings macro, which applies to impl blocks like so:
#[script_bindings(name = "test_fn")]
impl TestStruct {
/// My docs !!
///
/// Arguments:
/// * `_self` - the first argument
/// * `arg1` - the second argument
/// Returns:
/// * `return` - nothing
fn test_fn(_self: R<TestStruct>, mut arg1: usize) {}
}
pub fn main() {
let mut app = App::new();
register_test_fn(app.world_mut())
}
Note the documentation will automatically be picked up and stored for the purposes of reflection and documentation generation, including argument/return type specific docs.
Deriving FromScript and IntoScript
Generally all reflect types are wrapped in: R<T> V<T> or M<T> when writing script bindings. However some types may opt in to implement FromScript or IntoScript directly.
Doing this requires implementing a set of other traits which tell the runtime how to manage your type in conversion and function dispatch.
The most trivial way to allow your type to be used directly in bindings is to apply derive macros like so:
#![allow(unused)]
fn main() {
#[derive(Reflect, ScriptType)]
pub struct MyThing(usize);
#[script_bindings]
impl MyThing {
// Can now be used directly without V<> wrapper, acts exactly like V<MyThing>
pub fn test(thing: MyThing) -> MyThing {
thing
}
}
}
ScriptType implements FromScript, IntoScript, ArgMeta, GetTypeDependencies and TypedThrough at once, converting through V<Self>.
If you wish to customize one of the conversions, write that impl by hand and use #[script_type(from = custom)] or #[script_type(into = custom)]. This skips the generated impl and documents the type as opaque in generated docs. See the custom conversions example for more information.
Context Arguments
Each script function call always receives an additional context argument: FunctionCallContext.
You can opt-in to receive this argument in your own function definitions by adding it as the first argument.
The context contains requests from the caller to your function, such as “I am calling you from a 1-indexed array system, please convert the index first”, This argument is only relevant if you’re targeting multiple languages.
It also allows you to retrieve the world via FunctionCallContext::world().
You can use this as follows:
NamespaceBuilder::<ReflectReference>::new(&mut world)
.register(
"hello_world",
|ctx: FunctionCallContext, _self: ReflectReference, s: String| {
let world = ctx.world()?;
let should_use_0_indexing = ctx.convert_to_0_indexed();
println!("{should_use_0_indexing} {s}");
Ok(())
},
);
Dynamic Arguments
To accept any kind of value, i.e. numbers or strings alike, take ScriptValue arguments:
NamespaceBuilder::<ReflectReference>::new(&mut world)
.register(
"is_integer",
|s: ScriptValue| {
match s {
ScriptValue::Integer(i) => true,
_ => false
}
},
);
You can treat return values similarly. To accept a reference of any type while keeping it typed in the docs, see Generics. To accept callbacks, names or tables of options, see Typed arguments.
Typed arguments
These wrappers and derives keep the exact type of arguments which aren’t reflected values, in the book and the Lua language server files:
/// Spawns an enemy
#[derive(ScriptData)]
#[script_data(namespace = "game")]
struct SpawnOptions {
name: String,
speed: Option<Speed>, // optional
on_death: Option<FunctionOf<fn(V<Entity>) -> ()>>,
}
#[derive(ScriptData)]
#[script_data(namespace = "game")]
enum Speed {
Named(ByName<Pace>), // "Slow" | "Fast", for `enum Pace { Slow, Fast }`
Exact(f32), // 2.5
}
#[script_bindings(remote, namespace = "game")]
impl NamespaceMembers {
fn spawn(ctxt: FunctionCallContext, options: SpawnOptions) -> Result<V<Entity>, InteropError> { .. }
}
game.spawn({ name = "goblin", speed = "Fast", on_death = function(entity) end }) -- `entity` is an ecs.Entity
game.spawn({ name = "goblin", sped = 2 }) -- flagged by the language server, an error at runtime
| scripts pass | documented as | |
|---|---|---|
FunctionOf<fn(A, B) -> R> | a function, which is a DynamicScriptFunction in Rust | fun(arg1: A, arg2: B): R |
ByName<E> | a unit variant of the reflected enum E by its name as in Rust, or a reference to an E | "Slow" | "Fast" |
#[derive(ScriptData)] struct | a map of its fields: a table in Lua, an object in Rune | the class of its fields, a data type in the book |
#[derive(ScriptData)] enum | the value of any variant, each holding one value: the first variant whose type converts it | an alias of the union of the variants’ types (game.Speed), a data type in the book |
ScriptData is plain data, copied across: a struct is read from the map when passed and written to a new map when returned, so changing one doesn’t change the other. Use it for what crosses once (options, properties, events, results). Use a reflected type for what scripts hold a handle to, or Rust keeps as state. A type is one or the other: deriving both Reflect and ScriptData doesn’t compile.
Each field converts like a function argument of its type. A missing field takes its type’s default, so Option<T> fields can be left out. Unknown fields, missing fields without a default and mistyped fields are errors naming the field.
An enum’s variants are tried in order, so put the more specific of two types taking the same kind of value first, i.e. ByName before String.
Unions only try the types which could convert a value, as told by FromScript::could_convert. When implementing FromScript by hand, override it to rule out the kinds of values your type never converts.
Generics
Reflection only knows concrete types (Handle<Image>, Time<Virtual>), so generic signatures and types use markers standing for their parameters: A, B and C, from bevy_mod_scripting::bindings::function::generics. Markers only change the documentation and the Lua language server files, the values are references at runtime.
Note
The markers are real types:
Ais a reflected unit struct implementingAsset,Default,Cloneand the other traits generic parameters are usually bounded by, soHandle<A>andTime<A>are real types too. AHandle<Image>is not aHandle<A>, soV<Handle<A>>, which copies the value out, can’t receive one. UseValueOf<Handle<A>>. See theAAPI docs.
Generic functions
Two wrappers carry the markers in signatures:
ValueOf<T, R>: a value converted asR, aReflectReferenceunless given, documented as aT.TypeOf<R, A>: a type argument passed asR, i.e. a registration, documented as the parameterA.
Using the same marker ties them together, so get_component returns a value of the type it is given:
fn get_component(
ctxt: FunctionCallContext,
entity: V<Entity>,
registration: TypeOf<V<ScriptComponentRegistration>, A>,
) -> Result<Option<ValueOf<A>>, InteropError>
local bms = import_namespace("bms")
local Transform = import_namespace("transform").Transform
local transform = bms.world.get_component(assert(bms.current_entity()), Transform) -- typed as a Transform
print(transform)
A marker can also stand inside a type, i.e. ValueOf<Handle<A>> accepts the handle of any asset type, see References.
For values which aren’t references, give the conversion: ValueOf<A, ScriptValue> takes any value, typed as whatever the script passed:
// with `MyBox` declared as a generic type (see below): `boxed(5)` is a `MyBox<integer>`
fn boxed(initial: ValueOf<A, ScriptValue>) -> V<MyBox<A>> { .. }
Generic types
Instantiations of a generic type would be documented as unrelated types. Declare the generic type from your plugin, instantiated with markers, with its namespace, parameter names and docs:
use bevy_mod_scripting::bindings::function::generics::{A, GenericTypesAppExt};
app.register_generic_type::<Time<A>>("time", &["T"], "A clock, i.e. `Time<Virtual>`.");
Fields of type A are then documented as being of the parameter T, and instantiations as Time<T> applied to their arguments. Further parameters use B and C (Hashed<A, B>). A parameter with bounds the markers don’t satisfy gets a marker of its own:
bevy_mod_scripting::bindings::generic_marker! {
/// Stands for the material of `MyMaterialHolder<M>`
pub struct M;
}
impl MyMaterial for M {}
app.register_type::<M>()
.register_generic_type::<MyMaterialHolder<M>>("my_crate", &["M"], "...");
Fallible functions
Your script functions can return errors either by:
- Returning
Result<T: IntoScript, InteropError> - Returning
ScriptValueand manually creating theScriptValue::Error(into_interop_error.into())variant.
Reserved Functions
There are a few reserved functions that you can override by registering them on a specific type:
| Function Name | Description | Overridable? | Has Default Implementation? |
|---|---|---|---|
| get | a getter function, used for indexing into a type | no | yes |
| set | a setter function, used for setting a value on a type | no | yes |
| sub | a subtraction function, used for subtracting two values | yes | no |
| add | an addition function, used for adding two values | yes | no |
| mul | a multiplication function, used for multiplying two values | yes | no |
| div | a division function, used for dividing two values | yes | no |
| rem | a remainder function, used for getting the remainder of two values | yes | no |
| neg | a negation function, used for negating a value | yes | no |
| pow | a power function, used for raising a value to a power | yes | no |
| rsub, rdiv, rrem, rpow | the reflected sub, div, rem and pow, called on the right operand when the left one is not a value, i.e. 1 - v calls rsub(v, 1). add and mul are called with their operands swapped instead | yes | no |
| eq | an equality function, used for checking if two values are equal | yes | no |
| lt | a less than function, used for checking if a value is less than another | yes | no |
| iter | an iterator function, used for iterating over a value | no | yes |
| display | a display function, used for pretty printing values | no* | yes |
| debug | a display function, used for displaying the internals of a value | no* | yes |
* - You can register an instance of ReflectDisplayWithTypeInfo type data on Reflect implementing types to override their printing behavior
In this context overridable indicates whether language implementations will look for a specific function on your type before looking at the generic ReflectReference namespace. You can still remove the existing registration for these functions on the ReflectReference namespace if you want to replace them with your own implementation.
Note the ReflectReference namespace is special, in that functions defined on it, act like a fallback and hence apply to ALL references.
Where functions can live
The type in the impl block you apply script_bindings to (or the one passed to NamespaceBuilder) decides where the functions are available:
impl target | Available on | Receives |
|---|---|---|
MyType | MyType values and the MyType type, as imported from its namespace | whatever you declare |
ReflectReference | every value, after MyType’s own functions | the value |
StaticTypeRef | every type, after MyType’s own functions | the type, filled in automatically |
NamespaceMembers | the namespace given by namespace = "..." (or NamespaceBuilder::in_namespace), i.e. import_namespace("my_game") | whatever you declare |
When the same name exists in more than one place, the most specific one wins.
These types are defined by BMS, so script_bindings blocks on ReflectReference, StaticTypeRef or NamespaceMembers in your crate need the remote attribute.
Functions available on every type
The StaticTypeRef namespace is the equivalent for types, i.e. Vec3 in Vec3.new(..).
Functions registered on it are available on every type, and receive the type as their first argument, which is filled in automatically:
NamespaceBuilder::<StaticTypeRef>::new(app.world_mut()).register(
"describe",
|ctxt: FunctionCallContext, type_ref: V<StaticTypeRef>| -> Result<String, InteropError> {
Ok(type_ref.type_info(&ctxt.world()?)?.type_path().to_string())
},
);
local Vec3 = import_namespace("math").Vec3
print(Vec3.describe()) -- "glam::Vec3"
A function registered on the type itself always takes priority over one on StaticTypeRef.
The new constructor is implemented this way, see Constructing Arbitrary Types.
Types scripts don’t make or use this way, such as handles the runtime gives out, opt out with #[reflect(NoTypeFunctions)] (ReflectNoTypeFunctions): only their own functions remain, in scripts and in the generated docs.
Signatures which depend on the type
A shared function’s signature can refer to the type it is bound to, using the placeholder types BoundValue (a value of the type), BoundFields (a table of the type’s fields) and BoundHandle (a handle to an asset of the type).
Wherever the function is bound to a type, these are replaced with the type, so the documentation and the Lua language server files show, for example, MyStruct.new(payload: MyStruct.Fields): MyStruct rather than a generic table and reference, or Image.load(path: string): Handle<Image>.
Functions using BoundHandle are only documented on asset types, i.e. types registered with register_asset_reflect.
The same placeholders work for functions on EnumVariantRef, which are bound to each variant of each enum when the LAD file is built (as functions in the Variant namespace). Placeholders left unbound are documented as what they are at runtime, a ReflectReference and a table.
The enum variants of a type are also available on the type, i.e. MyEnum.Variant, after the functions.
Namespace members
Each type registered with the type registry is an entry in the table import_namespace returns for its namespace, i.e. import_namespace("math").Vec3.
Functions which don’t belong to a type are members of a namespace, declared on impl NamespaceMembers:
#[script_bindings(remote, namespace = "my_game")]
impl NamespaceMembers {
fn spawn_enemy(health: f32) { /* ... */ }
}
local my_game = import_namespace("my_game")
my_game.spawn_enemy(5.0)
Values are registered per namespace with AppScriptNamespaceMembers::register_value, and are made each time the namespace is imported.
The only globals are the builtins: import_namespace, export_namespace and register_callback. world is in the bms namespace: import_namespace("bms").world.
Types are not globals, which keeps types with the same name from shadowing each other. Use the filter of CoreScriptGlobalsPlugin to choose which types scripts can look up by name.
Script Systems
Warning
Script systems are an experimental feature.
Scripts can add their own systems to Bevy schedules. Each system runs a callback of the script which added it.
Systems introduced by scripts can run in parallel to other systems, and can be freely inserted between any other system, including other script systems.
BMS also provides utilities for visualising schedules using dot graphs, allowing low-effort modding frameworks for game authors.
Schedules
Bevy doesn’t support reflecting schedules, so BMS rolls its own schedule registry resource: AppScheduleRegistry, which can be used to add any custom schedules you want to interact with. The default Bevy schedules will be pre-populated for you.
Once you’ve registered your schedule you will be able to interact with it in scripts like below:
local world = import_namespace("bms").world
local update_schedule = world.get_schedule_by_name("Update")
local systems = update_schedule:systems()
local system_with_name = update_schedule:get_system_by_name("my_system")
Inserting Systems
To insert a system you will need to use bms.system_builder like below:
local bms = import_namespace("bms")
local attachment = bms.ScriptAttachment.new_entity_script(bms.current_entity(), bms.current_script())
local system = bms.system_builder("my_system", attachment)
:exclusive()
:after(some_other_system)
:before(another_system)
This will let you call world.add_system like so:
local world = import_namespace("bms").world
world.add_system(update_schedule,system)
Ordering and sets
Besides systems (after/before), script systems can be ordered against:
- other script systems, by callback label and script, which must have been added before:
:after_script_system("on_physics", attachment) - sets:
:after_set(set),:before_set(set), and put in sets::in_set(set)
Scripts register their own sets into a script.* namespace, i.e. to group and order the systems of a mod. A set is removed from its namespace when its script unloads, registering it again gives the same set:
local ai = world.register_new_system_set("script.my_mod", "ai")
-- other scripts: import_namespace("script.my_mod").ai
Rust sets the game registers are members of their namespace, the BMS bindings register the main Bevy sets (i.e. transform.TransformSystems.Propagate, time.TimeSystems):
app.register_script_system_set("transform.TransformSystems", "Propagate", TransformSystems::Propagate);
local propagate = import_namespace("transform.TransformSystems").Propagate
builder:in_set(ai):after_set(propagate)
world.get_system_set_by_name finds either kind by its full name, i.e. "transform.TransformSystems.Propagate" or "script.my_mod.ai".
Run conditions
:run_if only runs the system if the condition holds, conditions are evaluated in Rust without calling the script. Every condition passed to run_if must hold:
local c = bms.conditions
builder:run_if(c.any_with_component(Enemy))
:run_if(c.not_(c.resource_exists(Paused)))
:run_if(c.on_timer(0.5))
Conditions: resource_exists, resource_changed, resource_added, any_with_component, on_timer(seconds), run_once and the combinators not_, and_, or_ (named so as not, and, or are Lua keywords).
Lifetime
A script system is identified by its attachment and callback label: adding it again replaces the old one (with a warning). Script systems are removed when their script unloads or reloads, a reloading script adds them again in on_script_loaded.
Bevy cannot change a schedule while it runs, i.e. PreUpdate where scripts are loaded. Systems added to (or removed from) a running schedule are added (or removed) once it finishes, removed systems stop running right away. world.add_system then returns a system which can be used for ordering, but has no node in the schedule yet.
Errors in script systems are sent as ScriptErrorMessages, like those of other callbacks. Script systems can call other scripts with the limits described in Calling Other Scripts.
Parameters
The system builder allows script authors to parameterise systems, using resource and query functions.
The order in which those functions are called, will define the order in which arguments will be provided to the specified script callback.
For example:
local bms = import_namespace("bms")
local world = bms.world
bms.system_builder("my_system")
:query(
world.query()
:component(ComponentA)
:component(ComponentB)
:with(ComponentC)
:without(ComponentD)
)
:resource(ResourceA)
will create a system which calls the specified callback my_system with 2 arguments:
- The results of the query, each a list of the entity followed by the components in the order they were added:
{entity, a, b} - The
ReflectReferencetoResourceA
function my_system(results, resource_a)
for _, result in ipairs(results) do
local entity, a, b = result[1], result[2], result[3]
end
end
resource and component give read and write access. Use resource_read and component_read for read only access, systems reading the same resources and components can run in parallel, while systems writing them cannot:
bms.system_builder("my_system", attachment)
:query(world.query():component_read(ComponentA):component(ComponentB))
:resource_read(Time)
Queries can also retrieve components entities don’t need to have (optional, optional_read, nil for entities without them), and only match entities whose components were added or changed since the system last ran (added, changed, filters like with). Outside of systems, added and changed are relative to the last app update:
world.query()
:component(Transform)
:optional_read(Velocity)
:changed(Health)
Queries of a system may access the same components if they can’t match the same entities, i.e. component(A):with(B) and component(A):without(B), otherwise the system reports an error and doesn’t run.
Exclusive systems
An exclusive system can be created using the exclusive function call on the system builder.
This allows the system to access everything as in a normal event handler.
Non-exclusive systems, will only be able to access the set of components and resources as parameterized when building the system. This is why we can run the system in parallel to other non-overlapping systems.
Components are only accessible on the entities matched by the queries declaring them, i.e. with world.query():component(A):with(B) the system can’t access A on entities without B, since Bevy runs it in parallel with systems accessing A on those. Components only used as filters (with, without) can’t be accessed.
Exclusive systems on the other hand, cannot run in parallel.
Callback
The system injected will be similar to an event handler, however it will only trigger the specified script, and without any entity, in the first example you’d see the following lua callback:
function my_system()
print("I am a dynamic system")
end
get triggered every update.
Script Pipeline
The script pipeline processes script attachments and detachments, and runs the core callbacks along the way.
Before 0.16.0 scripts were processed atomically by load and unload commands. Since then the pipeline allows:
- Customizing callbacks during the process
- Budgeting the work done by the pipeline each frame
- Allowing async steps in the process
The pipeline works like this:
- A set of systems in
PreUpdate“filter” incomingScriptLifecycleMessages (attachments and detachments, processed in the order they were written) as well asScriptAssetModifiedMessages (some generated from asset events, others from component hooks). The filtered events are wrapped inForPlugin<P>(inner)events based on the language of the underlying events. - A set of other systems then converts those into active
ScriptMachines - Then inside the
ScriptProcessingSchedule<P>, which is only run inPreUpdateif there are active machines, we tick each machine until it either errors or reaches its final state.
Script Machines
State Machine
Script loading is handled by the following state machines:
graph TD;
A[Loading Initialized]
B[Reloading Initialized
Enter: OnUnloaded callback]
A --[ new context ]--> C
B --[ existing context]--> C
C[Context Assigned
Enter: OnLoaded, then OnReloaded callbacks]
C --> D
D[Loading Completed]
E[Unloading Initialized
Enter: OnUnloaded callback]
F[Context Removed]
G[Resident Removed]
E --[Last resident]--> F
E --[More residents]--> G
H[Unloading Completed]
F --> H
G --> H
Hooks, such as on_script_loaded, are implemented using Bevy observers, so you can hook into each step of the process with your own observers, i.e.:
app.add_observer(|_: On<LoadingCompleted<LuaScriptingPlugin>>| {
info!("a script finished loading");
});
Timing & Order
By default all machines are ticked to completion in the frame they start. Setting ScriptLoadingPipeline::tick_budget limits the amount of machine ticks (steps in the state machine above) per frame, spreading the loading of many scripts over multiple frames. The budget counts steps, not time, so a step running a slow callback can still take up the frame.
You can override this and many other settings (including disabling the core callbacks) by changing the ScriptLoadingPipeline<P> settings via your scripting plugin’s set_pipeline_settings.
The script loading/unloading order will look as follows:
- the order in which components are attached/detached, determines the order in which scripts are processed
- an attachment whose script asset is still loading holds back the attachments and detachments after it, until it finishes loading
- scripts are processed one-by-one, i.e. each machine is ticked to completion before the next one is started
- meaning for example if two scripts are loaded, their
on_script_loadedhooks will not run at the same “lockstep”.
- meaning for example if two scripts are loaded, their
- loading/unloading might happen over multiple frames, depending on the pipeline’s settings.
Determinism
Given the same inputs (the same order of attachments, detachments and app updates), scripts load in the same order and callbacks reach scripts in the same order, on every run and machine: script contexts are kept in insertion ordered maps, and the pipeline budget counts steps rather than time.
What BMS cannot control:
- which frame a script asset finishes loading in, as asset IO is asynchronous. Wait for scripts to load (see below) before relying on frame timing.
- language internals, for example Lua iterates tables with string keys (
pairs) in a different order on each run. BMS seeds Lua’smath.randomwith0when creating a context, callmath.randomseedto change it.
Waiting for scripts to load
In order to check on the pipeline and figure out when everything is ready, you can use the ScriptPipelineState<P> system parameter in a system as shown in the script_loading example.
Editor Support
BMS generates documentation and editor definitions for all bindings registered in your app, including your own.
LADfiles
BMS provides a custom Language Agnostic Declaration format (LAD), which can be used to integrate with other tooling.
If you use #[script_bindings] macros, these files will magically contain your code comments, bindings as well as everything else required to drive other powerful integrations.
The declaration file is generated from the type registry and serves as a light abstraction layer simplifying the traversal of all available types, namespaces and functions.
You can customize how / where and if these files are stored using the main BMS plugin group:
app.add_plugins(BMSPlugin.set::<ScriptingFilesGenerationPlugin>(
ScriptingFilesGenerationPlugin::new(
true, // enabled, you can use a compilation feature to disable this here
PathBuf::from("assets").join("definitions"),
Some(PathBuf::from("bindings.lad.json")), // do also save the ladfile itself
"Core BMS framework bindings",
true,
true,
),
));
This plugin is only available when one of the sub features (like lua_language_server_files) mentioned in this chapter is enabled.
You might not want to run this pipeline in your final binary, but rather bundle some of the generated files into some sort of development pack for modding. You can use compiler flags like #[cfg(not(debug_assertions))] to disable ladfile generation at runtime, or simply disable the lower level features within BMS to avoid compiling related dependencies too.
Lua Language Server
Note
This feature is in early stages: the definitions get you 90% of the way there, but there are rough edges.
LuaLS is an open source language server which integrates with many IDEs.
It is powered by lua specific annotation or definition files which BMS can generate directly from its own LADfiles.
To enable this simply enable the lua_language_server_files feature, and a bindings.d.lua definition file, plus a bindings.<namespace>.d.lua file per namespace, will be generated in the LADfile output directory in the Startup schedule.
Script writers can then use this generated file by pointing their .luarc.json file to these definitions:
{
"$schema": "https://raw.githubusercontent.com/LuaLS/vscode-lua/master/setting/schema.json",
"workspace.library": [
"assets/definitions"
],
"runtime.version": "Lua 5.4",
"hint.enable": false,
"workspace.preloadFileSize": 10000
}
The generated definitions file is large (over a megabyte with the default bindings), and the language server skips Lua files bigger than workspace.preloadFileSize (in KB, 500 by default).
If completions for BMS types are missing, i.e. Vec3. suggests nothing, raise this limit above the size of the generated file and restart the language server.
Examples
Rust examples live in the examples folder:
| Example | Shows |
|---|---|
game_of_life | A full app driven by Lua or Rune scripts, with callbacks, static scripts and custom bindings |
runscript | Running script files given on the command line |
script_loading | Waiting for scripts to load with ScriptPipelineState |
custom_conversions | Hand-written FromScript / IntoScript conversions |
docgen | Generating LAD files and Lua language server definitions |
Run one with cargo run --example <name> --features lua54 (docgen needs lua_language_server_files).
For example scripts, see the regression test suite in assets/tests, which covers every scripting function in Lua and Rune.
Scripting Reference
This part of the book covers the user-facing API of the scripting languages supported by BMS. This will be where you will want to forward your script users to get started with scripting in BMS.
If you are a modder, welcome! 👋 Apologies for the Rust-centricity of this guide, we are working on it!
Globals
Scripts have only a few builtin globals:
import_namespace(namespace): returns the types and functions of a namespaceexport_namespace(namespace, name, callback): see Exporting functionsregister_callback(label, function): registers a function as a callback handler
Everything else is imported. world is a static reference to the world, with all sorts of functions available: import_namespace("bms").world. BMS’ own functions are in bms, i.e. bms.current_entity() (the entity the script is attached to, or nil) and bms.current_script() (the script’s handle):
local bms = import_namespace("bms")
print(bms.current_entity())
In this section
| Page | Covers |
|---|---|
| Namespaces | Importing types, script defined components and events, exporting functions |
| References | What script values point at, assets and handles |
| Core Callbacks | on_script_loaded, on_script_unloaded, on_script_reloaded |
| Constructing Arbitrary Types | Type.new, enums and bms.construct |
| Calling Other Scripts | bms.run_script_callback and bms.queue_script_callback |
| Events and Messages | Sending and observing Bevy events and messages |
| Bundles | Inserting and spawning bundles |
| Core Bindings | Every type and function available to scripts |
Namespaces
Every type known to scripts lives in a namespace, and scripts reach types through their namespace: there are no globals named after types.
| Types | Namespace |
|---|---|
| bevy types covered by the bevy bindings, grouped by category | math, ecs, time, transform, color, input, window, asset, camera, render, sprite, text, ui, gizmos, animation, audio, state |
BMS’ own types (ScriptAttachment, ReflectReference, …) | bms |
| any other type | the name of the crate defining it, i.e. my_game |
primitives like i32 | the root namespace, "" |
A category namespace holds every type of the bevy crates it covers, i.e. math holds the types of glam and bevy_math, render those of bevy_render, bevy_pbr, bevy_light, bevy_mesh and bevy_image.
Type:namespace() returns a type’s namespace. Script registered components and events live in script.* namespaces, see below.
Importing a namespace
import_namespace(namespace) returns a table of the namespace’s types (and, for script namespaces, events and exported functions) by short name. Each type can be used to call its static functions, to access its enum variants, and wherever a type is expected:
local bms = import_namespace("bms")
local world = bms.world
local Vec3 = import_namespace("math").Vec3
local transform = import_namespace("transform")
local t = transform.Transform.from_translation(Vec3.new(0, 1, 0))
world.add_default_component(bms.current_entity(), transform.Transform)
Import once at the top of a script, and keep the types you use in locals. In Lua, don’t name the table of the math namespace math: that would hide Lua’s own math library.
- If two types in a namespace share a short name, the first one registered wins.
- Each call reads the shared type catalogue, so the result is always up to date. A table imported earlier does not pick up later registrations: import again.
- A namespace which does not exist is an error, with suggestions:
namespace "transfrom" does not exist. ... Did you mean: transform?
Overriding the namespace of a type
// on types with script bindings: keeps a namespace set before (with a warning)
#[script_bindings(namespace = "my_namespace")]
impl MyType { /* ... */ }
// on any type: always wins, before or after `script_bindings`
app.override_script_namespace::<MyType>("my_namespace"); // bevy_mod_scripting::bindings::ScriptNamespaceAppExt
// or directly
registry.register_type_data_with::<MyType, ScriptNamespace, _>("my_namespace");
Namespaces defined by scripts
Scripts register components and events into namespaces they pass explicitly. These start with script., followed by dot-separated segments of letters, digits and underscores:
local bms = import_namespace("bms")
local world = bms.world
local Enemy = world.register_new_component("script.game.ai", "Enemy")
local Hit = world.register_new_event("script.game.ai", "Hit")
-- anywhere, including other scripts
local ai = import_namespace("script.game.ai")
world.add_default_component(bms.current_entity(), ai.Enemy)
world.trigger_event(ai.Hit, { damage = 3 })
- Names are unique within a namespace, across components, events and exports:
script.game.ai.Enemyandscript.game.ui.Enemyare different components. - Registering a taken name is an error.
allow_existingreturns the existing registration instead, which is useful for scripts which run again. - A script namespace exists once something is registered or exported into it.
- Components and events stay registered when their script unloads, as Bevy cannot unregister components.
Values of script components are DynamicComponents, holding any value in data. Tables read from data are copies: assign a new table to change them.
local bms = import_namespace("bms")
local world = bms.world
local DynamicComponent = bms.DynamicComponent
world.insert_component(bms.current_entity(), Enemy, DynamicComponent.new({ data = { hp = 5 } }))
local enemy = world.get_component(bms.current_entity(), Enemy)
enemy.data = { hp = enemy.data.hp - 1 } -- `enemy.data.hp = 4` would not write through
Exporting functions
export_namespace(namespace, name, callback) makes a callback of the calling script callable by other scripts, in any language:
-- script A
local world = import_namespace("bms").world
register_callback("spawn_enemy_impl", function(health)
return world.spawn()
end)
export_namespace("script.game", "spawn_enemy", "spawn_enemy_impl")
-- script B, once script A has run
local enemy = import_namespace("script.game").spawn_enemy(5)
callbackis a function registered withregister_callback, or a top level function of that name. Only functions can be exported.- Calls run in the exporting script’s context, like
bms.run_script_callback(see Calling Other Scripts), and return the callback’s result. - A script cannot call its own exports, or those of scripts sharing its context, from one of its callbacks: its context is busy. Call the function directly instead.
- Exports are looked up on every call, so replaced exports are picked up and removed ones fail with an error.
- A path can only be exported by one script. Exporting it again from the same script replaces it. Exports can’t share a path with a component.
export_namespaceonly works inside a script callback.
When a script unloads or is about to reload, its exports and observers are removed right after its on_script_unloaded callback. Export from a callback which runs on load (e.g. on_script_loaded), so a reloaded script exports again.
Editor support
LAD files record each type’s namespace. The Lua language server definitions declare a namespace.<name> class per native namespace, and import_namespace("transform") returns the matching class, so completion works on imported tables. Script namespaces only exist at runtime and are untyped.
References
Most values scripts get from Rust are references: they point at a value living somewhere else, and reading or writing through them reads or writes that value. A reference is a base, saying where the value lives, plus a path to the field being accessed.
| Base | Points at | Scripts get one from | Valid until |
|---|---|---|---|
| Component | A component of an entity | world.get_component, queries | The component is removed or the entity despawned |
| Resource | A resource | world.get_resource, script system parameters | The resource is removed |
| Allocation | A value BMS owns for scripts | Type.new, :clone(), values returned by functions | Kept alive as long as any reference to it is |
| Asset | An asset in Assets<T>, by handle | Type.get_asset, world.get_asset | The asset is removed |
Accessing a field extends the path, so the result still points into the same value:
local bms = import_namespace("bms")
local world = bms.world
local Transform = import_namespace("transform").Transform
local transform = assert(world.get_component(assert(bms.current_entity()), Transform))
transform.translation.x = 5 -- writes the component
local copy = transform:clone() -- a new allocation, independent of the component
copy.translation.x = 0 -- the component keeps 5
Access is checked when a reference is used, not when it is made: a reference to a removed component fails with an error, and so does writing a value something else is reading at the same time, i.e. inside a query iteration. Script systems can only access what they declared, and assets, whose access is checked for all assets at once, only from exclusive script systems.
Assets
Handles are plain values (allocations holding a Handle<T>), and asset references point into the Assets<T> resource through one:
local world = import_namespace("bms").world
local Image = import_namespace("render").Image
local handle = Image.load("textures/icon.png") -- a Handle<Image>, loading in the background
-- later
if world.is_loaded(handle) then
local image = Image.get_asset(handle) -- a reference into Assets<Image>
print(image) -- reading or writing its fields reads or writes the asset
end
Warning
For now, reading or writing through an asset reference needs exclusive access to the whole world: Bevy’s
ReflectAssetonly reaches assets through the world as a whole, not through theAssets<T>resource alone. Asset access therefore conflicts with any other access held at the same time (i.e. inside a query iteration), and isn’t possible in non-exclusive script systems.
Every asset type has load, add_asset and get_asset, and world has the same operations taking the asset type, plus is_loaded, load_state and asset_path for any handle. They are listed with their types in Core Bindings. An asset type needs app.register_asset_reflect::<T>() to be usable from scripts.
References in Rust
Binding signatures choose how they receive references: R<T> borrows, M<T> borrows mutably, V<T> copies the value out, see Controlling Script Bindings. Return a ReflectReference to give scripts a reference, i.e. ReflectReference::new_allocated(value).
For references whose type matters only to the docs, use ValueOf<T>: a ReflectReference at runtime, documented as T. Combined with the A marker for a generic parameter, a function can take the handle of any asset type, and still show up as taking a Handle<A> in the docs and the Lua language server files:
use bevy_mod_scripting::bindings::function::generics::{A, ValueOf};
#[script_bindings(remote, namespace = "my_game")]
impl NamespaceMembers {
/// Works with the handles `Image.load`, `world.load_asset` and others return.
fn asset_id(ctxt: FunctionCallContext, handle: ValueOf<Handle<A>>) -> Result<String, InteropError> {
let untyped: UntypedHandle = handle.try_untyped_asset_handle(ctxt.world()?)?;
Ok(untyped.id().to_string())
}
/// Gives scripts a reference to an asset, as `Image.get_asset` does.
fn icon(ctxt: FunctionCallContext) -> Result<ValueOf<Image>, InteropError> {
let world = ctxt.world()?;
// `Icons` is a resource of your game, holding `Handle<Image>`s
let handle = world.with_resource(|icons: &Icons| icons.default.clone().untyped())?;
ReflectReference::new_asset_ref(handle, TypeId::of::<Image>(), world).map(ValueOf::new)
}
}
For a handle of one asset type, take ValueOf<Handle<Image>>. V<Handle<Image>> works too, but copies the handle out first.
Core Callbacks
On top of callbacks which are registered by your application, BMS provides a set of core callbacks which are always available (unless disabled via plugin settings).
The three core callbacks are:
on_script_loadedon_script_unloadedon_script_reloaded
For how callbacks work in general, see Callbacks. They run as part of the script pipeline.
on_script_loaded
This will be called right after a script has been loaded or reloaded. This is a good place to initialize your script. You should avoid placing a lot of logic into the global body of your script, and instead put it into this callback. Otherwise errors in the initialization will fail the loading of the script.
print("you can also use this space, but it's not recommended")
function on_script_loaded()
print("Hello world")
end
on_script_unloaded
This will be called right before a script is unloaded. This is a good place to clean up any resources that your script has allocated. This is called both before a script is removed as well as before a script is reloaded. If you want to preserve the state of your script across reloads, you can return a value from this callback, which will be passed to on_script_reloaded when the script is reloaded.
function on_script_unloaded()
print("Goodbye world")
return "house key"
end
on_script_reloaded
Called right after on_script_loaded but only if the script was reloaded.
The callback is passed a state argument, this state is exactly what is returned by the script through on_script_unloaded before a reload happens.
mode = 1
function on_script_reloaded(value)
if value then
print("I'm back. Thanks for the keys!")
else
print('I have not saved any state before unloading')
end
end
Using on_script_reloaded one can make a script reload preserve its current state.
Constructing Arbitrary Types
When interfacing with bevy, we do this via reflection.
While the bevy bindings do not cover constructors for every single type that bevy or other libraries provide, reflection allows us to construct some (not all types implement FromReflect) types from dynamic structs.
BMS exposes this ability to all script writers via the new function available on every type, as well as the more verbose bms.construct.
Type.new
Every type has a new function, taking a table of the fields to set. Types are reached through their namespace, i.e. import_namespace("my_game").MyStruct:
pub struct MyStruct {
pub my_field: String,
pub other_field: usize,
}
local MyStruct = import_namespace("my_game").MyStruct
local my_struct = MyStruct.new({
my_field = "hello",
other_field = 5,
})
pub struct MyTupleStruct(pub String);
Tuple structs and tuples are constructed using the index of the field as the key, the keys follow the indexing convention of the language, i.e. in Lua the first field is "1":
local my_tuple_struct = MyTupleStruct.new({
["1"] = "hello",
})
A list is taken to be the fields in order, which is usually the more natural way to write tuple structs:
local my_tuple_struct = MyTupleStruct.new({ "hello" })
Types which are not structs, tuple structs, tuples or enums, can be constructed only if they implement Default, using Type.new({}).
Defaults
Fields which are not provided are filled in, in the following order of priority:
- the value from the type’s
Defaultimplementation, if it has one. For enums, only if the default is the variant being constructed - the
Defaultof the field’s type, if it has one
If neither is available the construction fails, and the error names the missing field. Entries which are not fields of the type, i.e. a misspelled field name, are an error too, rather than being ignored in favour of a default. The generated Lua language server files mark exactly these fields as optional, see Editor support.
Naming and priority
new is a single function shared by all types, and is made available on every type.
A function with the same name registered on the type itself always takes priority, i.e. Vec3.new(x, y, z) is the Vec3 constructor from the math bindings, not the shared one.
For such types use bms.construct, which works for every type.
The name of the function is configurable via the ConstructorsPlugin:
app.add_plugins(BMSPlugin.set(ConstructorsPlugin {
constructor_name: "create".into(),
}));
The function is registered under the StaticTypeRef type, which is where functions available on all types are registered.
Enums
The following enum:
pub enum MyEnum {
VariantA {
field: String
},
VariantB(usize),
VariantC,
}
has its variants available as MyEnum.VariantA, MyEnum.VariantB and MyEnum.VariantC, which can be used to construct values of the variant using :new:
local a = MyEnum.VariantA:new({ field = "hello" })
local b = MyEnum.VariantB:new({ 5 })
local c = MyEnum.VariantC:new({})
The enum’s Default only fills in fields if it is the variant being constructed.
You can also pick the variant by name using MyEnum.new({ variant = "VariantA", field = "hello" }).
Discriminating variants
The variant a value is in can be obtained with :variant(), and compared with the variants of the enum:
if my_enum:variant() == MyEnum.VariantA then
print(my_enum.field)
end
This is also useful with enums that carry no data, such as keys:
local KeyCode = import_namespace("input").KeyCode
if event.key_code:variant() == KeyCode.KeyA then
print("A was pressed")
end
:variant() returns nil if the value is not an enum. If you need the name of the variant, :variant_name() is also available on both values and variants.
Variants named like functions
Functions on the type take priority over variants, so a variant named like a function cannot be accessed with MyEnum.Name.
Use world.get_enum_variant to get at it in that case:
local world = import_namespace("bms").world
local variant = world.get_enum_variant(import_namespace("my_game").MyEnum, "Name")
bms.construct
The bms.construct function constructs types from a registration.
It works for every type, including those whose own new function shadows the shared one, and is useful if you only have the type as a value:
local bms = import_namespace("bms")
local my_game = import_namespace("my_game") -- the crate defining the types
local concrete_my_struct = bms.construct(my_game.MyStruct, {
my_field = "hello"
})
local variantA = bms.construct(my_game.MyEnum, {
variant = "VariantA",
field = "hello"
})
local vec = bms.construct(import_namespace("math").Vec3, { x = 1, y = 2, z = 3 })
Missing fields are filled in from defaults in the same way as for new.
Editor support
The Lua language server files describe the table each constructor takes, so editors can complete and check the fields. A field is optional exactly when a default can fill it in, as described in Defaults:
#[derive(Reflect)]
pub struct MyStruct {
pub my_field: String,
pub handle: MyHandle, // no `Default`
}
---@class (exact) MyStruct.Fields
---@field my_field? string
---@field handle MyHandle
---@field [any] 'never'
---@param payload MyStruct.Fields
---@return MyStruct
function MyStruct.new(payload) end
The language server then warns about missing required fields, fields of the wrong type, and unknown fields, i.e. a misspelled my_feild.
The last line rejects unknown fields: until the language server checks exact classes against tables passed to functions (LuaLS/lua-language-server#1990), any undeclared field has to be of a type no value has, so the warning reads “Cannot assign string to 'never'”.
Tuple fields are declared under their integer keys, i.e. [1], which a list such as { "hello" } fills in, so prefer lists for tuple structs.
Types and variants without fields all take NoFields, i.e. {}.
Each enum variant has a class of its own, i.e. MyEnum.VariantA, so MyEnum.VariantA:new{ completes the fields of VariantA and returns a MyEnum.
The table of MyEnum.new{ variant = "VariantA", ... } is not described, as the language server cannot narrow its fields down by the variant given.
Prefer MyEnum.VariantA:new{...}, which is checked.
Since the type of bms.construct’s first argument is only known when the script runs, its table is not described.
Calling Other Scripts
Scripts can run callbacks of other scripts, in any scripting language, using two functions:
| Function | When the callback runs | Returns |
|---|---|---|
bms.run_script_callback(label, target, ...args) | Immediately, before the call returns | What the callback returned |
bms.queue_script_callback(label, target, ...args) | As soon as the current callback finishes, in the same frame | Nothing |
local bms = import_namespace("bms")
local ScriptAttachment, Recipients = bms.ScriptAttachment, bms.Recipients
local enemy_script = ScriptAttachment.new_entity_script(enemy, bms.current_script())
-- runs `take_damage(10, "fire")` in the enemy's script right away
local remaining_health = bms.run_script_callback("take_damage", enemy_script, 10, "fire")
-- runs `on_hit()` in every script once this callback is done
bms.queue_script_callback("on_hit", Recipients.all_scripts())
let bms = import_namespace("bms");
let ScriptAttachment = bms.ScriptAttachment;
let Recipients = bms.Recipients;
let enemy_script = ScriptAttachment.new_entity_script(enemy, bms.current_script());
// runs `take_damage(10, "fire")` in the enemy's script right away
let remaining_health = bms.run_script_callback("take_damage", enemy_script, 10, "fire");
// runs `on_hit()` in every script once this callback is done
bms.queue_script_callback("on_hit", Recipients.all_scripts());
Targets
The target is either a single script:
ScriptAttachment.new_static_script(script)ScriptAttachment.new_entity_script(entity, script)
or a set of Recipients:
Recipients.all_scripts(): every loaded script, once per script even if scripts share a contextRecipients.all_contexts(): every loaded context onceRecipients.static_script(script)Recipients.entity_script(entity, script)
For a single script, bms.run_script_callback returns the callback’s value. For recipients it returns a list with the value of each script which ran the callback.
Scripts which are still loading or unloading are skipped when targeting many scripts, while targeting a specific script which is not loaded is an error.
Errors
bms.run_script_callbackraises the callback’s error in the calling script, so it can be handled like any other error. For recipients, the first error is raised after all scripts ran the callback.- Errors of queued callbacks cannot reach the script which queued them, they are reported like other script errors (logged by default).
Which scripts can be called immediately
While a callback runs, its script context is busy, so bms.run_script_callback cannot run a callback in a busy context. This includes:
- the calling script itself (call the function directly instead),
- scripts sharing a context with the calling script,
- scripts further up the current chain of callbacks, e.g. A calls B, which calls A again.
These calls return an error instead. bms.queue_script_callback works for all of them, since queued callbacks only run once the current callback has finished.
Which scripts share a context depends on the context policy of the scripting plugin, by default none do.
Queued callbacks
- Queued callbacks run in the order they were queued, and can queue further callbacks, which run in the same go.
- They never run in the middle of the callback which queued them, even if it keeps using the world afterwards.
- To stop callbacks from queueing each other endlessly, at most 1024 queued callbacks run in one go. Any beyond that run later, and an error is reported.
Script systems
Script systems running in parallel with other systems (i.e. not marked exclusive) cannot use bms.run_script_callback, as another system might be running the target script at the same time.
Callbacks they queue run at the end of the frame instead, in the ScriptingSystemSet::RunQueuedCallbacks system set in the Last schedule.
Limits
- Callbacks can be nested at most 64 levels deep, i.e. a callback running another callback which runs another one and so on.
Events and Messages
Scripts can send Bevy events (observer-style, run immediately) and messages (buffered, read later by MessageReaders) using the reflection data Bevy generates for them.
| Function | Rust type data required | Behaviour |
|---|---|---|
world.trigger_event(type, value) | ReflectEvent | Triggers the event. Observers run, and all pending commands are applied, before the call returns. Also triggers script events. |
world.write_message(type, value) | ReflectMessage | Writes the message to its Messages<T> buffer, readers see it later in the frame. |
local world = import_namespace("bms").world
local my_game = import_namespace("my_game") -- the crate defining the types
world.trigger_event(my_game.MyEvent, my_game.MyEvent.new({ amount = 3 }))
world.write_message(my_game.MyMessage, my_game.MyMessage.new({ amount = 3 }))
The value is copied when sent, so the same value can be sent again, and changing it afterwards does not affect events already sent.
Registration requirements
Only types which are registered with the matching reflect attribute can be sent, anything else errors with a missing type data error:
#[derive(Event, Reflect)]
#[reflect(Event)]
struct MyEvent { amount: usize }
#[derive(Message, Reflect)]
#[reflect(Message)]
struct MyMessage { amount: usize }
app.register_type::<MyEvent>()
.register_type::<MyMessage>()
// messages must also be added as usual, otherwise there is nothing to write them to
.add_message::<MyMessage>();
- The type must be registered with
register_type, otherwise scripts cannot import it. #[reflect(Event)]is only generated for events using the default (global) trigger. Events with custom triggers, such as entity events, need a hand-writtenReflectEvent.- Types which do not implement
FromReflect(all fields must be reflectable) cannot be sent. - Bevy’s own events and messages are not usable unless they have the reflect attributes.
Things to be aware of
trigger_eventneeds exclusive access to the world, so it fails with an access error if the script is currently holding a borrowed reference elsewhere in the same call (e.g. inside a query iteration orwith_*access). Trigger events from regular callbacks.- Observers run before
trigger_eventreturns, and so do the commands they queue (as for other operations such as spawning). A Rust observer or command which runs a callback in the currently executing script context fails with an error. Usebms.run_script_callbackorbms.queue_script_callbackinstead (see Calling Other Scripts).
Observing events from scripts
world.add_observer(event, callback, components?, entities?) runs the calling script’s callback callback (registered with register_callback, or a top level function of that name) with a copy of the event, whenever the event is triggered. It returns the observer entity: despawn it to remove the observer.
local world = import_namespace("bms").world
local ecs = import_namespace("ecs")
local Mana = world.register_new_component("script.my_game", "Mana")
register_callback("on_mana_added", function(event)
print("Mana was added to", event.entity)
end)
local observer = world.add_observer(ecs.AddEvent, "on_mana_added", { Mana })
world.despawn(observer) -- later
- The lifecycle events
AddEvent,InsertEvent,DiscardEvent,RemoveEventandDespawnEvent(inecs) work for any native or script component. Other events need#[reflect(Event)]. - As in Bevy,
componentsis anORfilter, andentitiesrestricts the observer to those entities. - Callbacks run right after the triggering operation, in unspecified order. If the script’s context is busy (e.g. it triggered the event), the callback runs as soon as the busy callback finishes, so observers never re-enter a running script.
- The world is already past the change: removed component data can’t be read in
RemoveEventcallbacks. - Errors are reported like those of other callbacks (
ScriptErrorMessage), and don’t fail the triggering operation. add_observeronly works inside a script callback.
Script defined events
Scripts can define events carrying any value:
local world = import_namespace("bms").world
local Damaged = world.register_new_event("script.my_game", "Damaged")
register_callback("on_damaged", function(payload)
print("took damage:", payload.amount)
end)
world.add_observer(Damaged, "on_damaged")
world.trigger_event(Damaged, { amount = 5 })
register_new_eventfails if the name is taken, unlessallow_existing(third argument) is passed.- Script events are global:
componentsandentitiesare ignored. - Other scripts get them with
import_namespace, i.e.import_namespace("script.my_game").Damaged.
Built-in messages
The following BMS messages are reflected and can be written from scripts:
ScriptCallbackMessage: runs a callback on other scripts, processed later in the frame by the handler systems set up for its callback label. Labels without a handler system are never processed, preferbms.queue_script_callbackto run callbacks from scripts.ScriptLifecycleMessage(Attached/Detached),ScriptAssetModifiedMessage: drive the script loading pipeline
The internal loading pipeline state events (LoadingCompleted, ContextAssigned, …) are intentionally not reflected.
Bundles
Scripts can insert bundles defined in Rust, all components at once:
| Function | Behaviour |
|---|---|
world.insert_bundle(entity, type, value) | Inserts the bundle’s components into the entity. |
world.spawn_bundle(type, value) | Spawns an entity with the bundle and returns it. |
Bundles need ReflectBundle type data, and are constructed like any other type:
#[derive(Bundle, Reflect, Default)]
#[reflect(Bundle, Default)]
struct EnemyBundle {
health: Health,
transform: Transform,
}
app.register_type::<EnemyBundle>();
// tuples and foreign bundles: app.register_type_data::<(Health, Transform), ReflectBundle>()
local world = import_namespace("bms").world
local EnemyBundle = import_namespace("my_game").EnemyBundle
world.spawn_bundle(EnemyBundle, EnemyBundle.new({ health = Health.new({ hp = 10 }) }))
Core Bindings
Contents
This is an automatically generated file, you’ll find links to the contents below
| Section | Contents |
|---|---|
Types | Describes all available binding types |
Builtins | The values and functions every script has without importing anything |
Builtins
The only globals of scripts. Everything else is imported from a namespace, see the namespace pages under Types, i.e. import_namespace("bms").world.
Functions
| Name | Summary |
|---|---|
export_namespace | Exports a callback of the calling script as a function in a script namespace, so that any script (in any language) can… |
import_namespace | Imports a namespace, returning a table of the types, functions, values, events, system sets and exports in it by name. |
register_callback | Registers a function as the handler of a callback, taking precedence over a top level function of that name. |
export_namespace
Exports a callback of the calling script as a function in a script namespace, so that any script (in any language) can call it.
The callback is either a function registered with register_callback, or a top level function with that name.
Calls run in the exporting script and return what the callback returns.
register_callback("spawn_enemy_impl", function(health) ... end)
export_namespace("script.game", "spawn_enemy", "spawn_enemy_impl")
-- in another script, once the first one has run
import_namespace("script.game").spawn_enemy(5)
Arguments
name: the name of the function within the namespace.callback: the label of the callback of this script to export.
Returns: Nothing if the function was exported.
import_namespace
import_namespace(arg1: String) -> ScriptValue
Imports a namespace, returning a table of the types, functions, values, events, system sets and exports in it by name.
Bevy types with bindings live in a namespace per category (math, ecs, transform, ui, …), BMS’ own types and functions in bms,
any other type in the namespace named after the crate defining it. Namespaces defined by scripts start with script..
local bms = import_namespace("bms")
local Vec3 = import_namespace("math").Vec3
bms.world.spawn()
Fails with a list of similar namespaces if the namespace does not exist.
Returns: a table of the contents of the namespace keyed by name.
register_callback
register_callback(callback: String, function: DynamicFunction)
Registers a function as the handler of a callback, taking precedence over a top level function of that name.
register_callback("on_script_unloaded", function() print("unloading!") end)
Arguments
callback: the callback label to register the function against.function: the function handling the callback.
Types
Namespaces
Types are grouped by the namespace scripts import them from, i.e. import_namespace("math").
| Namespace | Contents |
|---|---|
alloc | 1 type |
animation | 10 types |
asset | 9 types, 2 values |
audio | 4 types |
bevy_platform | 3 types |
bevy_shader | 1 type |
bms | 30 types, 13 functions, 2 values |
camera | 17 types, 1 value |
camera.VisibilitySystems | 5 values |
color | 14 types |
core | 5 types |
ecs | 9 types |
gizmos | 1 type, 3 values |
input | 11 types, 1 value |
input.InputFocusSystems | 2 values |
math | 43 types |
petgraph | 1 type |
render | 23 types |
smol_str | 1 type |
sprite | 15 types |
text | 21 types, 2 values |
time | 9 types, 1 value |
transform | 2 types |
transform.TransformSystems | 1 value |
ui | 37 types, 1 value |
ui.UiSystems | 7 values |
uuid | 1 type |
wgpu_types | 1 type |
window | 16 types, 1 value |
window.CursorSystems | 1 value |
root | 27 types |
alloc
The types and functions in the alloc namespace, as returned by import_namespace("alloc").
Types
| Type | Summary |
|---|---|
Cow |
Cow
Opaque: scripts can't access its fields, only its functions.
Functions
| Name | Summary |
|---|---|
new | Constructs a new instance of the type from a table of its fields. |
new
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
animation
The types and functions in the animation namespace, as returned by import_namespace("animation").
Types
| Type | Summary |
|---|---|
ActiveAnimation | An animation that an AnimationPlayer is currently either playing or was playing, but is presently paused. |
AnimationClip | A list of VariableCurves and the AnimationTargetIds to which they apply. |
AnimationEventData | |
AnimationEventTarget | |
AnimationGraph | A graph structure that describes how animation clips are to be blended together. |
AnimationPlayer | Animation controls. |
AnimationTargetId | A component that identifies which parts of an AnimationClip asset can be applied to an entity. |
NodeIndex | |
RepeatAnimation | Repetition behavior of an animation. |
TimedAnimationEvent |
ActiveAnimation
An animation that an AnimationPlayer is currently either playing or was
playing, but is presently paused.
A stopped animation is considered no longer active.
Fields
| Field | Type |
|---|---|
weight | f32 |
repeat | RepeatAnimation |
speed | f32 |
elapsed | f32 |
seek_time | f32 |
last_seek_time | Optional<f32> |
completions | u32 |
just_completed | bool |
paused | bool |
Functions
| Name | Summary |
|---|---|
new | Constructs a new instance of the type from a table of its fields. |
new
new(payload: Fields<ActiveAnimation>) -> ActiveAnimation
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
AnimationClip
A list of VariableCurves and the AnimationTargetIds to which they
apply.
Because animation clips refer to targets by UUID, they can target any entity with that ID.
Fields
| Field | Type |
|---|---|
events | HashMap<AnimationEventTarget, Vec<TimedAnimationEvent>> |
duration | f32 |
Functions
| Name | Summary |
|---|---|
add_asset | Adds a value of this type as a new asset, returning a strong handle to it. |
get_asset | The asset a handle points to, or nil if it isn’t loaded or added yet. |
load | Starts loading an asset of this type from a path, returning a handle to it right away. |
new | Constructs a new instance of the type from a table of its fields. |
add_asset
add_asset(value: AnimationClip) -> Handle<AnimationClip>
Adds a value of this type as a new asset, returning a strong handle to it.
Arguments
value: The asset value.
Returns: A handle to the new asset.
get_asset
get_asset(handle: Handle<AnimationClip>) -> Optional<AnimationClip>
The asset a handle points to, or nil if it isn’t loaded or added yet.
Changes to the returned value change the asset.
Arguments
handle: The handle to the asset.
Returns: The asset, or nil.
load
load(path: String) -> Handle<AnimationClip>
Starts loading an asset of this type from a path, returning a handle to it right away.
Arguments
path: The asset path, relative to the assets folder.
Returns: A handle to the asset, which is loaded in the background.
new
new(payload: Fields<AnimationClip>) -> AnimationClip
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
AnimationEventData
Functions
| Name | Summary |
|---|---|
new | Constructs a new instance of the type from a table of its fields. |
new
new(payload: Fields<AnimationEventData>) -> AnimationEventData
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
AnimationEventTarget
Variants
| Variant | Fields |
|---|---|
Root | |
Node | (AnimationTargetId) |
Functions
| Name | Summary |
|---|---|
new | Constructs a new instance of the type from a table of its fields. |
new
new(payload: Fields<AnimationEventTarget>) -> AnimationEventTarget
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
Variant Functions
Node.new
new(variant: EnumVariantRef, payload: Fields<AnimationEventTarget::Node>) -> AnimationEventTarget
Root.new
new(variant: EnumVariantRef, payload: Fields<AnimationEventTarget::Root>) -> AnimationEventTarget
AnimationGraph
A graph structure that describes how animation clips are to be blended together.
Applications frequently want to be able to play multiple animations at once and to fine-tune the influence that animations have on a skinned mesh. Bevy uses an animation graph to store this information. Animation graphs are a directed acyclic graph (DAG) that describes how animations are to be weighted and combined together. Every frame, Bevy evaluates the graph from the root and blends the animations together in a bottom-up fashion to produce the final pose.
There are three types of nodes: blend nodes, add nodes, and clip nodes, all of which can have an associated weight. Blend nodes and add nodes have no associated animation clip and combine the animations of their children according to those children’s weights. Clip nodes specify an animation clip to play. When a graph is created, it starts with only a single blend node, the root node.
For example, consider the following graph:
┌────────────┐
│ │
│ Idle ├─────────────────────┐
│ │ │
└────────────┘ │
│
┌────────────┐ │ ┌────────────┐
│ │ │ │ │
│ Run ├──┐ ├──┤ Root │
│ │ │ ┌────────────┐ │ │ │
└────────────┘ │ │ Blend │ │ └────────────┘
├──┤ ├──┘
┌────────────┐ │ │ 0.5 │
│ │ │ └────────────┘
│ Walk ├──┘
│ │
└────────────┘
In this case, assuming that Idle, Run, and Walk are all playing with weight 1.0, the Run and Walk animations will be equally blended together, then their weights will be halved and finally blended with the Idle animation. Thus the weight of Run and Walk are effectively half of the weight of Idle.
Nodes can optionally have a mask, a bitfield that restricts the set of animation targets that the node and its descendants affect. Each bit in the mask corresponds to a mask group, which is a set of animation targets (bones). An animation target can belong to any number of mask groups within the context of an animation graph.
When the appropriate bit is set in a node’s mask, neither the node nor its descendants will animate any animation targets belonging to that mask group. That is, setting a mask bit to 1 disables the animation targets in that group. If an animation target belongs to multiple mask groups, masking any one of the mask groups that it belongs to will mask that animation target. (Thus an animation target will only be animated if all of its mask groups are unmasked.)
A common use of masks is to allow characters to hold objects. For this, the typical workflow is to assign each character’s hand to a mask group. Then, when the character picks up an object, the application masks out the hand that the object is held in for the character’s animation set, then positions the hand’s digits as necessary to grasp the object. The character’s animations will continue to play but will not affect the hand, which will continue to be depicted as holding the object.
Animation graphs are assets and can be serialized to and loaded from RON
files. Canonically, such files have an .animgraph.ron extension.
The animation graph implements RFC 51. See that document for more information.
Fields
| Field | Type |
|---|---|
graph | DiGraph<Unknown, Unknown, u32> |
root | NodeIndex |
mask_groups | HashMap<AnimationTargetId, u64> |
Functions
| Name | Summary |
|---|---|
from_clip | A new graph that plays handle on its own at full weight. |
new | Constructs a new instance of the type from a table of its fields. |
from_clip
from_clip(handle: Handle<AnimationClip>) -> AnimationGraph
A new graph that plays handle on its own at full weight.
new
new(payload: Fields<AnimationGraph>) -> AnimationGraph
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
Methods
| Name | Summary |
|---|---|
add_clip | Adds the clip handle under the node parent, with weight relative to its siblings. Returns the new node. |
root_node | The index of the root node of the graph, which all of its animations are blended into. |
add_clip
add_clip(self: AnimationGraph, handle: Handle<AnimationClip>, weight: f32, parent: NodeIndex) -> NodeIndex
Adds the clip handle under the node parent, with weight relative to its siblings. Returns the new node.
root_node
root_node(self: AnimationGraph) -> NodeIndex
The index of the root node of the graph, which all of its animations are blended into.
AnimationPlayer
Component
Animation controls.
Automatically added to any root animations of a scene when it is spawned.
Fields
| Field | Type |
|---|---|
active_animations | HashMap<NodeIndex, ActiveAnimation> |
Functions
| Name | Summary |
|---|---|
new | Constructs a new instance of the type from a table of its fields. |
new
new(payload: Fields<AnimationPlayer>) -> AnimationPlayer
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
Methods
| Name | Summary |
|---|---|
all_finished | Whether every playing animation has finished. True when nothing is playing. |
all_paused | Whether every playing animation is paused. True when nothing is playing. |
animation_is_finished | Whether the animation node has finished, or nil if it is not playing. |
is_playing_animation | Whether the animation node is playing or paused. |
pause_all | Pauses all playing animations. |
play | Starts playing the animation node. Does nothing if it is already playing. |
resume_all | Resumes all paused animations. |
seek_to | Jumps the animation node to seconds into its clip. Errors if it is not playing. |
set_repeat_forever | Makes the animation node repeat forever. Errors if it is not playing. |
set_speed | Sets the playback speed of the animation node, where 1.0 is normal speed. Errors if it is not playing. |
stop | Stops the animation node and removes it from the player. |
stop_all | Stops all animations and removes them from the player. |
all_finished
all_finished(self: AnimationPlayer) -> bool
Whether every playing animation has finished. True when nothing is playing.
all_paused
all_paused(self: AnimationPlayer) -> bool
Whether every playing animation is paused. True when nothing is playing.
animation_is_finished
animation_is_finished(self: AnimationPlayer, node: NodeIndex) -> Optional<bool>
Whether the animation node has finished, or nil if it is not playing.
is_playing_animation
is_playing_animation(self: AnimationPlayer, node: NodeIndex) -> bool
Whether the animation node is playing or paused.
pause_all
pause_all(self: AnimationPlayer)
Pauses all playing animations.
play
play(self: AnimationPlayer, node: NodeIndex)
Starts playing the animation node. Does nothing if it is already playing.
resume_all
resume_all(self: AnimationPlayer)
Resumes all paused animations.
seek_to
seek_to(self: AnimationPlayer, node: NodeIndex, seconds: f32)
Jumps the animation node to seconds into its clip. Errors if it is not playing.
set_repeat_forever
set_repeat_forever(self: AnimationPlayer, node: NodeIndex)
Makes the animation node repeat forever. Errors if it is not playing.
set_speed
set_speed(self: AnimationPlayer, node: NodeIndex, speed: f32)
Sets the playback speed of the animation node, where 1.0 is normal speed. Errors if it is not playing.
stop
stop(self: AnimationPlayer, node: NodeIndex)
Stops the animation node and removes it from the player.
stop_all
stop_all(self: AnimationPlayer)
Stops all animations and removes them from the player.
AnimationTargetId
Component
A component that identifies which parts of an AnimationClip asset can
be applied to an entity. Typically used alongside the
AnimatedBy component.
AnimationTargetId is implemented as a UUID. When importing an armature
or an animation clip, asset loaders typically use the full path name from
the armature to the bone to generate these UUIDs. The ID is unique to the
full path name and based only on the names. So, for example, any imported
armature with a bone at the root named Hips will assign the same
AnimationTargetId to its root bone. Likewise, any imported animation
clip that animates a root bone named Hips will reference the same
AnimationTargetId. Any animation is playable on any armature as long as
the bone names match, which allows for easy animation retargeting.
Note that asset loaders generally use the full path name to generate the
AnimationTargetId. Thus a bone named Chest directly connected to a
bone named Hips will have a different ID from a bone named Chest that’s
connected to a bone named Stomach.
Fields
| Index | Type |
|---|---|
0 | Uuid |
Functions
| Name | Summary |
|---|---|
new | Constructs a new instance of the type from a table of its fields. |
new
new(payload: Fields<AnimationTargetId>) -> AnimationTargetId
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
NodeIndex
Opaque: scripts can't access its fields, only its functions.
Functions
| Name | Summary |
|---|---|
new | A node index from its number. |
new
A node index from its number.
Scripts see this type as NodeIndex.
local NodeIndex = import_namespace("animation").NodeIndex
local node = NodeIndex.new(3)
assert(node:index() == 3)
let NodeIndex = import_namespace("animation").NodeIndex;
let node = NodeIndex.new(3);
assert!(node.index() == 3);
Methods
| Name | Summary |
|---|---|
index | The number of this node index. |
index
The number of this node index.
RepeatAnimation
Repetition behavior of an animation.
Variants
| Variant | Fields |
|---|---|
Never | |
Count | (u32) |
Forever |
Functions
| Name | Summary |
|---|---|
new | Constructs a new instance of the type from a table of its fields. |
new
new(payload: Fields<RepeatAnimation>) -> RepeatAnimation
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
Variant Functions
| Name | Summary |
|---|---|
Count.new | |
Forever.new | |
Never.new |
Count.new
new(variant: EnumVariantRef, payload: Fields<RepeatAnimation::Count>) -> RepeatAnimation
Forever.new
new(variant: EnumVariantRef, payload: Fields<RepeatAnimation::Forever>) -> RepeatAnimation
Never.new
new(variant: EnumVariantRef, payload: Fields<RepeatAnimation::Never>) -> RepeatAnimation
TimedAnimationEvent
Fields
| Field | Type |
|---|---|
time | f32 |
event | AnimationEventData |
Functions
| Name | Summary |
|---|---|
new | Constructs a new instance of the type from a table of its fields. |
new
new(payload: Fields<TimedAnimationEvent>) -> TimedAnimationEvent
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
asset
The types and functions in the asset namespace, as returned by import_namespace("asset").
Types
| Type | Summary |
|---|---|
ArcMutexValue<T> | A shared value of an asset of type T. |
AssetId<A> | The id of an asset of type A. |
AssetIndex | A generational runtime-only identifier for a specific Asset stored in Assets. |
AssetPath | Represents a path to an asset in a “virtual filesystem”. |
Handle<A> | A handle to an asset of type A. |
HandleTemplate<T> | A template for a handle to an asset of type T. |
LoadedFolder | Not reflected: scripts can only pass values of it around. |
LoadedUntypedAsset | Not reflected: scripts can only pass values of it around. |
RenderAssetUsages | Defines where the asset will be used. |
Values
| Name | Type |
|---|---|
AssetEventSystems | ReflectSystemSet |
AssetTrackingSystems | ReflectSystemSet |
ArcMutexValue<T>
Generic
A shared value of an asset of type T.
Opaque: scripts can't access its fields, only its functions.
Instantiations
ArcMutexValue<ShaderBuffer>, ArcMutexValue<TextureAtlasLayout>, ArcMutexValue<ScriptAsset>, ArcMutexValue<Image>, ArcMutexValue<Mesh>, ArcMutexValue<ColorMaterial>, ArcMutexValue<SpriteMeshMaterial>
Functions
| Name | Summary |
|---|---|
new | Constructs a new instance of the type from a table of its fields. |
new
On ArcMutexValue<ShaderBuffer>, ArcMutexValue<TextureAtlasLayout>, ArcMutexValue<ScriptAsset>, ArcMutexValue<Image>, ArcMutexValue<Mesh>, ArcMutexValue<ColorMaterial>, ArcMutexValue<SpriteMeshMaterial>
new(payload: Fields<ArcMutexValue<ShaderBuffer>>) -> ArcMutexValue<ShaderBuffer>
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
AssetId<A>
Generic
The id of an asset of type A.
Variants
| Variant | Fields |
|---|---|
Index | { index: AssetIndex } |
Uuid | { uuid: Uuid } |
Instantiations
Functions
| Name | Summary |
|---|---|
new | Constructs a new instance of the type from a table of its fields. |
new
On AssetId<ScriptAsset>
new(payload: Fields<AssetId<ScriptAsset>>) -> AssetId<ScriptAsset>
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
AssetIndex
A generational runtime-only identifier for a specific Asset stored in Assets. This is optimized for efficient runtime
usage and is not suitable for identifying assets across app runs.
Fields
Functions
| Name | Summary |
|---|---|
new | Constructs a new instance of the type from a table of its fields. |
new
new(payload: Fields<AssetIndex>) -> AssetIndex
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
AssetPath
Represents a path to an asset in a “virtual filesystem”.
Asset paths consist of three main parts:
AssetPath::source: The name of theAssetSourceto load the asset from. This is optional. If one is not set the default source will be used (which is theassetsfolder by default).AssetPath::path: The “virtual filesystem path” pointing to an asset source file.AssetPath::label: An optional “named sub asset”. When assets are loaded, they are allowed to load “sub assets” of any type, which are identified by a named “label”.
Asset paths are generally constructed (and visualized) as strings:
# use bevy_asset::{Asset, AssetServer, Handle};
# use bevy_reflect::TypePath;
#
# #[derive(Asset, TypePath, Default)]
# struct Mesh;
#
# #[derive(Asset, TypePath, Default)]
# struct Scene;
#
# let asset_server: AssetServer = panic!();
// This loads the `my_scene.scn` base asset from the default asset source.
let scene: Handle<Scene> = asset_server.load("my_scene.scn");
// This loads the `PlayerMesh` labeled asset from the `my_scene.scn` base asset in the default asset source.
let mesh: Handle<Mesh> = asset_server.load("my_scene.scn#PlayerMesh");
// This loads the `my_scene.scn` base asset from a custom 'remote' asset source.
let scene: Handle<Scene> = asset_server.load("remote://my_scene.scn");
AssetPath implements From for &'static str, &'static Path, and &'a String,
which allows us to optimize the static cases.
This means that the common case of asset_server.load("my_scene.scn") when it creates and
clones internal owned AssetPaths.
This also means that you should use AssetPath::parse in cases where &str is the explicit type.
Opaque: scripts can't access its fields, only its functions.
Functions
| Name | Summary |
|---|---|
new | Constructs a new instance of the type from a table of its fields. |
new
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
Handle<A>
Generic
A handle to an asset of type A.
Variants
| Variant | Fields |
|---|---|
Strong | (Arc<Unknown>) |
Uuid | (Uuid) |
Instantiations
Handle<ScriptAsset>, Handle<AnimationClip>, Handle<ShaderBuffer>, Handle<TextureAtlasLayout>, Handle<Image>, Handle<ColorMaterial>, Handle<()>, Handle<Mesh>, Handle<SpriteMeshMaterial>
Functions
| Name | Summary |
|---|---|
new | Constructs a new instance of the type from a table of its fields. |
new
On Handle<ScriptAsset>, Handle<AnimationClip>, Handle<ShaderBuffer>, Handle<TextureAtlasLayout>, Handle<Image>, Handle<ColorMaterial>, Handle<()>, Handle<Mesh>, Handle<SpriteMeshMaterial>
new(payload: Fields<Handle<ScriptAsset>>) -> Handle<ScriptAsset>
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
Methods
| Name | Summary |
|---|---|
asset_path | Retrieves the path of the script asset if present. |
asset_path
On Handle<ScriptAsset>
asset_path(handle: Handle<ScriptAsset>) -> Optional<String>
Retrieves the path of the script asset if present.
Assets can be unloaded, and as such if the given handle is no longer active, this will return None.
Arguments
handle: The handle to the script asset.
Returns: The asset path of the script asset.
HandleTemplate<T>
Generic
A template for a handle to an asset of type T.
Variants
| Variant | Fields |
|---|---|
Path | (AssetPath) |
Handle | (Handle<T>) |
Value | (ArcMutexValue<T>) |
Instantiations
HandleTemplate<ScriptAsset>, HandleTemplate<TextureAtlasLayout>, HandleTemplate<ShaderBuffer>, HandleTemplate<Mesh>, HandleTemplate<Image>, HandleTemplate<ColorMaterial>, HandleTemplate<SpriteMeshMaterial>
Functions
| Name | Summary |
|---|---|
new | Constructs a new instance of the type from a table of its fields. |
new
On HandleTemplate<ScriptAsset>, HandleTemplate<TextureAtlasLayout>, HandleTemplate<ShaderBuffer>, HandleTemplate<Mesh>, HandleTemplate<Image>, HandleTemplate<ColorMaterial>, HandleTemplate<SpriteMeshMaterial>
new(payload: Fields<HandleTemplate<ScriptAsset>>) -> HandleTemplate<ScriptAsset>
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
LoadedFolder
Not reflected: scripts can only pass values of it around.
Opaque: scripts can't access its fields, only its functions.
LoadedUntypedAsset
Not reflected: scripts can only pass values of it around.
Opaque: scripts can't access its fields, only its functions.
RenderAssetUsages
Defines where the asset will be used.
If an asset is set to the RENDER_WORLD but not the MAIN_WORLD, the asset data (pixel data,
mesh vertex data, etc) will be removed from the cpu-side asset once it’s been extracted and prepared
in the render world. The asset will remain in the assets collection, but with only metadata.
Unloading the asset data saves on memory, as for most cases it is no longer necessary to keep
it in RAM once it’s been uploaded to the GPU’s VRAM. However, this means you cannot access the
asset data from the CPU (via the Assets<T> resource) once unloaded (without re-loading it).
If you never need access to the asset from the CPU past the first frame it’s loaded on,
or only need very infrequent access, then set this to RENDER_WORLD. Otherwise, set this to
RENDER_WORLD | MAIN_WORLD.
If you have an asset that doesn’t actually need to end up in the render world, like an Image
that will be decoded into another Image asset, use MAIN_WORLD only.
Platform-specific
On Wasm, it is not possible for now to free reserved memory. To control memory usage, load assets in sequence and unload one before loading the next. See this discussion about memory management for more details.
Opaque: scripts can't access its fields, only its functions.
Functions
| Name | Summary |
|---|---|
new | Constructs a new instance of the type from a table of its fields. |
new
new(payload: Fields<RenderAssetUsages>) -> RenderAssetUsages
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
audio
The types and functions in the audio namespace, as returned by import_namespace("audio").
Types
| Type | Summary |
|---|---|
PlaybackMode | The way Bevy manages the sound playback. |
PlaybackSettings | Initial settings to be used when audio starts playing. |
SpatialScale | A scale factor applied to the positions of audio sources and listeners for spatial audio. |
Volume | A Volume represents an audio source’s volume level. |
PlaybackMode
The way Bevy manages the sound playback.
Variants
| Variant |
|---|
Once |
Loop |
Despawn |
Remove |
Functions
| Name | Summary |
|---|---|
new | Constructs a new instance of the type from a table of its fields. |
new
new(payload: Fields<PlaybackMode>) -> PlaybackMode
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
Variant Functions
| Name | Summary |
|---|---|
Despawn.new | |
Loop.new | |
Once.new | |
Remove.new |
Despawn.new
new(variant: EnumVariantRef, payload: Fields<PlaybackMode::Despawn>) -> PlaybackMode
Loop.new
new(variant: EnumVariantRef, payload: Fields<PlaybackMode::Loop>) -> PlaybackMode
Once.new
new(variant: EnumVariantRef, payload: Fields<PlaybackMode::Once>) -> PlaybackMode
Remove.new
new(variant: EnumVariantRef, payload: Fields<PlaybackMode::Remove>) -> PlaybackMode
PlaybackSettings
Component
Initial settings to be used when audio starts playing.
If you would like to control the audio while it is playing, query for the
AudioSink or SpatialAudioSink
components. Changes to this component will not be applied to already-playing audio.
Fields
| Field | Type |
|---|---|
mode | PlaybackMode |
volume | Volume |
speed | f32 |
paused | bool |
muted | bool |
spatial | bool |
spatial_scale | Optional<SpatialScale> |
start_position | Optional<Duration> |
duration | Optional<Duration> |
Functions
| Name | Summary |
|---|---|
despawn | Settings that play the sound once, then despawn the entity. |
looping | Settings that repeat the sound forever. |
new | Constructs a new instance of the type from a table of its fields. |
once | Settings that play the sound once, then do nothing. |
remove | Settings that play the sound once, then remove the audio components from the entity. |
despawn
despawn() -> PlaybackSettings
Settings that play the sound once, then despawn the entity.
looping
looping() -> PlaybackSettings
Settings that repeat the sound forever.
new
new(payload: Fields<PlaybackSettings>) -> PlaybackSettings
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
once
once() -> PlaybackSettings
Settings that play the sound once, then do nothing.
remove
remove() -> PlaybackSettings
Settings that play the sound once, then remove the audio components from the entity.
Methods
| Name | Summary |
|---|---|
with_spatial | A copy of the settings with spatial audio turned on or off. |
with_speed | A copy of the settings with the starting speed set to speed, where 1 is normal speed. |
with_volume | A copy of the settings with the starting volume set to linear, where 1 is the original volume and 0 is silent. |
with_spatial
with_spatial(self: PlaybackSettings, spatial: bool) -> PlaybackSettings
A copy of the settings with spatial audio turned on or off.
with_speed
with_speed(self: PlaybackSettings, speed: f32) -> PlaybackSettings
A copy of the settings with the starting speed set to speed, where 1 is normal speed.
with_volume
with_volume(self: PlaybackSettings, linear: f32) -> PlaybackSettings
A copy of the settings with the starting volume set to linear, where 1 is the original volume and 0 is silent.
SpatialScale
A scale factor applied to the positions of audio sources and listeners for spatial audio.
Default is Vec3::ONE.
Fields
| Index | Type |
|---|---|
0 | Vec3 |
Functions
| Name | Summary |
|---|---|
new | Constructs a new instance of the type from a table of its fields. |
new
new(payload: Fields<SpatialScale>) -> SpatialScale
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
Volume
A Volume represents an audio source’s volume level.
To create a new Volume from a linear scale value, use
Volume::Linear.
To create a new Volume from decibels, use Volume::Decibels.
Variants
Functions
| Name | Summary |
|---|---|
new | Constructs a new instance of the type from a table of its fields. |
new
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
Variant Functions
| Name | Summary |
|---|---|
Decibels.new | |
Linear.new |
Decibels.new
new(variant: EnumVariantRef, payload: Fields<Volume::Decibels>) -> Volume
Linear.new
new(variant: EnumVariantRef, payload: Fields<Volume::Linear>) -> Volume
bevy_platform
The types and functions in the bevy_platform namespace, as returned by import_namespace("bevy_platform").
Types
| Type | Summary |
|---|---|
Arc<Unknown> | |
FixedHasher | Not reflected: scripts can only pass values of it around. |
Hashed<V, S> | A value with its hash computed once, S builds the hasher. |
Arc<Unknown>
Opaque: scripts can't access its fields, only its functions.
Functions
| Name | Summary |
|---|---|
new | Constructs a new instance of the type from a table of its fields. |
new
new(payload: Fields<Arc<Unknown>>) -> Arc<Unknown>
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
FixedHasher
Not reflected: scripts can only pass values of it around.
Opaque: scripts can't access its fields, only its functions.
Hashed<V, S>
Generic
A value with its hash computed once, S builds the hasher.
Opaque: scripts can't access its fields, only its functions.
Instantiations
Functions
| Name | Summary |
|---|---|
new | Constructs a new instance of the type from a table of its fields. |
new
On Hashed<Cow, FixedHasher>
new(payload: Fields<Hashed<Cow, FixedHasher>>) -> Hashed<Cow, FixedHasher>
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
bevy_shader
The types and functions in the bevy_shader namespace, as returned by import_namespace("bevy_shader").
Types
| Type | Summary |
|---|---|
Shader | Not reflected: scripts can only pass values of it around. |
Shader
Not reflected: scripts can only pass values of it around.
Opaque: scripts can't access its fields, only its functions.
bms
The types and functions in the bms namespace, as returned by import_namespace("bms").
Types
| Type | Summary |
|---|---|
CallbackLabel | A string which disallows common invalid characters in callback labels, particularly at the start of the string |
DynamicComponent | A dynamic script component |
EnumVariantRef | A reference to a variant of an enum, independent of any value of that enum. |
FunctionArgInfo | Information about a function argument. |
FunctionInfo | Information about a function. |
FunctionReturnInfo | Information about a function return value. |
FunctionScope | Where a function lives, for its documentation and errors |
InteropError | An error occurring when converting between rust and a script context. |
Language | Represents a scripting language. |
Recipients | Describes the designated recipients of a script event |
ReflectableScheduleLabel | |
ReflectSchedule | A reflectable schedule. |
ReflectSystem | A reflectable system. |
ReflectSystemSet | A reflectable system set: a set node of a schedule graph, or a set scripts put and order their systems in. |
ScriptAsset | Represents a script loaded into memory as an asset |
ScriptAssetModifiedMessage | Emitted when a script asset is modified and all its attachments require re-loading |
ScriptAttachment | Specifies a unique attachment of a script. |
ScriptBundleRegistration | A reference to a bundle type’s reflection registration, i.e. a type with ReflectBundle type data. |
ScriptCallbackMessage | A callback message meant to trigger a callback in a subset/set of scripts in the world with the given arguments |
ScriptComponent | A component which identifies the scripts existing on an entity. |
ScriptComponentRegistration | A reference to a component type’s reflection registration. |
ScriptEventRegistration | A handle to a script registered event type. |
ScriptLifecycleMessage | Emitted when a script is attached or detached. |
ScriptQueryBuilder | The query builder is used to build ECS queries which retrieve spefific components filtered by specific conditions. |
ScriptQueryResult | A result from a query. |
ScriptResourceRegistration | A reference to a resource type’s reflection registration. |
ScriptRunCondition | A run condition of a script system, evaluated in Rust without calling into the script, see… |
ScriptSystemBuilder | A builder for systems living in scripts |
ScriptTypeRegistration | A reference to a type which is not a Resource or Component. |
VariadicTuple | A tuple variant of script value |
Values
| Name | Type |
|---|---|
conditions | Type<ScriptRunCondition> |
world | World |
Functions
| Name | Summary |
|---|---|
construct | Attempts to construct the given type, given an arbitrary map of values. |
current_entity | The entity the running script is attached to, or nil if it isn’t attached to one. |
current_script | The asset handle of the running script, or nil outside of a script callback. |
log_debug | Logs a Debug level message to the console * message: the message to log |
log_error | Logs a Error level message to the console * message: the message to log |
log_info | Logs a Information level message to the console |
log_trace | Logs a Trace level message to the console * message: the message to log |
log_warn | Logs a Warning level message to the console * message: the message to log |
pack_args | Packs, a variable amount of values, into a single list. |
queue_script_callback | Queues a callback to run on other scripts as soon as the current callback finishes, in the same frame. |
run_script_callback | Runs a callback on other scripts immediately, and returns what it returned. |
system_builder | Creates a new script system builder, which can be used to add new systems to the world. |
unpack_args | Unpacks, a list of values, into many separate values. |
construct
construct<A>(registration: Type<A>, payload: HashMap<String, ScriptValue>) -> A
Generic over A, the type given as registration.
Attempts to construct the given type, given an arbitrary map of values.
Unlike Type.new, this works for every type, including ones with a new function of their own.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types, as for Type.new.
Arguments
registration: The type to construct.payload: The values to use to construct the type, keyed by field name or index, or a list of the fields in order.
Returns: The constructed type.
current_entity
current_entity() -> Optional<Entity>
The entity the running script is attached to, or nil if it isn’t attached to one.
Returns: The entity, or nil.
current_script
current_script() -> Optional<Handle<ScriptAsset>>
The asset handle of the running script, or nil outside of a script callback.
If the asset is ever unloaded, the handle will be less useful.
Returns: The handle, or nil.
log_debug
log_debug(message: String)
Logs a Debug level message to the console
message: the message to log
log_error
log_error(message: String)
Logs a Error level message to the console
message: the message to log
log_info
log_info(message: String)
Logs a Information level message to the console
Arguments
message: the message to log
log_trace
log_trace(message: String)
Logs a Trace level message to the console
message: the message to log
log_warn
log_warn(message: String)
Logs a Warning level message to the console
message: the message to log
pack_args
pack_args(tuple: …) -> Vec<ScriptValue>
Packs, a variable amount of values, into a single list.
Arguments
tuple: The tuple of values to curry
Returns: The list of values destructured from the tuple
queue_script_callback
queue_script_callback(label: String, target: ScriptAttachment | Recipients, args: …)
Queues a callback to run on other scripts as soon as the current callback finishes, in the same frame.
Unlike run_script_callback, this works for any script, including the calling script itself and scripts sharing its context.
Queued callbacks run in the order they were queued, and their errors are reported as script errors instead of being raised here.
Arguments
label: The name of the callback to run.target: The script attachment or recipients to run the callback on.args: The arguments to pass to the callback.
Returns: Nothing if the callback was queued.
run_script_callback
run_script_callback(label: String, target: ScriptAttachment | Recipients, args: …) -> ScriptValue
Runs a callback on other scripts immediately, and returns what it returned.
For example run_script_callback("take_damage", ScriptAttachment.new_entity_script(enemy, script), 10)
calls take_damage(10) in that script before this function returns.
The target is either a single script attachment, returning that callback’s value,
or Recipients, returning a list with the value of each script which ran the callback.
Errors of the callbacks are raised in the calling script, for recipients only after all of them ran.
Callbacks cannot run immediately in a script whose context is busy, i.e. the calling script itself,
scripts sharing its context (depending on the context policy), or scripts further up the current chain of callbacks.
Use queue_script_callback for those. It is also unavailable in script systems running in parallel with other systems.
Arguments
label: The name of the callback to run.target: The script attachment or recipients to run the callback on.args: The arguments to pass to the callback.
Returns: The value returned by the callback, or a list of the values returned by each recipient.
system_builder
system_builder(callback: String, attachment: ScriptAttachment) -> ScriptSystemBuilder
Creates a new script system builder, which can be used to add new systems to the world.
Arguments
callback: The function name in the script this system should call when run.attachment: The script attachment to use for the system. This is the attachment that will be used for the system’s callback.
Returns: The system builder
unpack_args
unpack_args(values: Vec<ScriptValue>) -> …
Unpacks, a list of values, into many separate values.
Arguments
values: The list of values to uncurry
Returns: The tuple of all values provided
CallbackLabel
A string which disallows common invalid characters in callback labels, particularly at the start of the string
a valid callback label starts with a letter or underscore, and contains only ascii characters, as well as disallows some common keywords
Fields
| Index | Type |
|---|---|
0 | String |
Functions
| Name | Summary |
|---|---|
new | Constructs a new instance of the type from a table of its fields. |
new
new(payload: Fields<CallbackLabel>) -> CallbackLabel
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
DynamicComponent
A dynamic script component
Fields
| Field | Type |
|---|---|
data | ScriptValue |
Functions
| Name | Summary |
|---|---|
new | Constructs a new instance of the type from a table of its fields. |
new
new(payload: Fields<DynamicComponent>) -> DynamicComponent
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
EnumVariantRef
A reference to a variant of an enum, independent of any value of that enum.
This is what scripts see when accessing MyEnum.Variant, it can be compared to
the result of value:variant() and used to construct values of the variant.
Fields
Methods
| Name | Summary |
|---|---|
new | Constructs a value of this enum variant from a table of its fields. |
variant_name | Retrieves the name of the variant. |
new
new(variant: EnumVariantRef, payload: HashMap<String, ScriptValue>) -> ReflectReference
Constructs a value of this enum variant from a table of its fields. Missing fields are filled in from the enum’s default if it is this variant, then from the defaults of the fields’ types.
Arguments
variant: The variant to construct.payload: The fields of the variant, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
variant_name
variant_name(variant: EnumVariantRef) -> String
Retrieves the name of the variant.
Arguments
variant: The variant.
Returns: The name of the variant.
Operators
| Name | Summary |
|---|---|
eq | Checks whether two variants are the same variant of the same enum, or whether a value is in this variant. |
eq
eq(variant: EnumVariantRef, other: ScriptValue) -> bool
Checks whether two variants are the same variant of the same enum, or whether a value is in this variant.
Arguments
variant: The variant.other: The variant or value to compare with.
Returns: Whether the other value is the same variant.
FunctionArgInfo
Information about a function argument.
Fields
FunctionInfo
Information about a function.
Fields
| Field | Type |
|---|---|
name | Cow |
namespace | FunctionScope |
arg_info | Vec<FunctionArgInfo> |
return_info | FunctionReturnInfo |
docs | Optional<Cow> |
FunctionReturnInfo
Information about a function return value.
Fields
| Field | Type |
|---|---|
type_id | TypeId |
FunctionScope
Where a function lives, for its documentation and errors
Variants
| Variant | Fields |
|---|---|
OnType | (TypeId) |
Member | |
Builtin |
Variant Functions
| Name | Summary |
|---|---|
Builtin.new | |
Member.new | |
OnType.new |
Builtin.new
new(variant: EnumVariantRef, payload: Fields<FunctionScope::Builtin>) -> FunctionScope
Member.new
new(variant: EnumVariantRef, payload: Fields<FunctionScope::Member>) -> FunctionScope
OnType.new
new(variant: EnumVariantRef, payload: Fields<FunctionScope::OnType>) -> FunctionScope
InteropError
An error occurring when converting between rust and a script context.
Opaque: scripts can't access its fields, only its functions.
Language
Represents a scripting language. Languages which compile into another language should use the target language as their language.
Variants
Functions
| Name | Summary |
|---|---|
new | Constructs a new instance of the type from a table of its fields. |
new
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
Variant Functions
| Name | Summary |
|---|---|
External.new | |
Lua.new | |
Rune.new | |
Unknown.new |
External.new
new(variant: EnumVariantRef, payload: Fields<Language::External>) -> Language
Lua.new
new(variant: EnumVariantRef, payload: Fields<Language::Lua>) -> Language
Rune.new
new(variant: EnumVariantRef, payload: Fields<Language::Rune>) -> Language
Unknown.new
new(variant: EnumVariantRef, payload: Fields<Language::Unknown>) -> Language
Recipients
Describes the designated recipients of a script event
Variants
| Variant | Fields |
|---|---|
AllScripts | |
AllContexts | |
ScriptEntity | (Handle<ScriptAsset>, Entity) |
StaticScript | (Handle<ScriptAsset>) |
Functions
| Name | Summary |
|---|---|
all_contexts | Targets every loaded context once, i.e. scripts sharing a context only run the callback once. |
all_scripts | Targets every loaded script, once per script even if scripts share a context. |
entity_script | Targets a single script attached to an entity. |
new | Constructs a new instance of the type from a table of its fields. |
static_script | Targets a single static script. |
all_contexts
all_contexts() -> Recipients
Targets every loaded context once, i.e. scripts sharing a context only run the callback once.
Returns:
recipients: The recipients.
all_scripts
all_scripts() -> Recipients
Targets every loaded script, once per script even if scripts share a context.
Returns:
recipients: The recipients.
entity_script
entity_script(entity: Entity, script: Handle<ScriptAsset>) -> Recipients
Targets a single script attached to an entity.
Arguments
entity: The entity the script is attached to.script: The script asset.
Returns: The recipients.
new
new(payload: Fields<Recipients>) -> Recipients
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
static_script
static_script(script: Handle<ScriptAsset>) -> Recipients
Targets a single static script.
Arguments
script: The script asset.
Returns: The recipients.
Variant Functions
AllContexts.new
new(variant: EnumVariantRef, payload: Fields<Recipients::AllContexts>) -> Recipients
AllScripts.new
new(variant: EnumVariantRef, payload: Fields<Recipients::AllScripts>) -> Recipients
ScriptEntity.new
new(variant: EnumVariantRef, payload: Fields<Recipients::ScriptEntity>) -> Recipients
StaticScript.new
new(variant: EnumVariantRef, payload: Fields<Recipients::StaticScript>) -> Recipients
ReflectableScheduleLabel
Opaque: scripts can't access its fields, only its functions.
Functions
| Name | Summary |
|---|---|
new | Constructs a new instance of the type from a table of its fields. |
new
new(payload: Fields<ReflectableScheduleLabel>) -> ReflectableScheduleLabel
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
ReflectSchedule
A reflectable schedule.
Fields
| Field | Type |
|---|---|
type_path | str |
label | ReflectableScheduleLabel |
Methods
| Name | Summary |
|---|---|
get_system_by_name | Retrieves the system with the given name in the schedule |
render_dot | Renders the schedule as a dot graph string. |
systems | Retrieves all the systems in the schedule. |
get_system_by_name
get_system_by_name(schedule: ReflectSchedule, name: String) -> Optional<ReflectSystem>
Retrieves the system with the given name in the schedule
Arguments
schedule: The schedule to retrieve the system from.name: The identifier or full path of the system to retrieve.
Returns: The system with the given name, if it exists.
render_dot
render_dot(schedule: ReflectSchedule) -> String
Renders the schedule as a dot graph string.
Useful for debugging scheduling.
Arguments
schedule: The schedule to render.
Returns: The dot graph string.
systems
systems(schedule: ReflectSchedule) -> Vec<ReflectSystem>
Retrieves all the systems in the schedule.
Arguments
schedule: The schedule to retrieve the systems from.
Returns: The systems in the schedule.
ReflectSystem
A reflectable system.
Opaque: scripts can't access its fields, only its functions.
Methods
| Name | Summary |
|---|---|
identifier | Retrieves the identifier of the system |
path | Retrieves the full path of the system |
identifier
identifier(system: ReflectSystem) -> String
Retrieves the identifier of the system
Arguments
system: The system to retrieve the identifier from.
Returns: The identifier of the system, e.g. my_system
path
path(system: ReflectSystem) -> String
Retrieves the full path of the system
Arguments
system: The system to retrieve the path from.
Returns: The full path of the system, e.g. my_crate::systems::my_system<T>
ReflectSystemSet
A reflectable system set: a set node of a schedule graph, or a set scripts put and order their systems in.
Bevy does not expose the interned sets of a schedule graph, so set nodes of a graph only have a node id, while sets made from an interned set (i.e. the ones scripts use) only have the set.
Opaque: scripts can't access its fields, only its functions.
Methods
| Name | Summary |
|---|---|
name | Retrieves the name of the system set |
name
name(set: ReflectSystemSet) -> String
Retrieves the name of the system set
Arguments
set: The system set to retrieve the name from.
Returns: The debug name of the set, e.g. TransformSystems::Propagate or ScriptNamedSet("script.my_game.ai")
ScriptAsset
Asset
Represents a script loaded into memory as an asset
Opaque: scripts can't access its fields, only its functions.
Functions
| Name | Summary |
|---|---|
add_asset | Adds a value of this type as a new asset, returning a strong handle to it. |
get_asset | The asset a handle points to, or nil if it isn’t loaded or added yet. |
load | Starts loading an asset of this type from a path, returning a handle to it right away. |
new | Constructs a new instance of the type from a table of its fields. |
add_asset
add_asset(value: ScriptAsset) -> Handle<ScriptAsset>
Adds a value of this type as a new asset, returning a strong handle to it.
Arguments
value: The asset value.
Returns: A handle to the new asset.
get_asset
get_asset(handle: Handle<ScriptAsset>) -> Optional<ScriptAsset>
The asset a handle points to, or nil if it isn’t loaded or added yet.
Changes to the returned value change the asset.
Arguments
handle: The handle to the asset.
Returns: The asset, or nil.
load
load(path: String) -> Handle<ScriptAsset>
Starts loading an asset of this type from a path, returning a handle to it right away.
Arguments
path: The asset path, relative to the assets folder.
Returns: A handle to the asset, which is loaded in the background.
new
new(payload: Fields<ScriptAsset>) -> ScriptAsset
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
ScriptAssetModifiedMessage
Emitted when a script asset is modified and all its attachments require re-loading
Fields
| Index | Type |
|---|---|
0 | AssetId<ScriptAsset> |
Functions
| Name | Summary |
|---|---|
new | Constructs a new instance of the type from a table of its fields. |
new
new(payload: Fields<ScriptAssetModifiedMessage>) -> ScriptAssetModifiedMessage
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
ScriptAttachment
Specifies a unique attachment of a script. These attachments are mapped to bevy_mod_scripting_core::ContextKey’s depending on the context policy used.
Variants
| Variant | Fields |
|---|---|
EntityScript | (Entity, Handle<ScriptAsset>) |
StaticScript | (Handle<ScriptAsset>) |
Functions
| Name | Summary |
|---|---|
new | Constructs a new instance of the type from a table of its fields. |
new_entity_script | Creates a new script attachment descriptor for an entity attached script. |
new_static_script | Creates a new script attachment descriptor from a script asset. |
new
new(payload: Fields<ScriptAttachment>) -> ScriptAttachment
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
new_entity_script
new_entity_script(entity: Entity, script: Handle<ScriptAsset>) -> ScriptAttachment
Creates a new script attachment descriptor for an entity attached script.
Arguments
entity: The entity to attach the script to.script: The script asset to attach to the entity.
Returns: The new script attachment for the entity.
new_static_script
new_static_script(script: Handle<ScriptAsset>) -> ScriptAttachment
Creates a new script attachment descriptor from a script asset.
Arguments
script: The script asset to create the attachment from.
Returns: The new script attachment.
Variant Functions
| Name | Summary |
|---|---|
EntityScript.new | |
StaticScript.new |
EntityScript.new
new(variant: EnumVariantRef, payload: Fields<ScriptAttachment::EntityScript>) -> ScriptAttachment
StaticScript.new
new(variant: EnumVariantRef, payload: Fields<ScriptAttachment::StaticScript>) -> ScriptAttachment
ScriptBundleRegistration
A reference to a bundle type’s reflection registration, i.e. a type with ReflectBundle type data.
In general think of this as a handle to a type.
Opaque: scripts can't access its fields, only its functions.
Methods
| Name | Summary |
|---|---|
namespace | Retrieves the script namespace of the type, by default the name of the crate defining it. |
short_name | Retrieves the short name of the type. The short name is a more human-readable version of the type name. |
type_name | Retrieves the name of the type. |
namespace
namespace(registration: ScriptBundleRegistration) -> String
Retrieves the script namespace of the type, by default the name of the crate defining it. Types in the root namespace have the empty string as namespace.
Arguments
registration: The type registration.
Returns: The namespace of the type.
short_name
short_name(registration: ScriptBundleRegistration) -> str
Retrieves the short name of the type. The short name is a more human-readable version of the type name.
Arguments
registration: The type registration.
Returns: The short name of the
type_name
type_name(registration: ScriptBundleRegistration) -> str
Retrieves the name of the type.
Arguments
registration: The type registration.
Returns: The name of the type.
ScriptCallbackMessage
A callback message meant to trigger a callback in a subset/set of scripts in the world with the given arguments
Fields
| Field | Type |
|---|---|
label | CallbackLabel |
recipients | Recipients |
language | Optional<Language> |
args | Vec<ScriptValue> |
trigger_response | bool |
iteration | usize |
Functions
| Name | Summary |
|---|---|
new | Constructs a new instance of the type from a table of its fields. |
new
new(payload: Fields<ScriptCallbackMessage>) -> ScriptCallbackMessage
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
ScriptComponent
Component
A component which identifies the scripts existing on an entity.
Event handlers search for components with this component to figure out which scripts to run and on which entities.
Fields
| Index | Type |
|---|---|
0 | Vec<Handle<ScriptAsset>> |
Functions
| Name | Summary |
|---|---|
new | Constructs a new instance of the type from a table of its fields. |
new
new(payload: Fields<ScriptComponent>) -> ScriptComponent
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
ScriptComponentRegistration
A reference to a component type’s reflection registration.
In general think of this as a handle to a type.
Not to be confused with script registered dynamic components, although this can point to a script registered component.
Opaque with private fields: world accessors trust that component_id belongs to registration’s type.
Opaque: scripts can't access its fields, only its functions.
Methods
| Name | Summary |
|---|---|
namespace | Retrieves the script namespace of the type, by default the name of the crate defining it. |
short_name | Retrieves the short name of the type. The short name is a more human-readable version of the type name. |
type_name | Retrieves the name of the type. |
namespace
namespace(registration: ScriptComponentRegistration) -> String
Retrieves the script namespace of the type, by default the name of the crate defining it. Types in the root namespace have the empty string as namespace.
Arguments
registration: The type registration.
Returns: The namespace of the type.
short_name
short_name(registration: ScriptComponentRegistration) -> str
Retrieves the short name of the type. The short name is a more human-readable version of the type name.
Arguments
registration: The type registration.
Returns: The short name of the
type_name
type_name(registration: ScriptComponentRegistration) -> str
Retrieves the name of the type.
Arguments
registration: The type registration.
Returns: The name of the type.
ScriptEventRegistration
A handle to a script registered event type.
Opaque: scripts can't access its fields, only its functions.
Methods
| Name | Summary |
|---|---|
namespace | Retrieves the script namespace the event was registered in, i.e. script.game for script.game.Hit. |
short_name | Retrieves the name of the event within its namespace, i.e. Hit for script.game.Hit. |
namespace
namespace(registration: ScriptEventRegistration) -> String
Retrieves the script namespace the event was registered in, i.e. script.game for script.game.Hit.
Arguments
registration: The event registration.
Returns: The namespace of the event.
short_name
short_name(registration: ScriptEventRegistration) -> String
Retrieves the name of the event within its namespace, i.e. Hit for script.game.Hit.
Arguments
registration: The event registration.
Returns: The name of the event.
ScriptLifecycleMessage
Emitted when a script is attached or detached.
Both are one message type, so the pipeline processes them in the order they were written.
Variants
| Variant | Fields |
|---|---|
Attached | (ScriptAttachment) |
Detached | (ScriptAttachment) |
Functions
| Name | Summary |
|---|---|
new | Constructs a new instance of the type from a table of its fields. |
new
new(payload: Fields<ScriptLifecycleMessage>) -> ScriptLifecycleMessage
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
Variant Functions
| Name | Summary |
|---|---|
Attached.new | |
Detached.new |
Attached.new
new(variant: EnumVariantRef, payload: Fields<ScriptLifecycleMessage::Attached>) -> ScriptLifecycleMessage
Detached.new
new(variant: EnumVariantRef, payload: Fields<ScriptLifecycleMessage::Detached>) -> ScriptLifecycleMessage
ScriptQueryBuilder
The query builder is used to build ECS queries which retrieve spefific components filtered by specific conditions.
For example:
builder.component(componentA)
.component(componentB)
.with(componentC)
.without(componentD)
Will retrieve entities which:
- Have componentA
- Have componentB
- Have componentC
- Do not have componentD
As well as references to components:
- componentA
- componentB
Opaque: scripts can't access its fields, only its functions.
Functions
| Name | Summary |
|---|---|
new | Constructs a new instance of the type from a table of its fields. |
new
new(payload: Fields<ScriptQueryBuilder>) -> ScriptQueryBuilder
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
Methods
| Name | Summary |
|---|---|
added | Only matches entities whose component was added since the system last ran (outside of systems: since the last update). |
build | Builds the query and retrieves the entities and component references. |
changed | Only matches entities whose component was changed since the system last ran (outside of systems: since the last… |
component | Adds a component to be retrieved by the query |
component_read | Adds a component to be retrieved by the query, which can only be read. |
optional | Adds a component to be retrieved by the query, which entities don’t need to have, it is nil for those which don’t. |
optional_read | Like optional, but the component can only be read. |
with | Adds a component to filter the query by. This component will NOT be retrieved. |
without | Adds a component to filter the query by. This component will NOT be retrieved. |
added
added(query: ScriptQueryBuilder, component: ScriptComponentRegistration) -> ScriptQueryBuilder
Only matches entities whose component was added since the system last ran (outside of systems: since the last update). This component will NOT be retrieved.
Arguments
query: The query to add the filter tocomponent: The component to filter by
Returns: The query with the filter added
build
build(query: ScriptQueryBuilder) -> Vec<(Entity, …Optional<ReflectReference>)>
Builds the query and retrieves the entities and component references.
Each result is a list of the entity followed by the components in the order they were added to the query,
i.e. local entity, a, b = result[1], result[2], result[3] in Lua, absent optional components are nil.
Arguments
query: The query to build.
Returns: The entities and component references that match the query.
changed
changed(query: ScriptQueryBuilder, component: ScriptComponentRegistration) -> ScriptQueryBuilder
Only matches entities whose component was changed since the system last ran (outside of systems: since the last update). This component will NOT be retrieved.
Arguments
query: The query to add the filter tocomponent: The component to filter by
Returns: The query with the filter added
component
component(query: ScriptQueryBuilder, components: ScriptComponentRegistration) -> ScriptQueryBuilder
Adds a component to be retrieved by the query
Arguments
query: The query to add the component to
Returns: The query with the component added
component_read
component_read(query: ScriptQueryBuilder, component: ScriptComponentRegistration) -> ScriptQueryBuilder
Adds a component to be retrieved by the query, which can only be read.
Script systems reading a component can run in parallel with each other, unlike ones writing it.
Arguments
query: The query to add the component tocomponent: The component to add
Returns: The query with the component added
optional
optional(query: ScriptQueryBuilder, component: ScriptComponentRegistration) -> ScriptQueryBuilder
Adds a component to be retrieved by the query, which entities don’t need to have, it is nil for those which don’t.
Arguments
query: The query to add the component tocomponent: The component to add
Returns: The query with the component added
optional_read
optional_read(query: ScriptQueryBuilder, component: ScriptComponentRegistration) -> ScriptQueryBuilder
Like optional, but the component can only be read.
Arguments
query: The query to add the component tocomponent: The component to add
Returns: The query with the component added
with
with(query: ScriptQueryBuilder, with: ScriptComponentRegistration) -> ScriptQueryBuilder
Adds a component to filter the query by. This component will NOT be retrieved.
Arguments
query: The query to add the component to
Returns: The query with the component added
without
without(query: ScriptQueryBuilder, without: ScriptComponentRegistration) -> ScriptQueryBuilder
Adds a component to filter the query by. This component will NOT be retrieved.
Arguments
query: The query to add the component to
Returns: The query with the component added
ScriptQueryResult
A result from a query.
Scripts receive it as a plain list, the entity followed by the components in the order they were added to the query,
i.e. {entity, a, b} in Lua, with nil for absent optional components. Nothing is allocated for the result itself.
Opaque: scripts can't access its fields, only its functions.
ScriptResourceRegistration
A reference to a resource type’s reflection registration.
In general think of this as a handle to a type.
Opaque with private fields: world accessors trust that resource_id belongs to registration’s type.
Opaque: scripts can't access its fields, only its functions.
Methods
| Name | Summary |
|---|---|
namespace | Retrieves the script namespace of the type, by default the name of the crate defining it. |
short_name | Retrieves the short name of the type. The short name is a more human-readable version of the type name. |
type_name | Retrieves the name of the type. |
namespace
namespace(registration: ScriptResourceRegistration) -> String
Retrieves the script namespace of the type, by default the name of the crate defining it. Types in the root namespace have the empty string as namespace.
Arguments
registration: The type registration.
Returns: The namespace of the type.
short_name
short_name(registration: ScriptResourceRegistration) -> str
Retrieves the short name of the type. The short name is a more human-readable version of the type name.
Arguments
registration: The type registration.
Returns: The short name of the
type_name
type_name(registration: ScriptResourceRegistration) -> str
Retrieves the name of the type.
Arguments
registration: The type registration.
Returns: The name of the type.
ScriptRunCondition
A run condition of a script system, evaluated in Rust without calling into the script, see ScriptSystemBuilder::run_if.
Opaque: scripts can't access its fields, only its functions.
Functions
| Name | Summary |
|---|---|
any_with_component | Holds if any entity has the component. |
new | Constructs a new instance of the type from a table of its fields. |
on_timer | Holds once every given amount of seconds, measured with Time. |
resource_added | Holds if the resource was added since the system last ran. |
resource_changed | Holds if the resource changed since the system last ran, doesn’t hold if it doesn’t exist. |
resource_exists | Holds if the resource exists. |
run_once | Holds the first time it is evaluated only. |
any_with_component
any_with_component(component: ScriptComponentRegistration) -> ScriptRunCondition
Holds if any entity has the component.
Arguments
component: The component.
Returns: The condition.
new
new(payload: Fields<ScriptRunCondition>) -> ScriptRunCondition
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
on_timer
on_timer(seconds: f64) -> ScriptRunCondition
Holds once every given amount of seconds, measured with Time.
Arguments
seconds: The interval in seconds.
Returns: The condition.
resource_added
resource_added(resource: ScriptResourceRegistration) -> ScriptRunCondition
Holds if the resource was added since the system last ran.
Arguments
resource: The resource.
Returns: The condition.
resource_changed
resource_changed(resource: ScriptResourceRegistration) -> ScriptRunCondition
Holds if the resource changed since the system last ran, doesn’t hold if it doesn’t exist.
Arguments
resource: The resource.
Returns: The condition.
resource_exists
resource_exists(resource: ScriptResourceRegistration) -> ScriptRunCondition
Holds if the resource exists.
Arguments
resource: The resource.
Returns: The condition.
run_once
run_once() -> ScriptRunCondition
Holds the first time it is evaluated only.
Returns:
condition: The condition.
Methods
| Name | Summary |
|---|---|
and_ | Holds if both conditions hold, the second one is only evaluated if the first one holds. |
not_ | Holds if the condition doesn’t hold. Named not_ as not is a keyword in Lua. |
or_ | Holds if either condition holds, the second one is only evaluated if the first one doesn’t hold. |
and_
and_(a: ScriptRunCondition, b: ScriptRunCondition) -> ScriptRunCondition
Holds if both conditions hold, the second one is only evaluated if the first one holds.
Arguments
a: The first condition.b: The second condition.
Returns: The combined condition.
not_
not_(condition: ScriptRunCondition) -> ScriptRunCondition
Holds if the condition doesn’t hold. Named not_ as not is a keyword in Lua.
Arguments
condition: The condition.
Returns: The negated condition.
or_
or_(a: ScriptRunCondition, b: ScriptRunCondition) -> ScriptRunCondition
Holds if either condition holds, the second one is only evaluated if the first one doesn’t hold.
Arguments
a: The first condition.b: The second condition.
Returns: The combined condition.
ScriptSystemBuilder
A builder for systems living in scripts
Opaque: scripts can't access its fields, only its functions.
Functions
| Name | Summary |
|---|---|
new | Constructs a new instance of the type from a table of its fields. |
new
new(payload: Fields<ScriptSystemBuilder>) -> ScriptSystemBuilder
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
Methods
| Name | Summary |
|---|---|
after | Specifies the system is to run after the given system |
after_script_system | Specifies the system is to run after the script system with the given callback label of the given script. |
after_set | Specifies the system is to run after the given set. |
before | Specifies the system is to run before the given system. |
before_script_system | Specifies the system is to run before the script system with the given callback label of the given script. |
before_set | Specifies the system is to run before the given set. |
exclusive | Specifies the system is to run exclusively, meaning it can access anything, but will not run in parallel with other… |
in_set | Puts the system in the given set, ordering the set orders the system. |
query | Adds a query to the system builder. |
resource | Requests the system have access to the given resource. |
resource_read | Requests the system have read only access to the given resource. |
run_if | Only runs the system if the condition holds, see bms.conditions. All conditions must hold for the system to run. |
after
after(builder: ScriptSystemBuilder, system: ReflectSystem) -> ScriptSystemBuilder
Specifies the system is to run after the given system
Note: this is an experimental feature, and the ordering might not work correctly for script initialized systems
Arguments
builder: The system builder to add the dependency to.system: The system to run after.
Returns: The system builder with the dependency added.
after_script_system
after_script_system(builder: ScriptSystemBuilder, label: String, attachment: ScriptAttachment) -> ScriptSystemBuilder
Specifies the system is to run after the script system with the given callback label of the given script. That system must have been added before this one.
Arguments
builder: The system builder to add the dependency to.label: The callback label of the other script system.attachment: The script the other script system belongs to.
Returns: The system builder with the dependency added.
after_set
after_set(builder: ScriptSystemBuilder, set: ReflectSystemSet) -> ScriptSystemBuilder
Specifies the system is to run after the given set.
Sets are registered by scripts with register_new_system_set, game sets are found with get_system_set_by_name.
Arguments
builder: The system builder to add the dependency to.set: The system set.
Returns: The system builder with the dependency added.
before
before(builder: ScriptSystemBuilder, system: ReflectSystem) -> ScriptSystemBuilder
Specifies the system is to run before the given system.
Note: this is an experimental feature, and the ordering might not work correctly for script initialized systems
Arguments
builder: The system builder to add the dependency to.system: The system to run before.
Returns: The system builder with the dependency added.
before_script_system
before_script_system(builder: ScriptSystemBuilder, label: String, attachment: ScriptAttachment) -> ScriptSystemBuilder
Specifies the system is to run before the script system with the given callback label of the given script. That system must have been added before this one.
Arguments
builder: The system builder to add the dependency to.label: The callback label of the other script system.attachment: The script the other script system belongs to.
Returns: The system builder with the dependency added.
before_set
before_set(builder: ScriptSystemBuilder, set: ReflectSystemSet) -> ScriptSystemBuilder
Specifies the system is to run before the given set.
Sets are registered by scripts with register_new_system_set, game sets are found with get_system_set_by_name.
Arguments
builder: The system builder to add the dependency to.set: The system set.
Returns: The system builder with the dependency added.
exclusive
exclusive(builder: ScriptSystemBuilder) -> ScriptSystemBuilder
Specifies the system is to run exclusively, meaning it can access anything, but will not run in parallel with other systems.
Arguments
builder: The system builder to make exclusive.
Returns: The system builder that is now exclusive.
in_set
in_set(builder: ScriptSystemBuilder, set: ReflectSystemSet) -> ScriptSystemBuilder
Puts the system in the given set, ordering the set orders the system.
Sets are registered by scripts with register_new_system_set, game sets are found with get_system_set_by_name.
Arguments
builder: The system builder to put in the set.set: The system set.
Returns: The system builder in the set.
query
query(builder: ScriptSystemBuilder, query: ScriptQueryBuilder) -> ScriptSystemBuilder
Adds a query to the system builder.
Arguments
builder: The system builder to add the query to.query: The query to add.
Returns: The system builder with the query added.
resource
resource(builder: ScriptSystemBuilder, resource: ScriptResourceRegistration) -> ScriptSystemBuilder
Requests the system have access to the given resource. The resource will be added to the list of arguments of the callback in the order they’re provided.
Arguments
builder: The system builder to add the resource to.resource: The resource to add.
Returns: The system builder with the resource added.
resource_read
resource_read(builder: ScriptSystemBuilder, resource: ScriptResourceRegistration) -> ScriptSystemBuilder
Requests the system have read only access to the given resource. The resource will be added to the list of arguments of the callback in the order they’re provided.
Script systems reading a resource can run in parallel with each other, unlike ones writing it.
Arguments
builder: The system builder to add the resource to.resource: The resource to add.
Returns: The system builder with the resource added.
run_if
run_if(builder: ScriptSystemBuilder, condition: ScriptRunCondition) -> ScriptSystemBuilder
Only runs the system if the condition holds, see bms.conditions. All conditions must hold for the system to run.
Conditions are evaluated without calling into the script.
Arguments
builder: The system builder to add the condition to.condition: The condition.
Returns: The system builder with the condition added.
ScriptTypeRegistration
A reference to a type which is not a Resource or Component.
In general think of this as a handle to a type.
Opaque: scripts can't access its fields, only its functions.
Methods
| Name | Summary |
|---|---|
namespace | Retrieves the script namespace of the type, by default the name of the crate defining it. |
short_name | Retrieves the short name of the type. The short name is a more human-readable version of the type name. |
type_name | Retrieves the name of the type. |
namespace
namespace(registration: ScriptTypeRegistration) -> String
Retrieves the script namespace of the type, by default the name of the crate defining it. Types in the root namespace have the empty string as namespace.
Arguments
registration: The type registration.
Returns: The namespace of the type.
short_name
short_name(registration: ScriptTypeRegistration) -> String
Retrieves the short name of the type. The short name is a more human-readable version of the type name.
Arguments
registration: The type registration.
Returns: The short name of the
type_name
type_name(registration: ScriptTypeRegistration) -> String
Retrieves the name of the type.
Arguments
registration: The type registration.
Returns: The name of the type.
VariadicTuple
A tuple variant of script value
Opaque: scripts can't access its fields, only its functions.
Functions
| Name | Summary |
|---|---|
new | Constructs a new instance of the type from a table of its fields. |
new
new(payload: Fields<VariadicTuple>) -> VariadicTuple
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
camera
The types and functions in the camera namespace, as returned by import_namespace("camera").
Types
| Type | Summary |
|---|---|
Camera | The defining Component for camera entities, storing information about how and what to render through this camera. |
CameraOutputMode | Control how this Camera outputs once rendering is completed. |
ClearColorConfig | For a camera, specifies the color used to clear the viewport before rendering or when writing to the final render… |
ComputedCameraValues | Holds internally computed Camera values. |
ImageRenderTarget | A render target that renders to an Image. |
InheritedVisibility | Whether or not an entity is visible in the hierarchy. |
ManualTextureViewHandle | A unique id that corresponds to a specific ManualTextureView in the ManualTextureViews collection. |
MsaaWriteback | Controls when MSAA writeback occurs for a camera. |
OrthographicProjection | Project a 3D space onto a 2D surface using parallel lines, i.e., unlike PerspectiveProjection, the size of objects… |
RenderLayers | Defines which rendering layers an entity belongs to. |
RenderTarget | The “target” that a Camera will render to. For example, this could be a Window swapchain or an Image. |
RenderTargetInfo | Information about the current RenderTarget. |
ScalingMode | Scaling mode for OrthographicProjection. |
SubCameraView | Settings to define a camera sub view. |
Viewport | Render viewport configuration for the Camera component. |
ViewVisibility | Algorithmically computed indication of whether an entity is visible and should be extracted for rendering. |
Visibility | User indication of whether an entity is visible. Propagates down the entity hierarchy. |
Values
| Name | Type |
|---|---|
CameraUpdateSystems | ReflectSystemSet |
Camera
Component
The defining Component for camera entities,
storing information about how and what to render through this camera.
The Camera component is added to an entity to define the properties of the viewpoint from
which rendering occurs. It defines the position of the view to render, the projection method
to transform the 3D objects into a 2D image, as well as the render target into which that image
is produced.
Note that a Camera needs a CameraRenderGraph to render anything.
This is typically provided by adding a Camera2d or Camera3d component,
but custom render graphs can also be defined. Inserting a Camera with no render
graph will emit an error at runtime.
Fields
| Field | Type |
|---|---|
viewport | Optional<Viewport> |
order | isize |
is_active | bool |
computed | ComputedCameraValues |
output_mode | CameraOutputMode |
msaa_writeback | MsaaWriteback |
clear_color | ClearColorConfig |
invert_culling | bool |
sub_camera_view | Optional<SubCameraView> |
Functions
| Name | Summary |
|---|---|
new | Constructs a new instance of the type from a table of its fields. |
new
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
Methods
| Name | Summary |
|---|---|
logical_viewport_rect | The rectangle of the viewport in logical pixels, or nil if the camera has no target yet. |
logical_viewport_size | The size of the viewport in logical pixels, or nil if the camera has no target yet. |
physical_viewport_size | The size of the viewport in physical pixels, or nil if the camera has no target yet. |
viewport_to_world | A ray from the camera through a point on its viewport, or nil if the point cannot be converted. |
viewport_to_world_2d | The point in the 2D world seen through a point on the viewport, or nil if the point cannot be converted. |
world_to_viewport | The position on the viewport of a point in the world, or nil if the point cannot be converted. |
logical_viewport_rect
The rectangle of the viewport in logical pixels, or nil if the camera has no target yet.
logical_viewport_size
The size of the viewport in logical pixels, or nil if the camera has no target yet.
physical_viewport_size
The size of the viewport in physical pixels, or nil if the camera has no target yet.
viewport_to_world
viewport_to_world(self: Camera, camera_transform: GlobalTransform, viewport_position: Vec2) -> Optional<Ray3d>
A ray from the camera through a point on its viewport, or nil if the point cannot be converted.
viewport_to_world_2d
viewport_to_world_2d(self: Camera, camera_transform: GlobalTransform, viewport_position: Vec2) -> Optional<Vec2>
The point in the 2D world seen through a point on the viewport, or nil if the point cannot be converted.
world_to_viewport
world_to_viewport(self: Camera, camera_transform: GlobalTransform, world_position: Vec3) -> Optional<Vec2>
The position on the viewport of a point in the world, or nil if the point cannot be converted.
CameraOutputMode
Control how this Camera outputs once rendering is completed.
Variants
| Variant | Fields |
|---|---|
Write | { blend_state: Optional<BlendState>, clear_color: ClearColorConfig } |
Skip |
Functions
| Name | Summary |
|---|---|
new | Constructs a new instance of the type from a table of its fields. |
new
new(payload: Fields<CameraOutputMode>) -> CameraOutputMode
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
Variant Functions
Skip.new
new(variant: EnumVariantRef, payload: Fields<CameraOutputMode::Skip>) -> CameraOutputMode
Write.new
new(variant: EnumVariantRef, payload: Fields<CameraOutputMode::Write>) -> CameraOutputMode
ClearColorConfig
For a camera, specifies the color used to clear the viewport before rendering or when writing to the final render target texture.
Variants
| Variant | Fields |
|---|---|
Default | |
Custom | (Color) |
None |
Functions
| Name | Summary |
|---|---|
new | Constructs a new instance of the type from a table of its fields. |
new
new(payload: Fields<ClearColorConfig>) -> ClearColorConfig
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
Variant Functions
| Name | Summary |
|---|---|
Custom.new | |
Default.new | |
None.new |
Custom.new
new(variant: EnumVariantRef, payload: Fields<ClearColorConfig::Custom>) -> ClearColorConfig
Default.new
new(variant: EnumVariantRef, payload: Fields<ClearColorConfig::Default>) -> ClearColorConfig
None.new
new(variant: EnumVariantRef, payload: Fields<ClearColorConfig::None>) -> ClearColorConfig
ComputedCameraValues
Holds internally computed Camera values.
Fields
| Field | Type |
|---|---|
clip_from_view | Mat4 |
target_info | Optional<RenderTargetInfo> |
old_viewport_size | Optional<UVec2> |
old_sub_camera_view | Optional<SubCameraView> |
Functions
| Name | Summary |
|---|---|
new | Constructs a new instance of the type from a table of its fields. |
new
new(payload: Fields<ComputedCameraValues>) -> ComputedCameraValues
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
ImageRenderTarget
A render target that renders to an Image.
Fields
Functions
| Name | Summary |
|---|---|
new | Constructs a new instance of the type from a table of its fields. |
new
new(payload: Fields<ImageRenderTarget>) -> ImageRenderTarget
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
InheritedVisibility
Component
Whether or not an entity is visible in the hierarchy.
This is a computed component that users should not change manually.
To set the visibility of an entity, use Visibility instead.
For more information, see module level documentation.
This property is updated in VisibilityPropagate in the PostUpdate schedule.
Until then, it is not up to date with Visibility if it was changed
in the same frame.
If this is false, then ViewVisibility should also be false.
Fields
| Index | Type |
|---|---|
0 | bool |
Functions
| Name | Summary |
|---|---|
new | Constructs a new instance of the type from a table of its fields. |
new
new(payload: Fields<InheritedVisibility>) -> InheritedVisibility
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
Methods
| Name | Summary |
|---|---|
get | Whether the entity is visible, taking its parents into account. |
get
get(self: InheritedVisibility) -> bool
Whether the entity is visible, taking its parents into account.
ManualTextureViewHandle
Component
A unique id that corresponds to a specific ManualTextureView in the ManualTextureViews collection.
See ManualTextureViews in bevy_camera for more details.
Fields
| Index | Type |
|---|---|
0 | u32 |
Functions
| Name | Summary |
|---|---|
new | Constructs a new instance of the type from a table of its fields. |
new
new(payload: Fields<ManualTextureViewHandle>) -> ManualTextureViewHandle
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
MsaaWriteback
Controls when MSAA writeback occurs for a camera.
MSAA writeback copies the previous camera’s output into the MSAA sampled texture before rendering, allowing multiple cameras to layer their results when MSAA is enabled.
Variants
| Variant |
|---|
Off |
Auto |
Always |
Functions
| Name | Summary |
|---|---|
new | Constructs a new instance of the type from a table of its fields. |
new
new(payload: Fields<MsaaWriteback>) -> MsaaWriteback
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
Variant Functions
| Name | Summary |
|---|---|
Always.new | |
Auto.new | |
Off.new |
Always.new
new(variant: EnumVariantRef, payload: Fields<MsaaWriteback::Always>) -> MsaaWriteback
Auto.new
new(variant: EnumVariantRef, payload: Fields<MsaaWriteback::Auto>) -> MsaaWriteback
Off.new
new(variant: EnumVariantRef, payload: Fields<MsaaWriteback::Off>) -> MsaaWriteback
OrthographicProjection
Project a 3D space onto a 2D surface using parallel lines, i.e., unlike PerspectiveProjection,
the size of objects remains the same regardless of their distance to the camera.
The volume contained in the projection is called the view frustum. Since the viewport is rectangular and projection lines are parallel, the view frustum takes the shape of a cuboid.
Note that the scale of the projection and the apparent size of objects are inversely proportional. As the size of the projection increases, the size of objects decreases.
Examples
Configure the orthographic projection to one world unit per 100 window pixels:
let projection = Projection::Orthographic(OrthographicProjection {
scaling_mode: ScalingMode::WindowSize,
scale: 0.01,
..OrthographicProjection::default_2d()
});
Fields
Functions
| Name | Summary |
|---|---|
default_2d | The default projection for 2D cameras. |
default_3d | The default projection for 3D cameras. |
new | Constructs a new instance of the type from a table of its fields. |
default_2d
default_2d() -> OrthographicProjection
The default projection for 2D cameras.
default_3d
default_3d() -> OrthographicProjection
The default projection for 3D cameras.
new
new(payload: Fields<OrthographicProjection>) -> OrthographicProjection
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
RenderLayers
Component
Defines which rendering layers an entity belongs to.
A camera renders an entity only when their render layers intersect.
The Default instance of RenderLayers contains layer 0, the first layer. Entities
without this component also belong to layer 0.
An empty RenderLayers makes the entity invisible.
Fields
| Index | Type |
|---|---|
0 | Vec<u64> |
Functions
| Name | Summary |
|---|---|
layer | Render layers containing only the given layer. |
new | Constructs a new instance of the type from a table of its fields. |
none | Render layers containing no layers, so nothing is rendered with them. |
layer
layer(n: usize) -> RenderLayers
Render layers containing only the given layer.
new
new(payload: Fields<RenderLayers>) -> RenderLayers
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
none
none() -> RenderLayers
Render layers containing no layers, so nothing is rendered with them.
Methods
| Name | Summary |
|---|---|
intersects | Whether these render layers share at least one layer with another set. |
with | A copy of these render layers that also contains the given layer. |
without | A copy of these render layers without the given layer. |
intersects
intersects(self: RenderLayers, other: RenderLayers) -> bool
Whether these render layers share at least one layer with another set.
with
with(self: RenderLayers, n: usize) -> RenderLayers
A copy of these render layers that also contains the given layer.
without
without(self: RenderLayers, n: usize) -> RenderLayers
A copy of these render layers without the given layer.
Operators
| Name | Summary |
|---|---|
iter | The numbers of all layers in these render layers. |
iter
iter(self: RenderLayers) -> Vec<usize>
The numbers of all layers in these render layers.
RenderTarget
Component
The “target” that a Camera will render to. For example, this could be a Window
swapchain or an Image.
Variants
| Variant | Fields |
|---|---|
Window | (WindowRef) |
Image | (ImageRenderTarget) |
TextureView | (ManualTextureViewHandle) |
None | { size: UVec2 } |
Functions
| Name | Summary |
|---|---|
new | Constructs a new instance of the type from a table of its fields. |
new
new(payload: Fields<RenderTarget>) -> RenderTarget
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
Variant Functions
| Name | Summary |
|---|---|
Image.new | |
None.new | |
TextureView.new | |
Window.new |
Image.new
new(variant: EnumVariantRef, payload: Fields<RenderTarget::Image>) -> RenderTarget
None.new
new(variant: EnumVariantRef, payload: Fields<RenderTarget::None>) -> RenderTarget
TextureView.new
new(variant: EnumVariantRef, payload: Fields<RenderTarget::TextureView>) -> RenderTarget
Window.new
new(variant: EnumVariantRef, payload: Fields<RenderTarget::Window>) -> RenderTarget
RenderTargetInfo
Information about the current RenderTarget.
Fields
Functions
| Name | Summary |
|---|---|
new | Constructs a new instance of the type from a table of its fields. |
new
new(payload: Fields<RenderTargetInfo>) -> RenderTargetInfo
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
ScalingMode
Scaling mode for OrthographicProjection.
The effect of these scaling modes are combined with the OrthographicProjection::scale property.
For example, if the scaling mode is ScalingMode::Fixed { width: 100.0, height: 300 } and the scale is 2.0,
the projection will be 200 world units wide and 600 world units tall.
Examples
Configure the orthographic projection to two world units per window height:
let projection = Projection::Orthographic(OrthographicProjection {
scaling_mode: ScalingMode::FixedVertical { viewport_height: 2.0 },
..OrthographicProjection::default_2d()
});
Variants
| Variant | Fields |
|---|---|
WindowSize | |
Fixed | { width: f32, height: f32 } |
AutoMin | { min_width: f32, min_height: f32 } |
AutoMax | { max_width: f32, max_height: f32 } |
FixedVertical | { viewport_height: f32 } |
FixedHorizontal | { viewport_width: f32 } |
Functions
| Name | Summary |
|---|---|
new | Constructs a new instance of the type from a table of its fields. |
new
new(payload: Fields<ScalingMode>) -> ScalingMode
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
Variant Functions
AutoMax.new
new(variant: EnumVariantRef, payload: Fields<ScalingMode::AutoMax>) -> ScalingMode
AutoMin.new
new(variant: EnumVariantRef, payload: Fields<ScalingMode::AutoMin>) -> ScalingMode
Fixed.new
new(variant: EnumVariantRef, payload: Fields<ScalingMode::Fixed>) -> ScalingMode
FixedHorizontal.new
new(variant: EnumVariantRef, payload: Fields<ScalingMode::FixedHorizontal>) -> ScalingMode
FixedVertical.new
new(variant: EnumVariantRef, payload: Fields<ScalingMode::FixedVertical>) -> ScalingMode
WindowSize.new
new(variant: EnumVariantRef, payload: Fields<ScalingMode::WindowSize>) -> ScalingMode
SubCameraView
Settings to define a camera sub view.
When Camera::sub_camera_view is Some, only the sub-section of the
image defined by size and offset (relative to the full_size of the
whole image) is projected to the cameras viewport.
Take the example of the following multi-monitor setup:
┌───┬───┐
│ A │ B │
├───┼───┤
│ C │ D │
└───┴───┘
If each monitor is 1920x1080, the whole image will have a resolution of 3840x2160. For each monitor we can use a single camera with a viewport of the same size as the monitor it corresponds to. To ensure that the image is cohesive, we can use a different sub view on each camera:
- Camera A:
full_size= 3840x2160,size= 1920x1080,offset= 0,0 - Camera B:
full_size= 3840x2160,size= 1920x1080,offset= 1920,0 - Camera C:
full_size= 3840x2160,size= 1920x1080,offset= 0,1080 - Camera D:
full_size= 3840x2160,size= 1920x1080,offset= 1920,1080
However since only the ratio between the values is important, they could all
be divided by 120 and still produce the same image. Camera D would for
example have the following values:
full_size = 32x18, size = 16x9, offset = 16,9
Fields
Functions
| Name | Summary |
|---|---|
new | Constructs a new instance of the type from a table of its fields. |
new
new(payload: Fields<SubCameraView>) -> SubCameraView
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
Viewport
Render viewport configuration for the Camera component.
The viewport defines the area on the render target to which the camera renders its image. You can overlay multiple cameras in a single window using viewports to create effects like split screen, minimaps, and character viewers.
Note that the physical position is in actual screen coordinates and not virtual pixels for window targets.
You should use the scaling factor reported by the window, which on some OS’s defaults to a value other than 1.
Please see the example code (which assumes a single camera and window)
# use bevy_camera::{Camera, Projection, Viewport};
# use bevy_transform::prelude::Transform;
# use bevy_ecs::prelude::*;
# use bevy_math::UVec2;
# use bevy_window::Window;
# use bevy_utils::default;
fn update_viewport(
mut camera_query: Query<(&mut Camera, &mut Transform, &mut Projection)>,
windows: Query<&Window>
) {
let Ok((mut camera, _, _)) = camera_query.single_mut() else { return; };
let window = windows.single().expect("Window not found");
let scale = window.resolution.scale_factor();
camera.viewport = Some(Viewport {
physical_position: (UVec2::new(10, 10).as_vec2() * scale).as_uvec2(),
physical_size: (UVec2::new(100, 100).as_vec2() * scale).as_uvec2(),
..default()
});
}
Fields
Functions
| Name | Summary |
|---|---|
new | Constructs a new instance of the type from a table of its fields. |
new
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
ViewVisibility
Component
Algorithmically computed indication of whether an entity is visible and should be extracted for rendering.
Not to be confused with Visibility and InheritedVisibility.
For more information, see module level documentation.
If you wish to add a custom visibility system that sets this value, be sure to add it to the
CheckVisibility set.
Fields
| Index | Type |
|---|---|
0 | u8 |
Functions
| Name | Summary |
|---|---|
new | Constructs a new instance of the type from a table of its fields. |
new
new(payload: Fields<ViewVisibility>) -> ViewVisibility
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
Methods
| Name | Summary |
|---|---|
get | Whether the entity is visible to a camera this frame. |
get
get(self: ViewVisibility) -> bool
Whether the entity is visible to a camera this frame.
Visibility
Component
User indication of whether an entity is visible. Propagates down the entity hierarchy.
If an entity is hidden in this way, all Children (and all of their children and so on) who
are set to Inherited will also be hidden.
Users should set this component if they wish to change the visibility of an entity.
To read the visibility of an entity, query for its InheritedVisibility instead.
For more information, see module level documentation.
Variants
| Variant |
|---|
Inherited |
Hidden |
Visible |
Functions
| Name | Summary |
|---|---|
new | Constructs a new instance of the type from a table of its fields. |
new
new(payload: Fields<Visibility>) -> Visibility
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
Methods
| Name | Summary |
|---|---|
toggle_inherited_visible | Switches between inherited and visible. A hidden entity stays hidden. |
toggle_visible_hidden | Switches between visible and hidden. An inherited entity stays inherited. |
toggle_inherited_visible
toggle_inherited_visible(self: Visibility)
Switches between inherited and visible. A hidden entity stays hidden.
toggle_visible_hidden
toggle_visible_hidden(self: Visibility)
Switches between visible and hidden. An inherited entity stays inherited.
Variant Functions
| Name | Summary |
|---|---|
Hidden.new | |
Inherited.new | |
Visible.new |
Hidden.new
new(variant: EnumVariantRef, payload: Fields<Visibility::Hidden>) -> Visibility
Inherited.new
new(variant: EnumVariantRef, payload: Fields<Visibility::Inherited>) -> Visibility
Visible.new
new(variant: EnumVariantRef, payload: Fields<Visibility::Visible>) -> Visibility
camera.VisibilitySystems
The types and functions in the camera.VisibilitySystems namespace, as returned by import_namespace("camera.VisibilitySystems").
Values
| Name | Type |
|---|---|
CalculateBounds | ReflectSystemSet |
CheckVisibility | ReflectSystemSet |
MarkNewlyHiddenEntitiesInvisible | ReflectSystemSet |
UpdateFrusta | ReflectSystemSet |
VisibilityPropagate | ReflectSystemSet |
color
The types and functions in the color namespace, as returned by import_namespace("color").
Types
| Type | Summary |
|---|---|
Color | An enumerated type that can represent any of the color types in this crate. |
Hsla | Color in Hue-Saturation-Lightness (HSL) color space with alpha. |
Hsva | Color in Hue-Saturation-Value (HSV) color space with alpha. |
Hwba | Color in Hue-Whiteness-Blackness (HWB) color space with alpha. |
Laba | Color in LAB color space, with alpha
|
Lcha | Color in LCH color space, with alpha
|
LinearRgba | Linear RGB color with alpha. |
Okhsla | Color in Okhsl color space with alpha. |
Okhsva | Color in Okhsv color space with alpha. |
Okhwba | Color in Okhwb color space with alpha. |
Oklaba | Color in Oklab color space, with alpha
|
Oklcha | Color in Oklch color space, with alpha
|
Srgba | Non-linear standard RGB with alpha. |
Xyza | CIE 1931 color space, also known as XYZ, with an alpha channel. |
Color
An enumerated type that can represent any of the color types in this crate.
This is useful when you need to store a color in a data structure that can’t be generic over the color type.
Operations
Color supports all the standard color operations, such as mixing,
luminance and hue adjustment,
and diffing. These operations delegate to the concrete color space contained
by Color, but will convert to Oklch for operations which aren’t supported in the
current space. After performing the operation, if a conversion was required, the result will be
converted back into the original color space.
let red_hsv = Color::hsv(0., 1., 1.);
let red_srgb = Color::srgb(1., 0., 0.);
// HSV has a definition of hue, so it will be returned.
red_hsv.hue();
// SRGB doesn't have a native definition for hue.
// Converts to Oklch and returns that result.
red_srgb.hue();
Oklch has been chosen as the intermediary space in cases where conversion is required
due to its perceptual uniformity and broad support for Bevy’s color operations.
To avoid the cost of repeated conversion, and ensure consistent results where that is desired,
first convert this Color into your desired color space.
Variants
| Variant | Fields |
|---|---|
Srgba | (Srgba) |
LinearRgba | (LinearRgba) |
Hsla | (Hsla) |
Hsva | (Hsva) |
Hwba | (Hwba) |
Laba | (Laba) |
Lcha | (Lcha) |
Oklaba | (Oklaba) |
Oklcha | (Oklcha) |
Xyza | (Xyza) |
Okhsla | (Okhsla) |
Okhsva | (Okhsva) |
Okhwba | (Okhwba) |
Functions
| Name | Summary |
|---|---|
black | Opaque black. |
hex | A color from a hex string such as "#ff8800" or "#ff880080", or an error if the string is not valid hex. |
hsl | A color from hue (in degrees), saturation and lightness, fully opaque. |
hsla | A color from hue (in degrees), saturation, lightness and alpha. |
hsv | A color from hue (in degrees), saturation and value, fully opaque. |
hsva | A color from hue (in degrees), saturation, value and alpha. |
linear_rgb | A color from red, green and blue in the linear RGB space, each from 0 to 1, fully opaque. |
linear_rgba | A color from red, green, blue and alpha in the linear RGB space, each from 0 to 1. |
named | A named CSS color such as "rebecca_purple" (case-insensitive), or nil if there is no color with that name. |
new | Constructs a new instance of the type from a table of its fields. |
none | A fully transparent color. |
srgb | A color from red, green and blue in the sRGB space, each from 0 to 1, fully opaque. |
srgb_u8 | A color from red, green and blue in the sRGB space, each from 0 to 255, fully opaque. |
srgba | A color from red, green, blue and alpha in the sRGB space, each from 0 to 1. |
srgba_u8 | A color from red, green, blue and alpha in the sRGB space, each from 0 to 255. |
white | Opaque white. |
black
black() -> Color
Opaque black.
hex
A color from a hex string such as "#ff8800" or "#ff880080", or an error if the string is not valid hex.
hsl
A color from hue (in degrees), saturation and lightness, fully opaque.
hsla
A color from hue (in degrees), saturation, lightness and alpha.
hsv
A color from hue (in degrees), saturation and value, fully opaque.
hsva
A color from hue (in degrees), saturation, value and alpha.
linear_rgb
A color from red, green and blue in the linear RGB space, each from 0 to 1, fully opaque.
linear_rgba
A color from red, green, blue and alpha in the linear RGB space, each from 0 to 1.
named
A named CSS color such as "rebecca_purple" (case-insensitive), or nil if there is no color with that name.
new
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
none
none() -> Color
A fully transparent color.
srgb
A color from red, green and blue in the sRGB space, each from 0 to 1, fully opaque.
local Color = import_namespace("color").Color
local red = Color.srgb(1.0, 0.0, 0.0)
assert(red:to_srgba().red == 1.0)
let Color = import_namespace("color").Color;
let red = Color.srgb(1.0, 0.0, 0.0);
assert!(red.to_srgba().red == 1.0);
srgb_u8
A color from red, green and blue in the sRGB space, each from 0 to 255, fully opaque.
srgba
A color from red, green, blue and alpha in the sRGB space, each from 0 to 1.
srgba_u8
A color from red, green, blue and alpha in the sRGB space, each from 0 to 255.
white
white() -> Color
Opaque white.
Methods
| Name | Summary |
|---|---|
alpha | The alpha (opacity) of the color, from 0 (transparent) to 1 (opaque). |
darker | A darker copy of the color, amount from 0 to 1. |
is_fully_transparent | Whether the color is completely transparent. |
lighter | A lighter copy of the color, amount from 0 to 1. |
luminance | The perceived brightness of the color, from 0 (black) to 1 (white). |
mix | A color between this one and other, t = 0 gives this color and t = 1 gives other. |
set_alpha | Sets the alpha (opacity) of the color in place. |
to_hex | The color as an uppercase hex string such as "#FF8800", with alpha appended unless fully opaque. |
to_linear | The color converted to the linear RGB space. |
to_srgba | The color converted to the sRGB space. |
with_alpha | A copy of the color with its alpha set to alpha. |
alpha
The alpha (opacity) of the color, from 0 (transparent) to 1 (opaque).
darker
A darker copy of the color, amount from 0 to 1.
is_fully_transparent
Whether the color is completely transparent.
lighter
A lighter copy of the color, amount from 0 to 1.
luminance
The perceived brightness of the color, from 0 (black) to 1 (white).
mix
A color between this one and other, t = 0 gives this color and t = 1 gives other.
set_alpha
Sets the alpha (opacity) of the color in place.
to_hex
The color as an uppercase hex string such as "#FF8800", with alpha appended unless fully opaque.
to_linear
to_linear(self: Color) -> LinearRgba
The color converted to the linear RGB space.
to_srgba
The color converted to the sRGB space.
with_alpha
A copy of the color with its alpha set to alpha.
Operators
| Name | Summary |
|---|---|
eq | Whether both colors are the same color in the same color space. |
eq
Whether both colors are the same color in the same color space.
Variant Functions
| Name | Summary |
|---|---|
Hsla.new | |
Hsva.new | |
Hwba.new | |
Laba.new | |
Lcha.new | |
LinearRgba.new | |
Okhsla.new | |
Okhsva.new | |
Okhwba.new | |
Oklaba.new | |
Oklcha.new | |
Srgba.new | |
Xyza.new |
Hsla.new
new(variant: EnumVariantRef, payload: Fields<Color::Hsla>) -> Color
Hsva.new
new(variant: EnumVariantRef, payload: Fields<Color::Hsva>) -> Color
Hwba.new
new(variant: EnumVariantRef, payload: Fields<Color::Hwba>) -> Color
Laba.new
new(variant: EnumVariantRef, payload: Fields<Color::Laba>) -> Color
Lcha.new
new(variant: EnumVariantRef, payload: Fields<Color::Lcha>) -> Color
LinearRgba.new
new(variant: EnumVariantRef, payload: Fields<Color::LinearRgba>) -> Color
Okhsla.new
new(variant: EnumVariantRef, payload: Fields<Color::Okhsla>) -> Color
Okhsva.new
new(variant: EnumVariantRef, payload: Fields<Color::Okhsva>) -> Color
Okhwba.new
new(variant: EnumVariantRef, payload: Fields<Color::Okhwba>) -> Color
Oklaba.new
new(variant: EnumVariantRef, payload: Fields<Color::Oklaba>) -> Color
Oklcha.new
new(variant: EnumVariantRef, payload: Fields<Color::Oklcha>) -> Color
Srgba.new
new(variant: EnumVariantRef, payload: Fields<Color::Srgba>) -> Color
Xyza.new
new(variant: EnumVariantRef, payload: Fields<Color::Xyza>) -> Color
Hsla
Color in Hue-Saturation-Lightness (HSL) color space with alpha. Further information on this color model can be found on Wikipedia.
Fields
Functions
| Name | Summary |
|---|---|
new | reates a color from hue (degrees), saturation, lightness and alpha. |
new
reates a color from hue (degrees), saturation, lightness and alpha.
Methods
| Name | Summary |
|---|---|
to_color | The color as a Color, in the same color space. |
to_color
The color as a Color, in the same color space.
Hsva
Color in Hue-Saturation-Value (HSV) color space with alpha. Further information on this color model can be found on Wikipedia.
Fields
Functions
| Name | Summary |
|---|---|
new | reates a color from hue (degrees), saturation, value and alpha. |
new
reates a color from hue (degrees), saturation, value and alpha.
Methods
| Name | Summary |
|---|---|
to_color | The color as a Color, in the same color space. |
to_color
The color as a Color, in the same color space.
Hwba
Color in Hue-Whiteness-Blackness (HWB) color space with alpha. Further information on this color model can be found on Wikipedia.
Fields
Functions
| Name | Summary |
|---|---|
new | reates a color from hue (degrees), whiteness, blackness and alpha. |
new
reates a color from hue (degrees), whiteness, blackness and alpha.
Methods
| Name | Summary |
|---|---|
to_color | The color as a Color, in the same color space. |
to_color
The color as a Color, in the same color space.
Laba
Color in LAB color space, with alpha
Fields
Functions
| Name | Summary |
|---|---|
new | reates a color from lightness, a, b and alpha. |
new
reates a color from lightness, a, b and alpha.
Methods
| Name | Summary |
|---|---|
to_color | The color as a Color, in the same color space. |
to_color
The color as a Color, in the same color space.
Lcha
Color in LCH color space, with alpha
Fields
Functions
| Name | Summary |
|---|---|
new | reates a color from lightness, chroma, hue (degrees) and alpha. |
new
reates a color from lightness, chroma, hue (degrees) and alpha.
Methods
| Name | Summary |
|---|---|
to_color | The color as a Color, in the same color space. |
to_color
The color as a Color, in the same color space.
LinearRgba
Linear RGB color with alpha.
SDR colors are in [0.0, 1.0]. Values above 1.0 are HDR intensities.
Fields
Functions
| Name | Summary |
|---|---|
new | A color from linear red, green, blue and alpha, each from 0 to 1. |
rgb | A fully opaque color from linear red, green and blue, each from 0 to 1. |
new
new(red: f32, green: f32, blue: f32, alpha: f32) -> LinearRgba
A color from linear red, green, blue and alpha, each from 0 to 1.
local LinearRgba = import_namespace("color").LinearRgba
local c = LinearRgba.new(1.0, 0.0, 0.0, 1.0)
assert(c.red == 1.0)
let LinearRgba = import_namespace("color").LinearRgba;
let c = LinearRgba.new(1.0, 0.0, 0.0, 1.0);
assert!(c.red == 1.0);
rgb
rgb(red: f32, green: f32, blue: f32) -> LinearRgba
A fully opaque color from linear red, green and blue, each from 0 to 1.
Methods
| Name | Summary |
|---|---|
to_color | The color as a Color. |
to_color
to_color(self: LinearRgba) -> Color
The color as a Color.
Operators
| Name | Summary |
|---|---|
eq | Whether both colors have the same red, green, blue and alpha. |
mul | A copy with red, green and blue multiplied by factor, keeping alpha. Useful for making emissive colors brighter. |
eq
eq(self: LinearRgba, other: LinearRgba) -> bool
Whether both colors have the same red, green, blue and alpha.
mul
mul(self: LinearRgba, factor: f32) -> LinearRgba
A copy with red, green and blue multiplied by factor, keeping alpha. Useful for making emissive colors brighter.
Okhsla
Color in Okhsl color space with alpha. Further information on this color model can be found on https://bottosson.github.io/posts/colorpicker.
Okhsl is defined relative to the sRGB (Rec. 709) gamut. Converting a wide-gamut or
HDR color clamps the lightness to 1.0 but can push saturation outside [0.0, 1.0].
Fields
Functions
| Name | Summary |
|---|---|
new | Constructs a new instance of the type from a table of its fields. |
new
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
Okhsva
Color in Okhsv color space with alpha. Further information on this color model can be found on https://bottosson.github.io/posts/colorpicker.
Okhsv is defined relative to the sRGB (Rec. 709) gamut. Converting a wide-gamut or
HDR color can push saturation and value outside [0.0, 1.0].
Fields
Functions
| Name | Summary |
|---|---|
new | Constructs a new instance of the type from a table of its fields. |
new
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
Okhwba
Color in Okhwb color space with alpha. Further information on this color model can be found on https://bottosson.github.io/posts/colorpicker.
Fields
Functions
| Name | Summary |
|---|---|
new | Constructs a new instance of the type from a table of its fields. |
new
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
Oklaba
Color in Oklab color space, with alpha
Fields
Functions
| Name | Summary |
|---|---|
new | reates a color from lightness, a, b and alpha. |
new
reates a color from lightness, a, b and alpha.
Methods
| Name | Summary |
|---|---|
to_color | The color as a Color, in the same color space. |
to_color
The color as a Color, in the same color space.
Oklcha
Color in Oklch color space, with alpha
Fields
Functions
| Name | Summary |
|---|---|
new | reates a color from lightness, chroma, hue (degrees) and alpha. |
new
reates a color from lightness, chroma, hue (degrees) and alpha.
Methods
| Name | Summary |
|---|---|
to_color | The color as a Color, in the same color space. |
to_color
The color as a Color, in the same color space.
Srgba
Non-linear standard RGB with alpha.
SDR colors are in [0.0, 1.0]. Values above 1.0 are HDR intensities.
Fields
Functions
| Name | Summary |
|---|---|
hex | A color from a hex string such as "#ff8800" or "#ff880080", or an error if the string is not valid hex. |
new | A color from red, green, blue and alpha, each from 0 to 1. |
rgb | A fully opaque color from red, green and blue, each from 0 to 1. |
hex
A color from a hex string such as "#ff8800" or "#ff880080", or an error if the string is not valid hex.
new
A color from red, green, blue and alpha, each from 0 to 1.
local Srgba = import_namespace("color").Srgba
local c = Srgba.new(1.0, 0.0, 0.0, 0.5)
assert(c.alpha == 0.5)
let Srgba = import_namespace("color").Srgba;
let c = Srgba.new(1.0, 0.0, 0.0, 0.5);
assert!(c.alpha == 0.5);
rgb
A fully opaque color from red, green and blue, each from 0 to 1.
Methods
| Name | Summary |
|---|---|
to_color | The color as a Color. |
to_hex | The color as an uppercase hex string such as "#FF8800", with alpha appended unless fully opaque. |
with_alpha | A copy of the color with its alpha set to alpha. |
to_color
The color as a Color.
to_hex
The color as an uppercase hex string such as "#FF8800", with alpha appended unless fully opaque.
with_alpha
A copy of the color with its alpha set to alpha.
Operators
| Name | Summary |
|---|---|
eq | Whether both colors have the same red, green, blue and alpha. |
eq
Whether both colors have the same red, green, blue and alpha.
Xyza
CIE 1931 color space, also known as XYZ, with an alpha channel.
The SDR channel bounds below are the D65 white point, (0.9505, 1.0, 1.0889).
Fields
Functions
| Name | Summary |
|---|---|
new | reates a color from x, y, z and alpha. |
new
reates a color from x, y, z and alpha.
Methods
| Name | Summary |
|---|---|
to_color | The color as a Color, in the same color space. |
to_color
The color as a Color, in the same color space.
core
The types and functions in the core namespace, as returned by import_namespace("core").
Types
| Type | Summary |
|---|---|
NonZeroI16 | |
NonZeroU16 | |
NonZeroU32 | |
Range<T> | A range of values, from start up to but not including end. |
TypeId |
NonZeroI16
Opaque: scripts can't access its fields, only its functions.
Functions
| Name | Summary |
|---|---|
new | Constructs a new instance of the type from a table of its fields. |
new
new(payload: Fields<NonZeroI16>) -> NonZeroI16
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
NonZeroU16
Opaque: scripts can't access its fields, only its functions.
Functions
| Name | Summary |
|---|---|
new | Constructs a new instance of the type from a table of its fields. |
new
new(payload: Fields<NonZeroU16>) -> NonZeroU16
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
NonZeroU32
Opaque: scripts can't access its fields, only its functions.
Functions
| Name | Summary |
|---|---|
new | Constructs a new instance of the type from a table of its fields. |
new
new(payload: Fields<NonZeroU32>) -> NonZeroU32
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
Range<T>
Generic
A range of values, from start up to but not including end.
Opaque: scripts can't access its fields, only its functions.
Instantiations
Functions
| Name | Summary |
|---|---|
new | Constructs a new instance of the type from a table of its fields. |
new
On Range<f32>
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
TypeId
Opaque: scripts can't access its fields, only its functions.
Functions
| Name | Summary |
|---|---|
new | Constructs a new instance of the type from a table of its fields. |
new
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
ecs
The types and functions in the ecs namespace, as returned by import_namespace("ecs").
Types
| Type | Summary |
|---|---|
AddEvent | Trigger emitted when a component is inserted onto an entity that does not already have that component. |
ChildOf | Stores the parent entity of this child entity with this component. |
DespawnEvent | EntityEvent emitted for each component on an entity when it is despawned. |
DiscardEvent | Trigger emitted when a component is removed from an entity, regardless of whether or not it is later replaced. |
Entity | Unique identifier for an entity in a World. |
HashedStr | A wrapper over Hashed. |
InsertEvent | Trigger emitted when a component is inserted, regardless of whether or not the entity already had that component. |
Name | Component used to identify an entity. Stores a hash for faster comparisons. |
RemoveEvent | Trigger emitted when a component is removed from an entity, and runs before the component is removed, so you can still… |
AddEvent
Trigger emitted when a component is inserted onto an entity that does not already have that
component. Runs before Insert.
See ComponentHooks::on_add for more information.
Fields
| Field | Type |
|---|---|
entity | Entity |
Functions
| Name | Summary |
|---|---|
new | Constructs a new instance of the type from a table of its fields. |
new
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
ChildOf
Component
Stores the parent entity of this child entity with this component.
This is a Relationship component, and creates the canonical
“parent / child” hierarchy. This is the “source of truth” component, and it pairs with
the Children RelationshipTarget.
This relationship should be used for things like:
- Organizing entities in a scene
- Propagating configuration or data inherited from a parent, such as “visibility” or “world-space global transforms”.
- Ensuring a hierarchy is despawned when an entity is despawned.
ChildOf contains a single “target” Entity. When ChildOf is inserted on a “source” entity,
the “target” entity will automatically (and immediately, via a component hook) have a Children
component inserted, and the “source” entity will be added to that Children instance.
If the ChildOf component is replaced with a different “target” entity, the old target’s Children
will be automatically (and immediately, via a component hook) be updated to reflect that change.
Likewise, when the ChildOf component is removed, the “source” entity will be removed from the old
target’s Children. If this results in Children being empty, Children will be automatically removed.
When a parent is despawned, all children (and their descendants) will also be despawned.
You can create parent-child relationships in a variety of ways. The most direct way is to insert a ChildOf component:
let root = world.spawn_empty().id();
let child1 = world.spawn(ChildOf(root)).id();
let child2 = world.spawn(ChildOf(root)).id();
let grandchild = world.spawn(ChildOf(child1)).id();
assert_eq!(&**world.entity(root).get::<Children>().unwrap(), &[child1, child2]);
assert_eq!(&**world.entity(child1).get::<Children>().unwrap(), &[grandchild]);
world.entity_mut(child2).remove::<ChildOf>();
assert_eq!(&**world.entity(root).get::<Children>().unwrap(), &[child1]);
world.entity_mut(root).despawn();
assert!(world.get_entity(root).is_err());
assert!(world.get_entity(child1).is_err());
assert!(world.get_entity(grandchild).is_err());
However if you are spawning many children, you might want to use the EntityWorldMut::with_children helper instead:
let mut child1 = None;
let mut child2 = None;
let mut grandchild = None;
let root = world.spawn_empty().with_children(|p| {
child1 = Some(p.spawn_empty().with_children(|p| {
grandchild = Some(p.spawn_empty().id());
}).id());
child2 = Some(p.spawn_empty().id());
}).id();
assert_eq!(&**world.entity(root).get::<Children>().unwrap(), &[child1.unwrap(), child2.unwrap()]);
assert_eq!(&**world.entity(child1.unwrap()).get::<Children>().unwrap(), &[grandchild.unwrap()]);
Fields
| Index | Type |
|---|---|
0 | Entity |
Functions
| Name | Summary |
|---|---|
new | Constructs a new instance of the type from a table of its fields. |
new
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
Methods
| Name | Summary |
|---|---|
parent | The parent entity. |
parent
The parent entity.
DespawnEvent
EntityEvent emitted for each component on an entity when it is despawned.
See ComponentHooks::on_despawn for more information.
Fields
| Field | Type |
|---|---|
entity | Entity |
Functions
| Name | Summary |
|---|---|
new | Constructs a new instance of the type from a table of its fields. |
new
new(payload: Fields<DespawnEvent>) -> DespawnEvent
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
DiscardEvent
Trigger emitted when a component is removed from an entity, regardless of whether or not it is later replaced.
Runs before the value is replaced, so you can still access the original component data.
See ComponentHooks::on_discard for more information.
Fields
| Field | Type |
|---|---|
entity | Entity |
Functions
| Name | Summary |
|---|---|
new | Constructs a new instance of the type from a table of its fields. |
new
new(payload: Fields<DiscardEvent>) -> DiscardEvent
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
Entity
Unique identifier for an entity in a World.
Note that this is just an id, not the entity itself.
Further, the entity this id refers to may no longer exist in the World.
For more information about entities, their ids, and how to use them, see the module docs.
Aliasing
Once an entity is despawned, it ceases to exist.
However, its Entity id is still present, and may still be contained in some data.
This becomes problematic because it is possible for a later entity to be spawned at the exact same id!
If this happens, which is rare but very possible, it will be logged.
Aliasing can happen without warning.
Holding onto a Entity id corresponding to an entity well after that entity was despawned can cause un-intuitive behavior for both ordering, and comparing in general.
To prevent these bugs, it is generally best practice to stop holding an Entity or EntityGeneration value as soon as you know it has been despawned.
If you must do otherwise, do not assume the Entity id corresponds to the same entity it originally did.
See EntityGeneration’s docs for more information about aliasing and why it occurs.
Stability warning
For all intents and purposes, Entity should be treated as an opaque identifier. The internal bit
representation is liable to change from release to release as are the behaviors or performance
characteristics of any of its trait implementations (i.e. Ord, Hash, etc.). This means that changes in
Entity’s representation, though made readable through various functions on the type, are not considered
breaking changes under SemVer.
In particular, directly serializing with Serialize and Deserialize make zero guarantee of long
term wire format compatibility. Changes in behavior will cause serialized Entity values persisted
to long term storage (i.e. disk, databases, etc.) will fail to deserialize upon being updated.
Usage
This data type is returned by iterating a Query that has Entity as part of its query fetch type parameter (learn more).
It can also be obtained by calling EntityCommands::id or EntityWorldMut::id.
fn setup(mut commands: Commands) {
// Calling `spawn` returns `EntityCommands`.
let entity = commands.spawn(SomeComponent).id();
}
fn exclusive_system(world: &mut World) {
// Calling `spawn` returns `EntityWorldMut`.
let entity = world.spawn(SomeComponent).id();
}
It can be used to refer to a specific entity to apply EntityCommands, or to call Query::get (or similar methods) to access its components.
fn dispose_expired_food(mut commands: Commands, query: Query<Entity, With<Expired>>) {
for food_entity in &query {
commands.entity(food_entity).despawn();
}
}
Opaque: scripts can't access its fields, only its functions.
Functions
| Name | Summary |
|---|---|
from_bits | The entity from a number returned by to_bits, or nil if the number is not a valid entity. |
new | Constructs a new instance of the type from a table of its fields. |
from_bits
The entity from a number returned by to_bits, or nil if the number is not a valid entity.
new
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
Methods
| Name | Summary |
|---|---|
generation | How many times the index of this entity has been reused. |
index | The index of the entity. Indices of despawned entities are reused, so compare whole entities to tell them apart. |
to_bits | The entity as a single number, which can be turned back into the entity with from_bits. |
generation
How many times the index of this entity has been reused.
index
The index of the entity. Indices of despawned entities are reused, so compare whole entities to tell them apart.
to_bits
The entity as a single number, which can be turned back into the entity with from_bits.
Only meaningful while the app is running, don’t save it.
Operators
| Name | Summary |
|---|---|
eq | Whether two entities are the same. |
eq
Whether two entities are the same.
HashedStr
A wrapper over Hashed. This exists to make Name(“value”.into()) possible, which plays nicely with contexts like the bsn! macro.
Fields
| Index | Type |
|---|---|
0 | Hashed<Cow, FixedHasher> |
Functions
| Name | Summary |
|---|---|
new | Constructs a new instance of the type from a table of its fields. |
new
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
InsertEvent
Trigger emitted when a component is inserted, regardless of whether or not the entity already
had that component. Runs after Add, if it ran.
See ComponentHooks::on_insert for more information.
Fields
| Field | Type |
|---|---|
entity | Entity |
Functions
| Name | Summary |
|---|---|
new | Constructs a new instance of the type from a table of its fields. |
new
new(payload: Fields<InsertEvent>) -> InsertEvent
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
Name
Component
Component used to identify an entity. Stores a hash for faster comparisons.
The hash is eagerly re-computed upon each update to the name.
Name should not be treated as a globally unique identifier for entities,
as multiple entities can have the same name. Entity should be
used instead as the default unique identifier.
Fields
| Index | Type |
|---|---|
0 | HashedStr |
Functions
| Name | Summary |
|---|---|
new | Creates a new Name component, used to identify entities. |
new
Creates a new Name component, used to identify entities.
local Name = import_namespace("ecs").Name
local name = Name.new("player")
assert(name:as_str() == "player")
let Name = import_namespace("ecs").Name;
let name = Name.new("player");
assert!(name.as_str() == "player");
Methods
as_str
The name as a string.
set
Changes the name.
Operators
| Name | Summary |
|---|---|
eq | Whether the name is the same as another name or a string. |
eq
Whether the name is the same as another name or a string.
In Lua, == only compares a name with another name, use name:eq("text") for strings.
RemoveEvent
Trigger emitted when a component is removed from an entity, and runs before the component is
removed, so you can still access the component data.
See ComponentHooks::on_remove for more information.
Fields
| Field | Type |
|---|---|
entity | Entity |
Functions
| Name | Summary |
|---|---|
new | Constructs a new instance of the type from a table of its fields. |
new
new(payload: Fields<RemoveEvent>) -> RemoveEvent
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
gizmos
The types and functions in the gizmos namespace, as returned by import_namespace("gizmos").
Types
| Type | Summary |
|---|---|
Gizmos | Immediate mode debug drawing: lines and shapes drawn this frame. |
Values
| Name | Type |
|---|---|
FrustumGizmoSystems | ReflectSystemSet |
GizmoMeshSystems | ReflectSystemSet |
TransformGizmoSystems | ReflectSystemSet |
Gizmos
Immediate mode debug drawing: lines and shapes drawn this frame.
Every function draws straight away, the shapes are shown for the current frame only. Needs the gizmo plugin, without it the functions fail with an error.
local Color = import_namespace("color").Color
local Gizmos = import_namespace("gizmos").Gizmos
local Vec3 = import_namespace("math").Vec3
Gizmos.line(Vec3.zero(), Vec3.new(1, 0, 0), Color.white())
let Color = import_namespace("color").Color;
let Gizmos = import_namespace("gizmos").Gizmos;
let Vec3 = import_namespace("math").Vec3;
Gizmos.line(Vec3.zero(), Vec3.new(1.0, 0.0, 0.0), Color.white());
Functions
| Name | Summary |
|---|---|
arrow | Draws an arrow from the start to the end point. |
arrow_2d | Draws an arrow from the start to the end point in 2D. |
axes | Draws the red, green and blue axes of the transform, scaled by the length. |
circle | Draws a circle around the position, lying in the XY plane so it faces +Z. |
circle_2d | Draws a circle around the position in 2D. |
cross | Draws a cross of the given half size along the three axes, centred on the position. |
cuboid | Draws a unit cube, with the transform applied to it. |
line | Draws a line between two points. |
line_2d | Draws a line between two points in 2D. |
linestrip | Draws connected lines through the points, in order. |
linestrip_2d | Draws connected lines through the points in 2D, in order. |
new | Constructs a new instance of the type from a table of its fields. |
ray | Draws a line from the origin along the vector. |
ray_2d | Draws a line from the origin along the vector in 2D. |
rect | Draws a rectangle of the given size centred on the position, lying in the XY plane. |
rect_2d | Draws a rectangle of the given size centred on the position in 2D. |
sphere | Draws a wireframe sphere around the position. |
arrow
Draws an arrow from the start to the end point.
arrow_2d
Draws an arrow from the start to the end point in 2D.
axes
Draws the red, green and blue axes of the transform, scaled by the length.
circle
Draws a circle around the position, lying in the XY plane so it faces +Z.
circle_2d
Draws a circle around the position in 2D.
cross
Draws a cross of the given half size along the three axes, centred on the position.
cuboid
Draws a unit cube, with the transform applied to it.
line
Draws a line between two points.
line_2d
Draws a line between two points in 2D.
linestrip
Draws connected lines through the points, in order.
linestrip_2d
Draws connected lines through the points in 2D, in order.
new
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
ray
Draws a line from the origin along the vector.
ray_2d
Draws a line from the origin along the vector in 2D.
rect
Draws a rectangle of the given size centred on the position, lying in the XY plane.
rect_2d
Draws a rectangle of the given size centred on the position in 2D.
sphere
Draws a wireframe sphere around the position.
input
The types and functions in the input namespace, as returned by import_namespace("input").
Types
| Type | Summary |
|---|---|
Axis<T> | The position of the inputs of type T on an axis, i.e. GamepadInput. |
ButtonInput<T> | The pressed state of the inputs of type T, i.e. KeyCode. |
FocusCause | The cause for a FocusGained |
Gamepad | Stores a connected gamepad’s metadata such as the name and its GamepadButton and GamepadAxis. |
GamepadAxis | Represents gamepad input types that are mapped in the range -1.0, 1.0. |
GamepadButton | Represents gamepad input types that are mapped in the range 0.0, 1.0. |
GamepadInput | Encapsulation over GamepadAxis and GamepadButton. |
InputFocus | Resource representing which entity has input focus, if any. |
KeyCode | The key code of a KeyboardInput. |
MouseButton | A button on a mouse device. |
NativeKeyCode | Contains the platform-native physical key identifier |
Values
| Name | Type |
|---|---|
InputSystems | ReflectSystemSet |
Axis<T>
Generic
The position of the inputs of type T on an axis, i.e. GamepadInput.
Fields
| Field | Type |
|---|---|
axis_data | HashMap<T, f32> |
Instantiations
Functions
| Name | Summary |
|---|---|
new | Constructs a new instance of the type from a table of its fields. |
new
On Axis<GamepadInput>
new(payload: Fields<Axis<GamepadInput>>) -> Axis<GamepadInput>
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
ButtonInput<T>
Generic
The pressed state of the inputs of type T, i.e. KeyCode.
Fields
| Field | Type |
|---|---|
pressed | HashSet<T> |
just_pressed | HashSet<T> |
just_released | HashSet<T> |
Instantiations
ButtonInput<MouseButton>, ButtonInput<KeyCode>, ButtonInput<GamepadButton>
Functions
| Name | Summary |
|---|---|
new | Constructs a new instance of the type from a table of its fields. |
new
On ButtonInput<MouseButton>, ButtonInput<KeyCode>, ButtonInput<GamepadButton>
new(payload: Fields<ButtonInput<MouseButton>>) -> ButtonInput<MouseButton>
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
Methods
| Name | Summary |
|---|---|
get_pressed | The buttons which are held down. |
just_pressed | Whether the button was pressed during the last update. |
just_released | Whether the button was released during the last update. |
press | Holds the button down, as if it was pressed. |
pressed | Whether the button is held down. |
release | Lets go of the button, as if it was released. |
get_pressed
On ButtonInput<MouseButton>, ButtonInput<KeyCode>, ButtonInput<GamepadButton>
get_pressed(self: ButtonInput<MouseButton>) -> Vec<MouseButton>
The buttons which are held down.
just_pressed
On ButtonInput<MouseButton>, ButtonInput<KeyCode>, ButtonInput<GamepadButton>
just_pressed(self: ButtonInput<MouseButton>, button: MouseButton) -> bool
Whether the button was pressed during the last update.
just_released
On ButtonInput<MouseButton>, ButtonInput<KeyCode>, ButtonInput<GamepadButton>
just_released(self: ButtonInput<MouseButton>, button: MouseButton) -> bool
Whether the button was released during the last update.
press
On ButtonInput<MouseButton>, ButtonInput<KeyCode>, ButtonInput<GamepadButton>
press(self: ButtonInput<MouseButton>, button: MouseButton)
Holds the button down, as if it was pressed.
pressed
On ButtonInput<MouseButton>, ButtonInput<KeyCode>, ButtonInput<GamepadButton>
pressed(self: ButtonInput<MouseButton>, button: MouseButton) -> bool
Whether the button is held down.
release
On ButtonInput<MouseButton>, ButtonInput<KeyCode>, ButtonInput<GamepadButton>
release(self: ButtonInput<MouseButton>, button: MouseButton)
Lets go of the button, as if it was released.
FocusCause
The cause for a FocusGained
Sometimes widgets would like to know how their focus was gained so they can act accordingly.
For example, a text input may want to select all text when navigated into, but not when pressed.
Variants
| Variant |
|---|
Navigated |
Pressed |
Auto |
Functions
| Name | Summary |
|---|---|
new | Constructs a new instance of the type from a table of its fields. |
new
new(payload: Fields<FocusCause>) -> FocusCause
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
Variant Functions
| Name | Summary |
|---|---|
Auto.new | |
Navigated.new | |
Pressed.new |
Auto.new
new(variant: EnumVariantRef, payload: Fields<FocusCause::Auto>) -> FocusCause
Navigated.new
new(variant: EnumVariantRef, payload: Fields<FocusCause::Navigated>) -> FocusCause
Pressed.new
new(variant: EnumVariantRef, payload: Fields<FocusCause::Pressed>) -> FocusCause
Gamepad
Component
Stores a connected gamepad’s metadata such as the name and its GamepadButton and GamepadAxis.
An entity with this component is spawned automatically after GamepadConnectionEvent
and updated by gamepad_event_processing_system.
See also GamepadSettings for configuration.
Examples
fn gamepad_usage_system(gamepads: Query<(&Name, &Gamepad)>) {
for (name, gamepad) in &gamepads {
println!("{name}");
if gamepad.just_pressed(GamepadButton::North) {
println!("{} just pressed North", name)
}
if let Some(left_stick_x) = gamepad.get(GamepadAxis::LeftStickX) {
println!("left stick X: {}", left_stick_x)
}
}
}
Fields
| Field | Type |
|---|---|
vendor_id | Optional<u16> |
product_id | Optional<u16> |
digital | ButtonInput<GamepadButton> |
analog | Axis<GamepadInput> |
Functions
| Name | Summary |
|---|---|
new | Constructs a new instance of the type from a table of its fields. |
new
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
Methods
| Name | Summary |
|---|---|
dpad | The direction of the d-pad, from -1 to 1 on each axis. |
get | The value of the button or axis, from 0 to 1 for buttons and from -1 to 1 for axes, or nil if the gamepad has… |
just_pressed | Whether the button was pressed during the last update. |
just_released | Whether the button was released during the last update. |
left_stick | The position of the left stick, from -1 to 1 on each axis. |
pressed | Whether the button is held down. |
right_stick | The position of the right stick, from -1 to 1 on each axis. |
dpad
The direction of the d-pad, from -1 to 1 on each axis.
get
get(self: Gamepad, axis: GamepadAxis) -> Optional<f32>
The value of the button or axis, from 0 to 1 for buttons and from -1 to 1 for axes, or nil if the gamepad has no such input.
just_pressed
just_pressed(self: Gamepad, button: GamepadButton) -> bool
Whether the button was pressed during the last update.
just_released
just_released(self: Gamepad, button: GamepadButton) -> bool
Whether the button was released during the last update.
left_stick
The position of the left stick, from -1 to 1 on each axis.
pressed
pressed(self: Gamepad, button: GamepadButton) -> bool
Whether the button is held down.
right_stick
The position of the right stick, from -1 to 1 on each axis.
GamepadAxis
Represents gamepad input types that are mapped in the range -1.0, 1.0.
Usage
This is used to determine which axis has changed its value when receiving a
gamepad axis event. It is also used in the Gamepad component.
Variants
| Variant | Fields |
|---|---|
LeftStickX | |
LeftStickY | |
LeftZ | |
RightStickX | |
RightStickY | |
RightZ | |
Other | (u32) |
Functions
| Name | Summary |
|---|---|
new | Constructs a new instance of the type from a table of its fields. |
new
new(payload: Fields<GamepadAxis>) -> GamepadAxis
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
Variant Functions
| Name | Summary |
|---|---|
LeftStickX.new | |
LeftStickY.new | |
LeftZ.new | |
Other.new | |
RightStickX.new | |
RightStickY.new | |
RightZ.new |
LeftStickX.new
new(variant: EnumVariantRef, payload: Fields<GamepadAxis::LeftStickX>) -> GamepadAxis
LeftStickY.new
new(variant: EnumVariantRef, payload: Fields<GamepadAxis::LeftStickY>) -> GamepadAxis
LeftZ.new
new(variant: EnumVariantRef, payload: Fields<GamepadAxis::LeftZ>) -> GamepadAxis
Other.new
new(variant: EnumVariantRef, payload: Fields<GamepadAxis::Other>) -> GamepadAxis
RightStickX.new
new(variant: EnumVariantRef, payload: Fields<GamepadAxis::RightStickX>) -> GamepadAxis
RightStickY.new
new(variant: EnumVariantRef, payload: Fields<GamepadAxis::RightStickY>) -> GamepadAxis
RightZ.new
new(variant: EnumVariantRef, payload: Fields<GamepadAxis::RightZ>) -> GamepadAxis
GamepadButton
Represents gamepad input types that are mapped in the range 0.0, 1.0.
Usage
This is used to determine which button has changed its value when receiving gamepad button events.
It is also used in the Gamepad component.
Variants
| Variant | Fields |
|---|---|
South | |
East | |
North | |
West | |
C | |
Z | |
LeftTrigger | |
LeftTrigger2 | |
RightTrigger | |
RightTrigger2 | |
Select | |
Start | |
Mode | |
LeftThumb | |
RightThumb | |
DPadUp | |
DPadDown | |
DPadLeft | |
DPadRight | |
Other | (u32) |
Functions
| Name | Summary |
|---|---|
new | Constructs a new instance of the type from a table of its fields. |
new
new(payload: Fields<GamepadButton>) -> GamepadButton
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
Variant Functions
C.new
new(variant: EnumVariantRef, payload: Fields<GamepadButton::C>) -> GamepadButton
DPadDown.new
new(variant: EnumVariantRef, payload: Fields<GamepadButton::DPadDown>) -> GamepadButton
DPadLeft.new
new(variant: EnumVariantRef, payload: Fields<GamepadButton::DPadLeft>) -> GamepadButton
DPadRight.new
new(variant: EnumVariantRef, payload: Fields<GamepadButton::DPadRight>) -> GamepadButton
DPadUp.new
new(variant: EnumVariantRef, payload: Fields<GamepadButton::DPadUp>) -> GamepadButton
East.new
new(variant: EnumVariantRef, payload: Fields<GamepadButton::East>) -> GamepadButton
LeftThumb.new
new(variant: EnumVariantRef, payload: Fields<GamepadButton::LeftThumb>) -> GamepadButton
LeftTrigger.new
new(variant: EnumVariantRef, payload: Fields<GamepadButton::LeftTrigger>) -> GamepadButton
LeftTrigger2.new
new(variant: EnumVariantRef, payload: Fields<GamepadButton::LeftTrigger2>) -> GamepadButton
Mode.new
new(variant: EnumVariantRef, payload: Fields<GamepadButton::Mode>) -> GamepadButton
North.new
new(variant: EnumVariantRef, payload: Fields<GamepadButton::North>) -> GamepadButton
Other.new
new(variant: EnumVariantRef, payload: Fields<GamepadButton::Other>) -> GamepadButton
RightThumb.new
new(variant: EnumVariantRef, payload: Fields<GamepadButton::RightThumb>) -> GamepadButton
RightTrigger.new
new(variant: EnumVariantRef, payload: Fields<GamepadButton::RightTrigger>) -> GamepadButton
RightTrigger2.new
new(variant: EnumVariantRef, payload: Fields<GamepadButton::RightTrigger2>) -> GamepadButton
Select.new
new(variant: EnumVariantRef, payload: Fields<GamepadButton::Select>) -> GamepadButton
South.new
new(variant: EnumVariantRef, payload: Fields<GamepadButton::South>) -> GamepadButton
Start.new
new(variant: EnumVariantRef, payload: Fields<GamepadButton::Start>) -> GamepadButton
West.new
new(variant: EnumVariantRef, payload: Fields<GamepadButton::West>) -> GamepadButton
Z.new
new(variant: EnumVariantRef, payload: Fields<GamepadButton::Z>) -> GamepadButton
GamepadInput
Encapsulation over GamepadAxis and GamepadButton.
Variants
| Variant | Fields |
|---|---|
Axis | (GamepadAxis) |
Button | (GamepadButton) |
Functions
| Name | Summary |
|---|---|
new | Constructs a new instance of the type from a table of its fields. |
new
new(payload: Fields<GamepadInput>) -> GamepadInput
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
Variant Functions
| Name | Summary |
|---|---|
Axis.new | |
Button.new |
Axis.new
new(variant: EnumVariantRef, payload: Fields<GamepadInput::Axis>) -> GamepadInput
Button.new
new(variant: EnumVariantRef, payload: Fields<GamepadInput::Button>) -> GamepadInput
InputFocus
ComponentResource
Resource representing which entity has input focus, if any. Input events (other than pointer-like inputs) will be dispatched to the current focus entity, or to the primary window if no entity has focus.
Changing the input focus is as easy as modifying this resource.
To detect when an entity gains or loses focus, listen for the FocusGained and FocusLost events.
Examples
From within a system:
use bevy_ecs::prelude::*;
use bevy_input_focus::{FocusCause, InputFocus};
fn clear_focus(mut input_focus: ResMut<InputFocus>) {
input_focus.clear();
}
With exclusive (or deferred) world access:
use bevy_ecs::prelude::*;
use bevy_input_focus::{FocusCause, InputFocus};
fn set_focus_from_world(world: &mut World) {
let entity = world.spawn_empty().id();
// Fetch the resource from the world
let mut input_focus = world.resource_mut::<InputFocus>();
// Then mutate it!
input_focus.set(entity, FocusCause::Navigated);
// Or you can just insert a fresh copy of the resource
// which will overwrite the existing one.
world.insert_resource(InputFocus::from_entity(entity));
}
Fields
| Field | Type |
|---|---|
current_focus | Optional<Entity> |
recorded_changes | Vec<Optional<(Entity, FocusCause)>> |
original_focus | Optional<Entity> |
Functions
| Name | Summary |
|---|---|
new | Constructs a new instance of the type from a table of its fields. |
new
new(payload: Fields<InputFocus>) -> InputFocus
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
Methods
| Name | Summary |
|---|---|
clear | Takes the focus away from every entity. |
get | The entity which has the focus, or nil if no entity has it. |
set | Gives the focus to the entity, so it receives keyboard input. |
clear
clear(self: InputFocus)
Takes the focus away from every entity.
get
get(self: InputFocus) -> Optional<Entity>
The entity which has the focus, or nil if no entity has it.
set
set(self: InputFocus, entity: Entity)
Gives the focus to the entity, so it receives keyboard input.
KeyCode
The key code of a KeyboardInput.
Usage
It is used as the generic T value of an ButtonInput to create a Res<ButtonInput<KeyCode>>.
Code representing the location of a physical key
This mostly conforms to the UI Events Specification's KeyboardEvent.code with a few
exceptions:
- The keys that the specification calls
MetaLeftandMetaRightare namedSuperLeftandSuperRighthere. - The key that the specification calls “Super” is reported as
Unidentifiedhere.
Updating
The resource is updated inside of the keyboard_input_system.
Variants
| Variant | Fields |
|---|---|
Unidentified | (NativeKeyCode) |
Backquote | |
Backslash | |
BracketLeft | |
BracketRight | |
Comma | |
Digit0 | |
Digit1 | |
Digit2 | |
Digit3 | |
Digit4 | |
Digit5 | |
Digit6 | |
Digit7 | |
Digit8 | |
Digit9 | |
Equal | |
IntlBackslash | |
IntlRo | |
IntlYen | |
KeyA | |
KeyB | |
KeyC | |
KeyD | |
KeyE | |
KeyF | |
KeyG | |
KeyH | |
KeyI | |
KeyJ | |
KeyK | |
KeyL | |
KeyM | |
KeyN | |
KeyO | |
KeyP | |
KeyQ | |
KeyR | |
KeyS | |
KeyT | |
KeyU | |
KeyV | |
KeyW | |
KeyX | |
KeyY | |
KeyZ | |
Minus | |
Period | |
Quote | |
Semicolon | |
Slash | |
AltLeft | |
AltRight | |
Backspace | |
CapsLock | |
ContextMenu | |
ControlLeft | |
ControlRight | |
Enter | |
SuperLeft | |
SuperRight | |
ShiftLeft | |
ShiftRight | |
Space | |
Tab | |
Convert | |
KanaMode | |
Lang1 | |
Lang2 | |
Lang3 | |
Lang4 | |
Lang5 | |
NonConvert | |
Delete | |
End | |
Help | |
Home | |
Insert | |
PageDown | |
PageUp | |
ArrowDown | |
ArrowLeft | |
ArrowRight | |
ArrowUp | |
NumLock | |
Numpad0 | |
Numpad1 | |
Numpad2 | |
Numpad3 | |
Numpad4 | |
Numpad5 | |
Numpad6 | |
Numpad7 | |
Numpad8 | |
Numpad9 | |
NumpadAdd | |
NumpadBackspace | |
NumpadClear | |
NumpadClearEntry | |
NumpadComma | |
NumpadDecimal | |
NumpadDivide | |
NumpadEnter | |
NumpadEqual | |
NumpadHash | |
NumpadMemoryAdd | |
NumpadMemoryClear | |
NumpadMemoryRecall | |
NumpadMemoryStore | |
NumpadMemorySubtract | |
NumpadMultiply | |
NumpadParenLeft | |
NumpadParenRight | |
NumpadStar | |
NumpadSubtract | |
Escape | |
Fn | |
FnLock | |
PrintScreen | |
ScrollLock | |
Pause | |
BrowserBack | |
BrowserFavorites | |
BrowserForward | |
BrowserHome | |
BrowserRefresh | |
BrowserSearch | |
BrowserStop | |
Eject | |
LaunchApp1 | |
LaunchApp2 | |
LaunchMail | |
MediaPlayPause | |
MediaSelect | |
MediaStop | |
MediaTrackNext | |
MediaTrackPrevious | |
Power | |
Sleep | |
AudioVolumeDown | |
AudioVolumeMute | |
AudioVolumeUp | |
WakeUp | |
Meta | |
Hyper | |
Turbo | |
Abort | |
Resume | |
Suspend | |
Again | |
Copy | |
Cut | |
Find | |
Open | |
Paste | |
Props | |
Select | |
Undo | |
Hiragana | |
Katakana | |
F1 | |
F2 | |
F3 | |
F4 | |
F5 | |
F6 | |
F7 | |
F8 | |
F9 | |
F10 | |
F11 | |
F12 | |
F13 | |
F14 | |
F15 | |
F16 | |
F17 | |
F18 | |
F19 | |
F20 | |
F21 | |
F22 | |
F23 | |
F24 | |
F25 | |
F26 | |
F27 | |
F28 | |
F29 | |
F30 | |
F31 | |
F32 | |
F33 | |
F34 | |
F35 |
Functions
| Name | Summary |
|---|---|
any_just_pressed | Whether any of the keys was pressed during the last update. |
any_pressed | Whether any of the keys is held down. |
get_just_pressed | The keys which were pressed during the last update. |
get_pressed | The keys which are held down. |
new | Constructs a new instance of the type from a table of its fields. |
any_just_pressed
Whether any of the keys was pressed during the last update.
any_pressed
Whether any of the keys is held down.
get_just_pressed
get_just_pressed() -> Vec<KeyCode>
The keys which were pressed during the last update.
get_pressed
get_pressed() -> Vec<KeyCode>
The keys which are held down.
new
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
Methods
| Name | Summary |
|---|---|
just_pressed | Whether the key was pressed during the last update. |
just_released | Whether the key was released during the last update. |
pressed | Whether the key is held down, false if the input resource is missing. |
just_pressed
Whether the key was pressed during the last update.
just_released
Whether the key was released during the last update.
pressed
Whether the key is held down, false if the input resource is missing.
Variant Functions
Abort.new
new(variant: EnumVariantRef, payload: Fields<KeyCode::Abort>) -> KeyCode
Again.new
new(variant: EnumVariantRef, payload: Fields<KeyCode::Again>) -> KeyCode
AltLeft.new
new(variant: EnumVariantRef, payload: Fields<KeyCode::AltLeft>) -> KeyCode
AltRight.new
new(variant: EnumVariantRef, payload: Fields<KeyCode::AltRight>) -> KeyCode
ArrowDown.new
new(variant: EnumVariantRef, payload: Fields<KeyCode::ArrowDown>) -> KeyCode
ArrowLeft.new
new(variant: EnumVariantRef, payload: Fields<KeyCode::ArrowLeft>) -> KeyCode
ArrowRight.new
new(variant: EnumVariantRef, payload: Fields<KeyCode::ArrowRight>) -> KeyCode
ArrowUp.new
new(variant: EnumVariantRef, payload: Fields<KeyCode::ArrowUp>) -> KeyCode
AudioVolumeDown.new
new(variant: EnumVariantRef, payload: Fields<KeyCode::AudioVolumeDown>) -> KeyCode
AudioVolumeMute.new
new(variant: EnumVariantRef, payload: Fields<KeyCode::AudioVolumeMute>) -> KeyCode
AudioVolumeUp.new
new(variant: EnumVariantRef, payload: Fields<KeyCode::AudioVolumeUp>) -> KeyCode
Backquote.new
new(variant: EnumVariantRef, payload: Fields<KeyCode::Backquote>) -> KeyCode
Backslash.new
new(variant: EnumVariantRef, payload: Fields<KeyCode::Backslash>) -> KeyCode
Backspace.new
new(variant: EnumVariantRef, payload: Fields<KeyCode::Backspace>) -> KeyCode
BracketLeft.new
new(variant: EnumVariantRef, payload: Fields<KeyCode::BracketLeft>) -> KeyCode
BracketRight.new
new(variant: EnumVariantRef, payload: Fields<KeyCode::BracketRight>) -> KeyCode
BrowserBack.new
new(variant: EnumVariantRef, payload: Fields<KeyCode::BrowserBack>) -> KeyCode
BrowserFavorites.new
new(variant: EnumVariantRef, payload: Fields<KeyCode::BrowserFavorites>) -> KeyCode
BrowserForward.new
new(variant: EnumVariantRef, payload: Fields<KeyCode::BrowserForward>) -> KeyCode
BrowserHome.new
new(variant: EnumVariantRef, payload: Fields<KeyCode::BrowserHome>) -> KeyCode
BrowserRefresh.new
new(variant: EnumVariantRef, payload: Fields<KeyCode::BrowserRefresh>) -> KeyCode
BrowserSearch.new
new(variant: EnumVariantRef, payload: Fields<KeyCode::BrowserSearch>) -> KeyCode
BrowserStop.new
new(variant: EnumVariantRef, payload: Fields<KeyCode::BrowserStop>) -> KeyCode
CapsLock.new
new(variant: EnumVariantRef, payload: Fields<KeyCode::CapsLock>) -> KeyCode
Comma.new
new(variant: EnumVariantRef, payload: Fields<KeyCode::Comma>) -> KeyCode
ContextMenu.new
new(variant: EnumVariantRef, payload: Fields<KeyCode::ContextMenu>) -> KeyCode
ControlLeft.new
new(variant: EnumVariantRef, payload: Fields<KeyCode::ControlLeft>) -> KeyCode
ControlRight.new
new(variant: EnumVariantRef, payload: Fields<KeyCode::ControlRight>) -> KeyCode
Convert.new
new(variant: EnumVariantRef, payload: Fields<KeyCode::Convert>) -> KeyCode
Copy.new
new(variant: EnumVariantRef, payload: Fields<KeyCode::Copy>) -> KeyCode
Cut.new
new(variant: EnumVariantRef, payload: Fields<KeyCode::Cut>) -> KeyCode
Delete.new
new(variant: EnumVariantRef, payload: Fields<KeyCode::Delete>) -> KeyCode
Digit0.new
new(variant: EnumVariantRef, payload: Fields<KeyCode::Digit0>) -> KeyCode
Digit1.new
new(variant: EnumVariantRef, payload: Fields<KeyCode::Digit1>) -> KeyCode
Digit2.new
new(variant: EnumVariantRef, payload: Fields<KeyCode::Digit2>) -> KeyCode
Digit3.new
new(variant: EnumVariantRef, payload: Fields<KeyCode::Digit3>) -> KeyCode
Digit4.new
new(variant: EnumVariantRef, payload: Fields<KeyCode::Digit4>) -> KeyCode
Digit5.new
new(variant: EnumVariantRef, payload: Fields<KeyCode::Digit5>) -> KeyCode
Digit6.new
new(variant: EnumVariantRef, payload: Fields<KeyCode::Digit6>) -> KeyCode
Digit7.new
new(variant: EnumVariantRef, payload: Fields<KeyCode::Digit7>) -> KeyCode
Digit8.new
new(variant: EnumVariantRef, payload: Fields<KeyCode::Digit8>) -> KeyCode
Digit9.new
new(variant: EnumVariantRef, payload: Fields<KeyCode::Digit9>) -> KeyCode
Eject.new
new(variant: EnumVariantRef, payload: Fields<KeyCode::Eject>) -> KeyCode
End.new
new(variant: EnumVariantRef, payload: Fields<KeyCode::End>) -> KeyCode
Enter.new
new(variant: EnumVariantRef, payload: Fields<KeyCode::Enter>) -> KeyCode
Equal.new
new(variant: EnumVariantRef, payload: Fields<KeyCode::Equal>) -> KeyCode
Escape.new
new(variant: EnumVariantRef, payload: Fields<KeyCode::Escape>) -> KeyCode
F1.new
new(variant: EnumVariantRef, payload: Fields<KeyCode::F1>) -> KeyCode
F10.new
new(variant: EnumVariantRef, payload: Fields<KeyCode::F10>) -> KeyCode
F11.new
new(variant: EnumVariantRef, payload: Fields<KeyCode::F11>) -> KeyCode
F12.new
new(variant: EnumVariantRef, payload: Fields<KeyCode::F12>) -> KeyCode
F13.new
new(variant: EnumVariantRef, payload: Fields<KeyCode::F13>) -> KeyCode
F14.new
new(variant: EnumVariantRef, payload: Fields<KeyCode::F14>) -> KeyCode
F15.new
new(variant: EnumVariantRef, payload: Fields<KeyCode::F15>) -> KeyCode
F16.new
new(variant: EnumVariantRef, payload: Fields<KeyCode::F16>) -> KeyCode
F17.new
new(variant: EnumVariantRef, payload: Fields<KeyCode::F17>) -> KeyCode
F18.new
new(variant: EnumVariantRef, payload: Fields<KeyCode::F18>) -> KeyCode
F19.new
new(variant: EnumVariantRef, payload: Fields<KeyCode::F19>) -> KeyCode
F2.new
new(variant: EnumVariantRef, payload: Fields<KeyCode::F2>) -> KeyCode
F20.new
new(variant: EnumVariantRef, payload: Fields<KeyCode::F20>) -> KeyCode
F21.new
new(variant: EnumVariantRef, payload: Fields<KeyCode::F21>) -> KeyCode
F22.new
new(variant: EnumVariantRef, payload: Fields<KeyCode::F22>) -> KeyCode
F23.new
new(variant: EnumVariantRef, payload: Fields<KeyCode::F23>) -> KeyCode
F24.new
new(variant: EnumVariantRef, payload: Fields<KeyCode::F24>) -> KeyCode
F25.new
new(variant: EnumVariantRef, payload: Fields<KeyCode::F25>) -> KeyCode
F26.new
new(variant: EnumVariantRef, payload: Fields<KeyCode::F26>) -> KeyCode
F27.new
new(variant: EnumVariantRef, payload: Fields<KeyCode::F27>) -> KeyCode
F28.new
new(variant: EnumVariantRef, payload: Fields<KeyCode::F28>) -> KeyCode
F29.new
new(variant: EnumVariantRef, payload: Fields<KeyCode::F29>) -> KeyCode
F3.new
new(variant: EnumVariantRef, payload: Fields<KeyCode::F3>) -> KeyCode
F30.new
new(variant: EnumVariantRef, payload: Fields<KeyCode::F30>) -> KeyCode
F31.new
new(variant: EnumVariantRef, payload: Fields<KeyCode::F31>) -> KeyCode
F32.new
new(variant: EnumVariantRef, payload: Fields<KeyCode::F32>) -> KeyCode
F33.new
new(variant: EnumVariantRef, payload: Fields<KeyCode::F33>) -> KeyCode
F34.new
new(variant: EnumVariantRef, payload: Fields<KeyCode::F34>) -> KeyCode
F35.new
new(variant: EnumVariantRef, payload: Fields<KeyCode::F35>) -> KeyCode
F4.new
new(variant: EnumVariantRef, payload: Fields<KeyCode::F4>) -> KeyCode
F5.new
new(variant: EnumVariantRef, payload: Fields<KeyCode::F5>) -> KeyCode
F6.new
new(variant: EnumVariantRef, payload: Fields<KeyCode::F6>) -> KeyCode
F7.new
new(variant: EnumVariantRef, payload: Fields<KeyCode::F7>) -> KeyCode
F8.new
new(variant: EnumVariantRef, payload: Fields<KeyCode::F8>) -> KeyCode
F9.new
new(variant: EnumVariantRef, payload: Fields<KeyCode::F9>) -> KeyCode
Find.new
new(variant: EnumVariantRef, payload: Fields<KeyCode::Find>) -> KeyCode
Fn.new
new(variant: EnumVariantRef, payload: Fields<KeyCode::Fn>) -> KeyCode
FnLock.new
new(variant: EnumVariantRef, payload: Fields<KeyCode::FnLock>) -> KeyCode
Help.new
new(variant: EnumVariantRef, payload: Fields<KeyCode::Help>) -> KeyCode
Hiragana.new
new(variant: EnumVariantRef, payload: Fields<KeyCode::Hiragana>) -> KeyCode
Home.new
new(variant: EnumVariantRef, payload: Fields<KeyCode::Home>) -> KeyCode
Hyper.new
new(variant: EnumVariantRef, payload: Fields<KeyCode::Hyper>) -> KeyCode
Insert.new
new(variant: EnumVariantRef, payload: Fields<KeyCode::Insert>) -> KeyCode
IntlBackslash.new
new(variant: EnumVariantRef, payload: Fields<KeyCode::IntlBackslash>) -> KeyCode
IntlRo.new
new(variant: EnumVariantRef, payload: Fields<KeyCode::IntlRo>) -> KeyCode
IntlYen.new
new(variant: EnumVariantRef, payload: Fields<KeyCode::IntlYen>) -> KeyCode
KanaMode.new
new(variant: EnumVariantRef, payload: Fields<KeyCode::KanaMode>) -> KeyCode
Katakana.new
new(variant: EnumVariantRef, payload: Fields<KeyCode::Katakana>) -> KeyCode
KeyA.new
new(variant: EnumVariantRef, payload: Fields<KeyCode::KeyA>) -> KeyCode
KeyB.new
new(variant: EnumVariantRef, payload: Fields<KeyCode::KeyB>) -> KeyCode
KeyC.new
new(variant: EnumVariantRef, payload: Fields<KeyCode::KeyC>) -> KeyCode
KeyD.new
new(variant: EnumVariantRef, payload: Fields<KeyCode::KeyD>) -> KeyCode
KeyE.new
new(variant: EnumVariantRef, payload: Fields<KeyCode::KeyE>) -> KeyCode
KeyF.new
new(variant: EnumVariantRef, payload: Fields<KeyCode::KeyF>) -> KeyCode
KeyG.new
new(variant: EnumVariantRef, payload: Fields<KeyCode::KeyG>) -> KeyCode
KeyH.new
new(variant: EnumVariantRef, payload: Fields<KeyCode::KeyH>) -> KeyCode
KeyI.new
new(variant: EnumVariantRef, payload: Fields<KeyCode::KeyI>) -> KeyCode
KeyJ.new
new(variant: EnumVariantRef, payload: Fields<KeyCode::KeyJ>) -> KeyCode
KeyK.new
new(variant: EnumVariantRef, payload: Fields<KeyCode::KeyK>) -> KeyCode
KeyL.new
new(variant: EnumVariantRef, payload: Fields<KeyCode::KeyL>) -> KeyCode
KeyM.new
new(variant: EnumVariantRef, payload: Fields<KeyCode::KeyM>) -> KeyCode
KeyN.new
new(variant: EnumVariantRef, payload: Fields<KeyCode::KeyN>) -> KeyCode
KeyO.new
new(variant: EnumVariantRef, payload: Fields<KeyCode::KeyO>) -> KeyCode
KeyP.new
new(variant: EnumVariantRef, payload: Fields<KeyCode::KeyP>) -> KeyCode
KeyQ.new
new(variant: EnumVariantRef, payload: Fields<KeyCode::KeyQ>) -> KeyCode
KeyR.new
new(variant: EnumVariantRef, payload: Fields<KeyCode::KeyR>) -> KeyCode
KeyS.new
new(variant: EnumVariantRef, payload: Fields<KeyCode::KeyS>) -> KeyCode
KeyT.new
new(variant: EnumVariantRef, payload: Fields<KeyCode::KeyT>) -> KeyCode
KeyU.new
new(variant: EnumVariantRef, payload: Fields<KeyCode::KeyU>) -> KeyCode
KeyV.new
new(variant: EnumVariantRef, payload: Fields<KeyCode::KeyV>) -> KeyCode
KeyW.new
new(variant: EnumVariantRef, payload: Fields<KeyCode::KeyW>) -> KeyCode
KeyX.new
new(variant: EnumVariantRef, payload: Fields<KeyCode::KeyX>) -> KeyCode
KeyY.new
new(variant: EnumVariantRef, payload: Fields<KeyCode::KeyY>) -> KeyCode
KeyZ.new
new(variant: EnumVariantRef, payload: Fields<KeyCode::KeyZ>) -> KeyCode
Lang1.new
new(variant: EnumVariantRef, payload: Fields<KeyCode::Lang1>) -> KeyCode
Lang2.new
new(variant: EnumVariantRef, payload: Fields<KeyCode::Lang2>) -> KeyCode
Lang3.new
new(variant: EnumVariantRef, payload: Fields<KeyCode::Lang3>) -> KeyCode
Lang4.new
new(variant: EnumVariantRef, payload: Fields<KeyCode::Lang4>) -> KeyCode
Lang5.new
new(variant: EnumVariantRef, payload: Fields<KeyCode::Lang5>) -> KeyCode
LaunchApp1.new
new(variant: EnumVariantRef, payload: Fields<KeyCode::LaunchApp1>) -> KeyCode
LaunchApp2.new
new(variant: EnumVariantRef, payload: Fields<KeyCode::LaunchApp2>) -> KeyCode
LaunchMail.new
new(variant: EnumVariantRef, payload: Fields<KeyCode::LaunchMail>) -> KeyCode
MediaPlayPause.new
new(variant: EnumVariantRef, payload: Fields<KeyCode::MediaPlayPause>) -> KeyCode
MediaSelect.new
new(variant: EnumVariantRef, payload: Fields<KeyCode::MediaSelect>) -> KeyCode
MediaStop.new
new(variant: EnumVariantRef, payload: Fields<KeyCode::MediaStop>) -> KeyCode
MediaTrackNext.new
new(variant: EnumVariantRef, payload: Fields<KeyCode::MediaTrackNext>) -> KeyCode
MediaTrackPrevious.new
new(variant: EnumVariantRef, payload: Fields<KeyCode::MediaTrackPrevious>) -> KeyCode
Meta.new
new(variant: EnumVariantRef, payload: Fields<KeyCode::Meta>) -> KeyCode
Minus.new
new(variant: EnumVariantRef, payload: Fields<KeyCode::Minus>) -> KeyCode
NonConvert.new
new(variant: EnumVariantRef, payload: Fields<KeyCode::NonConvert>) -> KeyCode
NumLock.new
new(variant: EnumVariantRef, payload: Fields<KeyCode::NumLock>) -> KeyCode
Numpad0.new
new(variant: EnumVariantRef, payload: Fields<KeyCode::Numpad0>) -> KeyCode
Numpad1.new
new(variant: EnumVariantRef, payload: Fields<KeyCode::Numpad1>) -> KeyCode
Numpad2.new
new(variant: EnumVariantRef, payload: Fields<KeyCode::Numpad2>) -> KeyCode
Numpad3.new
new(variant: EnumVariantRef, payload: Fields<KeyCode::Numpad3>) -> KeyCode
Numpad4.new
new(variant: EnumVariantRef, payload: Fields<KeyCode::Numpad4>) -> KeyCode
Numpad5.new
new(variant: EnumVariantRef, payload: Fields<KeyCode::Numpad5>) -> KeyCode
Numpad6.new
new(variant: EnumVariantRef, payload: Fields<KeyCode::Numpad6>) -> KeyCode
Numpad7.new
new(variant: EnumVariantRef, payload: Fields<KeyCode::Numpad7>) -> KeyCode
Numpad8.new
new(variant: EnumVariantRef, payload: Fields<KeyCode::Numpad8>) -> KeyCode
Numpad9.new
new(variant: EnumVariantRef, payload: Fields<KeyCode::Numpad9>) -> KeyCode
NumpadAdd.new
new(variant: EnumVariantRef, payload: Fields<KeyCode::NumpadAdd>) -> KeyCode
NumpadBackspace.new
new(variant: EnumVariantRef, payload: Fields<KeyCode::NumpadBackspace>) -> KeyCode
NumpadClear.new
new(variant: EnumVariantRef, payload: Fields<KeyCode::NumpadClear>) -> KeyCode
NumpadClearEntry.new
new(variant: EnumVariantRef, payload: Fields<KeyCode::NumpadClearEntry>) -> KeyCode
NumpadComma.new
new(variant: EnumVariantRef, payload: Fields<KeyCode::NumpadComma>) -> KeyCode
NumpadDecimal.new
new(variant: EnumVariantRef, payload: Fields<KeyCode::NumpadDecimal>) -> KeyCode
NumpadDivide.new
new(variant: EnumVariantRef, payload: Fields<KeyCode::NumpadDivide>) -> KeyCode
NumpadEnter.new
new(variant: EnumVariantRef, payload: Fields<KeyCode::NumpadEnter>) -> KeyCode
NumpadEqual.new
new(variant: EnumVariantRef, payload: Fields<KeyCode::NumpadEqual>) -> KeyCode
NumpadHash.new
new(variant: EnumVariantRef, payload: Fields<KeyCode::NumpadHash>) -> KeyCode
NumpadMemoryAdd.new
new(variant: EnumVariantRef, payload: Fields<KeyCode::NumpadMemoryAdd>) -> KeyCode
NumpadMemoryClear.new
new(variant: EnumVariantRef, payload: Fields<KeyCode::NumpadMemoryClear>) -> KeyCode
NumpadMemoryRecall.new
new(variant: EnumVariantRef, payload: Fields<KeyCode::NumpadMemoryRecall>) -> KeyCode
NumpadMemoryStore.new
new(variant: EnumVariantRef, payload: Fields<KeyCode::NumpadMemoryStore>) -> KeyCode
NumpadMemorySubtract.new
new(variant: EnumVariantRef, payload: Fields<KeyCode::NumpadMemorySubtract>) -> KeyCode
NumpadMultiply.new
new(variant: EnumVariantRef, payload: Fields<KeyCode::NumpadMultiply>) -> KeyCode
NumpadParenLeft.new
new(variant: EnumVariantRef, payload: Fields<KeyCode::NumpadParenLeft>) -> KeyCode
NumpadParenRight.new
new(variant: EnumVariantRef, payload: Fields<KeyCode::NumpadParenRight>) -> KeyCode
NumpadStar.new
new(variant: EnumVariantRef, payload: Fields<KeyCode::NumpadStar>) -> KeyCode
NumpadSubtract.new
new(variant: EnumVariantRef, payload: Fields<KeyCode::NumpadSubtract>) -> KeyCode
Open.new
new(variant: EnumVariantRef, payload: Fields<KeyCode::Open>) -> KeyCode
PageDown.new
new(variant: EnumVariantRef, payload: Fields<KeyCode::PageDown>) -> KeyCode
PageUp.new
new(variant: EnumVariantRef, payload: Fields<KeyCode::PageUp>) -> KeyCode
Paste.new
new(variant: EnumVariantRef, payload: Fields<KeyCode::Paste>) -> KeyCode
Pause.new
new(variant: EnumVariantRef, payload: Fields<KeyCode::Pause>) -> KeyCode
Period.new
new(variant: EnumVariantRef, payload: Fields<KeyCode::Period>) -> KeyCode
Power.new
new(variant: EnumVariantRef, payload: Fields<KeyCode::Power>) -> KeyCode
PrintScreen.new
new(variant: EnumVariantRef, payload: Fields<KeyCode::PrintScreen>) -> KeyCode
Props.new
new(variant: EnumVariantRef, payload: Fields<KeyCode::Props>) -> KeyCode
Quote.new
new(variant: EnumVariantRef, payload: Fields<KeyCode::Quote>) -> KeyCode
Resume.new
new(variant: EnumVariantRef, payload: Fields<KeyCode::Resume>) -> KeyCode
ScrollLock.new
new(variant: EnumVariantRef, payload: Fields<KeyCode::ScrollLock>) -> KeyCode
Select.new
new(variant: EnumVariantRef, payload: Fields<KeyCode::Select>) -> KeyCode
Semicolon.new
new(variant: EnumVariantRef, payload: Fields<KeyCode::Semicolon>) -> KeyCode
ShiftLeft.new
new(variant: EnumVariantRef, payload: Fields<KeyCode::ShiftLeft>) -> KeyCode
ShiftRight.new
new(variant: EnumVariantRef, payload: Fields<KeyCode::ShiftRight>) -> KeyCode
Slash.new
new(variant: EnumVariantRef, payload: Fields<KeyCode::Slash>) -> KeyCode
Sleep.new
new(variant: EnumVariantRef, payload: Fields<KeyCode::Sleep>) -> KeyCode
Space.new
new(variant: EnumVariantRef, payload: Fields<KeyCode::Space>) -> KeyCode
SuperLeft.new
new(variant: EnumVariantRef, payload: Fields<KeyCode::SuperLeft>) -> KeyCode
SuperRight.new
new(variant: EnumVariantRef, payload: Fields<KeyCode::SuperRight>) -> KeyCode
Suspend.new
new(variant: EnumVariantRef, payload: Fields<KeyCode::Suspend>) -> KeyCode
Tab.new
new(variant: EnumVariantRef, payload: Fields<KeyCode::Tab>) -> KeyCode
Turbo.new
new(variant: EnumVariantRef, payload: Fields<KeyCode::Turbo>) -> KeyCode
Undo.new
new(variant: EnumVariantRef, payload: Fields<KeyCode::Undo>) -> KeyCode
Unidentified.new
new(variant: EnumVariantRef, payload: Fields<KeyCode::Unidentified>) -> KeyCode
WakeUp.new
new(variant: EnumVariantRef, payload: Fields<KeyCode::WakeUp>) -> KeyCode
MouseButton
A button on a mouse device.
Usage
It is used as the generic T value of an ButtonInput to create a bevy
resource.
Updating
The resource is updated inside of the mouse_button_input_system.
Variants
| Variant | Fields |
|---|---|
Left | |
Right | |
Middle | |
Back | |
Forward | |
Other | (u16) |
Functions
| Name | Summary |
|---|---|
any_just_pressed | Whether any of the mouse buttons was pressed during the last update. |
any_pressed | Whether any of the mouse buttons is held down. |
get_just_pressed | The mouse buttons which were pressed during the last update. |
get_pressed | The mouse buttons which are held down. |
new | Constructs a new instance of the type from a table of its fields. |
any_just_pressed
any_just_pressed(buttons: Vec<MouseButton>) -> bool
Whether any of the mouse buttons was pressed during the last update.
any_pressed
any_pressed(buttons: Vec<MouseButton>) -> bool
Whether any of the mouse buttons is held down.
get_just_pressed
get_just_pressed() -> Vec<MouseButton>
The mouse buttons which were pressed during the last update.
get_pressed
get_pressed() -> Vec<MouseButton>
The mouse buttons which are held down.
new
new(payload: Fields<MouseButton>) -> MouseButton
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
Methods
| Name | Summary |
|---|---|
just_pressed | Whether the mouse button was pressed during the last update. |
just_released | Whether the mouse button was released during the last update. |
pressed | Whether the mouse button is held down, false if the input resource is missing. |
just_pressed
just_pressed(button: MouseButton) -> bool
Whether the mouse button was pressed during the last update.
just_released
just_released(button: MouseButton) -> bool
Whether the mouse button was released during the last update.
pressed
pressed(button: MouseButton) -> bool
Whether the mouse button is held down, false if the input resource is missing.
Variant Functions
| Name | Summary |
|---|---|
Back.new | |
Forward.new | |
Left.new | |
Middle.new | |
Other.new | |
Right.new |
Back.new
new(variant: EnumVariantRef, payload: Fields<MouseButton::Back>) -> MouseButton
Forward.new
new(variant: EnumVariantRef, payload: Fields<MouseButton::Forward>) -> MouseButton
Left.new
new(variant: EnumVariantRef, payload: Fields<MouseButton::Left>) -> MouseButton
Middle.new
new(variant: EnumVariantRef, payload: Fields<MouseButton::Middle>) -> MouseButton
Other.new
new(variant: EnumVariantRef, payload: Fields<MouseButton::Other>) -> MouseButton
Right.new
new(variant: EnumVariantRef, payload: Fields<MouseButton::Right>) -> MouseButton
NativeKeyCode
Contains the platform-native physical key identifier
The exact values vary from platform to platform (which is part of why this is a per-platform enum), but the values are primarily tied to the key’s physical location on the keyboard.
This enum is primarily used to store raw keycodes when Winit doesn’t map a given native
physical key identifier to a meaningful KeyCode variant. In the presence of identifiers we
haven’t mapped for you yet, this lets you use KeyCode to:
- Correctly match key press and release events.
- On non-web platforms, support assigning keybinds to virtually any key through a UI.
Variants
Functions
| Name | Summary |
|---|---|
new | Constructs a new instance of the type from a table of its fields. |
new
new(payload: Fields<NativeKeyCode>) -> NativeKeyCode
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
Variant Functions
| Name | Summary |
|---|---|
Android.new | |
MacOS.new | |
Unidentified.new | |
Windows.new | |
Xkb.new |
Android.new
new(variant: EnumVariantRef, payload: Fields<NativeKeyCode::Android>) -> NativeKeyCode
MacOS.new
new(variant: EnumVariantRef, payload: Fields<NativeKeyCode::MacOS>) -> NativeKeyCode
Unidentified.new
new(variant: EnumVariantRef, payload: Fields<NativeKeyCode::Unidentified>) -> NativeKeyCode
Windows.new
new(variant: EnumVariantRef, payload: Fields<NativeKeyCode::Windows>) -> NativeKeyCode
Xkb.new
new(variant: EnumVariantRef, payload: Fields<NativeKeyCode::Xkb>) -> NativeKeyCode
input.InputFocusSystems
The types and functions in the input.InputFocusSystems namespace, as returned by import_namespace("input.InputFocusSystems").
Values
| Name | Type |
|---|---|
Dispatch | ReflectSystemSet |
FocusChangeEvents | ReflectSystemSet |
math
The types and functions in the math namespace, as returned by import_namespace("math").
Types
| Type | Summary |
|---|---|
Aabb2d | A 2D axis-aligned bounding box, or bounding rectangle |
Aabb3d | A 3D axis-aligned bounding box |
Affine2 | |
Affine3A | |
Annulus | A primitive shape formed by the region between two circles, also known as a ring. |
Capsule2d | A 2D capsule primitive, also known as a stadium or pill shape. |
Capsule3d | A 3D capsule primitive centered on the origin A three-dimensional capsule is defined as a surface at a distance… |
Circle | A circle primitive, representing the set of points some distance from the origin |
CompassOctant | A compass enum with 8 directions. |
Cone | A cone primitive centered on the midpoint between the tip of the cone and the center of its base. |
Cuboid | A cuboid primitive, which is like a cube, except that the x, y, and z dimensions are not required to be the same. |
Cylinder | A cylinder primitive centered on the origin |
Dir2 | A normalized vector pointing in a direction in 2D space |
Dir3 | A normalized vector pointing in a direction in 3D space |
DVec2 | |
DVec3 | |
EaseFunction | Curve functions over the unit interval, commonly used for easing transitions. |
EulerRot | |
IVec2 | |
IVec3 | |
JumpAt | Configuration options for the EaseFunction::Steps curves. This closely replicates the CSS step function specification. |
Mat2 | |
Mat3 | |
Mat3A | |
Mat4 | |
Plane3d | A bounded plane in 3D space. It forms a surface starting from the origin with a defined height and width. |
Quat | |
Ray2d | An infinite half-line starting at origin and going in direction in 2D space. |
Ray3d | An infinite half-line starting at origin and going in direction in 3D space. |
Rect | A rectangle defined by two opposite corners. |
Rectangle | A rectangle primitive, which is like a square, except that the width and height can be different |
RegularPolygon | A polygon centered on the origin where all vertices lie on a circle, equally far apart. |
Rot2 | A 2D rotation. |
Sphere | A sphere primitive, representing the set of all points some distance from the origin |
Torus | A torus primitive, often representing a ring or donut shape The set of points some distance from a circle centered at… |
Triangle2d | A triangle in 2D space |
URect | A rectangle defined by two opposite corners. |
UVec2 | |
UVec3 | |
Vec2 | |
Vec3 | |
Vec3A | |
Vec4 |
Aabb2d
A 2D axis-aligned bounding box, or bounding rectangle
Fields
Functions
| Name | Summary |
|---|---|
new | Constructs a new instance of the type from a table of its fields. |
new
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
Aabb3d
A 3D axis-aligned bounding box
Fields
Functions
| Name | Summary |
|---|---|
new | Constructs a new instance of the type from a table of its fields. |
new
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
Affine2
Fields
Functions
| Name | Summary |
|---|---|
new | Constructs a new instance of the type from a table of its fields. |
new
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
Affine3A
Fields
Functions
| Name | Summary |
|---|---|
new | Constructs a new instance of the type from a table of its fields. |
new
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
Annulus
A primitive shape formed by the region between two circles, also known as a ring.
Fields
Functions
| Name | Summary |
|---|---|
new | A ring with the given inner and outer radii. |
new
A ring with the given inner and outer radii.
Capsule2d
A 2D capsule primitive, also known as a stadium or pill shape.
A two-dimensional capsule is defined as a neighborhood of points at a distance (radius) from a line
Fields
Functions
| Name | Summary |
|---|---|
new | Constructs a new instance of the type from a table of its fields. |
new
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
Capsule3d
A 3D capsule primitive centered on the origin A three-dimensional capsule is defined as a surface at a distance (radius) from a line
Fields
Functions
| Name | Summary |
|---|---|
new | A capsule with the given radius and length of its middle section. |
new
A capsule with the given radius and length of its middle section.
Circle
A circle primitive, representing the set of points some distance from the origin
Fields
| Field | Type |
|---|---|
radius | f32 |
Functions
| Name | Summary |
|---|---|
new | A circle with the given radius. |
new
A circle with the given radius.
CompassOctant
A compass enum with 8 directions.
N (North)
▲
NW │ NE
╲ │ ╱
W (West) ┼─────► E (East)
╱ │ ╲
SW │ SE
▼
S (South)
Variants
| Variant |
|---|
North |
NorthEast |
East |
SouthEast |
South |
SouthWest |
West |
NorthWest |
Functions
| Name | Summary |
|---|---|
new | Constructs a new instance of the type from a table of its fields. |
new
new(payload: Fields<CompassOctant>) -> CompassOctant
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
Variant Functions
| Name | Summary |
|---|---|
East.new | |
North.new | |
NorthEast.new | |
NorthWest.new | |
South.new | |
SouthEast.new | |
SouthWest.new | |
West.new |
East.new
new(variant: EnumVariantRef, payload: Fields<CompassOctant::East>) -> CompassOctant
North.new
new(variant: EnumVariantRef, payload: Fields<CompassOctant::North>) -> CompassOctant
NorthEast.new
new(variant: EnumVariantRef, payload: Fields<CompassOctant::NorthEast>) -> CompassOctant
NorthWest.new
new(variant: EnumVariantRef, payload: Fields<CompassOctant::NorthWest>) -> CompassOctant
South.new
new(variant: EnumVariantRef, payload: Fields<CompassOctant::South>) -> CompassOctant
SouthEast.new
new(variant: EnumVariantRef, payload: Fields<CompassOctant::SouthEast>) -> CompassOctant
SouthWest.new
new(variant: EnumVariantRef, payload: Fields<CompassOctant::SouthWest>) -> CompassOctant
West.new
new(variant: EnumVariantRef, payload: Fields<CompassOctant::West>) -> CompassOctant
Cone
A cone primitive centered on the midpoint between the tip of the cone and the center of its base.
The cone is oriented with its tip pointing towards the Y axis.
Fields
Functions
| Name | Summary |
|---|---|
new | Constructs a new instance of the type from a table of its fields. |
new
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
Cuboid
A cuboid primitive, which is like a cube, except that the x, y, and z dimensions are not required to be the same.
Fields
| Field | Type |
|---|---|
half_size | Vec3 |
Functions
| Name | Summary |
|---|---|
from_size | A box with the given size as a Vec3. |
new | A box with the given length along the x, y and z axes. |
from_size
A box with the given size as a Vec3.
new
A box with the given length along the x, y and z axes.
Cylinder
A cylinder primitive centered on the origin
Fields
Functions
| Name | Summary |
|---|---|
new | A cylinder with the given radius and height. |
new
A cylinder with the given radius and height.
Dir2
A normalized vector pointing in a direction in 2D space
Fields
| Index | Type |
|---|---|
0 | Vec2 |
Functions
| Name | Summary |
|---|---|
neg_x | The direction along the negative x axis. |
neg_y | The direction along the negative y axis. |
new | A unit direction pointing the same way as the vector, or nil if the vector is zero or not finite. |
x | The direction along the positive x axis. |
y | The direction along the positive y axis. |
neg_x
neg_x() -> Dir2
The direction along the negative x axis.
neg_y
neg_y() -> Dir2
The direction along the negative y axis.
new
A unit direction pointing the same way as the vector, or nil if the vector is zero or not finite.
x
x() -> Dir2
The direction along the positive x axis.
y
y() -> Dir2
The direction along the positive y axis.
Methods
| Name | Summary |
|---|---|
as_vec2 | This direction as a unit Vec2. |
slerp | Spherically interpolates between this direction and other by t, from 0 to 1. |
as_vec2
This direction as a unit Vec2.
slerp
Spherically interpolates between this direction and other by t, from 0 to 1.
Operators
| Name | Summary |
|---|---|
eq | Whether both directions have exactly the same components. |
mul | This direction scaled by length, as a Vec2. |
neg | The opposite direction. |
eq
Whether both directions have exactly the same components.
mul
This direction scaled by length, as a Vec2.
neg
The opposite direction.
Dir3
A normalized vector pointing in a direction in 3D space
Fields
| Index | Type |
|---|---|
0 | Vec3 |
Functions
| Name | Summary |
|---|---|
neg_x | The direction along the negative x axis. |
neg_y | The direction along the negative y axis. |
neg_z | The direction along the negative z axis. |
new | A unit direction pointing the same way as the vector, or nil if the vector is zero or not finite. |
x | The direction along the positive x axis. |
y | The direction along the positive y axis. |
z | The direction along the positive z axis. |
neg_x
neg_x() -> Dir3
The direction along the negative x axis.
neg_y
neg_y() -> Dir3
The direction along the negative y axis.
neg_z
neg_z() -> Dir3
The direction along the negative z axis.
new
A unit direction pointing the same way as the vector, or nil if the vector is zero or not finite.
x
x() -> Dir3
The direction along the positive x axis.
y
y() -> Dir3
The direction along the positive y axis.
z
z() -> Dir3
The direction along the positive z axis.
Methods
| Name | Summary |
|---|---|
as_vec3 | This direction as a unit Vec3. |
slerp | Spherically interpolates between this direction and other by t, from 0 to 1. |
as_vec3
This direction as a unit Vec3.
slerp
Spherically interpolates between this direction and other by t, from 0 to 1.
Operators
| Name | Summary |
|---|---|
eq | Whether both directions have exactly the same components. |
mul | This direction scaled by length, as a Vec3. |
neg | The opposite direction. |
eq
Whether both directions have exactly the same components.
mul
This direction scaled by length, as a Vec3.
neg
The opposite direction.
DVec2
Fields
Functions
| Name | Summary |
|---|---|
new | Creates a new double precision vector. |
new
Creates a new double precision vector.
Methods
| Name | Summary |
|---|---|
as_vec2 | Converts to a single precision Vec2. |
as_vec2
Converts to a single precision Vec2.
DVec3
Fields
Functions
| Name | Summary |
|---|---|
new | Creates a new double precision vector. |
new
Creates a new double precision vector.
Methods
| Name | Summary |
|---|---|
as_vec3 | Converts to a single precision Vec3. |
as_vec3
Converts to a single precision Vec3.
EaseFunction
Curve functions over the unit interval, commonly used for easing transitions.
EaseFunction can be used on its own to interpolate between 0.0 and 1.0.
It can also be combined with EasingCurve to interpolate between other
intervals and types, including vectors and rotations.
Example
sample the smoothstep function at various points. This will return None
if the parameter is outside the unit interval.
let f = EaseFunction::SmoothStep;
assert_eq!(f.sample(-1.0), None);
assert_eq!(f.sample(0.0), Some(0.0));
assert_eq!(f.sample(0.5), Some(0.5));
assert_eq!(f.sample(1.0), Some(1.0));
assert_eq!(f.sample(2.0), None);
sample_clamped will clamp the parameter to the unit interval, so it
always returns a value.
assert_eq!(f.sample_clamped(-1.0), 0.0);
assert_eq!(f.sample_clamped(0.0), 0.0);
assert_eq!(f.sample_clamped(0.5), 0.5);
assert_eq!(f.sample_clamped(1.0), 1.0);
assert_eq!(f.sample_clamped(2.0), 1.0);
Variants
| Variant | Fields |
|---|---|
Linear | |
QuadraticIn | |
QuadraticOut | |
QuadraticInOut | |
CubicIn | |
CubicOut | |
CubicInOut | |
QuarticIn | |
QuarticOut | |
QuarticInOut | |
QuinticIn | |
QuinticOut | |
QuinticInOut | |
SmoothStepIn | |
SmoothStepOut | |
SmoothStep | |
SmootherStepIn | |
SmootherStepOut | |
SmootherStep | |
SineIn | |
SineOut | |
SineInOut | |
CircularIn | |
CircularOut | |
CircularInOut | |
ExponentialIn | |
ExponentialOut | |
ExponentialInOut | |
ElasticIn | |
ElasticOut | |
ElasticInOut | |
BackIn | |
BackOut | |
BackInOut | |
BounceIn | |
BounceOut | |
BounceInOut | |
Steps | (usize, JumpAt) |
Elastic | (f32) |
Functions
| Name | Summary |
|---|---|
new | Constructs a new instance of the type from a table of its fields. |
new
new(payload: Fields<EaseFunction>) -> EaseFunction
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
Methods
| Name | Summary |
|---|---|
sample | The eased value at t, clamped to between 0 and 1. |
sample
sample(self: EaseFunction, t: f32) -> f32
The eased value at t, clamped to between 0 and 1.
Variant Functions
BackIn.new
new(variant: EnumVariantRef, payload: Fields<EaseFunction::BackIn>) -> EaseFunction
BackInOut.new
new(variant: EnumVariantRef, payload: Fields<EaseFunction::BackInOut>) -> EaseFunction
BackOut.new
new(variant: EnumVariantRef, payload: Fields<EaseFunction::BackOut>) -> EaseFunction
BounceIn.new
new(variant: EnumVariantRef, payload: Fields<EaseFunction::BounceIn>) -> EaseFunction
BounceInOut.new
new(variant: EnumVariantRef, payload: Fields<EaseFunction::BounceInOut>) -> EaseFunction
BounceOut.new
new(variant: EnumVariantRef, payload: Fields<EaseFunction::BounceOut>) -> EaseFunction
CircularIn.new
new(variant: EnumVariantRef, payload: Fields<EaseFunction::CircularIn>) -> EaseFunction
CircularInOut.new
new(variant: EnumVariantRef, payload: Fields<EaseFunction::CircularInOut>) -> EaseFunction
CircularOut.new
new(variant: EnumVariantRef, payload: Fields<EaseFunction::CircularOut>) -> EaseFunction
CubicIn.new
new(variant: EnumVariantRef, payload: Fields<EaseFunction::CubicIn>) -> EaseFunction
CubicInOut.new
new(variant: EnumVariantRef, payload: Fields<EaseFunction::CubicInOut>) -> EaseFunction
CubicOut.new
new(variant: EnumVariantRef, payload: Fields<EaseFunction::CubicOut>) -> EaseFunction
Elastic.new
new(variant: EnumVariantRef, payload: Fields<EaseFunction::Elastic>) -> EaseFunction
ElasticIn.new
new(variant: EnumVariantRef, payload: Fields<EaseFunction::ElasticIn>) -> EaseFunction
ElasticInOut.new
new(variant: EnumVariantRef, payload: Fields<EaseFunction::ElasticInOut>) -> EaseFunction
ElasticOut.new
new(variant: EnumVariantRef, payload: Fields<EaseFunction::ElasticOut>) -> EaseFunction
ExponentialIn.new
new(variant: EnumVariantRef, payload: Fields<EaseFunction::ExponentialIn>) -> EaseFunction
ExponentialInOut.new
new(variant: EnumVariantRef, payload: Fields<EaseFunction::ExponentialInOut>) -> EaseFunction
ExponentialOut.new
new(variant: EnumVariantRef, payload: Fields<EaseFunction::ExponentialOut>) -> EaseFunction
Linear.new
new(variant: EnumVariantRef, payload: Fields<EaseFunction::Linear>) -> EaseFunction
QuadraticIn.new
new(variant: EnumVariantRef, payload: Fields<EaseFunction::QuadraticIn>) -> EaseFunction
QuadraticInOut.new
new(variant: EnumVariantRef, payload: Fields<EaseFunction::QuadraticInOut>) -> EaseFunction
QuadraticOut.new
new(variant: EnumVariantRef, payload: Fields<EaseFunction::QuadraticOut>) -> EaseFunction
QuarticIn.new
new(variant: EnumVariantRef, payload: Fields<EaseFunction::QuarticIn>) -> EaseFunction
QuarticInOut.new
new(variant: EnumVariantRef, payload: Fields<EaseFunction::QuarticInOut>) -> EaseFunction
QuarticOut.new
new(variant: EnumVariantRef, payload: Fields<EaseFunction::QuarticOut>) -> EaseFunction
QuinticIn.new
new(variant: EnumVariantRef, payload: Fields<EaseFunction::QuinticIn>) -> EaseFunction
QuinticInOut.new
new(variant: EnumVariantRef, payload: Fields<EaseFunction::QuinticInOut>) -> EaseFunction
QuinticOut.new
new(variant: EnumVariantRef, payload: Fields<EaseFunction::QuinticOut>) -> EaseFunction
SineIn.new
new(variant: EnumVariantRef, payload: Fields<EaseFunction::SineIn>) -> EaseFunction
SineInOut.new
new(variant: EnumVariantRef, payload: Fields<EaseFunction::SineInOut>) -> EaseFunction
SineOut.new
new(variant: EnumVariantRef, payload: Fields<EaseFunction::SineOut>) -> EaseFunction
SmoothStep.new
new(variant: EnumVariantRef, payload: Fields<EaseFunction::SmoothStep>) -> EaseFunction
SmoothStepIn.new
new(variant: EnumVariantRef, payload: Fields<EaseFunction::SmoothStepIn>) -> EaseFunction
SmoothStepOut.new
new(variant: EnumVariantRef, payload: Fields<EaseFunction::SmoothStepOut>) -> EaseFunction
SmootherStep.new
new(variant: EnumVariantRef, payload: Fields<EaseFunction::SmootherStep>) -> EaseFunction
SmootherStepIn.new
new(variant: EnumVariantRef, payload: Fields<EaseFunction::SmootherStepIn>) -> EaseFunction
SmootherStepOut.new
new(variant: EnumVariantRef, payload: Fields<EaseFunction::SmootherStepOut>) -> EaseFunction
Steps.new
new(variant: EnumVariantRef, payload: Fields<EaseFunction::Steps>) -> EaseFunction
EulerRot
Variants
| Variant |
|---|
ZYX |
ZXY |
YXZ |
YZX |
XYZ |
XZY |
ZYZ |
ZXZ |
YXY |
YZY |
XYX |
XZX |
ZYXEx |
ZXYEx |
YXZEx |
YZXEx |
XYZEx |
XZYEx |
ZYZEx |
ZXZEx |
YXYEx |
YZYEx |
XYXEx |
XZXEx |
Functions
| Name | Summary |
|---|---|
new | Constructs a new instance of the type from a table of its fields. |
new
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
Variant Functions
XYX.new
new(variant: EnumVariantRef, payload: Fields<EulerRot::XYX>) -> EulerRot
XYXEx.new
new(variant: EnumVariantRef, payload: Fields<EulerRot::XYXEx>) -> EulerRot
XYZ.new
new(variant: EnumVariantRef, payload: Fields<EulerRot::XYZ>) -> EulerRot
XYZEx.new
new(variant: EnumVariantRef, payload: Fields<EulerRot::XYZEx>) -> EulerRot
XZX.new
new(variant: EnumVariantRef, payload: Fields<EulerRot::XZX>) -> EulerRot
XZXEx.new
new(variant: EnumVariantRef, payload: Fields<EulerRot::XZXEx>) -> EulerRot
XZY.new
new(variant: EnumVariantRef, payload: Fields<EulerRot::XZY>) -> EulerRot
XZYEx.new
new(variant: EnumVariantRef, payload: Fields<EulerRot::XZYEx>) -> EulerRot
YXY.new
new(variant: EnumVariantRef, payload: Fields<EulerRot::YXY>) -> EulerRot
YXYEx.new
new(variant: EnumVariantRef, payload: Fields<EulerRot::YXYEx>) -> EulerRot
YXZ.new
new(variant: EnumVariantRef, payload: Fields<EulerRot::YXZ>) -> EulerRot
YXZEx.new
new(variant: EnumVariantRef, payload: Fields<EulerRot::YXZEx>) -> EulerRot
YZX.new
new(variant: EnumVariantRef, payload: Fields<EulerRot::YZX>) -> EulerRot
YZXEx.new
new(variant: EnumVariantRef, payload: Fields<EulerRot::YZXEx>) -> EulerRot
YZY.new
new(variant: EnumVariantRef, payload: Fields<EulerRot::YZY>) -> EulerRot
YZYEx.new
new(variant: EnumVariantRef, payload: Fields<EulerRot::YZYEx>) -> EulerRot
ZXY.new
new(variant: EnumVariantRef, payload: Fields<EulerRot::ZXY>) -> EulerRot
ZXYEx.new
new(variant: EnumVariantRef, payload: Fields<EulerRot::ZXYEx>) -> EulerRot
ZXZ.new
new(variant: EnumVariantRef, payload: Fields<EulerRot::ZXZ>) -> EulerRot
ZXZEx.new
new(variant: EnumVariantRef, payload: Fields<EulerRot::ZXZEx>) -> EulerRot
ZYX.new
new(variant: EnumVariantRef, payload: Fields<EulerRot::ZYX>) -> EulerRot
ZYXEx.new
new(variant: EnumVariantRef, payload: Fields<EulerRot::ZYXEx>) -> EulerRot
ZYZ.new
new(variant: EnumVariantRef, payload: Fields<EulerRot::ZYZ>) -> EulerRot
ZYZEx.new
new(variant: EnumVariantRef, payload: Fields<EulerRot::ZYZEx>) -> EulerRot
IVec2
Fields
Functions
| Name | Summary |
|---|---|
new | Creates a new vector. |
one | A vector with all components set to 1. |
splat | A vector with all components set to v. |
unit_x | The unit vector along the x axis. |
unit_y | The unit vector along the y axis. |
zero | A vector with all components set to 0. |
new
Creates a new vector.
one
one() -> IVec2
A vector with all components set to 1.
splat
A vector with all components set to v.
unit_x
unit_x() -> IVec2
The unit vector along the x axis.
unit_y
unit_y() -> IVec2
The unit vector along the y axis.
zero
zero() -> IVec2
A vector with all components set to 0.
Methods
| Name | Summary |
|---|---|
abs | The absolute value of every component. |
as_vec2 | Converts to a float vector. |
clamp | Clamps every component between the components of min and max. |
dot | The dot product of two vectors. |
length_squared | The squared length of the vector. |
max | The larger of each pair of components. |
max_element | The largest component. |
min | The smaller of each pair of components. |
min_element | The smallest component. |
to_array | The components as a list. |
abs
The absolute value of every component.
as_vec2
Converts to a float vector.
clamp
Clamps every component between the components of min and max.
dot
The dot product of two vectors.
length_squared
The squared length of the vector.
max
The larger of each pair of components.
max_element
The largest component.
min
The smaller of each pair of components.
min_element
The smallest component.
to_array
The components as a list.
Operators
| Name | Summary |
|---|---|
add | Adds a vector or a number to every component. |
div | Divides component-wise by a vector, or by a number. Errors if any divisor component is 0. |
eq | Whether all components are equal. |
mul | Multiplies component-wise by a vector, or scales by a number. |
neg | Negates every component. |
rem | The component-wise remainder of dividing by a vector, or by a number. Errors if any divisor component is 0. |
sub | Subtracts a vector or a number from every component. |
add
Adds a vector or a number to every component.
div
Divides component-wise by a vector, or by a number. Errors if any divisor component is 0.
eq
Whether all components are equal.
mul
Multiplies component-wise by a vector, or scales by a number.
neg
Negates every component.
rem
The component-wise remainder of dividing by a vector, or by a number. Errors if any divisor component is 0.
sub
Subtracts a vector or a number from every component.
IVec3
Fields
Functions
| Name | Summary |
|---|---|
new | Creates a new vector. |
one | A vector with all components set to 1. |
splat | A vector with all components set to v. |
unit_x | The unit vector along the x axis. |
unit_y | The unit vector along the y axis. |
unit_z | The unit vector along the z axis. |
zero | A vector with all components set to 0. |
new
Creates a new vector.
one
one() -> IVec3
A vector with all components set to 1.
splat
A vector with all components set to v.
unit_x
unit_x() -> IVec3
The unit vector along the x axis.
unit_y
unit_y() -> IVec3
The unit vector along the y axis.
unit_z
unit_z() -> IVec3
The unit vector along the z axis.
zero
zero() -> IVec3
A vector with all components set to 0.
Methods
| Name | Summary |
|---|---|
abs | The absolute value of every component. |
as_vec3 | Converts to a float vector. |
clamp | Clamps every component between the components of min and max. |
dot | The dot product of two vectors. |
length_squared | The squared length of the vector. |
max | The larger of each pair of components. |
max_element | The largest component. |
min | The smaller of each pair of components. |
min_element | The smallest component. |
to_array | The components as a list. |
abs
The absolute value of every component.
as_vec3
Converts to a float vector.
clamp
Clamps every component between the components of min and max.
dot
The dot product of two vectors.
length_squared
The squared length of the vector.
max
The larger of each pair of components.
max_element
The largest component.
min
The smaller of each pair of components.
min_element
The smallest component.
to_array
The components as a list.
Operators
| Name | Summary |
|---|---|
add | Adds a vector or a number to every component. |
div | Divides component-wise by a vector, or by a number. Errors if any divisor component is 0. |
eq | Whether all components are equal. |
mul | Multiplies component-wise by a vector, or scales by a number. |
neg | Negates every component. |
rem | The component-wise remainder of dividing by a vector, or by a number. Errors if any divisor component is 0. |
sub | Subtracts a vector or a number from every component. |
add
Adds a vector or a number to every component.
div
Divides component-wise by a vector, or by a number. Errors if any divisor component is 0.
eq
Whether all components are equal.
mul
Multiplies component-wise by a vector, or scales by a number.
neg
Negates every component.
rem
The component-wise remainder of dividing by a vector, or by a number. Errors if any divisor component is 0.
sub
Subtracts a vector or a number from every component.
JumpAt
Configuration options for the EaseFunction::Steps curves. This closely replicates the
CSS step function specification.
Variants
| Variant |
|---|
Start |
End |
None |
Both |
Functions
| Name | Summary |
|---|---|
new | Constructs a new instance of the type from a table of its fields. |
new
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
Variant Functions
Both.new
new(variant: EnumVariantRef, payload: Fields<JumpAt::Both>) -> JumpAt
End.new
new(variant: EnumVariantRef, payload: Fields<JumpAt::End>) -> JumpAt
None.new
new(variant: EnumVariantRef, payload: Fields<JumpAt::None>) -> JumpAt
Start.new
new(variant: EnumVariantRef, payload: Fields<JumpAt::Start>) -> JumpAt
Mat2
Fields
Functions
| Name | Summary |
|---|---|
new | Constructs a new instance of the type from a table of its fields. |
new
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
Mat3
Fields
Functions
| Name | Summary |
|---|---|
from_cols | A matrix with the given columns. |
from_diagonal | A matrix with the given diagonal and zeros elsewhere. |
from_quat | The rotation matrix of a rotation. |
from_rotation_x | A rotation matrix of angle radians around the x axis. |
from_rotation_y | A rotation matrix of angle radians around the y axis. |
from_rotation_z | A rotation matrix of angle radians around the z axis. |
identity | The identity matrix, which leaves vectors unchanged. |
new | Constructs a new instance of the type from a table of its fields. |
from_cols
A matrix with the given columns.
from_diagonal
A matrix with the given diagonal and zeros elsewhere.
from_quat
The rotation matrix of a rotation.
from_rotation_x
A rotation matrix of angle radians around the x axis.
from_rotation_y
A rotation matrix of angle radians around the y axis.
from_rotation_z
A rotation matrix of angle radians around the z axis.
identity
identity() -> Mat3
The identity matrix, which leaves vectors unchanged.
new
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
Methods
| Name | Summary |
|---|---|
col | The column at index, starting from 0. Errors if index is out of range. |
determinant | The determinant of the matrix. |
inverse | The matrix that undoes this one. |
mul_vec3 | Transforms a Vec3 by this matrix. |
row | The row at index, starting from 0. Errors if index is out of range. |
transform_point2 | Transforms a point in 2D, treating it as having a z of 1. |
transform_vector2 | Transforms a direction in 2D, ignoring translation. |
transpose | The matrix with rows and columns swapped. |
col
The column at index, starting from 0. Errors if index is out of range.
determinant
The determinant of the matrix.
inverse
The matrix that undoes this one.
mul_vec3
Transforms a Vec3 by this matrix.
row
The row at index, starting from 0. Errors if index is out of range.
transform_point2
Transforms a point in 2D, treating it as having a z of 1.
transform_vector2
Transforms a direction in 2D, ignoring translation.
transpose
The matrix with rows and columns swapped.
Operators
| Name | Summary |
|---|---|
add | Adds two matrices component-wise. |
div | Divides every component by a number. |
eq | Whether both matrices have exactly the same components. |
mul | Multiplies by a matrix, or transforms a vector, or scales every component by a number. |
sub | Subtracts two matrices component-wise. |
add
Adds two matrices component-wise.
div
Divides every component by a number.
eq
Whether both matrices have exactly the same components.
mul
Multiplies by a matrix, or transforms a vector, or scales every component by a number.
sub
Subtracts two matrices component-wise.
Mat3A
Fields
Functions
| Name | Summary |
|---|---|
new | Constructs a new instance of the type from a table of its fields. |
new
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
Mat4
Fields
Functions
| Name | Summary |
|---|---|
from_cols | A matrix with the given columns. |
from_quat | The rotation matrix of a rotation. |
from_rotation_translation | A matrix that rotates by rotation, then moves by translation. |
from_scale | A matrix that scales every axis by the matching component of scale. |
from_scale_rotation_translation | A matrix that scales by scale, then rotates by rotation, then moves by translation. |
from_translation | A matrix that moves points by translation. |
identity | The identity matrix, which leaves vectors unchanged. |
new | Constructs a new instance of the type from a table of its fields. |
from_cols
A matrix with the given columns.
from_quat
The rotation matrix of a rotation.
from_rotation_translation
A matrix that rotates by rotation, then moves by translation.
from_scale
A matrix that scales every axis by the matching component of scale.
from_scale_rotation_translation
A matrix that scales by scale, then rotates by rotation, then moves by translation.
from_translation
A matrix that moves points by translation.
identity
identity() -> Mat4
The identity matrix, which leaves vectors unchanged.
new
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
Methods
| Name | Summary |
|---|---|
col | The column at index, starting from 0. Errors if index is out of range. |
determinant | The determinant of the matrix. |
inverse | The matrix that undoes this one. |
project_point3 | Transforms a point in 3D by a projection matrix, including the perspective divide. |
row | The row at index, starting from 0. Errors if index is out of range. |
transform_point3 | Transforms a point in 3D, including translation and the projection divide. |
transform_vector3 | Transforms a direction in 3D, ignoring translation. |
transpose | The matrix with rows and columns swapped. |
col
The column at index, starting from 0. Errors if index is out of range.
determinant
The determinant of the matrix.
inverse
The matrix that undoes this one.
project_point3
Transforms a point in 3D by a projection matrix, including the perspective divide.
row
The row at index, starting from 0. Errors if index is out of range.
transform_point3
Transforms a point in 3D, including translation and the projection divide.
transform_vector3
Transforms a direction in 3D, ignoring translation.
transpose
The matrix with rows and columns swapped.
Operators
| Name | Summary |
|---|---|
add | Adds two matrices component-wise. |
div | Divides every component by a number. |
eq | Whether both matrices have exactly the same components. |
mul | Multiplies by a matrix, or transforms a vector, or scales every component by a number. |
sub | Subtracts two matrices component-wise. |
add
Adds two matrices component-wise.
div
Divides every component by a number.
eq
Whether both matrices have exactly the same components.
mul
Multiplies by a matrix, or transforms a vector, or scales every component by a number.
sub
Subtracts two matrices component-wise.
Plane3d
A bounded plane in 3D space. It forms a surface starting from the origin with a defined height and width.
Fields
Functions
| Name | Summary |
|---|---|
new | A plane facing normal with the given half size. Errors if the normal is zero or not finite. |
new
A plane facing normal with the given half size. Errors if the normal is zero or not finite.
Quat
Fields
Functions
| Name | Summary |
|---|---|
from_axis_angle | A rotation of angle radians around axis. Errors if the axis is zero or not finite. |
from_euler | A rotation from three angles in radians, applied in the given EulerRot order, i.e. EulerRot.YXZ. |
from_mat3 | The rotation described by a 3x3 rotation matrix. |
from_rotation_arc | The rotation that turns the direction from onto the direction to. Errors if either vector is zero or not finite. |
from_rotation_x | A rotation of angle radians around the x axis. |
from_rotation_y | A rotation of angle radians around the y axis. |
from_rotation_z | A rotation of angle radians around the z axis. |
identity | The identity rotation, which leaves everything unchanged. |
new | Constructs a new instance of the type from a table of its fields. |
from_axis_angle
A rotation of angle radians around axis. Errors if the axis is zero or not finite.
from_euler
A rotation from three angles in radians, applied in the given EulerRot order, i.e. EulerRot.YXZ.
from_mat3
The rotation described by a 3x3 rotation matrix.
from_rotation_arc
The rotation that turns the direction from onto the direction to. Errors if either vector is zero or not finite.
from_rotation_x
A rotation of angle radians around the x axis.
from_rotation_y
A rotation of angle radians around the y axis.
from_rotation_z
A rotation of angle radians around the z axis.
identity
identity() -> Quat
The identity rotation, which leaves everything unchanged.
new
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
Methods
| Name | Summary |
|---|---|
angle | The angle in radians this rotation turns by around its axis. |
angle_between | The angle in radians between two rotations. |
axis | The axis this rotation turns around. |
conjugate | The rotation with the vector part negated, which is the inverse for unit quaternions. |
dot | The dot product of two rotations. |
inverse | The rotation that undoes this one. |
is_normalized | Whether the quaternion has a length of 1. |
length | The length of the quaternion, which is 1 for a rotation. |
lerp | Linearly interpolates towards other, t = 0 gives this rotation and t = 1 gives other. |
mul_vec3 | Rotates a Vec3. |
normalize | The rotation scaled to a length of 1. |
slerp | Spherically interpolates towards other, t = 0 gives this rotation and t = 1 gives other. |
to_euler | The three angles in radians of this rotation, in the given EulerRot order. |
xyz | The vector part of the quaternion, i.e. the x, y and z components. |
angle
The angle in radians this rotation turns by around its axis.
angle_between
The angle in radians between two rotations.
axis
The axis this rotation turns around.
conjugate
The rotation with the vector part negated, which is the inverse for unit quaternions.
dot
The dot product of two rotations.
inverse
The rotation that undoes this one.
is_normalized
Whether the quaternion has a length of 1.
length
The length of the quaternion, which is 1 for a rotation.
lerp
Linearly interpolates towards other, t = 0 gives this rotation and t = 1 gives other.
mul_vec3
Rotates a Vec3.
normalize
The rotation scaled to a length of 1.
slerp
Spherically interpolates towards other, t = 0 gives this rotation and t = 1 gives other.
to_euler
The three angles in radians of this rotation, in the given EulerRot order.
xyz
The vector part of the quaternion, i.e. the x, y and z components.
Operators
| Name | Summary |
|---|---|
eq | Whether both rotations have exactly the same components. |
mul | Composes two rotations when given a rotation, or rotates a vector when given a Vec3. |
neg | The opposite rotation, with every component negated. |
eq
Whether both rotations have exactly the same components.
mul
Composes two rotations when given a rotation, or rotates a vector when given a Vec3.
neg
The opposite rotation, with every component negated.
Ray2d
An infinite half-line starting at origin and going in direction in 2D space.
Fields
Functions
| Name | Summary |
|---|---|
new | A ray from origin in the direction of direction. Errors if the direction is zero or not finite. |
new
A ray from origin in the direction of direction. Errors if the direction is zero or not finite.
Methods
| Name | Summary |
|---|---|
get_point | The point at distance along the ray from its origin. |
intersect_plane | The distance along the ray to the line through plane_origin with normal plane_normal, or nil if the ray never… |
get_point
The point at distance along the ray from its origin.
intersect_plane
The distance along the ray to the line through plane_origin with normal plane_normal, or nil if the ray never reaches it. Errors if the normal is zero or not finite.
Ray3d
An infinite half-line starting at origin and going in direction in 3D space.
Fields
Functions
| Name | Summary |
|---|---|
new | A ray from origin in the direction of direction. Errors if the direction is zero or not finite. |
new
A ray from origin in the direction of direction. Errors if the direction is zero or not finite.
Methods
| Name | Summary |
|---|---|
get_point | The point at distance along the ray from its origin. |
intersect_plane | The distance along the ray to the plane through plane_origin with normal plane_normal, or nil if the ray never… |
get_point
The point at distance along the ray from its origin.
intersect_plane
The distance along the ray to the plane through plane_origin with normal plane_normal, or nil if the ray never reaches it. Errors if the normal is zero or not finite.
Rect
A rectangle defined by two opposite corners.
The rectangle is axis aligned, and defined by its minimum and maximum coordinates,
stored in Rect::min and Rect::max, respectively. The minimum/maximum invariant
must be upheld by the user when directly assigning the fields, otherwise some methods
produce invalid results. It is generally recommended to use one of the constructor
methods instead, which will ensure this invariant is met, unless you already have
the minimum and maximum corners.
Fields
Functions
| Name | Summary |
|---|---|
from_center_half_size | A rectangle with the given center and half of its full size. |
from_center_size | A rectangle with the given center and full size. |
from_corners | A rectangle spanning the two given corners, in either order. |
new | A rectangle from its minimum corner (x0, y0) and maximum corner (x1, y1). |
from_center_half_size
A rectangle with the given center and half of its full size.
from_center_size
A rectangle with the given center and full size.
from_corners
A rectangle spanning the two given corners, in either order.
new
A rectangle from its minimum corner (x0, y0) and maximum corner (x1, y1).
Methods
| Name | Summary |
|---|---|
center | The center of the rectangle as a Vec2. |
contains | Whether the point lies inside the rectangle, including its edges. |
half_size | Half of the full size of the rectangle as a Vec2. |
height | The height of the rectangle. |
inflate | This rectangle grown by expansion on every side, or shrunk if it is negative. |
intersect | The overlap of this rectangle and other, which is empty if they do not overlap. |
is_empty | Whether the rectangle has no area. |
size | The full size of the rectangle as a Vec2. |
union | The smallest rectangle that contains both this one and other. |
width | The width of the rectangle. |
center
The center of the rectangle as a Vec2.
contains
Whether the point lies inside the rectangle, including its edges.
half_size
Half of the full size of the rectangle as a Vec2.
height
The height of the rectangle.
inflate
This rectangle grown by expansion on every side, or shrunk if it is negative.
intersect
The overlap of this rectangle and other, which is empty if they do not overlap.
is_empty
Whether the rectangle has no area.
size
The full size of the rectangle as a Vec2.
union
The smallest rectangle that contains both this one and other.
width
The width of the rectangle.
Operators
| Name | Summary |
|---|---|
eq | Whether both rectangles have exactly the same corners. |
eq
Whether both rectangles have exactly the same corners.
Rectangle
A rectangle primitive, which is like a square, except that the width and height can be different
Fields
| Field | Type |
|---|---|
half_size | Vec2 |
Functions
| Name | Summary |
|---|---|
from_size | A rectangle with the given size as a Vec2. |
new | A rectangle with the given width and height. |
from_size
A rectangle with the given size as a Vec2.
new
A rectangle with the given width and height.
RegularPolygon
A polygon centered on the origin where all vertices lie on a circle, equally far apart.
Fields
Functions
| Name | Summary |
|---|---|
new | A regular polygon with the given number of sides, all corners at circumradius from the center. |
new
new(circumradius: f32, sides: u32) -> RegularPolygon
A regular polygon with the given number of sides, all corners at circumradius from the center.
Rot2
A 2D rotation.
Example
use std::f32::consts::PI;
// Create rotations from counterclockwise angles in radians or degrees
let rotation1 = Rot2::radians(PI / 2.0);
let rotation2 = Rot2::degrees(45.0);
// Get the angle back as radians or degrees
assert_eq!(rotation1.as_degrees(), 90.0);
assert_eq!(rotation2.as_radians(), PI / 4.0);
// "Add" rotations together using `*`
#[cfg(feature = "approx")]
assert_relative_eq!(rotation1 * rotation2, Rot2::degrees(135.0));
// Rotate vectors
#[cfg(feature = "approx")]
assert_relative_eq!(rotation1 * Vec2::X, Vec2::Y);
Fields
Functions
| Name | Summary |
|---|---|
degrees | A counterclockwise rotation of degrees degrees. |
identity | The rotation that leaves everything unchanged. |
new | Constructs a new instance of the type from a table of its fields. |
radians | A counterclockwise rotation of radians radians. |
turn_fraction | A counterclockwise rotation of fraction of a full turn, so 1.0 is a full turn. |
degrees
A counterclockwise rotation of degrees degrees.
identity
identity() -> Rot2
The rotation that leaves everything unchanged.
new
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
radians
A counterclockwise rotation of radians radians.
turn_fraction
A counterclockwise rotation of fraction of a full turn, so 1.0 is a full turn.
Methods
| Name | Summary |
|---|---|
as_degrees | The angle of this rotation in degrees. |
as_radians | The angle of this rotation in radians. |
inverse | The rotation that undoes this one. |
nlerp | Linearly interpolates between this rotation and other by t, from 0 to 1, then normalizes. |
slerp | Spherically interpolates between this rotation and other by t, from 0 to 1. |
as_degrees
The angle of this rotation in degrees.
as_radians
The angle of this rotation in radians.
inverse
The rotation that undoes this one.
nlerp
Linearly interpolates between this rotation and other by t, from 0 to 1, then normalizes.
slerp
Spherically interpolates between this rotation and other by t, from 0 to 1.
Operators
| Name | Summary |
|---|---|
eq | Whether both rotations have exactly the same components. |
mul | Composes two rotations when given a rotation, or rotates a Vec2 when given a vector. |
eq
Whether both rotations have exactly the same components.
mul
Composes two rotations when given a rotation, or rotates a Vec2 when given a vector.
Sphere
A sphere primitive, representing the set of all points some distance from the origin
Fields
| Field | Type |
|---|---|
radius | f32 |
Functions
| Name | Summary |
|---|---|
new | A sphere with the given radius. |
new
A sphere with the given radius.
Torus
A torus primitive, often representing a ring or donut shape The set of points some distance from a circle centered at the origin
Fields
Functions
| Name | Summary |
|---|---|
new | A donut shape with the given inner and outer radii of its tube. |
new
A donut shape with the given inner and outer radii of its tube.
Triangle2d
A triangle in 2D space
Fields
| Field | Type |
|---|---|
vertices | [Vec2; 3] |
Functions
| Name | Summary |
|---|---|
new | Constructs a new instance of the type from a table of its fields. |
new
new(payload: Fields<Triangle2d>) -> Triangle2d
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
URect
A rectangle defined by two opposite corners.
The rectangle is axis aligned, and defined by its minimum and maximum coordinates,
stored in URect::min and URect::max, respectively. The minimum/maximum invariant
must be upheld by the user when directly assigning the fields, otherwise some methods
produce invalid results. It is generally recommended to use one of the constructor
methods instead, which will ensure this invariant is met, unless you already have
the minimum and maximum corners.
Fields
Functions
| Name | Summary |
|---|---|
new | Constructs a new instance of the type from a table of its fields. |
new
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
UVec2
Fields
Functions
| Name | Summary |
|---|---|
new | Creates a new vector. |
one | A vector with all components set to 1. |
splat | A vector with all components set to v. |
unit_x | The unit vector along the x axis. |
unit_y | The unit vector along the y axis. |
zero | A vector with all components set to 0. |
new
Creates a new vector.
one
one() -> UVec2
A vector with all components set to 1.
splat
A vector with all components set to v.
unit_x
unit_x() -> UVec2
The unit vector along the x axis.
unit_y
unit_y() -> UVec2
The unit vector along the y axis.
zero
zero() -> UVec2
A vector with all components set to 0.
Methods
| Name | Summary |
|---|---|
as_vec2 | Converts to a float vector. |
clamp | Clamps every component between the components of min and max. |
dot | The dot product of two vectors. |
length_squared | The squared length of the vector. |
max | The larger of each pair of components. |
max_element | The largest component. |
min | The smaller of each pair of components. |
min_element | The smallest component. |
to_array | The components as a list. |
as_vec2
Converts to a float vector.
clamp
Clamps every component between the components of min and max.
dot
The dot product of two vectors.
length_squared
The squared length of the vector.
max
The larger of each pair of components.
max_element
The largest component.
min
The smaller of each pair of components.
min_element
The smallest component.
to_array
The components as a list.
Operators
| Name | Summary |
|---|---|
add | Adds a vector or a number to every component. |
div | Divides component-wise by a vector, or by a number. Errors if any divisor component is 0. |
eq | Whether all components are equal. |
mul | Multiplies component-wise by a vector, or scales by a number. |
rem | The component-wise remainder of dividing by a vector, or by a number. Errors if any divisor component is 0. |
sub | Subtracts a vector or a number from every component. |
add
Adds a vector or a number to every component.
div
Divides component-wise by a vector, or by a number. Errors if any divisor component is 0.
eq
Whether all components are equal.
mul
Multiplies component-wise by a vector, or scales by a number.
rem
The component-wise remainder of dividing by a vector, or by a number. Errors if any divisor component is 0.
sub
Subtracts a vector or a number from every component.
UVec3
Fields
Functions
| Name | Summary |
|---|---|
new | Creates a new vector. |
one | A vector with all components set to 1. |
splat | A vector with all components set to v. |
unit_x | The unit vector along the x axis. |
unit_y | The unit vector along the y axis. |
unit_z | The unit vector along the z axis. |
zero | A vector with all components set to 0. |
new
Creates a new vector.
one
one() -> UVec3
A vector with all components set to 1.
splat
A vector with all components set to v.
unit_x
unit_x() -> UVec3
The unit vector along the x axis.
unit_y
unit_y() -> UVec3
The unit vector along the y axis.
unit_z
unit_z() -> UVec3
The unit vector along the z axis.
zero
zero() -> UVec3
A vector with all components set to 0.
Methods
| Name | Summary |
|---|---|
as_vec3 | Converts to a float vector. |
clamp | Clamps every component between the components of min and max. |
dot | The dot product of two vectors. |
length_squared | The squared length of the vector. |
max | The larger of each pair of components. |
max_element | The largest component. |
min | The smaller of each pair of components. |
min_element | The smallest component. |
to_array | The components as a list. |
as_vec3
Converts to a float vector.
clamp
Clamps every component between the components of min and max.
dot
The dot product of two vectors.
length_squared
The squared length of the vector.
max
The larger of each pair of components.
max_element
The largest component.
min
The smaller of each pair of components.
min_element
The smallest component.
to_array
The components as a list.
Operators
| Name | Summary |
|---|---|
add | Adds a vector or a number to every component. |
div | Divides component-wise by a vector, or by a number. Errors if any divisor component is 0. |
eq | Whether all components are equal. |
mul | Multiplies component-wise by a vector, or scales by a number. |
rem | The component-wise remainder of dividing by a vector, or by a number. Errors if any divisor component is 0. |
sub | Subtracts a vector or a number from every component. |
add
Adds a vector or a number to every component.
div
Divides component-wise by a vector, or by a number. Errors if any divisor component is 0.
eq
Whether all components are equal.
mul
Multiplies component-wise by a vector, or scales by a number.
rem
The component-wise remainder of dividing by a vector, or by a number. Errors if any divisor component is 0.
sub
Subtracts a vector or a number from every component.
Vec2
Fields
Functions
| Name | Summary |
|---|---|
from_angle | The unit vector of the given angle in radians, measured counterclockwise from the x axis. |
new | Creates a new vector. |
one | A vector with all components set to 1. |
splat | A vector with all components set to v. |
unit_x | The unit vector along the x axis. |
unit_y | The unit vector along the y axis. |
zero | A vector with all components set to 0. |
from_angle
The unit vector of the given angle in radians, measured counterclockwise from the x axis.
new
Creates a new vector.
local Vec2 = import_namespace("math").Vec2
local v = Vec2.new(3, 4)
assert(v:length() == 5)
let Vec2 = import_namespace("math").Vec2;
let v = Vec2.new(3.0, 4.0);
assert!(v.length() == 5.0);
one
one() -> Vec2
A vector with all components set to 1.
splat
A vector with all components set to v.
unit_x
unit_x() -> Vec2
The unit vector along the x axis.
unit_y
unit_y() -> Vec2
The unit vector along the y axis.
zero
zero() -> Vec2
A vector with all components set to 0.
Methods
| Name | Summary |
|---|---|
abs | The absolute value of every component. |
angle_to | The signed angle in radians to rotate this vector onto other. |
as_dvec2 | Converts to a double precision vector. |
as_ivec2 | Converts to an integer vector, rounding towards zero. |
as_uvec2 | Converts to an unsigned integer vector, rounding towards zero, negative values become 0. |
ceil | Rounds every component up. |
clamp | Clamps every component between the components of min and max. |
clamp_length | Scales the vector so that its length is between min and max. |
clamp_length_max | Scales the vector down so that its length is at most max. |
distance | The distance between two points. |
distance_squared | The squared distance between two points. |
dot | The dot product of two vectors. |
extend | A Vec3 with the given z. |
floor | Rounds every component down. |
fract | The fractional part of every component, i.e. x - floor(x). |
length | The length of the vector. |
length_squared | The squared length of the vector, faster than length when comparing lengths. |
lerp | Linearly interpolates towards other, t = 0 gives this vector and t = 1 gives other. |
max | The larger of each pair of components. |
max_element | The largest component. |
min | The smaller of each pair of components. |
min_element | The smallest component. |
move_towards | Moves towards target by at most max_distance, without overshooting. |
normalize | The vector scaled to a length of 1. Errors if the vector is zero, or not finite. |
normalize_or_zero | The vector scaled to a length of 1, or zero if that’s not possible. |
perp | The vector rotated by 90 degrees counterclockwise. |
perp_dot | The 2D cross product, positive if other is counterclockwise from this vector. |
project_onto | The projection of this vector onto other. |
rdiv | Divides a number by every component, for n / v. |
reflect | Reflects this vector off a surface with the given normal, which must be of length 1. |
reject_from | The part of this vector perpendicular to other. |
rotate | Rotates other by the angle of this vector, and scales it by its length. |
round | Rounds every component to the nearest integer. |
rsub | Subtracts every component from a number, for n - v. |
signum | The sign of every component: 1, -1, or NaN. |
to_angle | The angle of this vector in radians, measured counterclockwise from the x axis. |
to_array | The components as a list. |
try_normalize | The vector scaled to a length of 1, or nil if that’s not possible. |
abs
The absolute value of every component.
angle_to
The signed angle in radians to rotate this vector onto other.
as_dvec2
Converts to a double precision vector.
as_ivec2
Converts to an integer vector, rounding towards zero.
as_uvec2
Converts to an unsigned integer vector, rounding towards zero, negative values become 0.
ceil
Rounds every component up.
clamp
Clamps every component between the components of min and max.
clamp_length
Scales the vector so that its length is between min and max.
clamp_length_max
Scales the vector down so that its length is at most max.
distance
The distance between two points.
distance_squared
The squared distance between two points.
dot
The dot product of two vectors.
extend
A Vec3 with the given z.
floor
Rounds every component down.
fract
The fractional part of every component, i.e. x - floor(x).
length
The length of the vector.
length_squared
The squared length of the vector, faster than length when comparing lengths.
lerp
Linearly interpolates towards other, t = 0 gives this vector and t = 1 gives other.
max
The larger of each pair of components.
max_element
The largest component.
min
The smaller of each pair of components.
min_element
The smallest component.
move_towards
Moves towards target by at most max_distance, without overshooting.
normalize
The vector scaled to a length of 1. Errors if the vector is zero, or not finite.
normalize_or_zero
The vector scaled to a length of 1, or zero if that’s not possible.
perp
The vector rotated by 90 degrees counterclockwise.
perp_dot
The 2D cross product, positive if other is counterclockwise from this vector.
project_onto
The projection of this vector onto other.
rdiv
Divides a number by every component, for n / v.
reflect
Reflects this vector off a surface with the given normal, which must be of length 1.
reject_from
The part of this vector perpendicular to other.
rotate
Rotates other by the angle of this vector, and scales it by its length.
round
Rounds every component to the nearest integer.
rsub
Subtracts every component from a number, for n - v.
signum
The sign of every component: 1, -1, or NaN.
to_angle
The angle of this vector in radians, measured counterclockwise from the x axis.
to_array
The components as a list.
try_normalize
The vector scaled to a length of 1, or nil if that’s not possible.
Operators
| Name | Summary |
|---|---|
add | Adds a vector or a number to every component. |
div | Divides component-wise by a vector, or by a number. |
eq | Whether all components are equal. |
mul | Multiplies component-wise by a vector, or scales by a number. |
neg | Negates every component. |
rem | The component-wise remainder of dividing by a vector, or by a number. |
sub | Subtracts a vector or a number from every component. |
add
Adds a vector or a number to every component.
div
Divides component-wise by a vector, or by a number.
eq
Whether all components are equal.
mul
Multiplies component-wise by a vector, or scales by a number.
neg
Negates every component.
rem
The component-wise remainder of dividing by a vector, or by a number.
sub
Subtracts a vector or a number from every component.
Vec3
Fields
Functions
| Name | Summary |
|---|---|
new | Creates a new vector. |
one | A vector with all components set to 1. |
splat | A vector with all components set to v. |
unit_x | The unit vector along the x axis. |
unit_y | The unit vector along the y axis, which is up in bevy. |
unit_z | The unit vector along the z axis. |
zero | A vector with all components set to 0. |
new
Creates a new vector.
local Vec3 = import_namespace("math").Vec3
local v = Vec3.new(1, 2, 3)
assert(v + v == Vec3.new(2, 4, 6))
let Vec3 = import_namespace("math").Vec3;
let v = Vec3.new(1.0, 2.0, 3.0);
assert!(v + v == Vec3.new(2.0, 4.0, 6.0));
one
one() -> Vec3
A vector with all components set to 1.
splat
A vector with all components set to v.
unit_x
unit_x() -> Vec3
The unit vector along the x axis.
unit_y
unit_y() -> Vec3
The unit vector along the y axis, which is up in bevy.
unit_z
unit_z() -> Vec3
The unit vector along the z axis.
zero
zero() -> Vec3
A vector with all components set to 0.
Methods
| Name | Summary |
|---|---|
abs | The absolute value of every component. |
angle_between | The angle in radians between two vectors, between 0 and pi. |
any_orthogonal_vector | Some vector perpendicular to this one. |
as_dvec3 | Converts to a double precision vector. |
as_ivec3 | Converts to an integer vector, rounding towards zero. |
as_uvec3 | Converts to an unsigned integer vector, rounding towards zero, negative values become 0. |
ceil | Rounds every component up. |
clamp | Clamps every component between the components of min and max. |
clamp_length | Scales the vector so that its length is between min and max. |
clamp_length_max | Scales the vector down so that its length is at most max. |
cross | The cross product, perpendicular to both vectors. |
distance | The distance between two points. |
distance_squared | The squared distance between two points. |
dot | The dot product of two vectors. |
extend | A Vec4 with the given w. |
floor | Rounds every component down. |
fract | The fractional part of every component, i.e. x - floor(x). |
length | The length of the vector. |
length_squared | The squared length of the vector, faster than length when comparing lengths. |
lerp | Linearly interpolates towards other, t = 0 gives this vector and t = 1 gives other. |
max | The larger of each pair of components. |
max_element | The largest component. |
min | The smaller of each pair of components. |
min_element | The smallest component. |
move_towards | Moves towards target by at most max_distance, without overshooting. |
normalize | The vector scaled to a length of 1. Errors if the vector is zero, or not finite. |
normalize_or_zero | The vector scaled to a length of 1, or zero if that’s not possible. |
project_onto | The projection of this vector onto other. |
rdiv | Divides a number by every component, for n / v. |
reflect | Reflects this vector off a surface with the given normal, which must be of length 1. |
reject_from | The part of this vector perpendicular to other. |
round | Rounds every component to the nearest integer. |
rsub | Subtracts every component from a number, for n - v. |
signum | The sign of every component: 1, -1, or NaN. |
to_array | The components as a list. |
to_vec3a | Converts to a Vec3A, used by some bevy types such as bounding boxes. |
truncate | A Vec2 of the x and y components. |
try_normalize | The vector scaled to a length of 1, or nil if that’s not possible. |
abs
The absolute value of every component.
angle_between
The angle in radians between two vectors, between 0 and pi.
any_orthogonal_vector
Some vector perpendicular to this one.
as_dvec3
Converts to a double precision vector.
as_ivec3
Converts to an integer vector, rounding towards zero.
as_uvec3
Converts to an unsigned integer vector, rounding towards zero, negative values become 0.
ceil
Rounds every component up.
clamp
Clamps every component between the components of min and max.
clamp_length
Scales the vector so that its length is between min and max.
clamp_length_max
Scales the vector down so that its length is at most max.
cross
The cross product, perpendicular to both vectors.
distance
The distance between two points.
distance_squared
The squared distance between two points.
dot
The dot product of two vectors.
extend
A Vec4 with the given w.
floor
Rounds every component down.
fract
The fractional part of every component, i.e. x - floor(x).
length
The length of the vector.
length_squared
The squared length of the vector, faster than length when comparing lengths.
lerp
Linearly interpolates towards other, t = 0 gives this vector and t = 1 gives other.
max
The larger of each pair of components.
max_element
The largest component.
min
The smaller of each pair of components.
min_element
The smallest component.
move_towards
Moves towards target by at most max_distance, without overshooting.
normalize
The vector scaled to a length of 1. Errors if the vector is zero, or not finite.
normalize_or_zero
The vector scaled to a length of 1, or zero if that’s not possible.
project_onto
The projection of this vector onto other.
rdiv
Divides a number by every component, for n / v.
reflect
Reflects this vector off a surface with the given normal, which must be of length 1.
reject_from
The part of this vector perpendicular to other.
round
Rounds every component to the nearest integer.
rsub
Subtracts every component from a number, for n - v.
signum
The sign of every component: 1, -1, or NaN.
to_array
The components as a list.
to_vec3a
Converts to a Vec3A, used by some bevy types such as bounding boxes.
truncate
A Vec2 of the x and y components.
try_normalize
The vector scaled to a length of 1, or nil if that’s not possible.
Operators
| Name | Summary |
|---|---|
add | Adds a vector or a number to every component. |
div | Divides component-wise by a vector, or by a number. |
eq | Whether all components are equal. |
mul | Multiplies component-wise by a vector, or scales by a number. |
neg | Negates every component. |
rem | The component-wise remainder of dividing by a vector, or by a number. |
sub | Subtracts a vector or a number from every component. |
add
Adds a vector or a number to every component.
div
Divides component-wise by a vector, or by a number.
eq
Whether all components are equal.
mul
Multiplies component-wise by a vector, or scales by a number.
neg
Negates every component.
rem
The component-wise remainder of dividing by a vector, or by a number.
sub
Subtracts a vector or a number from every component.
Vec3A
Fields
Functions
| Name | Summary |
|---|---|
new | Creates a new vector. |
new
Creates a new vector.
Methods
| Name | Summary |
|---|---|
to_vec3 | Converts to a Vec3. |
to_vec3
Converts to a Vec3.
Vec4
Fields
Functions
| Name | Summary |
|---|---|
new | Creates a new vector. |
one | A vector with all components set to 1. |
splat | A vector with all components set to v. |
zero | A vector with all components set to 0. |
new
Creates a new vector.
one
one() -> Vec4
A vector with all components set to 1.
splat
A vector with all components set to v.
zero
zero() -> Vec4
A vector with all components set to 0.
Methods
| Name | Summary |
|---|---|
abs | The absolute value of every component. |
ceil | Rounds every component up. |
clamp | Clamps every component between the components of min and max. |
clamp_length | Scales the vector so that its length is between min and max. |
clamp_length_max | Scales the vector down so that its length is at most max. |
distance | The distance between two points. |
distance_squared | The squared distance between two points. |
dot | The dot product of two vectors. |
floor | Rounds every component down. |
fract | The fractional part of every component, i.e. x - floor(x). |
length | The length of the vector. |
length_squared | The squared length of the vector, faster than length when comparing lengths. |
lerp | Linearly interpolates towards other, t = 0 gives this vector and t = 1 gives other. |
max | The larger of each pair of components. |
max_element | The largest component. |
min | The smaller of each pair of components. |
min_element | The smallest component. |
move_towards | Moves towards target by at most max_distance, without overshooting. |
normalize | The vector scaled to a length of 1. Errors if the vector is zero, or not finite. |
normalize_or_zero | The vector scaled to a length of 1, or zero if that’s not possible. |
project_onto | The projection of this vector onto other. |
rdiv | Divides a number by every component, for n / v. |
reflect | Reflects this vector off a surface with the given normal, which must be of length 1. |
reject_from | The part of this vector perpendicular to other. |
round | Rounds every component to the nearest integer. |
rsub | Subtracts every component from a number, for n - v. |
signum | The sign of every component: 1, -1, or NaN. |
to_array | The components as a list. |
truncate | A Vec3 of the x, y and z components. |
try_normalize | The vector scaled to a length of 1, or nil if that’s not possible. |
abs
The absolute value of every component.
ceil
Rounds every component up.
clamp
Clamps every component between the components of min and max.
clamp_length
Scales the vector so that its length is between min and max.
clamp_length_max
Scales the vector down so that its length is at most max.
distance
The distance between two points.
distance_squared
The squared distance between two points.
dot
The dot product of two vectors.
floor
Rounds every component down.
fract
The fractional part of every component, i.e. x - floor(x).
length
The length of the vector.
length_squared
The squared length of the vector, faster than length when comparing lengths.
lerp
Linearly interpolates towards other, t = 0 gives this vector and t = 1 gives other.
max
The larger of each pair of components.
max_element
The largest component.
min
The smaller of each pair of components.
min_element
The smallest component.
move_towards
Moves towards target by at most max_distance, without overshooting.
normalize
The vector scaled to a length of 1. Errors if the vector is zero, or not finite.
normalize_or_zero
The vector scaled to a length of 1, or zero if that’s not possible.
project_onto
The projection of this vector onto other.
rdiv
Divides a number by every component, for n / v.
reflect
Reflects this vector off a surface with the given normal, which must be of length 1.
reject_from
The part of this vector perpendicular to other.
round
Rounds every component to the nearest integer.
rsub
Subtracts every component from a number, for n - v.
signum
The sign of every component: 1, -1, or NaN.
to_array
The components as a list.
truncate
A Vec3 of the x, y and z components.
try_normalize
The vector scaled to a length of 1, or nil if that’s not possible.
Operators
| Name | Summary |
|---|---|
add | Adds a vector or a number to every component. |
div | Divides component-wise by a vector, or by a number. |
eq | Whether all components are equal. |
mul | Multiplies component-wise by a vector, or scales by a number. |
neg | Negates every component. |
rem | The component-wise remainder of dividing by a vector, or by a number. |
sub | Subtracts a vector or a number from every component. |
add
Adds a vector or a number to every component.
div
Divides component-wise by a vector, or by a number.
eq
Whether all components are equal.
mul
Multiplies component-wise by a vector, or scales by a number.
neg
Negates every component.
rem
The component-wise remainder of dividing by a vector, or by a number.
sub
Subtracts a vector or a number from every component.
petgraph
The types and functions in the petgraph namespace, as returned by import_namespace("petgraph").
Types
| Type | Summary |
|---|---|
DiGraph<Unknown, Unknown, u32> |
DiGraph<Unknown, Unknown, u32>
Opaque: scripts can't access its fields, only its functions.
Functions
| Name | Summary |
|---|---|
new | Constructs a new instance of the type from a table of its fields. |
new
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
render
The types and functions in the render namespace, as returned by import_namespace("render").
Types
| Type | Summary |
|---|---|
AlphaMode | Sets how a material’s base color alpha channel is used for transparency. |
Image | An image, optimized for usage in rendering. |
Indices | An array of indices into the VertexAttributeValues for a mesh. |
JointAabb | |
JointIndex | |
Mesh | A 3D object made out of vertices representing triangles, lines, or points, with “attribute” values for each vertex. |
MeshAttributeCompressionFlags | If the corresponding attribute compression is enabled: - Position will be Snorm16x4 relative to the mesh’s AABB. |
MeshExtractableData<Indices> | |
MeshExtractableData<Unknown> | |
MeshExtractableData<Unknown> | |
MorphAttributes | Attributes differences used for morph targets. |
NoBackgroundMotionVectors | When added to a camera with MotionVectorPrepass, disables the automatic background motion vector prepass. |
OpaqueRendererMethod | Render method used for opaque materials. |
ParallaxMappingMethod | The parallax mapping method to use to compute depth based on the material’s depth_map. |
ReadbackOnce | Marker component that pairs with a Readback to indicate the entity should be despawned after the first… |
Screenshot | A component that signals to the renderer to capture a screenshot this frame. |
ScreenshotCaptured | |
ShaderBuffer | A storage buffer that is prepared as a RenderAsset and uploaded to the GPU. |
SkinnedMeshBounds | Data that can be used to calculate the AABB of a skinned mesh. |
SkinnedMeshInverseBindposes | Not reflected: scripts can only pass values of it around. |
StandardMaterial | A material with “standard” properties used in PBR lighting. |
TextureAtlas | An index into a TextureAtlasLayout, which corresponds to a specific section of a texture. |
UvChannel | An enum to define which UV attribute to use for a texture. |
AlphaMode
Sets how a material’s base color alpha channel is used for transparency.
Variants
| Variant | Fields |
|---|---|
Opaque | |
Mask | (f32) |
Blend | |
Premultiplied | |
AlphaToCoverage | |
Add | |
Multiply |
Functions
| Name | Summary |
|---|---|
new | Constructs a new instance of the type from a table of its fields. |
new
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
Variant Functions
| Name | Summary |
|---|---|
Add.new | |
AlphaToCoverage.new | |
Blend.new | |
Mask.new | |
Multiply.new | |
Opaque.new | |
Premultiplied.new |
Add.new
new(variant: EnumVariantRef, payload: Fields<AlphaMode::Add>) -> AlphaMode
AlphaToCoverage.new
new(variant: EnumVariantRef, payload: Fields<AlphaMode::AlphaToCoverage>) -> AlphaMode
Blend.new
new(variant: EnumVariantRef, payload: Fields<AlphaMode::Blend>) -> AlphaMode
Mask.new
new(variant: EnumVariantRef, payload: Fields<AlphaMode::Mask>) -> AlphaMode
Multiply.new
new(variant: EnumVariantRef, payload: Fields<AlphaMode::Multiply>) -> AlphaMode
Opaque.new
new(variant: EnumVariantRef, payload: Fields<AlphaMode::Opaque>) -> AlphaMode
Premultiplied.new
new(variant: EnumVariantRef, payload: Fields<AlphaMode::Premultiplied>) -> AlphaMode
Image
Asset
An image, optimized for usage in rendering.
Remote Inspection
To transmit an Image between two running Bevy apps, e.g. through BRP, use
SerializedImage, which requires the serialize feature.
This type is only meant for short-term transmission between same versions and should not be stored anywhere.
Opaque: scripts can't access its fields, only its functions.
Functions
| Name | Summary |
|---|---|
add_asset | Adds a value of this type as a new asset, returning a strong handle to it. |
get_asset | The asset a handle points to, or nil if it isn’t loaded or added yet. |
load | Starts loading an asset of this type from a path, returning a handle to it right away. |
new | Constructs a new instance of the type from a table of its fields. |
add_asset
Adds a value of this type as a new asset, returning a strong handle to it.
Arguments
value: The asset value.
Returns: A handle to the new asset.
get_asset
The asset a handle points to, or nil if it isn’t loaded or added yet.
Changes to the returned value change the asset.
Arguments
handle: The handle to the asset.
Returns: The asset, or nil.
load
Starts loading an asset of this type from a path, returning a handle to it right away.
Arguments
path: The asset path, relative to the assets folder.
Returns: A handle to the asset, which is loaded in the background.
new
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
Methods
| Name | Summary |
|---|---|
height | The height of the image in pixels. |
size | The size of the image in pixels. |
size_f32 | The size of the image in pixels, as decimal numbers. |
width | The width of the image in pixels. |
height
The height of the image in pixels.
size
The size of the image in pixels.
size_f32
The size of the image in pixels, as decimal numbers.
width
The width of the image in pixels.
Indices
An array of indices into the VertexAttributeValues for a mesh.
It describes the order in which the vertex attributes should be joined into faces.
Variants
Functions
| Name | Summary |
|---|---|
new | Constructs a new instance of the type from a table of its fields. |
new
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
Variant Functions
U16.new
new(variant: EnumVariantRef, payload: Fields<Indices::U16>) -> Indices
U32.new
new(variant: EnumVariantRef, payload: Fields<Indices::U32>) -> Indices
JointAabb
Fields
Functions
| Name | Summary |
|---|---|
new | Constructs a new instance of the type from a table of its fields. |
new
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
JointIndex
Fields
| Index | Type |
|---|---|
0 | u16 |
Functions
| Name | Summary |
|---|---|
new | Constructs a new instance of the type from a table of its fields. |
new
new(payload: Fields<JointIndex>) -> JointIndex
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
Mesh
Asset
A 3D object made out of vertices representing triangles, lines, or points, with “attribute” values for each vertex.
Meshes can be automatically generated by a bevy AssetLoader (generally by loading a Gltf file),
or by converting a primitive using into.
It is also possible to create one manually. They can be edited after creation.
Meshes can be rendered with a Mesh2d and MeshMaterial2d
or Mesh3d and MeshMaterial3d for 2D and 3D respectively.
A Mesh in Bevy is equivalent to a “primitive” in the glTF format, for a
glTF Mesh representation, see GltfMesh.
Manual creation
The following function will construct a flat mesh, to be rendered with a
StandardMaterial or ColorMaterial:
fn create_simple_parallelogram() -> Mesh {
// Create a new mesh using a triangle list topology, where each set of 3 vertices composes a triangle.
Mesh::new(PrimitiveTopology::TriangleList, RenderAssetUsages::default())
// Add 4 vertices, each with its own position attribute (coordinate in
// 3D space), for each of the corners of the parallelogram.
.with_inserted_attribute(
Mesh::ATTRIBUTE_POSITION,
vec![[0.0, 0.0, 0.0], [1.0, 2.0, 0.0], [2.0, 2.0, 0.0], [1.0, 0.0, 0.0]]
)
// Assign a UV coordinate to each vertex.
.with_inserted_attribute(
Mesh::ATTRIBUTE_UV_0,
vec![[0.0, 1.0], [0.5, 0.0], [1.0, 0.0], [0.5, 1.0]]
)
// Assign normals (everything points outwards)
.with_inserted_attribute(
Mesh::ATTRIBUTE_NORMAL,
vec![[0.0, 0.0, 1.0], [0.0, 0.0, 1.0], [0.0, 0.0, 1.0], [0.0, 0.0, 1.0]]
)
// After defining all the vertices and their attributes, build each triangle using the
// indices of the vertices that make it up in a counter-clockwise order.
.with_inserted_indices(Indices::U32(vec![
// First triangle
0, 3, 1,
// Second triangle
1, 3, 2
]))
}
You can see how it looks like here,
used in a Mesh3d with a square bevy logo texture, with added axis, points,
lines and text for clarity.
Other examples
For further visualization, explanation, and examples, see the built-in Bevy examples,
and the implementation of the built-in shapes.
In particular, generate_custom_mesh
teaches you to access and modify the attributes of a Mesh after creating it.
Common points of confusion
- UV maps in Bevy start at the top-left, see
ATTRIBUTE_UV_0, other APIs can have other conventions,OpenGLstarts at bottom-left. - It is possible and sometimes useful for multiple vertices to have the same position attribute value, it’s a common technique in 3D modeling for complex UV mapping or other calculations.
- Bevy performs frustum culling based on the
Aabbof meshes, which is calculated and added automatically for new meshes only. If a mesh is modified, the entity’sAabbneeds to be updated manually or deleted so that it is re-calculated.
Use with StandardMaterial
To render correctly with StandardMaterial, a mesh needs to have properly defined:
UVs: Bevy needs to know how to map a texture onto the mesh (also true forColorMaterial).Normals: Bevy needs to know how light interacts with your mesh. 0.0, 0.0, 1.0 is very common for simple flat meshes on the XY plane, because simple meshes are smooth and they don’t require complex light calculations.- Vertex winding order: by default,
StandardMaterial.cull_modeisSome(Face::Back), which means that Bevy would only render the “front” of each triangle, which is the side of the triangle from where the vertices appear in a counter-clockwise order.
Remote Inspection
To transmit a Mesh between two running Bevy apps, e.g. through BRP, use SerializedMesh.
This type is only meant for short-term transmission between same versions and should not be stored anywhere.
Fields
| Field | Type |
|---|---|
indices | MeshExtractableData<Indices> |
morph_targets | MeshExtractableData<Unknown> |
morph_target_names | MeshExtractableData<Unknown> |
asset_usage | RenderAssetUsages |
enable_raytracing | bool |
attribute_compression | MeshAttributeCompressionFlags |
final_aabb | Optional<Aabb3d> |
final_uv_ranges | [Optional<Aabb2d>; 2] |
skinned_mesh_bounds | Optional<SkinnedMeshBounds> |
Functions
| Name | Summary |
|---|---|
add_asset | Adds a value of this type as a new asset, returning a strong handle to it. |
from_shape | A mesh for a shape such as a cuboid or a sphere. Errors if the value is not a shape. |
get_asset | The asset a handle points to, or nil if it isn’t loaded or added yet. |
load | Starts loading an asset of this type from a path, returning a handle to it right away. |
new | Constructs a new instance of the type from a table of its fields. |
add_asset
Adds a value of this type as a new asset, returning a strong handle to it.
Arguments
value: The asset value.
Returns: A handle to the new asset.
from_shape
from_shape(shape: Cuboid | Sphere | Plane3d | Cylinder | Capsule3d | Cone | Torus | Circle | Rectangle | RegularPolygon | Capsule2d | Annulus | Triangle2d) -> Mesh
A mesh for a shape such as a cuboid or a sphere. Errors if the value is not a shape.
get_asset
The asset a handle points to, or nil if it isn’t loaded or added yet.
Changes to the returned value change the asset.
Arguments
handle: The handle to the asset.
Returns: The asset, or nil.
load
Starts loading an asset of this type from a path, returning a handle to it right away.
Arguments
path: The asset path, relative to the assets folder.
Returns: A handle to the asset, which is loaded in the background.
new
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
Methods
| Name | Summary |
|---|---|
count_vertices | The number of vertices in the mesh. |
count_vertices
The number of vertices in the mesh.
MeshAttributeCompressionFlags
If the corresponding attribute compression is enabled:
- Position will be Snorm16x4 relative to the mesh’s AABB. The w component is unused.
- Normal and tangent will be Snorm16x2 with octahedral encoding, using
octahedral_encode_signedandoctahedral_encode_tangent. - UV0 and UV1 will be Unorm16x2. UVs are remapped based on their min/max values so they can go beyond 0, 1, though a larger range will reduce precision.
Opaque: scripts can't access its fields, only its functions.
Functions
| Name | Summary |
|---|---|
new | Constructs a new instance of the type from a table of its fields. |
new
new(payload: Fields<MeshAttributeCompressionFlags>) -> MeshAttributeCompressionFlags
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
MeshExtractableData<Indices>
Variants
| Variant | Fields |
|---|---|
Data | (Indices) |
NoData | |
ExtractedToRenderWorld |
Functions
| Name | Summary |
|---|---|
new | Constructs a new instance of the type from a table of its fields. |
new
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
Variant Functions
| Name | Summary |
|---|---|
Data.new | |
ExtractedToRenderWorld.new | |
NoData.new |
Data.new
new(variant: EnumVariantRef, payload: Fields<MeshExtractableData<Indices>::Data>) -> MeshExtractableData<Indices>
ExtractedToRenderWorld.new
new(variant: EnumVariantRef, payload: Fields<MeshExtractableData<Indices>::ExtractedToRenderWorld>) -> MeshExtractableData<Indices>
NoData.new
new(variant: EnumVariantRef, payload: Fields<MeshExtractableData<Indices>::NoData>) -> MeshExtractableData<Indices>
MeshExtractableData<Unknown>
Variants
| Variant | Fields |
|---|---|
Data | (Vec<String>) |
NoData | |
ExtractedToRenderWorld |
Functions
| Name | Summary |
|---|---|
new | Constructs a new instance of the type from a table of its fields. |
new
new(payload: Fields<MeshExtractableData<Unknown>>) -> MeshExtractableData<Unknown>
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
Variant Functions
| Name | Summary |
|---|---|
Data.new | |
ExtractedToRenderWorld.new | |
NoData.new |
Data.new
new(variant: EnumVariantRef, payload: Fields<MeshExtractableData<Unknown>::Data>) -> MeshExtractableData<Unknown>
ExtractedToRenderWorld.new
new(variant: EnumVariantRef, payload: Fields<MeshExtractableData<Unknown>::ExtractedToRenderWorld>) -> MeshExtractableData<Unknown>
NoData.new
new(variant: EnumVariantRef, payload: Fields<MeshExtractableData<Unknown>::NoData>) -> MeshExtractableData<Unknown>
MeshExtractableData<Unknown>
Variants
| Variant | Fields |
|---|---|
Data | (Vec<MorphAttributes>) |
NoData | |
ExtractedToRenderWorld |
Functions
| Name | Summary |
|---|---|
new | Constructs a new instance of the type from a table of its fields. |
new
new(payload: Fields<MeshExtractableData<Unknown>>) -> MeshExtractableData<Unknown>
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
Variant Functions
| Name | Summary |
|---|---|
Data.new | |
ExtractedToRenderWorld.new | |
NoData.new |
Data.new
new(variant: EnumVariantRef, payload: Fields<MeshExtractableData<Unknown>::Data>) -> MeshExtractableData<Unknown>
ExtractedToRenderWorld.new
new(variant: EnumVariantRef, payload: Fields<MeshExtractableData<Unknown>::ExtractedToRenderWorld>) -> MeshExtractableData<Unknown>
NoData.new
new(variant: EnumVariantRef, payload: Fields<MeshExtractableData<Unknown>::NoData>) -> MeshExtractableData<Unknown>
MorphAttributes
Attributes differences used for morph targets.
Fields
Functions
| Name | Summary |
|---|---|
new | Constructs a new instance of the type from a table of its fields. |
new
new(payload: Fields<MorphAttributes>) -> MorphAttributes
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
NoBackgroundMotionVectors
Component
When added to a camera with MotionVectorPrepass, disables the automatic background motion
vector prepass.
By default, any camera with MotionVectorPrepass will automatically write camera-rotation
motion vectors for background pixels (those with no geometry, i.e. depth == 0 in reversed-Z).
Add this component to opt out, for example if you are writing custom background motion vectors
for your own effect.
Functions
| Name | Summary |
|---|---|
new | Constructs a new instance of the type from a table of its fields. |
new
new(payload: Fields<NoBackgroundMotionVectors>) -> NoBackgroundMotionVectors
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
OpaqueRendererMethod
Render method used for opaque materials.
The forward rendering main pass draws each mesh entity and shades it according to its corresponding material and the lights that affect it. Some render features like Screen Space Ambient Occlusion require running depth and normal prepasses, that are ‘deferred’-like prepasses over all mesh entities to populate depth and normal textures. This means that when using render features that require running prepasses, multiple passes over all visible geometry are required. This can be slow if there is a lot of geometry that cannot be batched into few draws.
Deferred rendering runs a prepass to gather not only geometric information like depth and normals, but also all the material properties like base color, emissive color, reflectance, metalness, etc, and writes them into a deferred ‘g-buffer’ texture. The deferred main pass is then a fullscreen pass that reads data from these textures and executes shading. This allows for one pass over geometry, but is at the cost of not being able to use MSAA, and has heavier bandwidth usage which can be unsuitable for low end mobile or other bandwidth-constrained devices.
If a material indicates OpaqueRendererMethod::Auto, DefaultOpaqueRendererMethod will be used.
Variants
| Variant |
|---|
Forward |
Deferred |
Auto |
Functions
| Name | Summary |
|---|---|
new | Constructs a new instance of the type from a table of its fields. |
new
new(payload: Fields<OpaqueRendererMethod>) -> OpaqueRendererMethod
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
Variant Functions
| Name | Summary |
|---|---|
Auto.new | |
Deferred.new | |
Forward.new |
Auto.new
new(variant: EnumVariantRef, payload: Fields<OpaqueRendererMethod::Auto>) -> OpaqueRendererMethod
Deferred.new
new(variant: EnumVariantRef, payload: Fields<OpaqueRendererMethod::Deferred>) -> OpaqueRendererMethod
Forward.new
new(variant: EnumVariantRef, payload: Fields<OpaqueRendererMethod::Forward>) -> OpaqueRendererMethod
ParallaxMappingMethod
The parallax mapping method to use to compute depth based on the
material’s depth_map.
Parallax Mapping uses a depth map texture to give the illusion of depth variation on a mesh surface that is geometrically flat.
See the parallax_mapping.wesl shader code for implementation details
and explanation of the methods used.
Variants
| Variant | Fields |
|---|---|
Occlusion | |
Relief | { max_steps: u32 } |
Functions
| Name | Summary |
|---|---|
new | Constructs a new instance of the type from a table of its fields. |
new
new(payload: Fields<ParallaxMappingMethod>) -> ParallaxMappingMethod
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
Variant Functions
| Name | Summary |
|---|---|
Occlusion.new | |
Relief.new |
Occlusion.new
new(variant: EnumVariantRef, payload: Fields<ParallaxMappingMethod::Occlusion>) -> ParallaxMappingMethod
Relief.new
new(variant: EnumVariantRef, payload: Fields<ParallaxMappingMethod::Relief>) -> ParallaxMappingMethod
ReadbackOnce
Marker component that pairs with a Readback to indicate the entity should be
despawned after the first ReadbackComplete event fires for it.
commands.spawn(ReadbackOnce::buffer(handle));
Functions
| Name | Summary |
|---|---|
new | Constructs a new instance of the type from a table of its fields. |
new
new(payload: Fields<ReadbackOnce>) -> ReadbackOnce
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
Screenshot
Component
A component that signals to the renderer to capture a screenshot this frame.
This component should be spawned on a new entity with an observer that will trigger
with ScreenshotCaptured when the screenshot is ready.
Screenshots are captured asynchronously and may not be available immediately after the frame that the component is spawned on. The observer should be used to handle the screenshot when it is ready.
Note that the screenshot entity will be despawned after the screenshot is captured and the observer is triggered.
Usage
fn take_screenshot(mut commands: Commands) {
commands.spawn(Screenshot::primary_window())
.observe(save_to_disk("screenshot.png"));
}
Fields
| Index | Type |
|---|---|
0 | RenderTarget |
Functions
| Name | Summary |
|---|---|
new | Constructs a new instance of the type from a table of its fields. |
new
new(payload: Fields<Screenshot>) -> Screenshot
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
ScreenshotCaptured
Fields
Functions
| Name | Summary |
|---|---|
new | Constructs a new instance of the type from a table of its fields. |
new
new(payload: Fields<ScreenshotCaptured>) -> ScreenshotCaptured
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
ShaderBuffer
Asset
A storage buffer that is prepared as a RenderAsset and uploaded to the GPU.
This buffer primarily exists in order to be embedded into a material that
implements the bevy_render_macros::AsBindGroup trait. Compared to
embedding a raw Buffer, ShaderBuffer has the advantage that the
buffer can be resized without regenerating the materials that embed it.
Opaque: scripts can't access its fields, only its functions.
Functions
| Name | Summary |
|---|---|
add_asset | Adds a value of this type as a new asset, returning a strong handle to it. |
get_asset | The asset a handle points to, or nil if it isn’t loaded or added yet. |
load | Starts loading an asset of this type from a path, returning a handle to it right away. |
new | Constructs a new instance of the type from a table of its fields. |
add_asset
add_asset(value: ShaderBuffer) -> Handle<ShaderBuffer>
Adds a value of this type as a new asset, returning a strong handle to it.
Arguments
value: The asset value.
Returns: A handle to the new asset.
get_asset
get_asset(handle: Handle<ShaderBuffer>) -> Optional<ShaderBuffer>
The asset a handle points to, or nil if it isn’t loaded or added yet.
Changes to the returned value change the asset.
Arguments
handle: The handle to the asset.
Returns: The asset, or nil.
load
load(path: String) -> Handle<ShaderBuffer>
Starts loading an asset of this type from a path, returning a handle to it right away.
Arguments
path: The asset path, relative to the assets folder.
Returns: A handle to the asset, which is loaded in the background.
new
new(payload: Fields<ShaderBuffer>) -> ShaderBuffer
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
SkinnedMeshBounds
Data that can be used to calculate the AABB of a skinned mesh.
Fields
| Field | Type |
|---|---|
aabbs | Vec<JointAabb> |
aabb_index_to_joint_index | Vec<JointIndex> |
Functions
| Name | Summary |
|---|---|
new | Constructs a new instance of the type from a table of its fields. |
new
new(payload: Fields<SkinnedMeshBounds>) -> SkinnedMeshBounds
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
SkinnedMeshInverseBindposes
Not reflected: scripts can only pass values of it around.
Opaque: scripts can't access its fields, only its functions.
StandardMaterial
A material with “standard” properties used in PBR lighting. Standard property values with pictures here: https://google.github.io/filament/notes/material_properties.html.
May be created directly from a Color or an Image.
The StandardMaterial can be extended with more data and custom
shaders using ExtendedMaterial. Examples of how to do this can
be found in the Bevy examples.
Fields
| Field | Type |
|---|---|
base_color | Color |
base_color_channel | UvChannel |
base_color_texture | Optional<Handle<Image>> |
emissive | LinearRgba |
emissive_exposure_weight | f32 |
emissive_channel | UvChannel |
emissive_texture | Optional<Handle<Image>> |
perceptual_roughness | f32 |
metallic | f32 |
metallic_roughness_channel | UvChannel |
metallic_roughness_texture | Optional<Handle<Image>> |
reflectance | f32 |
specular_tint | Color |
diffuse_transmission | f32 |
specular_transmission | f32 |
thickness | f32 |
ior | f32 |
attenuation_distance | f32 |
attenuation_color | Color |
normal_map_channel | UvChannel |
normal_map_texture | Optional<Handle<Image>> |
flip_normal_map_y | bool |
occlusion_channel | UvChannel |
occlusion_texture | Optional<Handle<Image>> |
clearcoat | f32 |
clearcoat_perceptual_roughness | f32 |
anisotropy_strength | f32 |
anisotropy_rotation | f32 |
double_sided | bool |
unlit | bool |
fog_enabled | bool |
alpha_mode | AlphaMode |
depth_bias | f32 |
depth_map | Optional<Handle<Image>> |
parallax_depth_scale | f32 |
parallax_mapping_method | ParallaxMappingMethod |
max_parallax_layer_count | f32 |
lightmap_exposure | f32 |
opaque_render_method | OpaqueRendererMethod |
deferred_lighting_pass_id | u8 |
uv_transform | Affine2 |
Functions
| Name | Summary |
|---|---|
from_color | A material with the given color as its base color and default settings for everything else. |
new | Constructs a new instance of the type from a table of its fields. |
from_color
from_color(color: Color) -> StandardMaterial
A material with the given color as its base color and default settings for everything else.
new
new(payload: Fields<StandardMaterial>) -> StandardMaterial
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
TextureAtlas
An index into a TextureAtlasLayout, which corresponds to a specific section of a texture.
It stores a handle to TextureAtlasLayout and the index of the current section of the atlas.
The texture atlas contains various sections of a given texture, allowing users to have a single
image file for either sprite animation or global mapping.
You can change the texture index of the atlas to animate the sprite or display only a section of the texture
for efficient rendering of related game objects.
Check the following examples for usage:
Fields
| Field | Type |
|---|---|
layout | Handle<TextureAtlasLayout> |
index | usize |
Functions
| Name | Summary |
|---|---|
new | Constructs a new instance of the type from a table of its fields. |
new
new(payload: Fields<TextureAtlas>) -> TextureAtlas
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
UvChannel
An enum to define which UV attribute to use for a texture.
It only supports two UV attributes, Mesh::ATTRIBUTE_UV_0 and
Mesh::ATTRIBUTE_UV_1.
The default is UvChannel::Uv0.
Variants
| Variant |
|---|
Uv0 |
Uv1 |
Functions
| Name | Summary |
|---|---|
new | Constructs a new instance of the type from a table of its fields. |
new
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
Variant Functions
Uv0.new
new(variant: EnumVariantRef, payload: Fields<UvChannel::Uv0>) -> UvChannel
Uv1.new
new(variant: EnumVariantRef, payload: Fields<UvChannel::Uv1>) -> UvChannel
smol_str
The types and functions in the smol_str namespace, as returned by import_namespace("smol_str").
Types
| Type | Summary |
|---|---|
SmolStr |
SmolStr
Opaque: scripts can't access its fields, only its functions.
Functions
| Name | Summary |
|---|---|
new | Constructs a new instance of the type from a table of its fields. |
new
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
sprite
The types and functions in the sprite namespace, as returned by import_namespace("sprite").
Types
| Type | Summary |
|---|---|
AlphaMode2d | Sets how a 2d material’s base color alpha channel is used for transparency. |
Anchor | Normalized (relative to its size) offset of a 2d renderable entity from its Transform. |
BorderRect | Defines border insets that shrink a rectangle from its minimum and maximum corners. |
ColorMaterial | A 2d material that renders 2d meshes with a texture tinted by a uniform color |
MeshMaterial2d<ColorMaterial> | A material used for rendering a Mesh2d. |
MeshMaterial2d<SpriteMeshMaterial> | A material used for rendering a Mesh2d. |
SliceScaleMode | Defines how a texture slice scales when resized |
Sprite | Describes a sprite to be rendered to a 2D camera |
SpriteAlphaMode | An enum describing how a sprite’s alpha channel will be handled. |
SpriteImageMode | Controls how the image is altered when scaled. |
SpriteMeshMaterial | |
SpriteScalingMode | Represents various modes for proportional scaling of a texture. |
TextureAtlasLayout | Stores a map used to lookup the position of a texture in a TextureAtlas. |
TextureSlicer | Slices a texture using the 9-slicing technique. |
TilemapChunkMaterial | Not reflected: scripts can only pass values of it around. |
AlphaMode2d
Sets how a 2d material’s base color alpha channel is used for transparency.
Currently, this only works with Mesh2d. Sprites are always transparent.
This is very similar to AlphaMode but this only applies to 2d meshes.
We use a separate type because 2d doesn’t support all the transparency modes that 3d does.
Variants
| Variant | Fields |
|---|---|
Opaque | |
Mask | (f32) |
Blend |
Functions
| Name | Summary |
|---|---|
new | Constructs a new instance of the type from a table of its fields. |
new
new(payload: Fields<AlphaMode2d>) -> AlphaMode2d
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
Variant Functions
| Name | Summary |
|---|---|
Blend.new | |
Mask.new | |
Opaque.new |
Blend.new
new(variant: EnumVariantRef, payload: Fields<AlphaMode2d::Blend>) -> AlphaMode2d
Mask.new
new(variant: EnumVariantRef, payload: Fields<AlphaMode2d::Mask>) -> AlphaMode2d
Opaque.new
new(variant: EnumVariantRef, payload: Fields<AlphaMode2d::Opaque>) -> AlphaMode2d
Anchor
Component
Normalized (relative to its size) offset of a 2d renderable entity from its Transform.
Fields
| Index | Type |
|---|---|
0 | Vec2 |
Functions
| Name | Summary |
|---|---|
bottom_center | The anchor in the middle of the bottom edge. |
bottom_left | The anchor in the bottom left corner. |
bottom_right | The anchor in the bottom right corner. |
center | The anchor in the middle of the sprite. |
center_left | The anchor in the middle of the left edge. |
center_right | The anchor in the middle of the right edge. |
new | Constructs a new instance of the type from a table of its fields. |
top_center | The anchor in the middle of the top edge. |
top_left | The anchor in the top left corner. |
top_right | The anchor in the top right corner. |
bottom_center
bottom_center() -> Anchor
The anchor in the middle of the bottom edge.
bottom_left
bottom_left() -> Anchor
The anchor in the bottom left corner.
bottom_right
bottom_right() -> Anchor
The anchor in the bottom right corner.
center
center() -> Anchor
The anchor in the middle of the sprite.
center_left
center_left() -> Anchor
The anchor in the middle of the left edge.
center_right
center_right() -> Anchor
The anchor in the middle of the right edge.
new
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
top_center
top_center() -> Anchor
The anchor in the middle of the top edge.
top_left
top_left() -> Anchor
The anchor in the top left corner.
top_right
top_right() -> Anchor
The anchor in the top right corner.
Methods
| Name | Summary |
|---|---|
as_vec | The offset of the anchor from the center, as a fraction of the sprite size. |
as_vec
The offset of the anchor from the center, as a fraction of the sprite size.
BorderRect
Defines border insets that shrink a rectangle from its minimum and maximum corners.
This struct is used to represent thickness or offsets from the four edges of a rectangle, with values increasing inwards.
Fields
Functions
| Name | Summary |
|---|---|
new | Constructs a new instance of the type from a table of its fields. |
new
new(payload: Fields<BorderRect>) -> BorderRect
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
ColorMaterial
Asset
A 2d material that renders 2d meshes with a texture tinted by a uniform color
Fields
| Field | Type |
|---|---|
color | Color |
alpha_mode | AlphaMode2d |
uv_transform | Affine2 |
texture | Optional<Handle<Image>> |
Functions
| Name | Summary |
|---|---|
add_asset | Adds a value of this type as a new asset, returning a strong handle to it. |
get_asset | The asset a handle points to, or nil if it isn’t loaded or added yet. |
load | Starts loading an asset of this type from a path, returning a handle to it right away. |
new | Constructs a new instance of the type from a table of its fields. |
add_asset
add_asset(value: ColorMaterial) -> Handle<ColorMaterial>
Adds a value of this type as a new asset, returning a strong handle to it.
Arguments
value: The asset value.
Returns: A handle to the new asset.
get_asset
get_asset(handle: Handle<ColorMaterial>) -> Optional<ColorMaterial>
The asset a handle points to, or nil if it isn’t loaded or added yet.
Changes to the returned value change the asset.
Arguments
handle: The handle to the asset.
Returns: The asset, or nil.
load
load(path: String) -> Handle<ColorMaterial>
Starts loading an asset of this type from a path, returning a handle to it right away.
Arguments
path: The asset path, relative to the assets folder.
Returns: A handle to the asset, which is loaded in the background.
new
new(payload: Fields<ColorMaterial>) -> ColorMaterial
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
MeshMaterial2d<ColorMaterial>
Component
A material used for rendering a Mesh2d.
See Material2d for general information about 2D materials and how to implement your own materials.
Example
// Spawn an entity with a mesh using `ColorMaterial`.
fn setup(
mut commands: Commands,
mut meshes: ResMut<Assets<Mesh>>,
mut materials: ResMut<Assets<ColorMaterial>>,
) {
commands.spawn((
Mesh2d(meshes.add(Circle::new(50.0))),
MeshMaterial2d(materials.add(ColorMaterial::from_color(RED))),
));
}
Fields
| Index | Type |
|---|---|
0 | Handle<ColorMaterial> |
Functions
| Name | Summary |
|---|---|
new | Constructs a new instance of the type from a table of its fields. |
new
new(payload: Fields<MeshMaterial2d<ColorMaterial>>) -> MeshMaterial2d<ColorMaterial>
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
MeshMaterial2d<SpriteMeshMaterial>
Component
A material used for rendering a Mesh2d.
See Material2d for general information about 2D materials and how to implement your own materials.
Example
// Spawn an entity with a mesh using `ColorMaterial`.
fn setup(
mut commands: Commands,
mut meshes: ResMut<Assets<Mesh>>,
mut materials: ResMut<Assets<ColorMaterial>>,
) {
commands.spawn((
Mesh2d(meshes.add(Circle::new(50.0))),
MeshMaterial2d(materials.add(ColorMaterial::from_color(RED))),
));
}
Fields
| Index | Type |
|---|---|
0 | Handle<SpriteMeshMaterial> |
Functions
| Name | Summary |
|---|---|
new | Constructs a new instance of the type from a table of its fields. |
new
new(payload: Fields<MeshMaterial2d<SpriteMeshMaterial>>) -> MeshMaterial2d<SpriteMeshMaterial>
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
SliceScaleMode
Defines how a texture slice scales when resized
Variants
| Variant | Fields |
|---|---|
Stretch | |
Tile | { stretch_value: f32 } |
Functions
| Name | Summary |
|---|---|
new | Constructs a new instance of the type from a table of its fields. |
new
new(payload: Fields<SliceScaleMode>) -> SliceScaleMode
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
Variant Functions
| Name | Summary |
|---|---|
Stretch.new | |
Tile.new |
Stretch.new
new(variant: EnumVariantRef, payload: Fields<SliceScaleMode::Stretch>) -> SliceScaleMode
Tile.new
new(variant: EnumVariantRef, payload: Fields<SliceScaleMode::Tile>) -> SliceScaleMode
Sprite
Component
Describes a sprite to be rendered to a 2D camera
Fields
| Field | Type |
|---|---|
image | Handle<Image> |
texture_atlas | Optional<TextureAtlas> |
color | Color |
flip_x | bool |
flip_y | bool |
custom_size | Optional<Vec2> |
rect | Optional<Rect> |
image_mode | SpriteImageMode |
alpha_mode | SpriteAlphaMode |
Functions
| Name | Summary |
|---|---|
from_atlas_image | A sprite that shows a section of an image from a texture atlas. |
from_color | A solid square of the given color and size. |
from_image | A sprite that shows the whole image. |
new | Constructs a new instance of the type from a table of its fields. |
sized | A sprite with no image that is drawn at the given size. |
from_atlas_image
from_atlas_image(image: Handle<Image>, atlas: TextureAtlas) -> Sprite
A sprite that shows a section of an image from a texture atlas.
from_color
A solid square of the given color and size.
from_image
A sprite that shows the whole image.
new
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
sized
A sprite with no image that is drawn at the given size.
SpriteAlphaMode
An enum describing how a sprite’s alpha channel will be handled.
The base color being modified is that of the texture after tinting.
The default is Blend.
Variants
| Variant | Fields |
|---|---|
Opaque | |
Mask | (f32) |
Blend |
Functions
| Name | Summary |
|---|---|
new | Constructs a new instance of the type from a table of its fields. |
new
new(payload: Fields<SpriteAlphaMode>) -> SpriteAlphaMode
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
Variant Functions
| Name | Summary |
|---|---|
Blend.new | |
Mask.new | |
Opaque.new |
Blend.new
new(variant: EnumVariantRef, payload: Fields<SpriteAlphaMode::Blend>) -> SpriteAlphaMode
Mask.new
new(variant: EnumVariantRef, payload: Fields<SpriteAlphaMode::Mask>) -> SpriteAlphaMode
Opaque.new
new(variant: EnumVariantRef, payload: Fields<SpriteAlphaMode::Opaque>) -> SpriteAlphaMode
SpriteImageMode
Controls how the image is altered when scaled.
Variants
| Variant | Fields |
|---|---|
Auto | |
Scale | (SpriteScalingMode) |
Sliced | (TextureSlicer) |
Tiled | { tile_x: bool, tile_y: bool, stretch_value: f32 } |
Functions
| Name | Summary |
|---|---|
new | Constructs a new instance of the type from a table of its fields. |
new
new(payload: Fields<SpriteImageMode>) -> SpriteImageMode
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
Variant Functions
| Name | Summary |
|---|---|
Auto.new | |
Scale.new | |
Sliced.new | |
Tiled.new |
Auto.new
new(variant: EnumVariantRef, payload: Fields<SpriteImageMode::Auto>) -> SpriteImageMode
Scale.new
new(variant: EnumVariantRef, payload: Fields<SpriteImageMode::Scale>) -> SpriteImageMode
Sliced.new
new(variant: EnumVariantRef, payload: Fields<SpriteImageMode::Sliced>) -> SpriteImageMode
Tiled.new
new(variant: EnumVariantRef, payload: Fields<SpriteImageMode::Tiled>) -> SpriteImageMode
SpriteMeshMaterial
Asset
Fields
| Field | Type |
|---|---|
image | Handle<Image> |
texture_atlas | Optional<TextureAtlas> |
color | Color |
flip_x | bool |
flip_y | bool |
custom_size | Optional<Vec2> |
rect | Optional<Rect> |
image_mode | SpriteImageMode |
alpha_mode | AlphaMode2d |
anchor | Vec2 |
texture_atlas_layout | Optional<TextureAtlasLayout> |
texture_atlas_index | usize |
Functions
| Name | Summary |
|---|---|
add_asset | Adds a value of this type as a new asset, returning a strong handle to it. |
get_asset | The asset a handle points to, or nil if it isn’t loaded or added yet. |
load | Starts loading an asset of this type from a path, returning a handle to it right away. |
new | Constructs a new instance of the type from a table of its fields. |
add_asset
add_asset(value: SpriteMeshMaterial) -> Handle<SpriteMeshMaterial>
Adds a value of this type as a new asset, returning a strong handle to it.
Arguments
value: The asset value.
Returns: A handle to the new asset.
get_asset
get_asset(handle: Handle<SpriteMeshMaterial>) -> Optional<SpriteMeshMaterial>
The asset a handle points to, or nil if it isn’t loaded or added yet.
Changes to the returned value change the asset.
Arguments
handle: The handle to the asset.
Returns: The asset, or nil.
load
load(path: String) -> Handle<SpriteMeshMaterial>
Starts loading an asset of this type from a path, returning a handle to it right away.
Arguments
path: The asset path, relative to the assets folder.
Returns: A handle to the asset, which is loaded in the background.
new
new(payload: Fields<SpriteMeshMaterial>) -> SpriteMeshMaterial
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
SpriteScalingMode
Represents various modes for proportional scaling of a texture.
Can be used in SpriteImageMode::Scale.
Variants
| Variant |
|---|
FillCenter |
FillStart |
FillEnd |
FitCenter |
FitStart |
FitEnd |
Functions
| Name | Summary |
|---|---|
new | Constructs a new instance of the type from a table of its fields. |
new
new(payload: Fields<SpriteScalingMode>) -> SpriteScalingMode
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
Variant Functions
FillCenter.new
new(variant: EnumVariantRef, payload: Fields<SpriteScalingMode::FillCenter>) -> SpriteScalingMode
FillEnd.new
new(variant: EnumVariantRef, payload: Fields<SpriteScalingMode::FillEnd>) -> SpriteScalingMode
FillStart.new
new(variant: EnumVariantRef, payload: Fields<SpriteScalingMode::FillStart>) -> SpriteScalingMode
FitCenter.new
new(variant: EnumVariantRef, payload: Fields<SpriteScalingMode::FitCenter>) -> SpriteScalingMode
FitEnd.new
new(variant: EnumVariantRef, payload: Fields<SpriteScalingMode::FitEnd>) -> SpriteScalingMode
FitStart.new
new(variant: EnumVariantRef, payload: Fields<SpriteScalingMode::FitStart>) -> SpriteScalingMode
TextureAtlasLayout
Asset
Stores a map used to lookup the position of a texture in a TextureAtlas.
This can be used to either use and look up a specific section of a texture, or animate frame-by-frame as a sprite sheet.
Optionally it can store a mapping from sub texture handles to the related area index (see
TextureAtlasBuilder).
Example usage animating sprite. Example usage animating sprite in response to an event. Example usage loading sprite sheet.
Fields
Functions
| Name | Summary |
|---|---|
add_asset | Adds a value of this type as a new asset, returning a strong handle to it. |
from_grid | A layout of equal tiles in a grid, numbered left to right and then top to bottom. |
get_asset | The asset a handle points to, or nil if it isn’t loaded or added yet. |
load | Starts loading an asset of this type from a path, returning a handle to it right away. |
new | Constructs a new instance of the type from a table of its fields. |
add_asset
add_asset(value: TextureAtlasLayout) -> Handle<TextureAtlasLayout>
Adds a value of this type as a new asset, returning a strong handle to it.
Arguments
value: The asset value.
Returns: A handle to the new asset.
from_grid
from_grid(tile_size: UVec2, columns: u32, rows: u32, padding: Optional<UVec2>, offset: Optional<UVec2>) -> TextureAtlasLayout
A layout of equal tiles in a grid, numbered left to right and then top to bottom. Padding and offset are in pixels, and default to none.
get_asset
get_asset(handle: Handle<TextureAtlasLayout>) -> Optional<TextureAtlasLayout>
The asset a handle points to, or nil if it isn’t loaded or added yet.
Changes to the returned value change the asset.
Arguments
handle: The handle to the asset.
Returns: The asset, or nil.
load
load(path: String) -> Handle<TextureAtlasLayout>
Starts loading an asset of this type from a path, returning a handle to it right away.
Arguments
path: The asset path, relative to the assets folder.
Returns: A handle to the asset, which is loaded in the background.
new
new(payload: Fields<TextureAtlasLayout>) -> TextureAtlasLayout
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
Operators
| Name | Summary |
|---|---|
len | The number of tiles in the layout. |
len
len(self: TextureAtlasLayout) -> usize
The number of tiles in the layout.
TextureSlicer
Slices a texture using the 9-slicing technique. This allows to reuse an image at various sizes without needing to prepare multiple assets. The associated texture will be split into nine portions, so that on resize the different portions scale or tile in different ways to keep the texture in proportion.
For example, when resizing a 9-sliced texture the corners will remain unscaled while the other sections will be scaled or tiled.
See 9-sliced textures.
Fields
| Field | Type |
|---|---|
border | BorderRect |
center_scale_mode | SliceScaleMode |
sides_scale_mode | SliceScaleMode |
max_corner_scale | f32 |
Functions
| Name | Summary |
|---|---|
new | Constructs a new instance of the type from a table of its fields. |
new
new(payload: Fields<TextureSlicer>) -> TextureSlicer
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
TilemapChunkMaterial
Not reflected: scripts can only pass values of it around.
Opaque: scripts can't access its fields, only its functions.
text
The types and functions in the text namespace, as returned by import_namespace("text").
Types
| Type | Summary |
|---|---|
EmSize | The font size, in logical pixels, used to resolve Val::Em values in a UI node. |
Font | Not reflected: scripts can only pass values of it around. |
FontFeatures | OpenType features for .otf fonts that support them. |
FontFeatureTag | An OpenType font feature tag. |
FontSize | The vertical height of rasterized glyphs in the font atlas in pixels. |
FontSmoothing | Determines which antialiasing method to use when rendering text. |
FontSource | Determines how the font face for a text sections is selected. |
FontStyle | The slant style of a font face: normal, italic, or oblique. |
FontVariations | OpenType font variations for variable fonts that support them. |
FontVariationTag | An OpenType font variation tag. |
FontWeight | How thick or bold the strokes of a font appear. |
FontWidth | The visual width of a font as a ratio of its normal width, typically 0.5 to 2.0. |
GenericFontFamily | Generic font families that are resolved through Parley’s font database. |
Justify | Describes the horizontal alignment of multiple lines of text relative to each other. |
LineBreak | Determines how lines will be broken when preventing text from running out of bounds. |
RemSize | The root font size, in logical pixels. |
Text | The top-level UI text component. |
Text2d | The top-level 2D text component. |
TextFont | TextFont determines the style of a text span within a ComputedTextBlock, specifically the font face, the font size… |
TextLayout | Component with text format settings for a block of text. |
TextSpan | A span of text in a tree of spans. |
Values
| Name | Type |
|---|---|
EditableTextSystems | ReflectSystemSet |
Text2dUpdateSystems | ReflectSystemSet |
EmSize
Component
The font size, in logical pixels, used to resolve Val::Em values in a UI node.
Em units are relative to the font size of the node they sit on, and this is that
font size made concrete. Required by Node, so every UI node has one.
If the node has a TextFont, the EmSize is derived from it whenever the TextFont,
RemSize or render-target info changes; until then any value you place on it persists.
If it does not have a TextFont, the value is yours to set, for example by an app-level
propagation system. EmSize defaults to DEFAULT_REM_SIZE_PX, which matches the default
RemSize but does not track changes to it. Use Val::Rem instead for values that
should follow the root font size.
Removing a TextFont leaves the last derived value in place.
Fields
| Index | Type |
|---|---|
0 | f32 |
Functions
| Name | Summary |
|---|---|
new | Constructs a new instance of the type from a table of its fields. |
new
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
Font
Not reflected: scripts can only pass values of it around.
Opaque: scripts can't access its fields, only its functions.
FontFeatures
OpenType features for .otf fonts that support them.
Examples features include ligatures, small-caps, and fractional number display. For the complete
list of OpenType features, see the spec at
<https://learn.microsoft.com/en-us/typography/opentype/spec/featurelist>.
Usage:
use bevy_text::{FontFeatureTag, FontFeatures};
// Create using the builder
let font_features = FontFeatures::builder()
.enable(FontFeatureTag::STANDARD_LIGATURES)
.set(FontFeatureTag::WEIGHT, 300)
.build();
// Create from a list
let more_font_features: FontFeatures = [
FontFeatureTag::STANDARD_LIGATURES,
FontFeatureTag::OLDSTYLE_FIGURES,
FontFeatureTag::TABULAR_FIGURES
].into();
Fields
| Field | Type |
|---|---|
features | Vec<(FontFeatureTag, u32)> |
Functions
| Name | Summary |
|---|---|
new | Constructs a new instance of the type from a table of its fields. |
new
new(payload: Fields<FontFeatures>) -> FontFeatures
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
FontFeatureTag
An OpenType font feature tag.
Fields
| Index | Type |
|---|---|
0 | [u8; 4] |
Functions
| Name | Summary |
|---|---|
new | Constructs a new instance of the type from a table of its fields. |
new
new(payload: Fields<FontFeatureTag>) -> FontFeatureTag
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
FontSize
The vertical height of rasterized glyphs in the font atlas in pixels.
This is multiplied by the scale factor, but not the text entity transform or camera projection.
The viewport variants are not supported by Text2d.
A new font atlas is generated for every combination of font handle and scaled font size which can have a strong performance impact.
Variants
Functions
| Name | Summary |
|---|---|
new | Constructs a new instance of the type from a table of its fields. |
new
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
Variant Functions
Px.new
new(variant: EnumVariantRef, payload: Fields<FontSize::Px>) -> FontSize
Rem.new
new(variant: EnumVariantRef, payload: Fields<FontSize::Rem>) -> FontSize
VMax.new
new(variant: EnumVariantRef, payload: Fields<FontSize::VMax>) -> FontSize
VMin.new
new(variant: EnumVariantRef, payload: Fields<FontSize::VMin>) -> FontSize
Vh.new
new(variant: EnumVariantRef, payload: Fields<FontSize::Vh>) -> FontSize
Vw.new
new(variant: EnumVariantRef, payload: Fields<FontSize::Vw>) -> FontSize
FontSmoothing
Determines which antialiasing method to use when rendering text. By default, text is rendered with grayscale antialiasing, but this can be changed to achieve a pixelated look.
Note: Subpixel antialiasing is not currently supported.
Variants
| Variant |
|---|
None |
AntiAliased |
Functions
| Name | Summary |
|---|---|
new | Constructs a new instance of the type from a table of its fields. |
new
new(payload: Fields<FontSmoothing>) -> FontSmoothing
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
Variant Functions
| Name | Summary |
|---|---|
AntiAliased.new | |
None.new |
AntiAliased.new
new(variant: EnumVariantRef, payload: Fields<FontSmoothing::AntiAliased>) -> FontSmoothing
None.new
new(variant: EnumVariantRef, payload: Fields<FontSmoothing::None>) -> FontSmoothing
FontSource
Determines how the font face for a text sections is selected.
A FontSource can be a handle to a font asset, a font family name,
a CSS font-family list, an ordered family list, or a generic font category
that is resolved using Parley’s font database.
Font family fallback (selection of a font when the requested font is not found)
is automatically handled by parley::fontique.
Be sure to enable the parley/system feature for automatic discovery of system fonts.
Generally speaking, these fallbacks are OS-specific, and do not require manual configuration.
You can check which font family is used for a given FontSource
by calling FontCx::get_family.
Variants
| Variant | Fields |
|---|---|
Handle | (Handle<Font>) |
Family | (SmolStr) |
Families | (SmolStr) |
List | (Vec<FontSource>) |
Generic | (GenericFontFamily) |
Functions
| Name | Summary |
|---|---|
new | Constructs a new instance of the type from a table of its fields. |
new
new(payload: Fields<FontSource>) -> FontSource
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
Variant Functions
| Name | Summary |
|---|---|
Families.new | |
Family.new | |
Generic.new | |
Handle.new | |
List.new |
Families.new
new(variant: EnumVariantRef, payload: Fields<FontSource::Families>) -> FontSource
Family.new
new(variant: EnumVariantRef, payload: Fields<FontSource::Family>) -> FontSource
Generic.new
new(variant: EnumVariantRef, payload: Fields<FontSource::Generic>) -> FontSource
Handle.new
new(variant: EnumVariantRef, payload: Fields<FontSource::Handle>) -> FontSource
List.new
new(variant: EnumVariantRef, payload: Fields<FontSource::List>) -> FontSource
FontStyle
The slant style of a font face: normal, italic, or oblique.
Variants
| Variant | Fields |
|---|---|
Normal | |
Italic | |
Oblique | (Optional<f32>) |
Functions
| Name | Summary |
|---|---|
new | Constructs a new instance of the type from a table of its fields. |
new
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
Variant Functions
| Name | Summary |
|---|---|
Italic.new | |
Normal.new | |
Oblique.new |
Italic.new
new(variant: EnumVariantRef, payload: Fields<FontStyle::Italic>) -> FontStyle
Normal.new
new(variant: EnumVariantRef, payload: Fields<FontStyle::Normal>) -> FontStyle
Oblique.new
new(variant: EnumVariantRef, payload: Fields<FontStyle::Oblique>) -> FontStyle
FontVariations
OpenType font variations for variable fonts that support them.
Variable fonts expose named axes (e.g. wght, FILL) that accept continuous f32 values.
This is distinct from FontFeatures, which mainly controls on/off OpenType layout features.
Usage
use bevy_text::{FontVariationTag, FontVariations};
let variations = FontVariations::builder()
.set(FontVariationTag::WEIGHT, 400.0)
.build();
Fields
| Field | Type |
|---|---|
variations | Vec<(FontVariationTag, f32)> |
Functions
| Name | Summary |
|---|---|
new | Constructs a new instance of the type from a table of its fields. |
new
new(payload: Fields<FontVariations>) -> FontVariations
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
FontVariationTag
An OpenType font variation tag.
Fields
| Index | Type |
|---|---|
0 | [u8; 4] |
Functions
| Name | Summary |
|---|---|
new | Constructs a new instance of the type from a table of its fields. |
new
new(payload: Fields<FontVariationTag>) -> FontVariationTag
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
FontWeight
How thick or bold the strokes of a font appear.
Valid font weights range from 1 to 1000, inclusive.
Weights above 1000 are clamped to 1000.
A weight of 0 is treated as FontWeight::DEFAULT.
Legacy names from when most fonts weren’t variable fonts are included as const values, but are misleading if used in documentation and examples, as valid weights for variable fonts are all of the numbers from 1-1000, and not all fonts which are not variable fonts have those weights supplied. If you use a custom font that supplies only specific weights, that will be documented where you purchased the font.
<https://developer.mozilla.org/en-US/docs/Web/CSS/Reference/Properties/font-weight>
Fields
| Index | Type |
|---|---|
0 | u16 |
Functions
| Name | Summary |
|---|---|
new | Constructs a new instance of the type from a table of its fields. |
new
new(payload: Fields<FontWeight>) -> FontWeight
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
FontWidth
The visual width of a font as a ratio of its normal width, typically 0.5 to 2.0.
<https://docs.microsoft.com/en-us/typography/opentype/spec/os2#uswidthclass>
Fields
| Index | Type |
|---|---|
0 | f32 |
Functions
| Name | Summary |
|---|---|
new | Constructs a new instance of the type from a table of its fields. |
new
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
GenericFontFamily
Generic font families that are resolved through Parley’s font database.
Variants
| Variant |
|---|
Serif |
SansSerif |
Cursive |
Fantasy |
Monospace |
SystemUi |
UiSerif |
UiSansSerif |
UiMonospace |
UiRounded |
Emoji |
Math |
FangSong |
Functions
| Name | Summary |
|---|---|
new | Constructs a new instance of the type from a table of its fields. |
new
new(payload: Fields<GenericFontFamily>) -> GenericFontFamily
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
Variant Functions
| Name | Summary |
|---|---|
Cursive.new | |
Emoji.new | |
FangSong.new | |
Fantasy.new | |
Math.new | |
Monospace.new | |
SansSerif.new | |
Serif.new | |
SystemUi.new | |
UiMonospace.new | |
UiRounded.new | |
UiSansSerif.new | |
UiSerif.new |
Cursive.new
new(variant: EnumVariantRef, payload: Fields<GenericFontFamily::Cursive>) -> GenericFontFamily
Emoji.new
new(variant: EnumVariantRef, payload: Fields<GenericFontFamily::Emoji>) -> GenericFontFamily
FangSong.new
new(variant: EnumVariantRef, payload: Fields<GenericFontFamily::FangSong>) -> GenericFontFamily
Fantasy.new
new(variant: EnumVariantRef, payload: Fields<GenericFontFamily::Fantasy>) -> GenericFontFamily
Math.new
new(variant: EnumVariantRef, payload: Fields<GenericFontFamily::Math>) -> GenericFontFamily
Monospace.new
new(variant: EnumVariantRef, payload: Fields<GenericFontFamily::Monospace>) -> GenericFontFamily
SansSerif.new
new(variant: EnumVariantRef, payload: Fields<GenericFontFamily::SansSerif>) -> GenericFontFamily
Serif.new
new(variant: EnumVariantRef, payload: Fields<GenericFontFamily::Serif>) -> GenericFontFamily
SystemUi.new
new(variant: EnumVariantRef, payload: Fields<GenericFontFamily::SystemUi>) -> GenericFontFamily
UiMonospace.new
new(variant: EnumVariantRef, payload: Fields<GenericFontFamily::UiMonospace>) -> GenericFontFamily
UiRounded.new
new(variant: EnumVariantRef, payload: Fields<GenericFontFamily::UiRounded>) -> GenericFontFamily
UiSansSerif.new
new(variant: EnumVariantRef, payload: Fields<GenericFontFamily::UiSansSerif>) -> GenericFontFamily
UiSerif.new
new(variant: EnumVariantRef, payload: Fields<GenericFontFamily::UiSerif>) -> GenericFontFamily
Justify
Describes the horizontal alignment of multiple lines of text relative to each other.
This only affects the internal positioning of the lines of text within a text entity and does not affect the text entity’s position.
Has no affect on a single line text entity, unless used together with a
TextBounds component with an explicit width value.
Variants
| Variant |
|---|
Left |
Center |
Right |
Justified |
Start |
End |
Functions
| Name | Summary |
|---|---|
new | Constructs a new instance of the type from a table of its fields. |
new
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
Variant Functions
| Name | Summary |
|---|---|
Center.new | |
End.new | |
Justified.new | |
Left.new | |
Right.new | |
Start.new |
Center.new
new(variant: EnumVariantRef, payload: Fields<Justify::Center>) -> Justify
End.new
new(variant: EnumVariantRef, payload: Fields<Justify::End>) -> Justify
Justified.new
new(variant: EnumVariantRef, payload: Fields<Justify::Justified>) -> Justify
Left.new
new(variant: EnumVariantRef, payload: Fields<Justify::Left>) -> Justify
Right.new
new(variant: EnumVariantRef, payload: Fields<Justify::Right>) -> Justify
Start.new
new(variant: EnumVariantRef, payload: Fields<Justify::Start>) -> Justify
LineBreak
Determines how lines will be broken when preventing text from running out of bounds.
Variants
| Variant |
|---|
WordBoundary |
AnyCharacter |
WordOrCharacter |
NoWrap |
Functions
| Name | Summary |
|---|---|
new | Constructs a new instance of the type from a table of its fields. |
new
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
Variant Functions
AnyCharacter.new
new(variant: EnumVariantRef, payload: Fields<LineBreak::AnyCharacter>) -> LineBreak
NoWrap.new
new(variant: EnumVariantRef, payload: Fields<LineBreak::NoWrap>) -> LineBreak
WordBoundary.new
new(variant: EnumVariantRef, payload: Fields<LineBreak::WordBoundary>) -> LineBreak
WordOrCharacter.new
new(variant: EnumVariantRef, payload: Fields<LineBreak::WordOrCharacter>) -> LineBreak
RemSize
The root font size, in logical pixels.
Rem units always resolve against this one global resource, including
FontSize::Rem, LetterSpacing::Rem and Val::Rem.
Fields
| Index | Type |
|---|---|
0 | f32 |
Functions
| Name | Summary |
|---|---|
new | Constructs a new instance of the type from a table of its fields. |
new
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
Text
Component
The top-level UI text component.
Adding Text to an entity will pull in required components for setting up a UI text node.
The string in this component is the first ‘text span’ in a hierarchy of text spans that are collected into
a ComputedTextBlock. See TextSpan for the component used by children of entities with Text.
// Basic usage.
world.spawn(Text::new("hello world!"));
// With non-default style.
world.spawn((
Text::new("hello world!"),
TextFont {
font: font_handle.clone().into(),
font_size: FontSize::Px(60.0),
..Default::default()
},
TextColor(BLUE.into()),
));
// With text justification.
world.spawn((
Text::new("hello world\nand bevy!"),
TextLayout::justify(Justify::Center)
));
// With spans
world.spawn(Text::new("hello ")).with_children(|parent| {
parent.spawn(TextSpan::new("world"));
parent.spawn((TextSpan::new("!"), TextColor(BLUE.into())));
});
Fields
| Index | Type |
|---|---|
0 | String |
Functions
| Name | Summary |
|---|---|
new | Creates a new text component holding text. |
new
Creates a new text component holding text.
local Text = import_namespace("text").Text
local text = Text.new("hi")
assert(text:as_str() == "hi")
let Text = import_namespace("text").Text;
let text = Text.new("hi");
assert!(text.as_str() == "hi");
Methods
as_str
The text as a string.
set
Replaces the text.
Text2d
Component
The top-level 2D text component.
Adding Text2d to an entity will pull in required components for setting up 2d text.
Example usage.
The string in this component is the first ‘text span’ in a hierarchy of text spans that are collected into
a ComputedTextBlock. See TextSpan for the component used by children of entities with Text2d.
With Text2d the justify field of TextLayout only affects the internal alignment of a block of text and not its
relative position, which is controlled by the Anchor component.
This means that for a block of text consisting of only one line that doesn’t wrap, the justify field will have no effect.
// Basic usage.
world.spawn(Text2d::new("hello world!"));
// With non-default style.
world.spawn((
Text2d::new("hello world!"),
TextFont {
font: font_handle.clone().into(),
font_size: FontSize::Px(60.0),
..Default::default()
},
TextColor(BLUE.into()),
));
// With text justification.
world.spawn((
Text2d::new("hello world\nand bevy!"),
TextLayout::justify(Justify::Center)
));
// With spans
world.spawn(Text2d::new("hello ")).with_children(|parent| {
parent.spawn(TextSpan::new("world"));
parent.spawn((TextSpan::new("!"), TextColor(BLUE.into())));
});
Viewport-based FontSize variants for Text2d are resolved based on the primary window’s logical size.
Fields
| Index | Type |
|---|---|
0 | String |
Functions
| Name | Summary |
|---|---|
new | Creates a new 2d text component holding text. |
new
Creates a new 2d text component holding text.
Methods
as_str
The text as a string.
set
Replaces the text.
TextFont
Component
TextFont determines the style of a text span within a ComputedTextBlock, specifically
the font face, the font size, the line height, and the antialiasing method.
Fields
| Field | Type |
|---|---|
font | FontSource |
font_size | FontSize |
weight | FontWeight |
width | FontWidth |
style | FontStyle |
font_smoothing | FontSmoothing |
font_features | FontFeatures |
font_variations | FontVariations |
Functions
| Name | Summary |
|---|---|
from_font_size | Creates a text font with the default font face and the given size in logical pixels. |
new | Constructs a new instance of the type from a table of its fields. |
from_font_size
Creates a text font with the default font face and the given size in logical pixels.
local TextFont = import_namespace("text").TextFont
local font = TextFont.from_font_size(20.0)
assert(font:with_font_size(30.0) ~= nil)
let TextFont = import_namespace("text").TextFont;
let font = TextFont.from_font_size(20.0);
assert!(font.with_font_size(30.0) != ());
new
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
Methods
| Name | Summary |
|---|---|
with_font | A copy of the text font that uses the font face font. |
with_font_size | A copy of the text font with its size set to font_size in logical pixels. |
with_font
A copy of the text font that uses the font face font.
with_font_size
A copy of the text font with its size set to font_size in logical pixels.
TextLayout
Component
Component with text format settings for a block of text.
A block of text is composed of text spans, which each have a separate string value and TextFont. Text
spans associated with a text block are collected into ComputedTextBlock for layout, and then inserted
to TextLayoutInfo for rendering.
See Text2d in bevy_sprite for the core component of 2d text, and Text in bevy_ui for UI text.
Fields
Functions
| Name | Summary |
|---|---|
new | Constructs a new instance of the type from a table of its fields. |
new_with_justify | A text layout that aligns lines with the given justification and wraps at word boundaries. |
new_with_no_wrap | A text layout that never wraps soft line breaks, only explicit newlines start a new line. |
new
new(payload: Fields<TextLayout>) -> TextLayout
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
new_with_justify
new_with_justify(justify: Justify) -> TextLayout
A text layout that aligns lines with the given justification and wraps at word boundaries.
new_with_no_wrap
new_with_no_wrap() -> TextLayout
A text layout that never wraps soft line breaks, only explicit newlines start a new line.
TextSpan
Component
A span of text in a tree of spans.
A TextSpan is only valid when it exists as a child of a parent that has either Text or
Text2d. The parent’s Text / Text2d component contains the base text content. Any children
with TextSpan extend this text by appending their content to the parent’s text in sequence to
form a ComputedTextBlock. The parent’s TextLayout determines the layout of the block
but each node has its own TextFont and TextColor.
Fields
| Index | Type |
|---|---|
0 | String |
Functions
| Name | Summary |
|---|---|
new | Creates a new text span holding text. |
new
Creates a new text span holding text.
Methods
as_str
The text as a string.
set
Replaces the text.
time
The types and functions in the time namespace, as returned by import_namespace("time").
Types
| Type | Summary |
|---|---|
Duration | |
Fixed | The fixed timestep game clock following virtual time. |
Instant | |
Real | Real time clock representing elapsed wall clock time. |
Stopwatch | A Stopwatch is a struct that tracks elapsed time when started. |
Time<T> | A clock, T is the kind of clock, i.e. Virtual or Fixed. |
Timer | Tracks elapsed time. Enters the finished state once duration is reached. |
TimerMode | Specifies Timer behavior. |
Virtual | The virtual game clock representing game time. |
Values
| Name | Type |
|---|---|
TimeSystems | ReflectSystemSet |
Duration
Opaque: scripts can't access its fields, only its functions.
Functions
| Name | Summary |
|---|---|
from_micros | A duration of micros microseconds. |
from_millis | A duration of millis milliseconds. |
from_nanos | A duration of nanos nanoseconds. |
from_secs | A duration of secs seconds. Errors if secs is negative or not finite. |
new | Constructs a new instance of the type from a table of its fields. |
zero | A duration of no time. |
from_micros
A duration of micros microseconds.
from_millis
A duration of millis milliseconds.
from_nanos
A duration of nanos nanoseconds.
from_secs
A duration of secs seconds. Errors if secs is negative or not finite.
new
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
zero
zero() -> Duration
A duration of no time.
Methods
| Name | Summary |
|---|---|
as_millis | The duration in whole milliseconds, rounded down. |
as_secs | The duration in seconds. |
as_secs_f64 | The duration in seconds, as a double precision number. |
is_zero | Whether the duration is zero. |
as_millis
The duration in whole milliseconds, rounded down.
as_secs
The duration in seconds.
as_secs_f64
The duration in seconds, as a double precision number.
is_zero
Whether the duration is zero.
Operators
| Name | Summary |
|---|---|
add | The sum of two durations, capped at the largest representable duration. |
div | The duration divided by divisor. Errors if divisor is not positive. |
eq | Whether two durations are equal. |
lt | Whether this duration is shorter than other. |
mul | The duration scaled by factor. Errors if factor is negative or not finite. |
sub | The difference of two durations, or zero if rhs is the longer one. |
add
The sum of two durations, capped at the largest representable duration.
div
The duration divided by divisor. Errors if divisor is not positive.
eq
Whether two durations are equal.
lt
Whether this duration is shorter than other.
mul
The duration scaled by factor. Errors if factor is negative or not finite.
sub
The difference of two durations, or zero if rhs is the longer one.
Fixed
The fixed timestep game clock following virtual time.
A specialization of the Time structure. For method documentation, see
Time<Fixed>#impl-Time<Fixed>.
It is automatically inserted as a resource by
TimePlugin and updated based on
Time<Virtual>. The fixed clock is automatically set as the
generic Time resource during FixedUpdate
schedule processing.
The fixed timestep clock advances in fixed-size increments, which is extremely useful for writing logic (like physics) that should have consistent behavior, regardless of framerate.
The default timestep() is 64 hertz, or 15625
microseconds. This value was chosen because using 60 hertz has the potential
for a pathological interaction with the monitor refresh rate where the game
alternates between running two fixed timesteps and zero fixed timesteps per
frame (for example when running two fixed timesteps takes longer than a
frame). Additionally, the value is a power of two which losslessly converts
into f32 and f64.
To run a system on a fixed timestep, add it to one of the FixedMain
schedules, most commonly FixedUpdate.
This schedule is run a number of times between
PreUpdate and Update
according to the accumulated overstep() time divided by
the timestep(). This means the schedule may run 0, 1 or
more times during a single update (which typically corresponds to a rendered
frame).
Time<Fixed> and the generic Time resource will report a
delta() equal to timestep() and always
grow elapsed() by one timestep() per
iteration.
The fixed timestep clock follows the Time<Virtual> clock, which
means it is affected by pause(),
set_relative_speed() and
set_max_delta() from virtual time. If the virtual
clock is paused, the FixedUpdate schedule will
not run. It is guaranteed that the elapsed() time in
Time<Fixed> is always between the previous elapsed() and the current
elapsed() value in Time<Virtual>, so the values are compatible.
Changing the timestep size while the game is running should not normally be
done, as having a regular interval is the point of this schedule, but it may
be necessary for effects like “bullet-time” if the normal granularity of the
fixed timestep is too big for the slowed down time. In this case,
set_timestep() and be called to set a new value. The
new value will be used immediately for the next run of the
FixedUpdate schedule, meaning that it will affect
the delta() value for the very next
FixedUpdate, even if it is still during the same
frame. Any overstep() present in the accumulator will be
processed according to the new timestep() value.
Fields
Functions
| Name | Summary |
|---|---|
new | Constructs a new instance of the type from a table of its fields. |
new
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
Instant
Opaque: scripts can't access its fields, only its functions.
Functions
| Name | Summary |
|---|---|
new | Constructs a new instance of the type from a table of its fields. |
new
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
Methods
| Name | Summary |
|---|---|
duration_since | The duration from earlier to this instant, or zero if earlier is later. |
elapsed | The duration since this instant was taken. |
duration_since
The duration from earlier to this instant, or zero if earlier is later.
elapsed
The duration since this instant was taken.
Real
Real time clock representing elapsed wall clock time.
A specialization of the Time structure. For method documentation, see
Time<Real>#impl-Time<Real>.
It is automatically inserted as a resource by
TimePlugin and updated with time instants according
to TimeUpdateStrategy.^disclaimer
Note:
Using TimeUpdateStrategy::ManualDuration
allows for mocking the wall clock for testing purposes.
Besides this use case, it is not recommended to do this, as it will no longer
represent “wall clock” time as intended.
The delta() and elapsed() values of this
clock should be used for anything which deals specifically with real time
(wall clock time). It will not be affected by relative game speed
adjustments, pausing or other adjustments.^disclaimer
The clock does not count time from startup() to
first_update()) into elapsed, but instead will
start counting time from the first update call. delta() and
elapsed() will report zero on the first update as there
is no previous update instant. This means that a delta() of
zero must be handled without errors in application logic, as it may
theoretically also happen at other times.
Instants for startup(),
first_update() and
last_update() are recorded and accessible.
[`Time<Real>#impl-Time<Real>`](./timet.md) is only a *mock* of wall clock time.
Fields
Functions
| Name | Summary |
|---|---|
new | Constructs a new instance of the type from a table of its fields. |
new
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
Stopwatch
A Stopwatch is a struct that tracks elapsed time when started.
Note that in order to advance the stopwatch tick MUST be called.
Examples
use std::time::Duration;
let mut stopwatch = Stopwatch::new();
assert_eq!(stopwatch.elapsed_secs(), 0.0);
stopwatch.tick(Duration::from_secs_f32(1.0)); // tick one second
assert_eq!(stopwatch.elapsed_secs(), 1.0);
stopwatch.pause();
stopwatch.tick(Duration::from_secs_f32(1.0)); // paused stopwatches don't tick
assert_eq!(stopwatch.elapsed_secs(), 1.0);
stopwatch.reset(); // reset the stopwatch
assert!(stopwatch.is_paused());
assert_eq!(stopwatch.elapsed_secs(), 0.0);
Fields
Functions
| Name | Summary |
|---|---|
new | A stopwatch at zero, which is running. |
new
new() -> Stopwatch
A stopwatch at zero, which is running.
Methods
| Name | Summary |
|---|---|
elapsed | The time the stopwatch has run for. |
elapsed_secs | The time the stopwatch has run for, in seconds. |
is_paused | Whether the stopwatch is paused. |
pause | Stops the stopwatch from advancing until it is unpaused. |
reset | Sets the stopwatch back to zero elapsed time. |
set_elapsed | Sets the time the stopwatch has run for. |
tick | Advances the stopwatch by delta, given in seconds or as a duration. Errors if the time is negative. |
unpause | Resumes a paused stopwatch. |
elapsed
The time the stopwatch has run for.
elapsed_secs
The time the stopwatch has run for, in seconds.
is_paused
Whether the stopwatch is paused.
pause
pause(self: Stopwatch)
Stops the stopwatch from advancing until it is unpaused.
reset
reset(self: Stopwatch)
Sets the stopwatch back to zero elapsed time.
set_elapsed
Sets the time the stopwatch has run for.
tick
Advances the stopwatch by delta, given in seconds or as a duration. Errors if the time is negative.
unpause
unpause(self: Stopwatch)
Resumes a paused stopwatch.
Time<T>
Generic
A clock, T is the kind of clock, i.e. Virtual or Fixed.
Fields
| Field | Type |
|---|---|
context | T |
wrap_period | Duration |
delta | Duration |
delta_secs | f32 |
delta_secs_f64 | f64 |
elapsed | Duration |
elapsed_secs | f32 |
elapsed_secs_f64 | f64 |
elapsed_wrapped | Duration |
elapsed_secs_wrapped | f32 |
elapsed_secs_wrapped_f64 | f64 |
Instantiations
Time<Virtual>, Time<()>, Time<Real>, Time<Fixed>
Functions
| Name | Summary |
|---|---|
new | Constructs a new instance of the type from a table of its fields. |
new
On Time<Virtual>, Time<()>, Time<Real>, Time<Fixed>
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
Methods
| Name | Summary |
|---|---|
delta | The time that passed since the previous update. |
delta_secs | The time that passed since the previous update, in seconds. |
delta_secs_f64 | The time that passed since the previous update, in seconds as a double precision number. |
elapsed | The total time that passed since the clock started. |
elapsed_secs | The total time that passed since the clock started, in seconds. |
elapsed_secs_f64 | The total time that passed since the clock started, in seconds as a double precision number. |
elapsed_secs_wrapped | The total time that passed since the clock started, in seconds, wrapped to a period so it stays precise for long… |
is_paused | Whether the clock is paused. |
max_delta | The largest time a single update can add to the clock, longer frames are cut short. |
overstep_fraction | How far the clock is into the next fixed update step, from 0 to 1. |
pause | Stops the clock until it is unpaused, the time does not advance while paused. |
relative_speed | The speed of the clock relative to real time, 1 is real time and 2 is twice as fast. |
set_max_delta | Sets the largest time a single update can add to the clock. |
set_relative_speed | Sets the speed of the clock relative to real time. Errors if speed is negative or not finite. |
set_timestep_seconds | Sets the length of one fixed update step, in seconds. Errors if seconds is not positive or not finite. |
timestep | The length of one fixed update step. |
unpause | Resumes a paused clock. |
delta
On Time<Virtual>, Time<()>, Time<Real>, Time<Fixed>
The time that passed since the previous update.
delta_secs
On Time<Virtual>, Time<()>, Time<Real>, Time<Fixed>
The time that passed since the previous update, in seconds.
delta_secs_f64
On Time<Virtual>, Time<()>, Time<Real>, Time<Fixed>
The time that passed since the previous update, in seconds as a double precision number.
elapsed
On Time<Virtual>, Time<()>, Time<Real>, Time<Fixed>
The total time that passed since the clock started.
elapsed_secs
On Time<Virtual>, Time<()>, Time<Real>, Time<Fixed>
The total time that passed since the clock started, in seconds.
elapsed_secs_f64
On Time<Virtual>, Time<()>, Time<Real>, Time<Fixed>
The total time that passed since the clock started, in seconds as a double precision number.
elapsed_secs_wrapped
On Time<Virtual>, Time<()>, Time<Real>, Time<Fixed>
The total time that passed since the clock started, in seconds, wrapped to a period so it stays precise for long running apps.
is_paused
On Time<Virtual>
Whether the clock is paused.
max_delta
On Time<Virtual>
The largest time a single update can add to the clock, longer frames are cut short.
overstep_fraction
On Time<Fixed>
How far the clock is into the next fixed update step, from 0 to 1.
pause
On Time<Virtual>
Stops the clock until it is unpaused, the time does not advance while paused.
relative_speed
On Time<Virtual>
The speed of the clock relative to real time, 1 is real time and 2 is twice as fast.
set_max_delta
On Time<Virtual>
Sets the largest time a single update can add to the clock.
set_relative_speed
On Time<Virtual>
Sets the speed of the clock relative to real time. Errors if speed is negative or not finite.
set_timestep_seconds
On Time<Fixed>
Sets the length of one fixed update step, in seconds. Errors if seconds is not positive or not finite.
timestep
On Time<Fixed>
The length of one fixed update step.
unpause
On Time<Virtual>
Resumes a paused clock.
Timer
Tracks elapsed time. Enters the finished state once duration is reached.
Note that in order to advance the timer tick MUST be called.
Timer modes
There are two timer modes (TimerMode):
- Non repeating timers will stop tracking and stay in the finished state until reset.
- Repeating timers will only be in the finished state on each tick
durationis reached or exceeded, and can still be reset at any given point.
Pausing timers
You can pause a timer using Timer::pause. Paused timers will not have elapsed time increased.
Elapsing multiple times a frame
Repeating timers might elapse multiple times per frame if the time is advanced by more than the timer duration.
You can check how many times a timer elapsed each tick with Timer::times_finished_this_tick.
For non-repeating timers, this will always be 0 or 1.
Fields
| Field | Type |
|---|---|
stopwatch | Stopwatch |
duration | Duration |
mode | TimerMode |
finished | bool |
times_finished_this_tick | u32 |
Functions
| Name | Summary |
|---|---|
from_seconds | A timer which runs for secs seconds, in mode. Errors if secs is negative or not finite. |
new | A timer which runs for duration, in mode. |
from_seconds
A timer which runs for secs seconds, in mode. Errors if secs is negative or not finite.
local Timer = import_namespace("time").Timer
local TimerMode = import_namespace("time").TimerMode
local timer = Timer.from_seconds(2, TimerMode.Repeating)
timer:tick(1)
assert(not timer:finished())
timer:tick(1.5)
assert(timer:finished())
let Timer = import_namespace("time").Timer;
let TimerMode = import_namespace("time").TimerMode;
let timer = Timer.from_seconds(2.0, TimerMode.Repeating);
timer.tick(1.0);
assert!(!timer.finished());
timer.tick(1.5);
assert!(timer.finished());
new
A timer which runs for duration, in mode.
Methods
| Name | Summary |
|---|---|
almost_finish | Makes the timer finish on its next tick. |
duration | The duration the timer runs for. |
elapsed | The time the timer has run for. |
elapsed_secs | The time the timer has run for, in seconds. |
finished | Whether the timer has run for its full duration. |
fraction | How much of the duration has passed, from 0 to 1. |
fraction_remaining | How much of the duration is left, from 0 to 1. |
just_finished | Whether the timer finished during the last tick. |
mode | Whether the timer runs once, or repeats. |
pause | Stops the timer from advancing until it is unpaused. |
paused | Whether the timer is paused. |
remaining | The time left until the timer finishes. |
remaining_secs | The time left until the timer finishes, in seconds. |
reset | Sets the timer back to zero elapsed time, keeping its duration and mode. |
set_duration | Sets the duration the timer runs for. |
set_elapsed | Sets the time the timer has run for. |
set_mode | Sets whether the timer runs once, or repeats. |
tick | Advances the timer by delta, given in seconds or as a duration. Errors if the time is negative. |
times_finished_this_tick | How many times the timer finished during the last tick, which can be more than once for a short timer. |
unpause | Resumes a paused timer. |
almost_finish
almost_finish(self: Timer)
Makes the timer finish on its next tick.
duration
The duration the timer runs for.
elapsed
The time the timer has run for.
elapsed_secs
The time the timer has run for, in seconds.
finished
Whether the timer has run for its full duration.
fraction
How much of the duration has passed, from 0 to 1.
fraction_remaining
How much of the duration is left, from 0 to 1.
just_finished
Whether the timer finished during the last tick.
mode
Whether the timer runs once, or repeats.
pause
pause(self: Timer)
Stops the timer from advancing until it is unpaused.
paused
Whether the timer is paused.
remaining
The time left until the timer finishes.
remaining_secs
The time left until the timer finishes, in seconds.
reset
reset(self: Timer)
Sets the timer back to zero elapsed time, keeping its duration and mode.
set_duration
Sets the duration the timer runs for.
set_elapsed
Sets the time the timer has run for.
set_mode
Sets whether the timer runs once, or repeats.
tick
Advances the timer by delta, given in seconds or as a duration. Errors if the time is negative.
times_finished_this_tick
How many times the timer finished during the last tick, which can be more than once for a short timer.
unpause
unpause(self: Timer)
Resumes a paused timer.
TimerMode
Specifies Timer behavior.
Variants
| Variant |
|---|
Once |
Repeating |
Functions
| Name | Summary |
|---|---|
new | Constructs a new instance of the type from a table of its fields. |
new
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
Variant Functions
| Name | Summary |
|---|---|
Once.new | |
Repeating.new |
Once.new
new(variant: EnumVariantRef, payload: Fields<TimerMode::Once>) -> TimerMode
Repeating.new
new(variant: EnumVariantRef, payload: Fields<TimerMode::Repeating>) -> TimerMode
Virtual
The virtual game clock representing game time.
A specialization of the Time structure. For method documentation, see
Time<Virtual>#impl-Time<Virtual>.
Normally used as Time<Virtual>. It is automatically inserted as a resource
by TimePlugin and updated based on
Time<Real>. The virtual clock is automatically set as the default
generic Time resource for the update.
The virtual clock differs from real time clock in that it can be paused, sped up and slowed down. It also limits how much it can advance in a single update in order to prevent unexpected behavior in cases where updates do not happen at regular intervals (e.g. coming back after the program was suspended a long time).
The virtual clock can be paused by calling pause(),
unpaused by calling unpause(), or toggled by calling
toggle(). When the game clock is
paused delta() will be zero on each update, and
elapsed() will not grow.
effective_speed() will return 0.0. Calling
pause() will not affect value the delta()
value for the update currently being processed.
The speed of the virtual clock can be changed by calling
set_relative_speed(). A value of 2.0 means
that virtual clock should advance twice as fast as real time, meaning that
delta() values will be double of what
Time<Real>::delta() reports and
elapsed() will go twice as fast as
Time<Real>::elapsed(). Calling
set_relative_speed() will not affect the
delta() value for the update currently being processed.
The maximum amount of delta time that can be added by a single update can be
set by set_max_delta(). This value serves a dual
purpose in the virtual clock.
If the game temporarily freezes due to any reason, such as disk access, a
blocking system call, or operating system level suspend, reporting the full
elapsed delta time is likely to cause bugs in game logic. Usually if a
laptop is suspended for an hour, it doesn’t make sense to try to simulate
the game logic for the elapsed hour when resuming. Instead it is better to
lose the extra time and pretend a shorter duration of time passed. Setting
max_delta() to a relatively short time means that the
impact on game logic will be minimal.
If the game lags for some reason, meaning that it will take a longer time to compute a frame than the real time that passes during the computation, then we would fall behind in processing virtual time. If this situation persists, and computing a frame takes longer depending on how much virtual time has passed, the game would enter a “death spiral” where computing each frame takes longer and longer and the game will appear to freeze. By limiting the maximum time that can be added at once, we also limit the amount of virtual time the game needs to compute for each frame. This means that the game will run slow, and it will run slower than real time, but it will not freeze and it will recover as soon as computation becomes fast again.
You should set max_delta() to a value that is
approximately the minimum FPS your game should have even if heavily lagged
for a moment. The actual FPS when lagged will be somewhat lower than this,
depending on how much more time it takes to compute a frame compared to real
time. You should also consider how stable your FPS is, as the limit will
also dictate how big of an FPS drop you can accept without losing time and
falling behind real time.
Fields
Functions
| Name | Summary |
|---|---|
new | Constructs a new instance of the type from a table of its fields. |
new
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
transform
The types and functions in the transform namespace, as returned by import_namespace("transform").
Types
| Type | Summary |
|---|---|
GlobalTransform | GlobalTransform is an affine transformation from entity-local coordinates to worldspace coordinates. |
Transform | Describe the position of an entity. If the entity has a parent, the position is relative to its parent position. |
GlobalTransform
Component
GlobalTransform is an affine transformation from entity-local coordinates to worldspace coordinates.
You cannot directly mutate GlobalTransform; instead, you change an entity’s transform by manipulating
its Transform, which indirectly causes Bevy to update its GlobalTransform.
- To get the global transform of an entity, you should get its
GlobalTransform. - For transform hierarchies to work correctly, you must have both a
Transformand aGlobalTransform.GlobalTransformis automatically inserted wheneverTransformis inserted.
Transform and GlobalTransform
Transform transforms an entity relative to its parent’s reference frame, or relative to world space coordinates,
if it doesn’t have a ChildOf component.
GlobalTransform is managed by Bevy; it is computed by successively applying the Transform of each ancestor
entity which has a Transform. This is done automatically by Bevy-internal systems in the TransformSystems::Propagate
system set.
This system runs during PostUpdate. If you
update the Transform of an entity in this schedule or after, you will notice a 1 frame lag
before the GlobalTransform is updated.
Examples
transform
Fields
| Index | Type |
|---|---|
0 | Affine3A |
Functions
| Name | Summary |
|---|---|
from_xyz | A transform at the position x, y, z, with no rotation and a scale of 1. |
identity | The identity transform, which maps every point to itself. |
new | Constructs a new instance of the type from a table of its fields. |
from_xyz
from_xyz(x: f32, y: f32, z: f32) -> GlobalTransform
A transform at the position x, y, z, with no rotation and a scale of 1.
identity
identity() -> GlobalTransform
The identity transform, which maps every point to itself.
new
new(payload: Fields<GlobalTransform>) -> GlobalTransform
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
Methods
| Name | Summary |
|---|---|
back | The direction opposite to forward, +z in local space. |
compute_transform | The transform as a Transform, with the same position, rotation and scale. |
down | The local down direction, -y. |
forward | The direction the transform faces, -z in local space. |
left | The direction to the local left, -x in local space. |
reparented_to | The local Transform that gives this world transform when parented to parent. |
right | The direction to the local right, +x in local space. |
rotation | The rotation in world space. |
scale | The scale in world space. |
to_matrix | The matrix equivalent to this transform. |
transform_point | Applies the transform to a point in local space, giving its world space position. |
translation | The position in world space. |
up | The local up direction, +y. |
back
back(self: GlobalTransform) -> Vec3
The direction opposite to forward, +z in local space.
compute_transform
compute_transform(self: GlobalTransform) -> Transform
The transform as a Transform, with the same position, rotation and scale.
down
down(self: GlobalTransform) -> Vec3
The local down direction, -y.
forward
forward(self: GlobalTransform) -> Vec3
The direction the transform faces, -z in local space.
left
left(self: GlobalTransform) -> Vec3
The direction to the local left, -x in local space.
reparented_to
reparented_to(self: GlobalTransform, parent: GlobalTransform) -> Transform
The local Transform that gives this world transform when parented to parent.
right
right(self: GlobalTransform) -> Vec3
The direction to the local right, +x in local space.
rotation
rotation(self: GlobalTransform) -> Quat
The rotation in world space.
scale
scale(self: GlobalTransform) -> Vec3
The scale in world space.
to_matrix
to_matrix(self: GlobalTransform) -> Mat4
The matrix equivalent to this transform.
transform_point
transform_point(self: GlobalTransform, point: Vec3) -> Vec3
Applies the transform to a point in local space, giving its world space position.
translation
translation(self: GlobalTransform) -> Vec3
The position in world space.
up
up(self: GlobalTransform) -> Vec3
The local up direction, +y.
Operators
| Name | Summary |
|---|---|
eq | Whether both transforms have exactly the same components. |
mul | Composes two transforms when given a global transform, or applies a local transform to this one. |
eq
eq(self: GlobalTransform, other: GlobalTransform) -> bool
Whether both transforms have exactly the same components.
mul
mul(self: GlobalTransform, rhs: GlobalTransform | Transform) -> GlobalTransform
Composes two transforms when given a global transform, or applies a local transform to this one.
Transform
Component
Describe the position of an entity. If the entity has a parent, the position is relative to its parent position.
- To place or move an entity, you should set its
Transform. - To get the global transform of an entity, you should get its
GlobalTransform. - To be displayed, an entity must have both a
Transformand aGlobalTransform.GlobalTransformis automatically inserted wheneverTransformis inserted.
Transforms compose from right to left: if t1 and t2 are transforms, then t1 * t2
corresponds to applying t2 first, then applying t1.
Transform and GlobalTransform
Transform is the position of an entity relative to its parent position, or the reference
frame if it doesn’t have a ChildOf component.
GlobalTransform is the position of an entity relative to the reference frame.
GlobalTransform is updated from Transform in the TransformSystems::Propagate
system set.
This system runs during PostUpdate. If you
update the Transform of an entity during this set or after, you will notice a 1 frame lag
before the GlobalTransform is updated.
Examples
transform
Fields
Functions
| Name | Summary |
|---|---|
from_matrix | The transform described by a 4x4 matrix. |
from_rotation | A transform with the given rotation. |
from_scale | A transform with the given scale. |
from_translation | A transform at the given position. |
from_xyz | A transform at the position x, y, z. |
identity | The transform with no translation, no rotation and a scale of 1. |
new | Constructs a new instance of the type from a table of its fields. |
from_matrix
The transform described by a 4x4 matrix.
from_rotation
A transform with the given rotation.
from_scale
A transform with the given scale.
from_translation
A transform at the given position.
from_xyz
A transform at the position x, y, z.
local Transform = import_namespace("transform").Transform
local t = Transform.from_xyz(1, 2, 3)
assert(t.translation.x == 1)
let Transform = import_namespace("transform").Transform;
let t = Transform.from_xyz(1.0, 2.0, 3.0);
assert!(t.translation.x == 1.0);
identity
identity() -> Transform
The transform with no translation, no rotation and a scale of 1.
new
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
Methods
| Name | Summary |
|---|---|
back | The direction opposite to forward, +z in local space. |
down | The local down direction, -y. |
forward | The direction the transform faces, -z in local space. |
is_finite | Whether every component is a finite number. |
left | The direction to the local left, -x in local space. |
local_x | The local x axis, as a direction. |
local_y | The local y axis, as a direction. |
local_z | The local z axis, as a direction. |
look_at | Rotates this transform to face target, with up as the up direction. Errors if up is zero. |
look_to | Rotates this transform to face along direction, with up as the up direction. Errors if either vector is zero. |
looking_at | A copy of this transform rotated to face target, with up as the up direction. Errors if up is zero. |
looking_to | A copy of this transform rotated to face along direction, with up as the up direction. |
mul_transform | Composes this transform with other, applying other first. |
right | The direction to the local right, +x in local space. |
rotate | Rotates this transform by rotation, in the parent’s space. |
rotate_around | Rotates this transform by rotation around point, moving it along the circle. |
rotate_axis | Rotates this transform by angle radians around axis. Errors if the axis is zero. |
rotate_local | Rotates this transform by rotation, in its own local space. |
rotate_local_x | Rotates this transform by angle radians around its local x axis. |
rotate_local_y | Rotates this transform by angle radians around its local y axis. |
rotate_local_z | Rotates this transform by angle radians around its local z axis. |
rotate_x | Rotates this transform by angle radians around the x axis. |
rotate_y | Rotates this transform by angle radians around the y axis. |
rotate_z | Rotates this transform by angle radians around the z axis. |
to_matrix | The matrix equivalent to this transform. |
transform_point | Applies the transform to a point: scales, rotates, then translates it. |
translate_around | Moves this transform around point by rotation, without changing its rotation. |
up | The local up direction, +y. |
with_rotation | A copy of this transform with a new rotation. |
with_scale | A copy of this transform with a new scale. |
with_translation | A copy of this transform with a new position. |
back
The direction opposite to forward, +z in local space.
down
The local down direction, -y.
forward
The direction the transform faces, -z in local space.
is_finite
Whether every component is a finite number.
left
The direction to the local left, -x in local space.
local_x
The local x axis, as a direction.
local_y
The local y axis, as a direction.
local_z
The local z axis, as a direction.
look_at
Rotates this transform to face target, with up as the up direction. Errors if up is zero.
look_to
Rotates this transform to face along direction, with up as the up direction. Errors if either vector is zero.
looking_at
A copy of this transform rotated to face target, with up as the up direction. Errors if up is zero.
looking_to
A copy of this transform rotated to face along direction, with up as the up direction. Errors if either vector is zero.
mul_transform
Composes this transform with other, applying other first.
right
The direction to the local right, +x in local space.
rotate
Rotates this transform by rotation, in the parent’s space.
rotate_around
Rotates this transform by rotation around point, moving it along the circle.
rotate_axis
Rotates this transform by angle radians around axis. Errors if the axis is zero.
rotate_local
Rotates this transform by rotation, in its own local space.
rotate_local_x
Rotates this transform by angle radians around its local x axis.
rotate_local_y
Rotates this transform by angle radians around its local y axis.
rotate_local_z
Rotates this transform by angle radians around its local z axis.
rotate_x
Rotates this transform by angle radians around the x axis.
rotate_y
Rotates this transform by angle radians around the y axis.
rotate_z
Rotates this transform by angle radians around the z axis.
to_matrix
The matrix equivalent to this transform.
transform_point
Applies the transform to a point: scales, rotates, then translates it.
translate_around
Moves this transform around point by rotation, without changing its rotation.
up
The local up direction, +y.
with_rotation
A copy of this transform with a new rotation.
with_scale
A copy of this transform with a new scale.
with_translation
A copy of this transform with a new position.
Operators
| Name | Summary |
|---|---|
eq | Whether both transforms have exactly the same components. |
mul | Composes two transforms when given a transform, or transforms a point when given a Vec3. |
eq
Whether both transforms have exactly the same components.
mul
Composes two transforms when given a transform, or transforms a point when given a Vec3.
transform.TransformSystems
The types and functions in the transform.TransformSystems namespace, as returned by import_namespace("transform.TransformSystems").
Values
| Name | Type |
|---|---|
Propagate | ReflectSystemSet |
ui
The types and functions in the ui namespace, as returned by import_namespace("ui").
Types
| Type | Summary |
|---|---|
AlignContent | Used to control how items are distributed. |
AlignItems | Used to control how each individual item is aligned by default within the space they’re given. |
AlignSelf | Used to control how the specified item is aligned within the space it’s given. |
BackgroundColor | The background color of the node |
BorderColor | The border color of the UI node. |
BorderRadius | Used to add rounded corners to a UI node. |
BoxSizing | Which part of a Node’s box length styles like width and height control |
ComputedNode | Provides the computed size and layout properties of a UI Node. |
CornerRadius | The horizontal and vertical radii of a rounded corner’s elliptical arc. |
Display | Defines the layout model used by this node. |
FlexDirection | Defines how flexbox items are ordered within a flexbox |
FlexWrap | Defines if flexbox items appear on a single line or on multiple lines |
GlobalZIndex | GlobalZIndex allows a Node entity anywhere in the UI hierarchy to escape the implicit draw ordering of the UI’s… |
GridAutoFlow | Controls whether grid items are placed row-wise or column-wise as well as whether the sparse or dense packing algorithm… |
GridPlacement | Represents the position of a grid item in a single axis. |
GridTrack | A GridTrack is a Row or Column of a CSS Grid. |
GridTrackRepetition | How many times to repeat a repeated grid track |
ImageNode | A UI Node that renders an image. |
InlineDirection | Sets the inline axis direction (LTR or RTL) used for layout. |
JustifyContent | Used to control how items are distributed. |
JustifyItems | Used to control how each individual item is aligned by default within the space they’re given. |
JustifySelf | Used to control how the specified item is aligned within the space it’s given. |
MaxTrackSizingFunction | |
MinTrackSizingFunction | |
Node | The base component for UI entities. It describes UI layout and style properties. |
NodeImageMode | Controls how the image is altered to fit within the layout and how the layout algorithm determines the space in the… |
Outline | The Outline component adds an outline outside the edge of a UI node. Outlines do not take up space in the layout. |
Overflow | Whether to show or hide overflowing items |
OverflowAxis | Whether to show or hide overflowing items |
OverflowClipMargin | The bounds of the visible area when a UI node is clipped. |
PositionType | The strategy used to position this node |
RepeatedGridTrack | Represents a possibly repeated GridTrack. |
ResolvedBorderRadius | Represents the resolved border radii values for a UI node. |
UiRect | A type which is commonly used to define margins, paddings and borders. |
Val | Represents the possible value types for layout properties. |
VisualBox | Used to determine which region of a UI node is used for visual bounds. |
ZIndex | Indicates that this Node entity’s front-to-back ordering is not controlled solely by its location in the UI… |
Values
| Name | Type |
|---|---|
AccessibilityUiSystems | ReflectSystemSet |
AlignContent
Used to control how items are distributed.
- For Flexbox containers, controls alignment of lines if
flex_wrapis set toFlexWrap::Wrapand there are multiple lines of items. - For CSS Grid containers, controls alignment of grid rows.
Safe alignments
Safe alignments will fall back to Self::Start if aligning the items would overflow the container, so
the start of the content stays visible.
https://developer.mozilla.org/en-US/docs/Web/CSS/align-content
Variants
| Variant |
|---|
Default |
Start |
StartSafe |
End |
EndSafe |
FlexStart |
FlexStartSafe |
FlexEnd |
FlexEndSafe |
Center |
CenterSafe |
Stretch |
SpaceBetween |
SpaceEvenly |
SpaceAround |
Functions
| Name | Summary |
|---|---|
new | Constructs a new instance of the type from a table of its fields. |
new
new(payload: Fields<AlignContent>) -> AlignContent
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
Variant Functions
Center.new
new(variant: EnumVariantRef, payload: Fields<AlignContent::Center>) -> AlignContent
CenterSafe.new
new(variant: EnumVariantRef, payload: Fields<AlignContent::CenterSafe>) -> AlignContent
Default.new
new(variant: EnumVariantRef, payload: Fields<AlignContent::Default>) -> AlignContent
End.new
new(variant: EnumVariantRef, payload: Fields<AlignContent::End>) -> AlignContent
EndSafe.new
new(variant: EnumVariantRef, payload: Fields<AlignContent::EndSafe>) -> AlignContent
FlexEnd.new
new(variant: EnumVariantRef, payload: Fields<AlignContent::FlexEnd>) -> AlignContent
FlexEndSafe.new
new(variant: EnumVariantRef, payload: Fields<AlignContent::FlexEndSafe>) -> AlignContent
FlexStart.new
new(variant: EnumVariantRef, payload: Fields<AlignContent::FlexStart>) -> AlignContent
FlexStartSafe.new
new(variant: EnumVariantRef, payload: Fields<AlignContent::FlexStartSafe>) -> AlignContent
SpaceAround.new
new(variant: EnumVariantRef, payload: Fields<AlignContent::SpaceAround>) -> AlignContent
SpaceBetween.new
new(variant: EnumVariantRef, payload: Fields<AlignContent::SpaceBetween>) -> AlignContent
SpaceEvenly.new
new(variant: EnumVariantRef, payload: Fields<AlignContent::SpaceEvenly>) -> AlignContent
Start.new
new(variant: EnumVariantRef, payload: Fields<AlignContent::Start>) -> AlignContent
StartSafe.new
new(variant: EnumVariantRef, payload: Fields<AlignContent::StartSafe>) -> AlignContent
Stretch.new
new(variant: EnumVariantRef, payload: Fields<AlignContent::Stretch>) -> AlignContent
AlignItems
Used to control how each individual item is aligned by default within the space they’re given.
- For Flexbox containers, sets default cross axis alignment of the child items.
- For CSS Grid containers, controls block (vertical) axis alignment of children of this grid container within their grid areas.
Safe alignments
Safe alignments will fall back to Self::Start if aligning the items would overflow the container, so
the start of the content stays visible.
https://developer.mozilla.org/en-US/docs/Web/CSS/align-items
Variants
| Variant |
|---|
Default |
Start |
StartSafe |
End |
EndSafe |
FlexStart |
FlexStartSafe |
FlexEnd |
FlexEndSafe |
Center |
CenterSafe |
Baseline |
Stretch |
Functions
| Name | Summary |
|---|---|
new | Constructs a new instance of the type from a table of its fields. |
new
new(payload: Fields<AlignItems>) -> AlignItems
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
Variant Functions
| Name | Summary |
|---|---|
Baseline.new | |
Center.new | |
CenterSafe.new | |
Default.new | |
End.new | |
EndSafe.new | |
FlexEnd.new | |
FlexEndSafe.new | |
FlexStart.new | |
FlexStartSafe.new | |
Start.new | |
StartSafe.new | |
Stretch.new |
Baseline.new
new(variant: EnumVariantRef, payload: Fields<AlignItems::Baseline>) -> AlignItems
Center.new
new(variant: EnumVariantRef, payload: Fields<AlignItems::Center>) -> AlignItems
CenterSafe.new
new(variant: EnumVariantRef, payload: Fields<AlignItems::CenterSafe>) -> AlignItems
Default.new
new(variant: EnumVariantRef, payload: Fields<AlignItems::Default>) -> AlignItems
End.new
new(variant: EnumVariantRef, payload: Fields<AlignItems::End>) -> AlignItems
EndSafe.new
new(variant: EnumVariantRef, payload: Fields<AlignItems::EndSafe>) -> AlignItems
FlexEnd.new
new(variant: EnumVariantRef, payload: Fields<AlignItems::FlexEnd>) -> AlignItems
FlexEndSafe.new
new(variant: EnumVariantRef, payload: Fields<AlignItems::FlexEndSafe>) -> AlignItems
FlexStart.new
new(variant: EnumVariantRef, payload: Fields<AlignItems::FlexStart>) -> AlignItems
FlexStartSafe.new
new(variant: EnumVariantRef, payload: Fields<AlignItems::FlexStartSafe>) -> AlignItems
Start.new
new(variant: EnumVariantRef, payload: Fields<AlignItems::Start>) -> AlignItems
StartSafe.new
new(variant: EnumVariantRef, payload: Fields<AlignItems::StartSafe>) -> AlignItems
Stretch.new
new(variant: EnumVariantRef, payload: Fields<AlignItems::Stretch>) -> AlignItems
AlignSelf
Used to control how the specified item is aligned within the space it’s given.
- For Flexbox items, controls cross axis alignment of the item.
- For CSS Grid items, controls block (vertical) axis alignment of a grid item within its grid area.
Safe alignments
Safe alignments will fall back to Self::Start if aligning the items would overflow the container, so
the start of the content stays visible.
https://developer.mozilla.org/en-US/docs/Web/CSS/align-self
Variants
| Variant |
|---|
Auto |
Start |
StartSafe |
End |
EndSafe |
FlexStart |
FlexStartSafe |
FlexEnd |
FlexEndSafe |
Center |
CenterSafe |
Baseline |
Stretch |
Functions
| Name | Summary |
|---|---|
new | Constructs a new instance of the type from a table of its fields. |
new
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
Variant Functions
| Name | Summary |
|---|---|
Auto.new | |
Baseline.new | |
Center.new | |
CenterSafe.new | |
End.new | |
EndSafe.new | |
FlexEnd.new | |
FlexEndSafe.new | |
FlexStart.new | |
FlexStartSafe.new | |
Start.new | |
StartSafe.new | |
Stretch.new |
Auto.new
new(variant: EnumVariantRef, payload: Fields<AlignSelf::Auto>) -> AlignSelf
Baseline.new
new(variant: EnumVariantRef, payload: Fields<AlignSelf::Baseline>) -> AlignSelf
Center.new
new(variant: EnumVariantRef, payload: Fields<AlignSelf::Center>) -> AlignSelf
CenterSafe.new
new(variant: EnumVariantRef, payload: Fields<AlignSelf::CenterSafe>) -> AlignSelf
End.new
new(variant: EnumVariantRef, payload: Fields<AlignSelf::End>) -> AlignSelf
EndSafe.new
new(variant: EnumVariantRef, payload: Fields<AlignSelf::EndSafe>) -> AlignSelf
FlexEnd.new
new(variant: EnumVariantRef, payload: Fields<AlignSelf::FlexEnd>) -> AlignSelf
FlexEndSafe.new
new(variant: EnumVariantRef, payload: Fields<AlignSelf::FlexEndSafe>) -> AlignSelf
FlexStart.new
new(variant: EnumVariantRef, payload: Fields<AlignSelf::FlexStart>) -> AlignSelf
FlexStartSafe.new
new(variant: EnumVariantRef, payload: Fields<AlignSelf::FlexStartSafe>) -> AlignSelf
Start.new
new(variant: EnumVariantRef, payload: Fields<AlignSelf::Start>) -> AlignSelf
StartSafe.new
new(variant: EnumVariantRef, payload: Fields<AlignSelf::StartSafe>) -> AlignSelf
Stretch.new
new(variant: EnumVariantRef, payload: Fields<AlignSelf::Stretch>) -> AlignSelf
BackgroundColor
Component
The background color of the node
This serves as the “fill” color.
Fields
| Index | Type |
|---|---|
0 | Color |
Functions
| Name | Summary |
|---|---|
new | Constructs a new instance of the type from a table of its fields. |
new
new(payload: Fields<BackgroundColor>) -> BackgroundColor
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
BorderColor
Component
The border color of the UI node.
Fields
Functions
| Name | Summary |
|---|---|
all | A border with the same color on all four sides. |
new | Constructs a new instance of the type from a table of its fields. |
all
all(color: Color) -> BorderColor
A border with the same color on all four sides.
new
new(payload: Fields<BorderColor>) -> BorderColor
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
BorderRadius
Used to add rounded corners to a UI node. You can set a UI node to have uniformly rounded corners, elliptical corners, or specify a different radius for each corner. If a given radius exceeds half the length of the node’s height or width, the radius will be calculated as half the height or width.
Percentage horizontal and vertical values are based on the node’s width and height, respectively.
Example
fn setup_ui(mut commands: Commands) {
commands.spawn((
Node {
width: Val::Px(100.),
height: Val::Px(100.),
border: UiRect::all(Val::Px(2.)),
border_radius: BorderRadius {
// rounded corners, x and y radii equal
top_left: CornerRadius::circular(px(10.)),
top_right: percent(20.).into(),
// elliptical corner
bottom_right: CornerRadius::new(px(30.), px(20.)),
bottom_left: CornerRadius { x: px(10.), y: px(40.) },
},
..Default::default()
},
BackgroundColor(BLUE.into()),
));
}
https://developer.mozilla.org/en-US/docs/Web/CSS/border-radius
Fields
| Field | Type |
|---|---|
top_left | CornerRadius |
top_right | CornerRadius |
bottom_right | CornerRadius |
bottom_left | CornerRadius |
Functions
| Name | Summary |
|---|---|
all | Every corner rounded by the same length. |
max | The most rounding possible, which makes the node a capsule, or a circle if it is square. |
new | Constructs a new instance of the type from a table of its fields. |
percent | Each corner rounded by a percentage, in the order top left, top right, bottom right, bottom left. |
px | Each corner rounded by a length in logical pixels, in the order top left, top right, bottom right, bottom left. |
zero | No rounding, so every corner is a right angle. |
all
all(radius: Val) -> BorderRadius
Every corner rounded by the same length.
max
max() -> BorderRadius
The most rounding possible, which makes the node a capsule, or a circle if it is square.
new
new(payload: Fields<BorderRadius>) -> BorderRadius
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
percent
percent(top_left: f32, top_right: f32, bottom_right: f32, bottom_left: f32) -> BorderRadius
Each corner rounded by a percentage, in the order top left, top right, bottom right, bottom left.
px
px(top_left: f32, top_right: f32, bottom_right: f32, bottom_left: f32) -> BorderRadius
Each corner rounded by a length in logical pixels, in the order top left, top right, bottom right, bottom left.
zero
zero() -> BorderRadius
No rounding, so every corner is a right angle.
BoxSizing
Which part of a Node’s box length styles like width and height control
See: https://developer.mozilla.org/en-US/docs/Web/CSS/box-sizing
Variants
| Variant |
|---|
BorderBox |
ContentBox |
Functions
| Name | Summary |
|---|---|
new | Constructs a new instance of the type from a table of its fields. |
new
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
Variant Functions
| Name | Summary |
|---|---|
BorderBox.new | |
ContentBox.new |
BorderBox.new
new(variant: EnumVariantRef, payload: Fields<BoxSizing::BorderBox>) -> BoxSizing
ContentBox.new
new(variant: EnumVariantRef, payload: Fields<BoxSizing::ContentBox>) -> BoxSizing
ComputedNode
Component
Provides the computed size and layout properties of a UI Node.
All of the fields are automatically calculated by ui_layout_system
during PostUpdate in the UiSystems::Layout set.
The fields are measured in physical pixels.
You can multiply by the inverse_scale_factor field to convert back to logical pixels.
Fields in this struct are public but should only rarely be directly modified.
For example, in a scrollbar you may want to derive the handle’s size from the proportion of
scrollable content in-view. You can directly modify ComputedNode after layout to set the
handle size without a frame delay.
Fields
| Field | Type |
|---|---|
size | Vec2 |
content_size | Vec2 |
scrollbar_size | Vec2 |
scroll_position | Vec2 |
outline_width | f32 |
outline_offset | f32 |
unrounded_size | Vec2 |
border | BorderRect |
border_radius | ResolvedBorderRadius |
padding | BorderRect |
inverse_scale_factor | f32 |
em_size | EmSize |
rem_size | RemSize |
Functions
| Name | Summary |
|---|---|
new | Constructs a new instance of the type from a table of its fields. |
new
new(payload: Fields<ComputedNode>) -> ComputedNode
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
Methods
| Name | Summary |
|---|---|
content_size | The width and height of the node’s content in physical pixels, as calculated by the last layout. |
inverse_scale_factor | The factor that turns physical pixels into logical pixels for this node. |
is_empty | Whether the node has no width or no height, so that nothing is drawn for it. |
size | The width and height of the node in physical pixels, as calculated by the last layout. |
content_size
content_size(self: ComputedNode) -> Vec2
The width and height of the node’s content in physical pixels, as calculated by the last layout.
inverse_scale_factor
inverse_scale_factor(self: ComputedNode) -> f32
The factor that turns physical pixels into logical pixels for this node.
is_empty
is_empty(self: ComputedNode) -> bool
Whether the node has no width or no height, so that nothing is drawn for it.
size
size(self: ComputedNode) -> Vec2
The width and height of the node in physical pixels, as calculated by the last layout.
CornerRadius
The horizontal and vertical radii of a rounded corner’s elliptical arc. If one field is auto, the resolved radius will be circular and clamped to half the length of the node’s shortest side. If either field is zero, or both are auto, the node will have square corners.
Example
let radius = Val::Px(10.0);
let size = Vec2::new(100.0, 50.0);
let viewport_size = Vec2::new(1920.0, 1080.0);
let em_size = EmSize(20.0);
let rem_size = RemSize(20.0);
let c1 = CornerRadius {
x: radius,
y: Val::ZERO,
};
let c2 = CornerRadius {
x: Val::ZERO,
y: radius,
};
let r = c1.resolve(1.0, size, viewport_size, em_size, rem_size);
assert_eq!(
r,
c2.resolve(1.0, size, viewport_size, em_size, rem_size).yx(),
);
assert_eq!(
r,
Vec2::new(10.0, 0.0),
);
Fields
Functions
| Name | Summary |
|---|---|
new | Constructs a new instance of the type from a table of its fields. |
new
new(payload: Fields<CornerRadius>) -> CornerRadius
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
Display
Defines the layout model used by this node.
Part of the Node component.
Variants
| Variant |
|---|
Flex |
Grid |
Block |
None |
Functions
| Name | Summary |
|---|---|
new | Constructs a new instance of the type from a table of its fields. |
new
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
Variant Functions
Block.new
new(variant: EnumVariantRef, payload: Fields<Display::Block>) -> Display
Flex.new
new(variant: EnumVariantRef, payload: Fields<Display::Flex>) -> Display
Grid.new
new(variant: EnumVariantRef, payload: Fields<Display::Grid>) -> Display
None.new
new(variant: EnumVariantRef, payload: Fields<Display::None>) -> Display
FlexDirection
Defines how flexbox items are ordered within a flexbox
Variants
| Variant |
|---|
Row |
Column |
RowReverse |
ColumnReverse |
Functions
| Name | Summary |
|---|---|
new | Constructs a new instance of the type from a table of its fields. |
new
new(payload: Fields<FlexDirection>) -> FlexDirection
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
Variant Functions
| Name | Summary |
|---|---|
Column.new | |
ColumnReverse.new | |
Row.new | |
RowReverse.new |
Column.new
new(variant: EnumVariantRef, payload: Fields<FlexDirection::Column>) -> FlexDirection
ColumnReverse.new
new(variant: EnumVariantRef, payload: Fields<FlexDirection::ColumnReverse>) -> FlexDirection
Row.new
new(variant: EnumVariantRef, payload: Fields<FlexDirection::Row>) -> FlexDirection
RowReverse.new
new(variant: EnumVariantRef, payload: Fields<FlexDirection::RowReverse>) -> FlexDirection
FlexWrap
Defines if flexbox items appear on a single line or on multiple lines
Variants
| Variant |
|---|
NoWrap |
Wrap |
WrapReverse |
Functions
| Name | Summary |
|---|---|
new | Constructs a new instance of the type from a table of its fields. |
new
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
Variant Functions
| Name | Summary |
|---|---|
NoWrap.new | |
Wrap.new | |
WrapReverse.new |
NoWrap.new
new(variant: EnumVariantRef, payload: Fields<FlexWrap::NoWrap>) -> FlexWrap
Wrap.new
new(variant: EnumVariantRef, payload: Fields<FlexWrap::Wrap>) -> FlexWrap
WrapReverse.new
new(variant: EnumVariantRef, payload: Fields<FlexWrap::WrapReverse>) -> FlexWrap
GlobalZIndex
Component
GlobalZIndex allows a Node entity anywhere in the UI hierarchy to escape the implicit draw ordering of the UI’s layout tree and
be rendered above or below other UI nodes.
Root UI nodes without a GlobalZIndex component receive an implicit global z-index of 0.
Nodes with a GlobalZIndex of greater than 0 will be drawn on top of nodes without a GlobalZIndex or nodes with a lower GlobalZIndex.
Nodes with a GlobalZIndex of less than 0 will be drawn below nodes without a GlobalZIndex or nodes with a greater GlobalZIndex.
The order of nodes with the same GlobalZIndex is stable between frames.
If two Nodes have the same GlobalZIndex, ties are decided in order by:
- The node with the higher
ZIndex. - The node that was newly added this frame.
- The node with a changed
GlobalZIndexorZIndex.
Otherwise the order is preserved from the previous frame.
Fields
| Index | Type |
|---|---|
0 | i32 |
Functions
| Name | Summary |
|---|---|
new | Constructs a new instance of the type from a table of its fields. |
new
new(payload: Fields<GlobalZIndex>) -> GlobalZIndex
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
GridAutoFlow
Controls whether grid items are placed row-wise or column-wise as well as whether the sparse or dense packing algorithm is used.
The “dense” packing algorithm attempts to fill in holes earlier in the grid, if smaller items come up later. This may cause items to appear out-of-order when doing so would fill in holes left by larger items.
Defaults to GridAutoFlow::Row.
https://developer.mozilla.org/en-US/docs/Web/CSS/grid-auto-flow
Variants
| Variant |
|---|
Row |
Column |
RowDense |
ColumnDense |
Functions
| Name | Summary |
|---|---|
new | Constructs a new instance of the type from a table of its fields. |
new
new(payload: Fields<GridAutoFlow>) -> GridAutoFlow
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
Variant Functions
| Name | Summary |
|---|---|
Column.new | |
ColumnDense.new | |
Row.new | |
RowDense.new |
Column.new
new(variant: EnumVariantRef, payload: Fields<GridAutoFlow::Column>) -> GridAutoFlow
ColumnDense.new
new(variant: EnumVariantRef, payload: Fields<GridAutoFlow::ColumnDense>) -> GridAutoFlow
Row.new
new(variant: EnumVariantRef, payload: Fields<GridAutoFlow::Row>) -> GridAutoFlow
RowDense.new
new(variant: EnumVariantRef, payload: Fields<GridAutoFlow::RowDense>) -> GridAutoFlow
GridPlacement
Represents the position of a grid item in a single axis.
There are 3 fields which may be set:
start: which grid line the item should start atend: which grid line the item should end atspan: how many tracks the item should span
The default span is 1. If neither start or end is set then the item will be placed automatically.
Generally, at most two fields should be set. If all three fields are specified then span will be ignored. If end specifies an earlier
grid line than start then end will be ignored and the item will have a span of 1.
https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Grid_Layout/Line-based_Placement_with_CSS_Grid
Fields
| Field | Type |
|---|---|
start | Optional<NonZeroI16> |
span | Optional<NonZeroU16> |
end | Optional<NonZeroI16> |
Functions
| Name | Summary |
|---|---|
new | Constructs a new instance of the type from a table of its fields. |
new
new(payload: Fields<GridPlacement>) -> GridPlacement
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
GridTrack
A GridTrack is a Row or Column of a CSS Grid. This struct specifies what size the track should be.
See below for the different “track sizing functions” you can specify.
Fields
| Field | Type |
|---|---|
min_sizing_function | MinTrackSizingFunction |
max_sizing_function | MaxTrackSizingFunction |
Functions
| Name | Summary |
|---|---|
new | Constructs a new instance of the type from a table of its fields. |
new
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
GridTrackRepetition
How many times to repeat a repeated grid track
https://developer.mozilla.org/en-US/docs/Web/CSS/repeat
Variants
| Variant | Fields |
|---|---|
Count | (u16) |
AutoFill | |
AutoFit |
Functions
| Name | Summary |
|---|---|
new | Constructs a new instance of the type from a table of its fields. |
new
new(payload: Fields<GridTrackRepetition>) -> GridTrackRepetition
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
Variant Functions
| Name | Summary |
|---|---|
AutoFill.new | |
AutoFit.new | |
Count.new |
AutoFill.new
new(variant: EnumVariantRef, payload: Fields<GridTrackRepetition::AutoFill>) -> GridTrackRepetition
AutoFit.new
new(variant: EnumVariantRef, payload: Fields<GridTrackRepetition::AutoFit>) -> GridTrackRepetition
Count.new
new(variant: EnumVariantRef, payload: Fields<GridTrackRepetition::Count>) -> GridTrackRepetition
ImageNode
Component
A UI Node that renders an image.
Fields
| Field | Type |
|---|---|
color | Color |
image | Handle<Image> |
texture_atlas | Optional<TextureAtlas> |
flip_x | bool |
flip_y | bool |
rect | Optional<Rect> |
image_mode | NodeImageMode |
visual_box | VisualBox |
Functions
| Name | Summary |
|---|---|
new | A node that draws the given Image, untinted. |
new
A node that draws the given Image, untinted.
Methods
| Name | Summary |
|---|---|
with_color | A copy of the node that tints its image with color. |
with_color
A copy of the node that tints its image with color.
InlineDirection
Sets the inline axis direction (LTR or RTL) used for layout.
Variants
| Variant |
|---|
Ltr |
Rtl |
Functions
| Name | Summary |
|---|---|
new | Constructs a new instance of the type from a table of its fields. |
new
new(payload: Fields<InlineDirection>) -> InlineDirection
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
Variant Functions
Ltr.new
new(variant: EnumVariantRef, payload: Fields<InlineDirection::Ltr>) -> InlineDirection
Rtl.new
new(variant: EnumVariantRef, payload: Fields<InlineDirection::Rtl>) -> InlineDirection
JustifyContent
Used to control how items are distributed.
- For Flexbox containers, controls alignment of items in the main axis.
- For CSS Grid containers, controls alignment of grid columns.
Safe alignments
Safe alignments will fall back to Self::Start if aligning the items would overflow the container, so
the start of the content stays visible.
https://developer.mozilla.org/en-US/docs/Web/CSS/justify-content
Variants
| Variant |
|---|
Default |
Start |
StartSafe |
End |
EndSafe |
FlexStart |
FlexStartSafe |
FlexEnd |
FlexEndSafe |
Center |
CenterSafe |
Stretch |
SpaceBetween |
SpaceEvenly |
SpaceAround |
Functions
| Name | Summary |
|---|---|
new | Constructs a new instance of the type from a table of its fields. |
new
new(payload: Fields<JustifyContent>) -> JustifyContent
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
Variant Functions
Center.new
new(variant: EnumVariantRef, payload: Fields<JustifyContent::Center>) -> JustifyContent
CenterSafe.new
new(variant: EnumVariantRef, payload: Fields<JustifyContent::CenterSafe>) -> JustifyContent
Default.new
new(variant: EnumVariantRef, payload: Fields<JustifyContent::Default>) -> JustifyContent
End.new
new(variant: EnumVariantRef, payload: Fields<JustifyContent::End>) -> JustifyContent
EndSafe.new
new(variant: EnumVariantRef, payload: Fields<JustifyContent::EndSafe>) -> JustifyContent
FlexEnd.new
new(variant: EnumVariantRef, payload: Fields<JustifyContent::FlexEnd>) -> JustifyContent
FlexEndSafe.new
new(variant: EnumVariantRef, payload: Fields<JustifyContent::FlexEndSafe>) -> JustifyContent
FlexStart.new
new(variant: EnumVariantRef, payload: Fields<JustifyContent::FlexStart>) -> JustifyContent
FlexStartSafe.new
new(variant: EnumVariantRef, payload: Fields<JustifyContent::FlexStartSafe>) -> JustifyContent
SpaceAround.new
new(variant: EnumVariantRef, payload: Fields<JustifyContent::SpaceAround>) -> JustifyContent
SpaceBetween.new
new(variant: EnumVariantRef, payload: Fields<JustifyContent::SpaceBetween>) -> JustifyContent
SpaceEvenly.new
new(variant: EnumVariantRef, payload: Fields<JustifyContent::SpaceEvenly>) -> JustifyContent
Start.new
new(variant: EnumVariantRef, payload: Fields<JustifyContent::Start>) -> JustifyContent
StartSafe.new
new(variant: EnumVariantRef, payload: Fields<JustifyContent::StartSafe>) -> JustifyContent
Stretch.new
new(variant: EnumVariantRef, payload: Fields<JustifyContent::Stretch>) -> JustifyContent
JustifyItems
Used to control how each individual item is aligned by default within the space they’re given.
- For Flexbox containers, this property has no effect. See
justify_contentfor main axis alignment of flex items. - For CSS Grid containers, sets default inline (horizontal) axis alignment of child items within their grid areas.
Safe alignments
Safe alignments will fall back to Self::Start if aligning the items would overflow the container, so
the start of the content stays visible.
https://developer.mozilla.org/en-US/docs/Web/CSS/justify-items
Variants
| Variant |
|---|
Default |
Start |
StartSafe |
End |
EndSafe |
Center |
CenterSafe |
Baseline |
Stretch |
Functions
| Name | Summary |
|---|---|
new | Constructs a new instance of the type from a table of its fields. |
new
new(payload: Fields<JustifyItems>) -> JustifyItems
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
Variant Functions
| Name | Summary |
|---|---|
Baseline.new | |
Center.new | |
CenterSafe.new | |
Default.new | |
End.new | |
EndSafe.new | |
Start.new | |
StartSafe.new | |
Stretch.new |
Baseline.new
new(variant: EnumVariantRef, payload: Fields<JustifyItems::Baseline>) -> JustifyItems
Center.new
new(variant: EnumVariantRef, payload: Fields<JustifyItems::Center>) -> JustifyItems
CenterSafe.new
new(variant: EnumVariantRef, payload: Fields<JustifyItems::CenterSafe>) -> JustifyItems
Default.new
new(variant: EnumVariantRef, payload: Fields<JustifyItems::Default>) -> JustifyItems
End.new
new(variant: EnumVariantRef, payload: Fields<JustifyItems::End>) -> JustifyItems
EndSafe.new
new(variant: EnumVariantRef, payload: Fields<JustifyItems::EndSafe>) -> JustifyItems
Start.new
new(variant: EnumVariantRef, payload: Fields<JustifyItems::Start>) -> JustifyItems
StartSafe.new
new(variant: EnumVariantRef, payload: Fields<JustifyItems::StartSafe>) -> JustifyItems
Stretch.new
new(variant: EnumVariantRef, payload: Fields<JustifyItems::Stretch>) -> JustifyItems
JustifySelf
Used to control how the specified item is aligned within the space it’s given.
- For children of flex nodes, this property has no effect. See
justify_contentfor main axis alignment of flex items. - For CSS Grid items, controls inline (horizontal) axis alignment of a grid item within its grid area.
Safe alignments
Safe alignments will fall back to Self::Start if aligning the items would overflow the container, so
the start of the content stays visible.
https://developer.mozilla.org/en-US/docs/Web/CSS/justify-self
Variants
| Variant |
|---|
Auto |
Start |
StartSafe |
End |
EndSafe |
Center |
CenterSafe |
Baseline |
Stretch |
Functions
| Name | Summary |
|---|---|
new | Constructs a new instance of the type from a table of its fields. |
new
new(payload: Fields<JustifySelf>) -> JustifySelf
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
Variant Functions
| Name | Summary |
|---|---|
Auto.new | |
Baseline.new | |
Center.new | |
CenterSafe.new | |
End.new | |
EndSafe.new | |
Start.new | |
StartSafe.new | |
Stretch.new |
Auto.new
new(variant: EnumVariantRef, payload: Fields<JustifySelf::Auto>) -> JustifySelf
Baseline.new
new(variant: EnumVariantRef, payload: Fields<JustifySelf::Baseline>) -> JustifySelf
Center.new
new(variant: EnumVariantRef, payload: Fields<JustifySelf::Center>) -> JustifySelf
CenterSafe.new
new(variant: EnumVariantRef, payload: Fields<JustifySelf::CenterSafe>) -> JustifySelf
End.new
new(variant: EnumVariantRef, payload: Fields<JustifySelf::End>) -> JustifySelf
EndSafe.new
new(variant: EnumVariantRef, payload: Fields<JustifySelf::EndSafe>) -> JustifySelf
Start.new
new(variant: EnumVariantRef, payload: Fields<JustifySelf::Start>) -> JustifySelf
StartSafe.new
new(variant: EnumVariantRef, payload: Fields<JustifySelf::StartSafe>) -> JustifySelf
Stretch.new
new(variant: EnumVariantRef, payload: Fields<JustifySelf::Stretch>) -> JustifySelf
MaxTrackSizingFunction
Variants
| Variant | Fields |
|---|---|
Px | (f32) |
Percent | (f32) |
Em | (f32) |
Rem | (f32) |
MinContent | |
MaxContent | |
FitContentPx | (f32) |
FitContentPercent | (f32) |
Auto | |
Fraction | (f32) |
VMin | (f32) |
VMax | (f32) |
Vh | (f32) |
Vw | (f32) |
Functions
| Name | Summary |
|---|---|
new | Constructs a new instance of the type from a table of its fields. |
new
new(payload: Fields<MaxTrackSizingFunction>) -> MaxTrackSizingFunction
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
Variant Functions
| Name | Summary |
|---|---|
Auto.new | |
Em.new | |
FitContentPercent.new | |
FitContentPx.new | |
Fraction.new | |
MaxContent.new | |
MinContent.new | |
Percent.new | |
Px.new | |
Rem.new | |
VMax.new | |
VMin.new | |
Vh.new | |
Vw.new |
Auto.new
new(variant: EnumVariantRef, payload: Fields<MaxTrackSizingFunction::Auto>) -> MaxTrackSizingFunction
Em.new
new(variant: EnumVariantRef, payload: Fields<MaxTrackSizingFunction::Em>) -> MaxTrackSizingFunction
FitContentPercent.new
new(variant: EnumVariantRef, payload: Fields<MaxTrackSizingFunction::FitContentPercent>) -> MaxTrackSizingFunction
FitContentPx.new
new(variant: EnumVariantRef, payload: Fields<MaxTrackSizingFunction::FitContentPx>) -> MaxTrackSizingFunction
Fraction.new
new(variant: EnumVariantRef, payload: Fields<MaxTrackSizingFunction::Fraction>) -> MaxTrackSizingFunction
MaxContent.new
new(variant: EnumVariantRef, payload: Fields<MaxTrackSizingFunction::MaxContent>) -> MaxTrackSizingFunction
MinContent.new
new(variant: EnumVariantRef, payload: Fields<MaxTrackSizingFunction::MinContent>) -> MaxTrackSizingFunction
Percent.new
new(variant: EnumVariantRef, payload: Fields<MaxTrackSizingFunction::Percent>) -> MaxTrackSizingFunction
Px.new
new(variant: EnumVariantRef, payload: Fields<MaxTrackSizingFunction::Px>) -> MaxTrackSizingFunction
Rem.new
new(variant: EnumVariantRef, payload: Fields<MaxTrackSizingFunction::Rem>) -> MaxTrackSizingFunction
VMax.new
new(variant: EnumVariantRef, payload: Fields<MaxTrackSizingFunction::VMax>) -> MaxTrackSizingFunction
VMin.new
new(variant: EnumVariantRef, payload: Fields<MaxTrackSizingFunction::VMin>) -> MaxTrackSizingFunction
Vh.new
new(variant: EnumVariantRef, payload: Fields<MaxTrackSizingFunction::Vh>) -> MaxTrackSizingFunction
Vw.new
new(variant: EnumVariantRef, payload: Fields<MaxTrackSizingFunction::Vw>) -> MaxTrackSizingFunction
MinTrackSizingFunction
Variants
| Variant | Fields |
|---|---|
Px | (f32) |
Percent | (f32) |
Em | (f32) |
Rem | (f32) |
MinContent | |
MaxContent | |
Auto | |
VMin | (f32) |
VMax | (f32) |
Vh | (f32) |
Vw | (f32) |
Functions
| Name | Summary |
|---|---|
new | Constructs a new instance of the type from a table of its fields. |
new
new(payload: Fields<MinTrackSizingFunction>) -> MinTrackSizingFunction
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
Variant Functions
| Name | Summary |
|---|---|
Auto.new | |
Em.new | |
MaxContent.new | |
MinContent.new | |
Percent.new | |
Px.new | |
Rem.new | |
VMax.new | |
VMin.new | |
Vh.new | |
Vw.new |
Auto.new
new(variant: EnumVariantRef, payload: Fields<MinTrackSizingFunction::Auto>) -> MinTrackSizingFunction
Em.new
new(variant: EnumVariantRef, payload: Fields<MinTrackSizingFunction::Em>) -> MinTrackSizingFunction
MaxContent.new
new(variant: EnumVariantRef, payload: Fields<MinTrackSizingFunction::MaxContent>) -> MinTrackSizingFunction
MinContent.new
new(variant: EnumVariantRef, payload: Fields<MinTrackSizingFunction::MinContent>) -> MinTrackSizingFunction
Percent.new
new(variant: EnumVariantRef, payload: Fields<MinTrackSizingFunction::Percent>) -> MinTrackSizingFunction
Px.new
new(variant: EnumVariantRef, payload: Fields<MinTrackSizingFunction::Px>) -> MinTrackSizingFunction
Rem.new
new(variant: EnumVariantRef, payload: Fields<MinTrackSizingFunction::Rem>) -> MinTrackSizingFunction
VMax.new
new(variant: EnumVariantRef, payload: Fields<MinTrackSizingFunction::VMax>) -> MinTrackSizingFunction
VMin.new
new(variant: EnumVariantRef, payload: Fields<MinTrackSizingFunction::VMin>) -> MinTrackSizingFunction
Vh.new
new(variant: EnumVariantRef, payload: Fields<MinTrackSizingFunction::Vh>) -> MinTrackSizingFunction
Vw.new
new(variant: EnumVariantRef, payload: Fields<MinTrackSizingFunction::Vw>) -> MinTrackSizingFunction
Node
Component
The base component for UI entities. It describes UI layout and style properties.
When defining new types of UI entities, require Node to make them behave like UI nodes.
Nodes can be laid out using either Flexbox or CSS Grid Layout.
See below for general learning resources and for documentation on the individual style properties.
Flexbox
- MDN: Basic Concepts of Flexbox
- A Complete Guide To Flexbox by CSS Tricks. This is detailed guide with illustrations and comprehensive written explanation of the different Flexbox properties and how they work.
- Flexbox Froggy. An interactive tutorial/game that teaches the essential parts of Flexbox in a fun engaging way.
CSS Grid
- MDN: Basic Concepts of Grid Layout
- A Complete Guide To CSS Grid by CSS Tricks. This is detailed guide with illustrations and comprehensive written explanation of the different CSS Grid properties and how they work.
- CSS Grid Garden. An interactive tutorial/game that teaches the essential parts of CSS Grid in a fun engaging way.
See also
RelativeCursorPositionto obtain the cursor position relative to this node
Fields
| Field | Type |
|---|---|
display | Display |
box_sizing | BoxSizing |
position_type | PositionType |
overflow | Overflow |
scrollbar_width | f32 |
overflow_clip_margin | OverflowClipMargin |
left | Val |
right | Val |
top | Val |
bottom | Val |
width | Val |
height | Val |
min_width | Val |
min_height | Val |
max_width | Val |
max_height | Val |
aspect_ratio | Optional<f32> |
align_items | AlignItems |
justify_items | JustifyItems |
align_self | AlignSelf |
justify_self | JustifySelf |
align_content | AlignContent |
justify_content | JustifyContent |
direction | InlineDirection |
margin | UiRect |
padding | UiRect |
border | UiRect |
border_radius | BorderRadius |
flex_direction | FlexDirection |
flex_wrap | FlexWrap |
flex_grow | f32 |
flex_shrink | f32 |
flex_basis | Val |
row_gap | Val |
column_gap | Val |
grid_auto_flow | GridAutoFlow |
grid_template_rows | Vec<RepeatedGridTrack> |
grid_template_columns | Vec<RepeatedGridTrack> |
grid_auto_rows | Vec<GridTrack> |
grid_auto_columns | Vec<GridTrack> |
grid_row | GridPlacement |
grid_column | GridPlacement |
Functions
| Name | Summary |
|---|---|
new | Constructs a new instance of the type from a table of its fields. |
new
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
NodeImageMode
Controls how the image is altered to fit within the layout and how the layout algorithm determines the space in the layout for the image
Variants
| Variant | Fields |
|---|---|
Auto | |
Stretch | |
Sliced | (TextureSlicer) |
Tiled | { tile_x: bool, tile_y: bool, stretch_value: f32 } |
Functions
| Name | Summary |
|---|---|
new | Constructs a new instance of the type from a table of its fields. |
new
new(payload: Fields<NodeImageMode>) -> NodeImageMode
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
Variant Functions
| Name | Summary |
|---|---|
Auto.new | |
Sliced.new | |
Stretch.new | |
Tiled.new |
Auto.new
new(variant: EnumVariantRef, payload: Fields<NodeImageMode::Auto>) -> NodeImageMode
Sliced.new
new(variant: EnumVariantRef, payload: Fields<NodeImageMode::Sliced>) -> NodeImageMode
Stretch.new
new(variant: EnumVariantRef, payload: Fields<NodeImageMode::Stretch>) -> NodeImageMode
Tiled.new
new(variant: EnumVariantRef, payload: Fields<NodeImageMode::Tiled>) -> NodeImageMode
Outline
Component
The Outline component adds an outline outside the edge of a UI node.
Outlines do not take up space in the layout.
To add an Outline to a UI node you can spawn a (Node, Outline) tuple bundle:
fn setup_ui(mut commands: Commands) {
commands.spawn((
Node {
width: Val::Px(100.),
height: Val::Px(100.),
..Default::default()
},
BackgroundColor(BLUE.into()),
Outline::new(Val::Px(10.), Val::ZERO, RED.into())
));
}
Outline components can also be added later to existing UI nodes:
fn outline_hovered_button_system(
mut commands: Commands,
mut node_query: Query<(Entity, &Hovered, Option<&mut Outline>), Changed<Hovered>>,
) {
for (entity, hovered, mut maybe_outline) in node_query.iter_mut() {
let outline_color =
if hovered.get() {
Color::WHITE
} else {
Color::NONE
};
if let Some(mut outline) = maybe_outline {
outline.color = outline_color;
} else {
commands.entity(entity).insert(Outline::new(Val::Px(10.), Val::ZERO, outline_color));
}
}
}
Inserting and removing an Outline component repeatedly will result in table moves, so it is generally preferable to
set Outline::color to Color::NONE to hide an outline.
Fields
Functions
| Name | Summary |
|---|---|
new | Constructs a new instance of the type from a table of its fields. |
new
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
Overflow
Whether to show or hide overflowing items
Fields
| Field | Type |
|---|---|
x | OverflowAxis |
y | OverflowAxis |
Functions
| Name | Summary |
|---|---|
clip | Content that overflows the node is clipped on both axes. |
clip_x | Content that overflows the node is clipped on the horizontal axis only. |
clip_y | Content that overflows the node is clipped on the vertical axis only. |
hidden | Content that overflows the node is hidden on both axes, with the layout making room for it to be cut off. |
new | Constructs a new instance of the type from a table of its fields. |
scroll | Content that overflows the node can be scrolled on both axes. |
visible | Content that overflows the node is shown. |
clip
clip() -> Overflow
Content that overflows the node is clipped on both axes.
clip_x
clip_x() -> Overflow
Content that overflows the node is clipped on the horizontal axis only.
clip_y
clip_y() -> Overflow
Content that overflows the node is clipped on the vertical axis only.
hidden
hidden() -> Overflow
Content that overflows the node is hidden on both axes, with the layout making room for it to be cut off.
new
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
scroll
scroll() -> Overflow
Content that overflows the node can be scrolled on both axes.
visible
visible() -> Overflow
Content that overflows the node is shown.
OverflowAxis
Whether to show or hide overflowing items
Variants
| Variant |
|---|
Visible |
Clip |
Hidden |
Scroll |
Functions
| Name | Summary |
|---|---|
new | Constructs a new instance of the type from a table of its fields. |
new
new(payload: Fields<OverflowAxis>) -> OverflowAxis
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
Variant Functions
| Name | Summary |
|---|---|
Clip.new | |
Hidden.new | |
Scroll.new | |
Visible.new |
Clip.new
new(variant: EnumVariantRef, payload: Fields<OverflowAxis::Clip>) -> OverflowAxis
Hidden.new
new(variant: EnumVariantRef, payload: Fields<OverflowAxis::Hidden>) -> OverflowAxis
Scroll.new
new(variant: EnumVariantRef, payload: Fields<OverflowAxis::Scroll>) -> OverflowAxis
Visible.new
new(variant: EnumVariantRef, payload: Fields<OverflowAxis::Visible>) -> OverflowAxis
OverflowClipMargin
The bounds of the visible area when a UI node is clipped.
Fields
Functions
| Name | Summary |
|---|---|
new | Constructs a new instance of the type from a table of its fields. |
new
new(payload: Fields<OverflowClipMargin>) -> OverflowClipMargin
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
PositionType
The strategy used to position this node
Variants
| Variant |
|---|
Relative |
Absolute |
Functions
| Name | Summary |
|---|---|
new | Constructs a new instance of the type from a table of its fields. |
new
new(payload: Fields<PositionType>) -> PositionType
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
Variant Functions
| Name | Summary |
|---|---|
Absolute.new | |
Relative.new |
Absolute.new
new(variant: EnumVariantRef, payload: Fields<PositionType::Absolute>) -> PositionType
Relative.new
new(variant: EnumVariantRef, payload: Fields<PositionType::Relative>) -> PositionType
RepeatedGridTrack
Represents a possibly repeated GridTrack.
The repetition parameter can either be:
- The integer
1, in which case the track is non-repeated. - a
u16count to repeat the track N times. - A
GridTrackRepetition::AutoFitorGridTrackRepetition::AutoFill.
Note: that in the common case you want a non-repeating track (repetition count 1), you may use the constructor methods on GridTrack
to create a RepeatedGridTrack. i.e. GridTrack::px(10.0) is equivalent to RepeatedGridTrack::px(1, 10.0).
You may only use one auto-repetition per track list. And if your track list contains an auto repetition then all tracks (in and outside of the repetition) must be fixed size (px or percent). Integer repetitions are just shorthand for writing out N tracks longhand and are not subject to the same limitations.
Fields
| Field | Type |
|---|---|
repetition | GridTrackRepetition |
tracks | Vec<GridTrack> |
Functions
| Name | Summary |
|---|---|
new | Constructs a new instance of the type from a table of its fields. |
new
new(payload: Fields<RepeatedGridTrack>) -> RepeatedGridTrack
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
ResolvedBorderRadius
Represents the resolved border radii values for a UI node.
The values are in physical pixels.
Fields
Functions
| Name | Summary |
|---|---|
new | Constructs a new instance of the type from a table of its fields. |
new
new(payload: Fields<ResolvedBorderRadius>) -> ResolvedBorderRadius
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
UiRect
A type which is commonly used to define margins, paddings and borders.
Examples
Margin
A margin is used to create space around UI elements, outside of any defined borders.
let margin = UiRect::all(Val::Auto); // Centers the UI element
Padding
A padding is used to create space around UI elements, inside of any defined borders.
let padding = UiRect {
left: Val::Px(10.0),
right: Val::Px(20.0),
top: Val::Px(30.0),
bottom: Val::Px(40.0),
};
Borders
A border is used to define the width of the border of a UI element.
let border = UiRect {
left: Val::Px(10.0),
right: Val::Px(20.0),
top: Val::Px(30.0),
bottom: Val::Px(40.0),
};
Fields
Functions
| Name | Summary |
|---|---|
all | A rectangle with the same length on all four sides. |
axes | A rectangle with one length for the left and right sides and another for the top and bottom. |
horizontal | A rectangle with the length on its left and right sides only. |
new | A rectangle with a length for each of its left, right, top and bottom sides. |
percent | A rectangle with percentages of the parent for its left, right, top and bottom sides. |
px | A rectangle with lengths in logical pixels for its left, right, top and bottom sides. |
vertical | A rectangle with the length on its top and bottom sides only. |
zero | A rectangle with no space on any side. |
all
A rectangle with the same length on all four sides.
axes
A rectangle with one length for the left and right sides and another for the top and bottom.
horizontal
A rectangle with the length on its left and right sides only.
new
A rectangle with a length for each of its left, right, top and bottom sides.
percent
A rectangle with percentages of the parent for its left, right, top and bottom sides.
px
A rectangle with lengths in logical pixels for its left, right, top and bottom sides.
vertical
A rectangle with the length on its top and bottom sides only.
zero
zero() -> UiRect
A rectangle with no space on any side.
Val
Represents the possible value types for layout properties.
This enum allows specifying values for various Node properties in different units,
such as logical pixels, percentages, or automatically determined values.
Val also implements core::str::FromStr to allow parsing values from strings in the format #.#px. Whitespaces between the value and unit is allowed. The following units are supported:
px: logical pixels%: percentagevw: percentage of the viewport widthvh: percentage of the viewport heightvmin: percentage of the viewport’s smaller dimensionvmax: percentage of the viewport’s larger dimension
Additionally, auto will be parsed as Val::Auto.
Variants
Functions
| Name | Summary |
|---|---|
auto | A length that the layout works out from the node and its contents. |
new | Constructs a new instance of the type from a table of its fields. |
percent | A length as a percentage of the parent’s size along the axis it applies to. |
px | A length in logical pixels, such as Val.px(100) for 100 pixels. |
vh | A length as a percentage of the viewport height. |
vmax | A length as a percentage of the viewport’s larger dimension. |
vmin | A length as a percentage of the viewport’s smaller dimension. |
vw | A length as a percentage of the viewport width. |
auto
auto() -> Val
A length that the layout works out from the node and its contents.
new
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
percent
A length as a percentage of the parent’s size along the axis it applies to.
px
A length in logical pixels, such as Val.px(100) for 100 pixels.
local Node = import_namespace("ui").Node
local Val = import_namespace("ui").Val
local node = Node.new({ width = Val.px(100) })
assert(node.width[1] == 100)
let Node = import_namespace("ui").Node;
let Val = import_namespace("ui").Val;
let node = Node.new(#{ width: Val.px(100.0) });
assert!(node.width[0] == 100.0);
vh
A length as a percentage of the viewport height.
vmax
A length as a percentage of the viewport’s larger dimension.
vmin
A length as a percentage of the viewport’s smaller dimension.
vw
A length as a percentage of the viewport width.
Variant Functions
Auto.new
new(variant: EnumVariantRef, payload: Fields<Val::Auto>) -> Val
Em.new
new(variant: EnumVariantRef, payload: Fields<Val::Em>) -> Val
Percent.new
new(variant: EnumVariantRef, payload: Fields<Val::Percent>) -> Val
Px.new
new(variant: EnumVariantRef, payload: Fields<Val::Px>) -> Val
Rem.new
new(variant: EnumVariantRef, payload: Fields<Val::Rem>) -> Val
VMax.new
new(variant: EnumVariantRef, payload: Fields<Val::VMax>) -> Val
VMin.new
new(variant: EnumVariantRef, payload: Fields<Val::VMin>) -> Val
Vh.new
new(variant: EnumVariantRef, payload: Fields<Val::Vh>) -> Val
Vw.new
new(variant: EnumVariantRef, payload: Fields<Val::Vw>) -> Val
VisualBox
Used to determine which region of a UI node is used for visual bounds.
Variants
| Variant |
|---|
ContentBox |
PaddingBox |
BorderBox |
Functions
| Name | Summary |
|---|---|
new | Constructs a new instance of the type from a table of its fields. |
new
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
Variant Functions
| Name | Summary |
|---|---|
BorderBox.new | |
ContentBox.new | |
PaddingBox.new |
BorderBox.new
new(variant: EnumVariantRef, payload: Fields<VisualBox::BorderBox>) -> VisualBox
ContentBox.new
new(variant: EnumVariantRef, payload: Fields<VisualBox::ContentBox>) -> VisualBox
PaddingBox.new
new(variant: EnumVariantRef, payload: Fields<VisualBox::PaddingBox>) -> VisualBox
ZIndex
Component
Indicates that this Node entity’s front-to-back ordering is not controlled solely
by its location in the UI hierarchy. A node with a higher z-index will appear on top
of sibling nodes with a lower z-index.
UI nodes that have the same z-index will appear according to the order in which they appear in the UI hierarchy. In such a case, the last node to be added to its parent will appear in front of its siblings.
Nodes without this component will be treated as if they had a value of
ZIndex(0).
Use GlobalZIndex if you need to order separate UI hierarchies or nodes that are
not siblings in a given UI hierarchy.
Fields
| Index | Type |
|---|---|
0 | i32 |
Functions
| Name | Summary |
|---|---|
new | Constructs a new instance of the type from a table of its fields. |
new
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
ui.UiSystems
The types and functions in the ui.UiSystems namespace, as returned by import_namespace("ui.UiSystems").
Values
| Name | Type |
|---|---|
Content | ReflectSystemSet |
Focus | ReflectSystemSet |
Layout | ReflectSystemSet |
PostLayout | ReflectSystemSet |
Prepare | ReflectSystemSet |
Propagate | ReflectSystemSet |
Stack | ReflectSystemSet |
uuid
The types and functions in the uuid namespace, as returned by import_namespace("uuid").
Types
| Type | Summary |
|---|---|
Uuid |
Uuid
Opaque: scripts can't access its fields, only its functions.
Functions
| Name | Summary |
|---|---|
new | Constructs a new instance of the type from a table of its fields. |
new
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
wgpu_types
The types and functions in the wgpu_types namespace, as returned by import_namespace("wgpu_types").
Types
| Type | Summary |
|---|---|
BlendState |
BlendState
Opaque: scripts can't access its fields, only its functions.
Functions
| Name | Summary |
|---|---|
new | Constructs a new instance of the type from a table of its fields. |
new
new(payload: Fields<BlendState>) -> BlendState
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
window
The types and functions in the window namespace, as returned by import_namespace("window").
Types
| Type | Summary |
|---|---|
CompositeAlphaMode | Specifies how the alpha channel of the textures should be handled during compositing, for a Window. |
EnabledButtons | Specifies which Window control buttons should be enabled. |
InternalWindowState | Stores internal Window state that isn’t directly accessible. |
MonitorSelection | References a screen monitor. |
PresentMode | Presentation mode for a Window. |
ScreenEdge | The edges of a screen. Corresponds to winit::platform::ios::ScreenEdge. |
VideoMode | Represents a video mode that a monitor supports |
VideoModeSelection | References an exclusive fullscreen video mode. |
Window | The defining Component for window entities, storing information about how it should appear and behave. |
WindowLevel | Specifies where a Window should appear relative to other overlapping windows (on top or under) . |
WindowMode | Defines the way a Window is displayed. |
WindowPosition | Defines where a Window should be placed on the screen. |
WindowRef | Reference to a Window, whether it be a direct link to a specific entity or a more vague defaulting choice. |
WindowResizeConstraints | The size limits on a Window. |
WindowResolution | Controls the size of a Window |
WindowTheme | The Window theme variant to use. |
Values
| Name | Type |
|---|---|
ExitSystems | ReflectSystemSet |
CompositeAlphaMode
Specifies how the alpha channel of the textures should be handled during compositing, for a Window.
Variants
| Variant |
|---|
Auto |
Opaque |
PreMultiplied |
PostMultiplied |
Inherit |
Functions
| Name | Summary |
|---|---|
new | Constructs a new instance of the type from a table of its fields. |
new
new(payload: Fields<CompositeAlphaMode>) -> CompositeAlphaMode
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
Variant Functions
| Name | Summary |
|---|---|
Auto.new | |
Inherit.new | |
Opaque.new | |
PostMultiplied.new | |
PreMultiplied.new |
Auto.new
new(variant: EnumVariantRef, payload: Fields<CompositeAlphaMode::Auto>) -> CompositeAlphaMode
Inherit.new
new(variant: EnumVariantRef, payload: Fields<CompositeAlphaMode::Inherit>) -> CompositeAlphaMode
Opaque.new
new(variant: EnumVariantRef, payload: Fields<CompositeAlphaMode::Opaque>) -> CompositeAlphaMode
PostMultiplied.new
new(variant: EnumVariantRef, payload: Fields<CompositeAlphaMode::PostMultiplied>) -> CompositeAlphaMode
PreMultiplied.new
new(variant: EnumVariantRef, payload: Fields<CompositeAlphaMode::PreMultiplied>) -> CompositeAlphaMode
EnabledButtons
Specifies which Window control buttons should be enabled.
Platform-specific
iOS, Android, and the Web do not have window control buttons.
On some Linux environments these values have no effect.
Fields
Functions
| Name | Summary |
|---|---|
new | Constructs a new instance of the type from a table of its fields. |
new
new(payload: Fields<EnabledButtons>) -> EnabledButtons
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
InternalWindowState
Stores internal Window state that isn’t directly accessible.
Fields
| Field | Type |
|---|---|
minimize_request | Optional<bool> |
maximize_request | Optional<bool> |
drag_move_request | bool |
drag_resize_request | Optional<CompassOctant> |
physical_cursor_position | Optional<DVec2> |
Functions
| Name | Summary |
|---|---|
new | Constructs a new instance of the type from a table of its fields. |
new
new(payload: Fields<InternalWindowState>) -> InternalWindowState
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
MonitorSelection
References a screen monitor.
Used when centering a Window on a monitor.
Variants
Functions
| Name | Summary |
|---|---|
new | Constructs a new instance of the type from a table of its fields. |
new
new(payload: Fields<MonitorSelection>) -> MonitorSelection
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
Variant Functions
| Name | Summary |
|---|---|
Current.new | |
Entity.new | |
Index.new | |
Primary.new |
Current.new
new(variant: EnumVariantRef, payload: Fields<MonitorSelection::Current>) -> MonitorSelection
Entity.new
new(variant: EnumVariantRef, payload: Fields<MonitorSelection::Entity>) -> MonitorSelection
Index.new
new(variant: EnumVariantRef, payload: Fields<MonitorSelection::Index>) -> MonitorSelection
Primary.new
new(variant: EnumVariantRef, payload: Fields<MonitorSelection::Primary>) -> MonitorSelection
PresentMode
Presentation mode for a Window.
The presentation mode specifies when a frame is presented to the window. The Fifo
option corresponds to a traditional VSync, where the framerate is capped by the
display refresh rate. Both Immediate and Mailbox are low-latency and are not
capped by the refresh rate, but may not be available on all platforms. Tearing
may be observed with Immediate mode, but will not be observed with Mailbox or
Fifo.
AutoVsync or AutoNoVsync will gracefully fallback to Fifo when unavailable.
Immediate or Mailbox will panic if not supported by the platform.
Variants
| Variant |
|---|
AutoVsync |
AutoNoVsync |
Fifo |
FifoRelaxed |
Immediate |
Mailbox |
Functions
| Name | Summary |
|---|---|
new | Constructs a new instance of the type from a table of its fields. |
new
new(payload: Fields<PresentMode>) -> PresentMode
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
Variant Functions
AutoNoVsync.new
new(variant: EnumVariantRef, payload: Fields<PresentMode::AutoNoVsync>) -> PresentMode
AutoVsync.new
new(variant: EnumVariantRef, payload: Fields<PresentMode::AutoVsync>) -> PresentMode
Fifo.new
new(variant: EnumVariantRef, payload: Fields<PresentMode::Fifo>) -> PresentMode
FifoRelaxed.new
new(variant: EnumVariantRef, payload: Fields<PresentMode::FifoRelaxed>) -> PresentMode
Immediate.new
new(variant: EnumVariantRef, payload: Fields<PresentMode::Immediate>) -> PresentMode
Mailbox.new
new(variant: EnumVariantRef, payload: Fields<PresentMode::Mailbox>) -> PresentMode
ScreenEdge
The edges of a screen. Corresponds to winit::platform::ios::ScreenEdge.
Platform-specific
- Only used on iOS.
Variants
| Variant |
|---|
None |
Top |
Left |
Bottom |
Right |
All |
Functions
| Name | Summary |
|---|---|
new | Constructs a new instance of the type from a table of its fields. |
new
new(payload: Fields<ScreenEdge>) -> ScreenEdge
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
Variant Functions
All.new
new(variant: EnumVariantRef, payload: Fields<ScreenEdge::All>) -> ScreenEdge
Bottom.new
new(variant: EnumVariantRef, payload: Fields<ScreenEdge::Bottom>) -> ScreenEdge
Left.new
new(variant: EnumVariantRef, payload: Fields<ScreenEdge::Left>) -> ScreenEdge
None.new
new(variant: EnumVariantRef, payload: Fields<ScreenEdge::None>) -> ScreenEdge
Right.new
new(variant: EnumVariantRef, payload: Fields<ScreenEdge::Right>) -> ScreenEdge
Top.new
new(variant: EnumVariantRef, payload: Fields<ScreenEdge::Top>) -> ScreenEdge
VideoMode
Represents a video mode that a monitor supports
Fields
Functions
| Name | Summary |
|---|---|
new | Constructs a new instance of the type from a table of its fields. |
new
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
VideoModeSelection
References an exclusive fullscreen video mode.
Used when setting WindowMode::Fullscreen on a window.
Variants
| Variant | Fields |
|---|---|
Current | |
Specific | (VideoMode) |
Functions
| Name | Summary |
|---|---|
new | Constructs a new instance of the type from a table of its fields. |
new
new(payload: Fields<VideoModeSelection>) -> VideoModeSelection
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
Variant Functions
| Name | Summary |
|---|---|
Current.new | |
Specific.new |
Current.new
new(variant: EnumVariantRef, payload: Fields<VideoModeSelection::Current>) -> VideoModeSelection
Specific.new
new(variant: EnumVariantRef, payload: Fields<VideoModeSelection::Specific>) -> VideoModeSelection
Window
Component
The defining Component for window entities,
storing information about how it should appear and behave.
Each window corresponds to an entity, and is uniquely identified by the value of their Entity.
When the Window component is added to an entity, a new window will be opened.
When it is removed or the entity is despawned, the window will close.
The primary window entity (and the corresponding window) is spawned by default
by WindowPlugin and is marked with the PrimaryWindow component.
This component is synchronized with winit through bevy_winit:
it will reflect the current state of the window and can be modified to change this state.
Example
Because this component is synchronized with winit, it can be used to perform
OS-integrated windowing operations. For example, here’s a simple system
to change the window mode:
fn change_window_mode(mut windows: Query<&mut Window, With<PrimaryWindow>>) {
// Query returns one window typically.
for mut window in windows.iter_mut() {
window.mode =
WindowMode::Fullscreen(MonitorSelection::Current, VideoModeSelection::Current);
}
}
Fields
| Field | Type |
|---|---|
present_mode | PresentMode |
mode | WindowMode |
position | WindowPosition |
resolution | WindowResolution |
title | String |
name | Optional<String> |
composite_alpha_mode | CompositeAlphaMode |
resize_constraints | WindowResizeConstraints |
resizable | bool |
enabled_buttons | EnabledButtons |
decorations | bool |
transparent | bool |
focused | bool |
window_level | WindowLevel |
canvas | Optional<String> |
fit_canvas_to_parent | bool |
prevent_default_event_handling | bool |
internal | InternalWindowState |
ime_enabled | bool |
ime_position | Vec2 |
window_theme | Optional<WindowTheme> |
visible | bool |
skip_taskbar | bool |
clip_children | bool |
desired_maximum_frame_latency | Optional<NonZeroU32> |
recognize_pinch_gesture | bool |
recognize_rotation_gesture | bool |
recognize_doubletap_gesture | bool |
recognize_pan_gesture | Optional<(u8, u8)> |
movable_by_window_background | bool |
fullsize_content_view | bool |
has_shadow | bool |
titlebar_shown | bool |
titlebar_transparent | bool |
titlebar_show_title | bool |
titlebar_show_buttons | bool |
borderless_game | bool |
prefers_home_indicator_hidden | bool |
prefers_status_bar_hidden | bool |
preferred_screen_edges_deferring_system_gestures | ScreenEdge |
Functions
| Name | Summary |
|---|---|
new | Constructs a new instance of the type from a table of its fields. |
primary | The primary window, or nil if there is none. |
primary_entity | The entity of the primary window, or nil if there is none. |
new
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
primary
primary() -> Optional<Window>
The primary window, or nil if there is none.
primary_entity
primary_entity() -> Optional<Entity>
The entity of the primary window, or nil if there is none.
Methods
| Name | Summary |
|---|---|
cursor_position | The position of the cursor in logical pixels from the top left, or nil if the cursor is outside the window. |
height | The height of the window in logical pixels. |
physical_height | The height of the window in physical pixels. |
physical_width | The width of the window in physical pixels. |
scale_factor | The ratio of physical to logical pixels, for example 2 on a high density screen. |
set_cursor_position | Moves the cursor to the position in logical pixels, or hides it outside the window when given nil. |
size | The size of the window in logical pixels. |
width | The width of the window in logical pixels. |
cursor_position
The position of the cursor in logical pixels from the top left, or nil if the cursor is outside the window.
height
The height of the window in logical pixels.
physical_height
The height of the window in physical pixels.
physical_width
The width of the window in physical pixels.
scale_factor
The ratio of physical to logical pixels, for example 2 on a high density screen.
set_cursor_position
Moves the cursor to the position in logical pixels, or hides it outside the window when given nil.
size
The size of the window in logical pixels.
width
The width of the window in logical pixels.
WindowLevel
Specifies where a Window should appear relative to other overlapping windows (on top or under) .
Levels are groups of windows with respect to their z-position.
The relative ordering between windows in different window levels is fixed. The z-order of windows within the same window level may change dynamically on user interaction.
Platform-specific
- iOS / Android / Web / Wayland: Unsupported.
Variants
| Variant |
|---|
AlwaysOnBottom |
Normal |
AlwaysOnTop |
Functions
| Name | Summary |
|---|---|
new | Constructs a new instance of the type from a table of its fields. |
new
new(payload: Fields<WindowLevel>) -> WindowLevel
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
Variant Functions
| Name | Summary |
|---|---|
AlwaysOnBottom.new | |
AlwaysOnTop.new | |
Normal.new |
AlwaysOnBottom.new
new(variant: EnumVariantRef, payload: Fields<WindowLevel::AlwaysOnBottom>) -> WindowLevel
AlwaysOnTop.new
new(variant: EnumVariantRef, payload: Fields<WindowLevel::AlwaysOnTop>) -> WindowLevel
Normal.new
new(variant: EnumVariantRef, payload: Fields<WindowLevel::Normal>) -> WindowLevel
WindowMode
Defines the way a Window is displayed.
Variants
| Variant | Fields |
|---|---|
Windowed | |
BorderlessFullscreen | (MonitorSelection) |
Fullscreen | (MonitorSelection, VideoModeSelection) |
Functions
| Name | Summary |
|---|---|
new | Constructs a new instance of the type from a table of its fields. |
new
new(payload: Fields<WindowMode>) -> WindowMode
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
Variant Functions
| Name | Summary |
|---|---|
BorderlessFullscreen.new | |
Fullscreen.new | |
Windowed.new |
BorderlessFullscreen.new
new(variant: EnumVariantRef, payload: Fields<WindowMode::BorderlessFullscreen>) -> WindowMode
Fullscreen.new
new(variant: EnumVariantRef, payload: Fields<WindowMode::Fullscreen>) -> WindowMode
Windowed.new
new(variant: EnumVariantRef, payload: Fields<WindowMode::Windowed>) -> WindowMode
WindowPosition
Defines where a Window should be placed on the screen.
Variants
| Variant | Fields |
|---|---|
Automatic | |
Centered | (MonitorSelection) |
At | (IVec2) |
Functions
| Name | Summary |
|---|---|
new | Constructs a new instance of the type from a table of its fields. |
new
new(payload: Fields<WindowPosition>) -> WindowPosition
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
Variant Functions
| Name | Summary |
|---|---|
At.new | |
Automatic.new | |
Centered.new |
At.new
new(variant: EnumVariantRef, payload: Fields<WindowPosition::At>) -> WindowPosition
Automatic.new
new(variant: EnumVariantRef, payload: Fields<WindowPosition::Automatic>) -> WindowPosition
Centered.new
new(variant: EnumVariantRef, payload: Fields<WindowPosition::Centered>) -> WindowPosition
WindowRef
Reference to a Window, whether it be a direct link to a specific entity or
a more vague defaulting choice.
Variants
| Variant | Fields |
|---|---|
Primary | |
Entity | (Entity) |
Functions
| Name | Summary |
|---|---|
new | Constructs a new instance of the type from a table of its fields. |
new
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
Variant Functions
| Name | Summary |
|---|---|
Entity.new | |
Primary.new |
Entity.new
new(variant: EnumVariantRef, payload: Fields<WindowRef::Entity>) -> WindowRef
Primary.new
new(variant: EnumVariantRef, payload: Fields<WindowRef::Primary>) -> WindowRef
WindowResizeConstraints
The size limits on a Window.
These values are measured in logical pixels (see WindowResolution), so the user’s
scale factor does affect the size limits on the window.
Please note that if the window is resizable, then when the window is maximized it may have a size outside of these limits. The functionality required to disable maximizing is not yet exposed by winit.
Fields
Functions
| Name | Summary |
|---|---|
new | Constructs a new instance of the type from a table of its fields. |
new
new(payload: Fields<WindowResizeConstraints>) -> WindowResizeConstraints
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
WindowResolution
Controls the size of a Window
Physical, logical and requested sizes
There are three sizes associated with a window:
- the physical size, which represents the actual height and width in physical pixels the window occupies on the monitor,
- the logical size, which represents the size that should be used to scale elements inside the window, measured in logical pixels,
- the requested size, measured in logical pixels, which is the value submitted to the API when creating the window, or requesting that it be resized.
Scale factor
The reason logical size and physical size are separated and can be different is to account for the cases where:
- several monitors have different pixel densities,
- the user has set up a pixel density preference in its operating system,
- the Bevy
Apphas specified a specific scale factor between both.
The factor between physical size and logical size can be retrieved with
WindowResolution::scale_factor.
For the first two cases, a scale factor is set automatically by the operating
system through the window backend. You can get it with
WindowResolution::base_scale_factor.
For the third case, you can override this automatic scale factor with
WindowResolution::set_scale_factor_override.
Requested and obtained sizes
The logical size should be equal to the requested size after creating/resizing,
when possible.
The reason the requested size and logical size might be different
is because the corresponding physical size might exceed limits (either the
size limits of the monitor, or limits defined in WindowResizeConstraints).
Note: The requested size is not kept in memory, for example requesting a size too big for the screen, making the logical size different from the requested size, and then setting a scale factor that makes the previous requested size within the limits of the screen will not get back that previous requested size.
Fields
Functions
| Name | Summary |
|---|---|
new | Creates a resolution from a size in physical pixels. |
new
new(physical_width: u32, physical_height: u32) -> WindowResolution
Creates a resolution from a size in physical pixels.
local WindowResolution = import_namespace("window").WindowResolution
local resolution = WindowResolution.new(800, 600)
assert(resolution:width() == 800)
let WindowResolution = import_namespace("window").WindowResolution;
let resolution = WindowResolution.new(800, 600);
assert!(resolution.width() == 800.0);
Methods
| Name | Summary |
|---|---|
height | The height in logical pixels. |
scale_factor | The ratio of physical to logical pixels. |
set | Sets the size in logical pixels. |
width | The width in logical pixels. |
height
height(self: WindowResolution) -> f32
The height in logical pixels.
scale_factor
scale_factor(self: WindowResolution) -> f32
The ratio of physical to logical pixels.
set
set(self: WindowResolution, width: f32, height: f32)
Sets the size in logical pixels.
width
width(self: WindowResolution) -> f32
The width in logical pixels.
WindowTheme
The Window theme variant to use.
Variants
| Variant |
|---|
Light |
Dark |
Functions
| Name | Summary |
|---|---|
new | Constructs a new instance of the type from a table of its fields. |
new
new(payload: Fields<WindowTheme>) -> WindowTheme
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
Variant Functions
Dark.new
new(variant: EnumVariantRef, payload: Fields<WindowTheme::Dark>) -> WindowTheme
Light.new
new(variant: EnumVariantRef, payload: Fields<WindowTheme::Light>) -> WindowTheme
window.CursorSystems
The types and functions in the window.CursorSystems namespace, as returned by import_namespace("window.CursorSystems").
Values
| Name | Type |
|---|---|
Update | ReflectSystemSet |
root
The types without a crate, such as primitives.
Types
| Type | Summary |
|---|---|
bool | A boolean value |
char | An 8-bit character |
DynamicFunction | A callable dynamic function |
DynamicFunctionMut | A stateful and callable dynamic function |
f32 | |
f64 | A 64-bit floating point number |
FunctionCallContext | Function call context, if accepted by a function, means the function can access the world in arbitrary ways. |
i128 | A signed 128-bit integer |
i16 | A signed 16-bit integer |
i32 | A signed 32-bit integer |
i64 | A signed 64-bit integer |
i8 | A signed 8-bit integer |
isize | A signed pointer-sized integer |
OsString | A heap allocated OS string |
PathBuf | A heap allocated file path |
ReflectReference | A reference to a reflectable type |
ScriptValue | A value representing the union of all representable values |
StaticTypeRef | A type itself, used to reach its static members, i.e. Vec3 in Vec3.new{}. Functions on it are shared by all types |
str | A string slice |
String | A heap allocated string |
u128 | An unsigned 128-bit integer |
u16 | An unsigned 16-bit integer |
u32 | An unsigned 32-bit integer |
u64 | An unsigned 64-bit integer |
u8 | An unsigned 8-bit integer |
usize | An unsigned pointer-sized integer |
World | The ECS world containing all Components, Resources and Systems. Main point of interaction with a Bevy App. |
bool
A boolean value
Opaque: scripts can't access its fields, only its functions.
Functions
| Name | Summary |
|---|---|
new | Constructs a new instance of the type from a table of its fields. |
new
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
char
An 8-bit character
Opaque: scripts can't access its fields, only its functions.
Functions
| Name | Summary |
|---|---|
new | Constructs a new instance of the type from a table of its fields. |
new
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
DynamicFunction
A callable dynamic function
Opaque: scripts can't access its fields, only its functions.
DynamicFunctionMut
A stateful and callable dynamic function
Opaque: scripts can't access its fields, only its functions.
Functions
| Name | Summary |
|---|---|
new | Constructs a new instance of the type from a table of its fields. |
new
new(payload: Fields<DynamicFunctionMut>) -> DynamicFunctionMut
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
f32
Opaque: scripts can't access its fields, only its functions.
Functions
| Name | Summary |
|---|---|
new | Constructs a new instance of the type from a table of its fields. |
new
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
f64
A 64-bit floating point number
Opaque: scripts can't access its fields, only its functions.
Functions
| Name | Summary |
|---|---|
new | Constructs a new instance of the type from a table of its fields. |
new
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
FunctionCallContext
Function call context, if accepted by a function, means the function can access the world in arbitrary ways.
Opaque: scripts can't access its fields, only its functions.
Functions
| Name | Summary |
|---|---|
new | Constructs a new instance of the type from a table of its fields. |
new
new(payload: Fields<FunctionCallContext>) -> FunctionCallContext
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
i128
A signed 128-bit integer
Opaque: scripts can't access its fields, only its functions.
Functions
| Name | Summary |
|---|---|
new | Constructs a new instance of the type from a table of its fields. |
new
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
i16
A signed 16-bit integer
Opaque: scripts can't access its fields, only its functions.
Functions
| Name | Summary |
|---|---|
new | Constructs a new instance of the type from a table of its fields. |
new
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
i32
A signed 32-bit integer
Opaque: scripts can't access its fields, only its functions.
Functions
| Name | Summary |
|---|---|
new | Constructs a new instance of the type from a table of its fields. |
new
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
i64
A signed 64-bit integer
Opaque: scripts can't access its fields, only its functions.
Functions
| Name | Summary |
|---|---|
new | Constructs a new instance of the type from a table of its fields. |
new
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
i8
A signed 8-bit integer
Opaque: scripts can't access its fields, only its functions.
Functions
| Name | Summary |
|---|---|
new | Constructs a new instance of the type from a table of its fields. |
new
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
isize
A signed pointer-sized integer
Opaque: scripts can't access its fields, only its functions.
Functions
| Name | Summary |
|---|---|
new | Constructs a new instance of the type from a table of its fields. |
new
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
OsString
A heap allocated OS string
Opaque: scripts can't access its fields, only its functions.
PathBuf
A heap allocated file path
Opaque: scripts can't access its fields, only its functions.
ReflectReference
A reference to a reflectable type
Opaque: scripts can't access its fields, only its functions.
Functions
| Name | Summary |
|---|---|
clear | Clears the container, if the reference is an appropriate container type. |
clone | Creates an independent copy of the value, so that changing one doesn’t change the other. |
functions | Lists the functions available on the reference. |
insert | Inserts the value into the reference at the specified index, if the reference is an appropriate container type. |
map_get | Gets and clones the value under the specified key if the underlying type is a map type. |
new | Constructs a new instance of the type from a table of its fields. |
pop | Pops the value from the reference, if the reference is an appropriate container type. |
push | Pushes the value into the reference, if the reference is an appropriate container type. |
remove | Removes the value at the specified key from the reference, if the reference is an appropriate container type. |
variant | If this is an enum, returns a reference to the variant it is currently in. |
variant_name | If this type is an enum, will return the name of the variant it represents on the type. |
clear
clear(reference: ReflectReference)
Clears the container, if the reference is an appropriate container type.
Arguments
reference: The reference to clear.
Returns: Nothing if the reference was cleared
clone
clone(reference: ReflectReference) -> ScriptValue
Creates an independent copy of the value, so that changing one doesn’t change the other.
Arguments
reference: The value to copy.
Returns: The copy.
functions
functions(reference: ReflectReference) -> Vec<FunctionInfo>
Lists the functions available on the reference.
Arguments
reference: The reference to list the functions of.
Returns: The functions available on the reference.
insert
insert(reference: ReflectReference, key: ScriptValue, value: ScriptValue)
Inserts the value into the reference at the specified index, if the reference is an appropriate container type.
Arguments
reference: The reference to insert the value into.key: The index to insert the value at.value: The value to insert.
Returns: Nothing if the value was inserted successfully.
map_get
map_get(reference: ReflectReference, key: ScriptValue) -> Optional<ScriptValue>
Gets and clones the value under the specified key if the underlying type is a map type.
Arguments
reference: The reference to index into.key: The key to index with.
Returns: The value at the key, if the reference is a map.
new
new(payload: Fields<ReflectReference>) -> ReflectReference
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
pop
pop(reference: ReflectReference) -> ScriptValue
Pops the value from the reference, if the reference is an appropriate container type.
Arguments
reference: The reference to pop the value from.
Returns: The value that was popped, if the reference supports popping.
push
push(reference: ReflectReference, value: ScriptValue)
Pushes the value into the reference, if the reference is an appropriate container type.
Arguments
reference: The reference to push the value into.value: The value to push.
Returns: Nothing if the value was pushed successfully.
remove
remove(reference: ReflectReference, key: ScriptValue) -> ScriptValue
Removes the value at the specified key from the reference, if the reference is an appropriate container type.
Arguments
reference: The reference to remove the value from.key: The key to remove the value at.
Returns: The removed value if any
variant
variant(reference: ReflectReference) -> Optional<EnumVariantRef>
If this is an enum, returns a reference to the variant it is currently in.
This can be compared to MyEnum.Variant to check which variant a value is in.
Arguments
reference: The reference to get the variant of.
Returns: The variant, if the reference is an enum.
variant_name
variant_name(reference: ReflectReference) -> Optional<String>
If this type is an enum, will return the name of the variant it represents on the type.
Arguments
reference: The reference to get the variant name of.
Returns: The name of the variant, if the reference is an enum.
Operators
| Name | Summary |
|---|---|
debug | Displays a debug representation of this reference. |
display | Displays this reference and its contents if possible. |
eq | Whether two values are equal, compared through reflection. |
iter | Iterates over the reference, if the reference is an appropriate container type. |
len | Retrieves the length of the reference, if the reference is an appropriate container type. |
debug
debug(reference: ReflectReference) -> String
Displays a debug representation of this reference.
This is useful for debugging and logging.
Arguments
reference: The reference to display.
Returns: The display string.
display
display(reference: ReflectReference) -> String
Displays this reference and its contents if possible.
This is useful for debugging and logging.
Arguments
reference: The reference to display.
Returns: The display string.
eq
eq(reference: ReflectReference, other: ScriptValue) -> bool
Whether two values are equal, compared through reflection.
This is what == uses for types which don’t define their own equality.
Values of different types, and values which can’t be compared, are not equal.
An enum value is equal to an enum variant, i.e. MyEnum.Variant, if it is in that variant.
Arguments
reference: The value to compare.other: The value to compare with.
Returns: Whether the values are equal.
iter
iter(reference: ReflectReference) -> DynamicFunctionMut
Iterates over the reference, if the reference is an appropriate container type.
Returns an “next” iterator function.
The iterator function should be called until it returns nil to signal the end of the iteration.
Arguments
reference: The reference to iterate over.
Returns: The iterator function.
len
len(reference: ReflectReference) -> Optional<usize>
Retrieves the length of the reference, if the reference is an appropriate container type.
Arguments
reference: The reference to get the length of.
Returns: The length of the reference, if the reference is a container.
ScriptValue
A value representing the union of all representable values
Opaque: scripts can't access its fields, only its functions.
Functions
| Name | Summary |
|---|---|
new | Constructs a new instance of the type from a table of its fields. |
new
new(payload: Fields<ScriptValue>) -> ScriptValue
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
StaticTypeRef
A type itself, used to reach its static members, i.e. Vec3 in Vec3.new{}. Functions on it are shared by all types
Opaque: scripts can't access its fields, only its functions.
Functions
| Name | Summary |
|---|---|
add_asset | Adds a value of this type as a new asset, returning a strong handle to it. |
get_asset | The asset a handle points to, or nil if it isn’t loaded or added yet. |
load | Starts loading an asset of this type from a path, returning a handle to it right away. |
new | Constructs a new instance of the type from a table of its fields. |
add_asset
add_asset<A>(asset_type: Type<A>, value: A) -> Handle<A>
Generic over A, the type given as asset_type.
Adds a value of this type as a new asset, returning a strong handle to it.
Arguments
asset_type: The asset type, filled in automatically.value: The asset value.
Returns: A handle to the new asset.
get_asset
get_asset<A>(asset_type: Type<A>, handle: Handle<A>) -> Optional<A>
Generic over A, the type given as asset_type.
The asset a handle points to, or nil if it isn’t loaded or added yet.
Changes to the returned value change the asset.
Arguments
asset_type: The asset type, filled in automatically.handle: The handle to the asset.
Returns: The asset, or nil.
load
Generic over A, the type given as asset_type.
Starts loading an asset of this type from a path, returning a handle to it right away.
Arguments
asset_type: The asset type, filled in automatically.path: The asset path, relative to the assets folder.
Returns: A handle to the asset, which is loaded in the background.
new
new(type: StaticTypeRef, payload: HashMap<String, ScriptValue>) -> ReflectReference
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
type: The type to construct.payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
str
A string slice
Opaque: scripts can't access its fields, only its functions.
String
A heap allocated string
Opaque: scripts can't access its fields, only its functions.
Functions
| Name | Summary |
|---|---|
new | Constructs a new instance of the type from a table of its fields. |
new
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
u128
An unsigned 128-bit integer
Opaque: scripts can't access its fields, only its functions.
Functions
| Name | Summary |
|---|---|
new | Constructs a new instance of the type from a table of its fields. |
new
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
u16
An unsigned 16-bit integer
Opaque: scripts can't access its fields, only its functions.
Functions
| Name | Summary |
|---|---|
new | Constructs a new instance of the type from a table of its fields. |
new
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
u32
An unsigned 32-bit integer
Opaque: scripts can't access its fields, only its functions.
Functions
| Name | Summary |
|---|---|
new | Constructs a new instance of the type from a table of its fields. |
new
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
u64
An unsigned 64-bit integer
Opaque: scripts can't access its fields, only its functions.
Functions
| Name | Summary |
|---|---|
new | Constructs a new instance of the type from a table of its fields. |
new
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
u8
An unsigned 8-bit integer
Opaque: scripts can't access its fields, only its functions.
Functions
| Name | Summary |
|---|---|
new | Constructs a new instance of the type from a table of its fields. |
new
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
usize
An unsigned pointer-sized integer
Opaque: scripts can't access its fields, only its functions.
Functions
| Name | Summary |
|---|---|
new | Constructs a new instance of the type from a table of its fields. |
new
Constructs a new instance of the type from a table of its fields.
Missing fields are filled in from the type’s default, then from the defaults of the fields’ types.
For enums use the variant key, or construct from a variant directly.
Arguments
payload: The fields of the type, keyed by name or index, or a list of the fields in order.
Returns: The constructed value.
World
The ECS world containing all Components, Resources and Systems. Main point of interaction with a Bevy App.
Opaque: scripts can't access its fields, only its functions.
Functions
| Name | Summary |
|---|---|
add_asset | Adds a value as a new asset of its type, returning a strong handle to it. |
add_default_component | Adds the given resource to the world. |
add_observer | Adds an observer which runs the callback callback of the calling script whenever an event of the given type is… |
add_system | Adds the given system to the world. |
asset_path | The path the asset was loaded from, or nil if the handle is invalid or the asset was not loaded from a path. |
despawn | Despawns the given entity. |
despawn_descendants | Despawn the descendants of the given entity. |
despawn_recursive | Despawns the entity and all its descendants. |
exit | Quits the program. |
find_entity_by_name | The first entity with the given Name, or nil if there is none. |
fixed_time | The clock of the fixed update step, which advances in steps of the fixed timestep. |
gamepads | The entities of the connected gamepads. |
get_asset | Retrieves an asset by its handle and asset type registration. |
get_children | Retrieves the children of the given entity. |
get_component | Tries to retrieve the given component type on an entity. |
get_enum_variant | Retrieves the variant of an enum by name. |
get_parent | Retrieves the parent of the given entity. |
get_resource | Retrieves the resource with the given registration. |
get_schedule_by_name | Retrieves the schedule with the given name, Also ensures the schedule is initialized before returning it. |
get_state | The current value of the state of the given type, or nil if the app has no such state. |
get_system_set_by_name | Retrieves a system set by its full name, i.e. |
get_type_by_name | Returns either a ScriptComponentRegistration, ScriptResourceRegistration or ScriptBundleRegistration depending on… |
has_asset | Checks if can get asset handle |
has_component | Checks if the given entity has the given component. |
has_entity | Checks if the given entity exists. |
has_resource | Checks if the world has the given resource. |
insert_bundle | Inserts the given bundle value into the provided entity, all of its components at once. |
insert_children | Inserts the given children entities into the provided parent entity. |
insert_component | Inserts the given component value into the provided entity |
is_loaded | Whether the asset and all of its dependencies are loaded. |
load_asset | Starts loading an asset of the given type from a path, returning a handle to it right away. |
load_state | The loading state of the asset: "NotLoaded", "Loading", "Loaded" or "Failed". |
push_children | Pushes the given children entities into the provided parent entity. |
query | Creates a new ScriptQueryBuilder which can be used to query the ECS. |
real_time | The clock of the real world, which always advances at the system’s pace. |
register_new_component | Registers a new component type with the world. |
register_new_event | Registers a new script event. |
register_new_system_set | Registers a new system set, which script systems can be put in and ordered against. |
remove_component | Removes the given component from the entity. |
remove_resource | Removes the given resource from the world. |
set_next_state | Sets the state to change to in the next state transition, for the type of the given state value. |
spawn | Spawns a new entity and returns it |
spawn_bundle | Spawns a new entity with the given bundle value and returns it. |
time | The default clock: in Update it advances by the frame time, in FixedUpdate by the fixed timestep. |
trigger_event | Triggers an observer-style event: either a Rust event type with #[reflect(Event)], or an event registered with… |
virtual_time | The clock which can be paused and slowed down, it is the one games usually move objects with. |
write_message | Writes a buffered message. The message type must be registered and have #[reflect(Message)]. |
add_asset
add_asset<A>(value: A) -> Handle<A>
Generic over A.
Adds a value as a new asset of its type, returning a strong handle to it.
Arguments
value: The asset value, of a type registered for asset reflection.
Returns: A handle to the new asset.
add_default_component
add_default_component(entity: Entity, registration: ScriptComponentRegistration)
Adds the given resource to the world.
Arguments
registration: The resource to add.
Returns: Nothing if the resource was added successfully.
add_observer
add_observer(event: ScriptTypeRegistration | ScriptEventRegistration, callback: String, components: Optional<Vec<ScriptComponentRegistration>>, entities: Optional<Vec<Entity>>) -> Entity
Adds an observer which runs the callback callback of the calling script whenever an event of the given type is triggered.
The callback is a normal script callback: either a function registered with register_callback, or a top level function with that name.
It receives a copy of the event (or the payload, for script events), and is run by the same machinery as other callbacks:
right after the operation which triggered the event, unless the script’s context is busy running another callback
(e.g. the one that triggered the event), in which case it runs as soon as that callback finishes.
Observers never re-enter a running script. The order in which the observers of an event run is unspecified.
Removed component data is no longer available inside the callback. Errors of the callback are reported like those of other callbacks.
The event type must have #[reflect(Event)]. The lifecycle events (AddEvent, InsertEvent, DiscardEvent,
RemoveEvent, DespawnEvent, imported with import_namespace("bevy_ecs")) are supported out of the box, and run for the given components.
Arguments
event: The type of the event to observe, or an event registered withregister_new_event.callback: The label of the callback to run, receives the event.components: The components the observer is interested in, for component lifecycle events. Ignored for script events.entities: If given, the observer only runs for these entities. Ignored for script events.
Returns: The observer entity, despawn it to remove the observer.
add_system
add_system(schedule: ReflectSchedule, builder: ScriptSystemBuilder) -> ReflectSystem
Adds the given system to the world.
Arguments
schedule: The schedule to add the system to.builder: The system builder specifying the system and its dependencies.
Returns: The system that was added.
asset_path
Generic over A.
The path the asset was loaded from, or nil if the handle is invalid or the asset was not loaded from a path.
Arguments
handle: The handle to the asset.
Returns: The asset path, if known.
despawn
despawn(entity: Entity)
Despawns the given entity.
Arguments
entity: The entity to despawn.
despawn_descendants
despawn_descendants(entity: Entity)
Despawn the descendants of the given entity.
Arguments
entity: The entity to despawn the descendants of.
Returns: Nothing if the descendants were despawned successfully.
despawn_recursive
despawn_recursive(entity: Entity)
Despawns the entity and all its descendants.
Arguments
entity: The entity to despawn recursively.
Returns: Nothing if the entity and its descendants were despawned successfully.
exit
exit()
Quits the program.
Returns: Nothing if the program was exited successfully.
find_entity_by_name
The first entity with the given Name, or nil if there is none.
fixed_time
The clock of the fixed update step, which advances in steps of the fixed timestep.
gamepads
gamepads() -> Vec<Entity>
The entities of the connected gamepads.
get_asset
get_asset<A>(handle_reference: Handle<A>, registration: Type<A>) -> Optional<A>
Generic over A, the type given as registration.
Retrieves an asset by its handle and asset type registration.
Arguments
handle_reference: The handle to the asset (as a reflect reference).registration: The type registration of the asset type.
Returns: The asset reference, if the asset is loaded.
get_children
Retrieves the children of the given entity.
Arguments
entity: The entity to retrieve the children of.
Returns: The children of the entity.
get_component
get_component<A>(entity: Entity, registration: Type<A>) -> Optional<A>
Generic over A, the type given as registration.
Tries to retrieve the given component type on an entity.
Arguments
entity: The entity to retrieve the component from.registration: The component to retrieve.
Returns: The component on the entity, if it exists.
get_enum_variant
get_enum_variant(registration: ScriptTypeRegistration | ScriptComponentRegistration | ScriptResourceRegistration | ScriptBundleRegistration, variant_name: String) -> Optional<EnumVariantRef>
Retrieves the variant of an enum by name.
This is the same as accessing MyEnum.Variant, but works for variants which share a name with a function.
Arguments
registration: The enum type.variant_name: The name of the variant.
Returns: The variant, if the type is an enum with such a variant.
get_parent
Retrieves the parent of the given entity.
Arguments
entity: The entity to retrieve the parent of.
Returns: The parent of the entity
get_resource
get_resource<A>(registration: Type<A>) -> Optional<A>
Generic over A, the type given as registration.
Retrieves the resource with the given registration.
Arguments
registration: The registration of the resource to retrieve.
Returns: The resource, if it exists.
get_schedule_by_name
get_schedule_by_name(name: String) -> Optional<ReflectSchedule>
Retrieves the schedule with the given name, Also ensures the schedule is initialized before returning it.
Schedules in bevy are “containers” for systems, each schedule runs separately and contains different systems.
By default among others bevy contains the following schedules:
Update: Runs every frame.PostUpdate: Runs after theUpdateschedule.FixedUpdate: Runs at a fixed rate.
Arguments
name: The name of the schedule to retrieve.
Returns: The schedule with the given name, if it exists
get_state
get_state<A>(state_type: Type<A>) -> Optional<A>
Generic over A, the type given as state_type.
The current value of the state of the given type, or nil if the app has no such state.
The state type is passed as its registration, see world.get_type_by_name.
get_system_set_by_name
get_system_set_by_name(name: String) -> Optional<ReflectSystemSet>
Retrieves a system set by its full name, i.e. transform.TransformSystems.Propagate for a set of the game,
or script.my_game.ai for a set registered by a script.
The sets of the game are also members of their namespace, i.e. import_namespace("transform.TransformSystems").Propagate.
Arguments
name: The full name of the system set.
Returns: The system set with the given name, if it exists.
get_type_by_name
get_type_by_name<A>(type_name: Type<A>) -> Optional<Type<A>>
Generic over A, the type given as type_name.
Returns either a ScriptComponentRegistration, ScriptResourceRegistration or ScriptBundleRegistration depending on the type of the type requested.
If the type is none of these returns a ScriptTypeRegistration.
Arguments
type_name: The full path of the type to retrieve, i.e.bevy_transform::components::transform::Transformorscript.my_game.Enemy.
Returns: The registration of the type, if it exists.
has_asset
Generic over A.
Checks if can get asset handle
has_component
has_component(entity: Entity, registration: ScriptComponentRegistration) -> bool
Checks if the given entity has the given component.
Arguments
entity: The entity to check.registration: The component to check for.
Returns: Whether the entity has the component.
has_entity
Checks if the given entity exists.
Returns: Whether the entity exists.
has_resource
has_resource(registration: ScriptResourceRegistration) -> bool
Checks if the world has the given resource.
Arguments
registration: The registration of the resource to check for.
Returns: Whether the world has the resource.
insert_bundle
insert_bundle(entity: Entity, registration: ScriptBundleRegistration, value: ReflectReference)
Inserts the given bundle value into the provided entity, all of its components at once.
The bundle type must be registered in rust with #[reflect(Bundle)].
Arguments
entity: The entity to insert the bundle into.registration: The bundle registration of the bundle to insert.value: The value of the bundle to insert. Can be constructed like any other value, i.e. usingconstructor the type’snewfunction.
Returns: Nothing if the bundle was inserted successfully.
insert_children
Inserts the given children entities into the provided parent entity.
Arguments
entity: The parent entity to receive childrenindex: The index to insert the children atchildren: The children entities to insert
Returns: Nothing if the children were inserted successfully.
insert_component
insert_component<A>(entity: Entity, registration: Type<A>, value: A)
Generic over A, the type given as registration.
Inserts the given component value into the provided entity
Arguments
entity: The entity to insert the component into.registration: The component registration of the component to insert.value: The value of the component to insert. Can be constructed usingconstruct
Returns: Nothing if the component was inserted successfully.
is_loaded
Generic over A.
Whether the asset and all of its dependencies are loaded.
Arguments
handle: The handle to the asset.
Returns: Whether the asset and its dependencies are loaded.
load_asset
Generic over A, the type given as asset_type.
Starts loading an asset of the given type from a path, returning a handle to it right away.
Arguments
path: The asset path, relative to the assets folder.asset_type: The type of the asset, i.e.bevy_mod_scripting_asset::script_asset::ScriptAsset.
Returns: A handle to the asset, which is loaded in the background.
load_state
Generic over A.
The loading state of the asset: "NotLoaded", "Loading", "Loaded" or "Failed".
Arguments
handle: The handle to the asset.
Returns: The name of the loading state.
push_children
Pushes the given children entities into the provided parent entity.
Arguments
entity: The parent entity to receive childrenchildren: The children entities to push
Returns: Nothing if the children were pushed successfully.
query
query() -> ScriptQueryBuilder
Creates a new ScriptQueryBuilder which can be used to query the ECS.
Returns:
query: The new query builder.
real_time
The clock of the real world, which always advances at the system’s pace.
register_new_component
register_new_component(namespace: String, name: String, allow_existing: Optional<bool>) -> ScriptComponentRegistration
Registers a new component type with the world.
The component will behave like any other native component for all intents and purposes.
The type that will be instantiated to back this component will be DynamicComponent which contains just one field:
data
This field can be set to any value and modified freely.
Arguments
namespace: The script namespace to register the component in, it must start withscript., i.e.script.my_game. Scripts cannot add to other namespaces.name: The name of the component type, unique within the namespace. The component can later be found asimport_namespace(namespace).name.allow_existing: If true, returns the registration of the already registered component with this name instead of failing. Defaults to false.
Returns: The registration of the new component type if successful.
register_new_event
register_new_event(namespace: String, name: String, allow_existing: Optional<bool>) -> ScriptEventRegistration
Registers a new script event.
Script events carry an arbitrary payload, and can be observed with add_observer and triggered with trigger_event.
Arguments
namespace: The script namespace to register the event in, it must start withscript., i.e.script.my_game.name: The name of the event, unique within the namespace.allow_existing: If true, returns the already registered event with this name instead of failing. Defaults to false.
Returns: The handle of the new event.
register_new_system_set
register_new_system_set(namespace: String, name: String, allow_existing: Optional<bool>) -> ReflectSystemSet
Registers a new system set, which script systems can be put in and ordered against.
The set is removed from its namespace when the script unloads, registering it again (i.e. after a reload) gives the same set.
Arguments
namespace: The script namespace to register the set in, it must start withscript., i.e.script.my_game.name: The name of the set, unique within the namespace. The set can later be found asimport_namespace(namespace).name.allow_existing: If true, returns the already registered set with this name instead of failing. Defaults to false.
Returns: The new system set.
remove_component
remove_component(entity: Entity, registration: ScriptComponentRegistration)
Removes the given component from the entity.
Arguments
entity: The entity to remove the component from.registration: The component to remove.
Returns: Nothing if the component was removed successfully or didn’t exist in the first place.
remove_resource
remove_resource(registration: ScriptResourceRegistration)
Removes the given resource from the world.
Arguments
registration: The resource to remove.
Returns: Nothing if the resource was removed successfully or didn’t exist in the first place.
set_next_state
set_next_state(value: ReflectReference)
Sets the state to change to in the next state transition, for the type of the given state value.
Errors if the value is not of a state type that the app has.
spawn
spawn() -> Entity
Spawns a new entity and returns it
Returns: The newly spawned entity
spawn_bundle
spawn_bundle(registration: ScriptBundleRegistration, value: ReflectReference) -> Entity
Spawns a new entity with the given bundle value and returns it.
Arguments
registration: The bundle registration of the bundle to insert.value: The value of the bundle to insert.
Returns: The newly spawned entity
time
time() -> Time<()>
The default clock: in Update it advances by the frame time, in FixedUpdate by the fixed timestep.
trigger_event
trigger_event(event: ScriptTypeRegistration | ScriptEventRegistration, value: Optional<ScriptValue>)
Triggers an observer-style event: either a Rust event type with #[reflect(Event)], or an event registered with register_new_event.
Observers run immediately, and the commands they queue are applied before this function returns.
Arguments
event: The type of the event, or the script event.value: The event value, e.g. built withconstruct, for Rust events. Any value (or nothing) for script events, which is passed to the observers.
Returns: Nothing if the event was triggered successfully.
virtual_time
The clock which can be paused and slowed down, it is the one games usually move objects with.
write_message
write_message(registration: ScriptTypeRegistration, message: ReflectReference)
Writes a buffered message. The message type must be registered and have #[reflect(Message)].
Arguments
registration: The type of the message.message: The message value, e.g. built withconstruct.
Returns: Nothing if the message was written successfully.
Developing BMS
This section is for developers who want to contribute to the BMS project. It covers various topics necessary for understanding the project and contributing to it.
Contributing
Please see the code of conduct as well as the contributing guidelines first.
In this section
- Setup: preparing a local development environment
- Writing Bindings: adding bindings for Bevy crates
- New Languages: what it takes to support another scripting language
- RFCs: design proposals and their discussion
Setup
BMS uses an xtask setup, which sets up everything you need for local development:
cargo xtask init
It currently configures the following IDEs:
If you’d like to add support for another IDE, please feel free to open a PR!
Writing Bindings
The bevy bindings shipped with BMS are hand written, using the #[script_bindings] macro (see Controlling Script Bindings).
They live in crates/bindings/bevy_mod_scripting_bevy_<category>_bindings, one crate per area of functionality (i.e. math, ecs, ui) rather than one per upstream bevy crate.
The aim is a small, well documented scripting surface, which reads naturally from a script and compiles quickly.
Namespaces
Scripts reach types through the namespace of their category, i.e. import_namespace("math").Vec3 (see Namespaces). So each bindings crate:
- passes
namespace = "<category>"to every#[script_bindings]attribute, except onimpl Worldblocks and on functions shared by all types (impl StaticTypeRef), which would otherwise move those BMS types into the category - calls
set_crate_script_namespacesfrom its plugin’sfinish, with the bevy crates it covers, so their types without bindings land in the same namespace
Generic types
Declare the generic types of the crate from its plugin, in the namespace of the category (register_generic_type::<Time<A>>("time", ...)), and use the markers in generic function signatures, see Generics.
Only declare types whose parameter is part of what they are (Handle, Time, ButtonInput), not containers like Arc<T>. Undeclared instantiations get a class each, named after their arguments (render.MeshExtractableData.Indices).
What to bind
Every reflected type is already usable from scripts without any bindings:
- fields are read and written through references, i.e.
transform.translation.x = 2 - every type can be constructed with
Type.new({...}), see Constructing Arbitrary Types - enum variants are available as
Type.Variant - containers support
len,iter,pushetc., and every value can be printed
So only bind what scripts can’t already do, or can’t do comfortably:
- methods with behaviour, i.e.
Vec3:normalize()orTransform:look_at(...) - constructors for types which are built often (vectors, colors), or whose fields are private (i.e.
Name), or whose meaning isn’t obvious from their fields (i.e.Quat.from_rotation_y) - operators, by registering functions named
add,sub,mul,div,rem,neg,pow,eqorlt. With a number on the left, i.e.2 * v,addandmulare called with the operands swapped, the others callrsub,rdiv,rremorrpowon the right operand, which you register where they make sense
Do not write getters or setters for public fields.
Performance
- Take non primitive arguments as
R<T>orM<T>. These are a downcast of the reference the script holds, whileV<T>rebuilds the value through reflection. Clone natively if you need ownership. - Return a reference with an extended path when returning a part of the receiver; it costs nothing, and writes to it reach the original value. Returning
V<T>allocates a new value. - There is one function per name: registering a name again replaces the function. For mixed operands accept a
Union, i.e.rhs: Union<R<Vec3>, f32>. - Mutate in place by taking
M<Self>; pure functions return new values.
Native types
Hot value types, i.e. Vec3, can be stored by the languages themselves instead of being referenced through the world. Functions read them without converting to ScriptValues:
// fields are read and written with typed accessors
script_native!(world, Vec3 { x: f32, y: f32, z: f32 });
// components (and resources) of native types are native handles: `get_component` returns one, `t.translation` is a
// handle to the field, `t.translation.x = 5` writes the component
script_native!(world, Transform { translation: Vec3, rotation: Quat, scale: Vec3 });
Values of types with fields of native types (Transform.from_xyz(..)) stay references, so writes to their fields aren’t lost on a copy. Handles claim access to their component for each call, and error once the entity or component is gone. Arguments which aren’t native, i.e. references, are converted as usual.
Documentation
Doc comments end up in the generated docs and in editor declaration files, and are read by script writers rather than Rust developers:
- start with one short sentence, and only describe the arguments when they are not obvious
- avoid Rust specific terms, i.e. say “or nil” rather than
Option - link bevy types using their full Rust path, i.e.
[`Vec3`](glam::Vec3), these will be resolved to the bevy docs
Examples
Keep examples short and only add them where they help. Write one block per language, one after the other, using the multi-lang-example code block attribute followed by the language:
```multi-lang-example,lua
local Vec3 = import_namespace("math").Vec3
local v = Vec3.new(1, 2, 3)
assert(v.x == 1)
```
```multi-lang-example,rune
let Vec3 = import_namespace("math").Vec3;
let v = Vec3.new(1, 2, 3);
assert!(v.x == 1.0);
```
which renders as a single block with a tab per language:
local Vec3 = import_namespace("math").Vec3
local v = Vec3.new(1, 2, 3)
assert(v.x == 1)
let Vec3 = import_namespace("math").Vec3;
let v = Vec3.new(1, 2, 3);
assert!(v.x == 1.0);
Examples are tests: they must run as written and check their own results with assert.
Every multi-lang-example block in the doc comments under crates/ and in the book is run by the doc_example_tests test, with the scenario in assets/doc_examples/default.bmsscenario (the same app as the script tests):
cargo test --test doc_example_tests --features lua54,rune,bevy_math_bindings -- math
Examples of a bindings crate whose feature is disabled are ignored.
If an example needs a different setup, i.e. a window, name a scenario with the scenario attribute, i.e. multi-lang-example,lua,scenario=window, which refers to assets/doc_examples/window.bmsscenario.
Mark examples which can’t run in a test app with ignore, i.e. multi-lang-example,lua,ignore, and say what they need in the surrounding docs.
Tests
Each bindings crate has its script tests under assets/tests/bindings/<category>/, with a script per language per type or topic, i.e. assets/tests/bindings/math/vec.lua and assets/tests/bindings/math/vec.rn.
Run them with:
cargo test --test script_tests --features lua54,rune -- bindings/math
Adding New Languages to BMS
If you are interested in adding a new language to BMS, please read this section first. Adding a new language is a non-trivial task depending on the language you want to add. It also requires a lot of effort and time to maintain a new language, so unless the language you want to add is widely used and has a large community, it might not be worth the effort.
Evaluating Feasibility
In order for a language to work well with BMS it’s necessary it supports the following features:
- Interoperability with Rust. If you can’t call it from Rust easilly and there is no existing crate that can do it for you, it’s a no-go.
- First class functions. Or at least the ability to call an arbitrary function with an arbitrary number of arguments from a script. Without this feature, you would need to separately generate code for the bevy bindings which is painful and goes against the grain of BMS.
First Classs Functions
They don’t necessarily have to be first class from the script POV, but they need to be first class from the POV of the host language. This means that the host language needs to be able to call a function with an arbitrary number of arguments.
Examples
Let’s say your language supports a Value type which can be returned to the script. And it has a Value::Function variant. The type on the Rust side would look something like this:
pub enum Value {
Function(Arc<Fn(&[Value]) -> Value>),
// other variants
}
This is fine, and can be integrated with BMS. Since an Fn function can be a closure capturing a DynamicScriptFunction. If there is no support for FnMut closures though, you might face issues in the implementation. Iterators in bevy_mod_scripting_functions for example use DynamicScriptFunctionMut which cannot work with Fn closures.
Now let’s imagine instead another language with a similar enum, supports this type instead:
#![allow(unused)]
fn main() {
pub enum Value {
Function(Arc<dyn Function>),
// other variants
}
pub trait Function {
fn call(&self, args: Vec<Value>) -> Value;
fn num_params() -> usize;
}
}
This implies that to call this function, you need to be able to know the amount of arguments it expects at COMPILE time. This is not compatibile with dynamic functions, and would require a lot of code generation to make work with BMS. Languages with no support for dynamic functions are not compatible with BMS.
Interoperability with Rust
Not all languages can easilly be called from Rust. Lua has a wonderful crate which works out the ffi and safety issues for us. But not all languages have this luxury. If you can’t call it from Rust easilly and there is no existing crate that can do it for you, integrating with BMS might not be the best idea.
Necessary Features
In order for a language to be called “implemented” in BMS, it needs to support the following features.
Values
Every ScriptValue variant needs a counterpart in the language, in both directions. Two of them are handles rather than data:
ScriptValue::Reference: a reference to a reflected value, usually a userdata/custom type wrappingReflectReference.ScriptValue::Type: a type itself, i.e. what scripts use to reach a type’s static members. It carries only aTypeIdand never allocates.
Every context gets the builtins as globals, nothing else: bevy_mod_scripting_bindings::builtins::builtins() (import_namespace, export_namespace) plus the language’s own register_callback:
for (name, function) in builtins() {
context.globals().set(name, LuaScriptValue::from(ScriptValue::Function(function)))?;
}
Script handlers, loaders etc. must be implemented such that the ThreadWorldContainer is set for every interaction with script contexts, or anywhere else it might be needed.
Typed calls and native values
A language calls every function with DynamicScriptFunction::call_with (see bevy_mod_scripting_bindings::native), passing:
- an
ArgSourceover its own values: numbers, booleans, native values, and any argument converted to aScriptValue(the slow path) - a
ReturnSink, which receives numbers, booleans, new native values orScriptValues
DynamicScriptFunctionMut converts into a DynamicScriptFunction (.into()), so both are called the same way.
Native values are stored by the language as NativeStorage ([NativeHeader][value]): in memory it owns which never moves (a Lua userdata), or in a NativeBox. The language reaches their fields through the NativeType’s accessors and their methods through the functions registered on the type; anything else goes through NativeStorage::to_script_value, a reference to a copy. A language can decline native values (ReturnSink::native returning false), which then come back as references.
Dispatching to Rust
All lookup rules live in bevy_mod_scripting_bindings::dispatch; a language maps its operators and metamethods onto it, and converts the values:
| Script operation | dispatch function |
|---|---|
v.name, v[key] | index, returns Member::Method or Member::Static |
v.name = x | set_index |
Type.name on a ScriptValue::Type | static_index |
v + x, -, *, /, %, ^, ==, < | binary with the matching ScriptOperatorNames (dispatches to add, sub, mul, div, rem, pow, eq, lt) |
2 * v (value on the right) | binary too, which calls the operator’s reflected function (mul, rsub, …) |
-v | unary with Negation (neg) |
#v | len (lists directly, references through len) |
| iteration | iter, returns a function to call until it returns ScriptValue::Unit |
| printing | display / debug |
Receivers
index returns functions which are called on the indexed value as Member::Method, without the value bound to them. Delivering the receiver is the language’s job:
- Lua passes it with its colon syntax,
v:length(), so the function is returned as is. - Rune has method syntax, but resolves
v.nameby a table fixed when its context is built, so every identifier in the script is registered when it is compiled (andv["name"]always works), seebevy_mod_scripting_rune::types. The receiver is passed to the function as the first argument.
Static members
Type.name resolves, in order, to:
- functions registered on the type itself
- functions shared by all types (registered on
StaticTypeRef, i.e. thenewconstructor), with the type bound as their first argument byDynamicScriptFunction::bind_to_type - the type’s enum variants
Types reach scripts in two forms, which resolve static members the same way:
ScriptValue::Type, i.e.world(import_namespace("bms").world), indexed withdispatch::static_index- type registrations, i.e. the entries of
import_namespace, which are references and are indexed withdispatch::indexlike any other value
Binding the type is done by BMS, so languages never handle StaticTypeRef arguments themselves.
RFCs
An RFC is a request for comments from contributors, users and various other stakeholders. When an RFC is created it is usually done with the intention of gathering opinions and knowledge around the topic.
For BMS the process looks as follows:
- An RFC is created and modified via PRs to the RFC file under
docs/src/RequestsForComments/XX-RFCTITLE/XX-RFCTITLE.md. - The creator of an RFC also starts an issue for discussion of the RFC on github linking to the file.
- Once enough perspectives are gathered an RFC can be closed and the decision implemented.
Abandoning Codegen
Summary
Codegen has played a big role from the start for BMS, giving us great benefits, but mainly the ability to quickly ‘sync’ our scripting API with each new bevy release (instead of a manual review each time).
This was especially important before the introduction of a unified scripting function registry, which would have meant writing a version of each API per language.
However, I believe that as Bevy is maturing, the APIs that people rely on are likely to be more stable than ever, and I have a hypothesis that a large majority of the generated bindings are simply left unused.
The other side of the coin is that codegen is somewhat problematic due to:
- Largely increased compilation times
- The need to stay in sync with the rustc codebase (the compiler internals we use to plug into the compilation)
I believe it’s time to finally abandon this concept, and commit to hand writing a core scripting API over the important parts of bevy.
Status Quo
A little context for those who are not aware of how codegen works in our case.
Automatic Bindings
The code under /codegen contains crates which create a custom cargo executable (a driver and the entry point). This works with cargo to execute a custom rustc compilation, which on top of compiling and error checking the code, also runs our custom hooks.
In these hooks we scan through the available types and generate artifacts as we go (caches and lookups), which are then used to render code templates. All of the crates found under crates/bindings are fully rendered via this process.
These templates direct the generator to produce #[script_bindings] invocations, just as if they were handwritten, based on the functions available.
The process is slightly limited due to the presence of generics and other rust quirks which can’t be handled automatically, e.g. fn hello<A: ToString>(a: A) wouldn’t work, even though it’s somewhat trivial to deal with by hand.
At the end we are left with tonnes of bindings crates for all the important bevy crates.
An example can be seen in our book with the SRGBA struct:
Note that the docgen is not tied to codegen, the same documentation would be produced if you manually wrote the script bindings macro invocations yourself.
Existing Manual Bindings
Not all of our bindings are automatically generated like this however. The crate bevy_mod_scripting_functions contains a load of hand-written core types and functions, like World::get_type_by_name or World::get_component, and way more.
These already live happily alongside the generated bindings, and are the model for what this RFC proposes we do everywhere.
Motivation
With the above in mind, I form the following hypotheses:
- Automatically generated bindings are okay at best, with many functions missing and docs mentioning rust constructs explicitly (since they come directly from docstrings)
- Most of them are unused
- The lack of functionality for generating bindings for 3rd party libraries means the codegen is not as useful as it could be
- Bevy’s API is stabilizing, and upcoming work on enums and constructors will make many bindings unnecessary anyway
Proposal
Based on the above, I propose the following:
- Handwriting binding crates with high quality multi language docstrings
- Empowering the community to build their own bindings crates for their favourite libraries
In this new world we would focus on writing the most critical pieces of integration with bevy. Instead of putting in effort to maintain a bespoke rustc compiler plugin, we could provide github action templates to let people build out bindings quickly.
Migration
The codegen runs on our side, not on the consumer’s machine, and its output is committed. So no feature flag or default-on/off transition is needed:
- Remove the
codegenproject, keeping whatever it last generated as plain source. - Iterate on and clean up those bindings, deleting ones that are no longer needed as the enum and constructor work lands.
This starts from a non-breaking state, and I’d like to begin as early as the 0.20 cycle rather than waiting for the editor.
Bindings for 3rd party libraries (e.g. bevy_hanabi, UI, physics) would not live in core, which would only keep Bevy-native bindings. Instead we’d make it easy to set up small community bindings crates that sync to the main test suite and publish easily.
Alternatives
We could also of course make our current codegen better, more flexible and generally stronger, however some of its core problems will always remain (like bad documentation at best, and long compilation times).
Benefits
- Clean compilation times have potential to go down by as much as 10 minutes (on my machine), which also makes clean CI builds cheaper
- Bevy bindings quality increases, and a smaller API surface is easier for beginners
- Intermediate file sizes decrease (i.e. LAD files, LUA declaration files)
Drawbacks
- Each bevy version upgrade might take longer, due to the need to identify API surface changes. However, this should be fairly well mitigated by our test suite and also thanks to AI tools nowadays
- Potentially smaller (but hopefully higher quality) API surface immediately after the switch
Release Notes
This section contains migration guides and release notes relevant to the bevy_mod_scripting crate.
This used to live in the repository, so for older release notes or guides, refer to the GitHub repository
Migration Guide: 0.13 to 0.14-alpha or 0.14 to 0.15
The most important changes to be aware of in this release are:
-
BMS now uses
Handle<ScriptAsset>as its principle means of referring to scripts as opposed to theScriptIdthat was used previously. -
BMS exposes many more choices for deciding how scripts are associated with the contexts in which they run.
-
script_idis replaced withscript_assetwhich now has a type ofHandle<ScriptAsset>.
Handles
The use of handles for scripts is perhaps the biggest user-facing change. It makes BMS asset usage follow Bevy’s conventions. It requires less configuration. It is more idiomatic.
ScriptComponent Change
In prior versions, ScriptComponent accepted a vector of ScriptIds, which was a type alias for Cow<'static, str>.
-pub struct ScriptComponent(pub Vec<Cow<'static, str>>);
+pub struct ScriptComponent(pub Vec<Handle<ScriptAsset>>);
Because ScriptComponent accepts handles, it is no longer necessary to store the handles somewhere to prevent the script from unloading. Nor is it necessary to configure an asset path to script id mapper.
ScriptComponent(vec![asset_server.load("foo.lua")])
It is still beneficial to retain script assets in memory, for certain features to work. For example,
script_asset will not be able to retrieve the asset path of the script if it’s not retained.
ScriptId Change
The ScriptId has changed from being a string to being an asset ID.
-type ScriptId = Cow<'static, str>
+type ScriptId = AssetId<ScriptAsset>
No Evaluation on Load
In prior versions, BMS would immediately evaluate a ScriptAsset when it was loaded, and if multiple script assets were loaded, they would be evaluated in non-deterministic order. (See issue #426.) Script assets no longer evaluate immediately. Script assets are only evaluated when their handles are added to a ScriptComponent or they are added to StaticScripts.
In addition when a ScriptComponent loads its scripts, it loads them sequentially.
ScriptAssetSettings Removed
The ScriptAssetSettings has been removed. Let us address each of its fields in turn.
script_id_mapper
See AssetPathToScriptIdMapper section.
extension_to_language_map and supported_extensions
This is now represented by the LanguageExtensions resource, which can be configured directly during initialization
pub struct LanguageExtensions(HashMap<&'static str, Language>);
or by the ConfigureScriptAssetSettings trait:
app.add_supported_script_extensions(&["p8lua"], Language::Lua);
In addition one can configure the language of an asset when it is loaded:
asset_server.load_with_settings("hello.p8lua", |settings: &mut ScriptSettings| {
settings.language = Some(Language::Lua);
});
or when it is created:
let content = String::from("x = 0");
let mut script = ScriptAsset::from(content);
script.language = Language::Lua;
ScriptMetadata and ScriptMetadataStore Removed
These were present to associate the previous ScriptId with the asset ID and language.
That is no longer necessary as the ScriptAsset knows its own language.
pub struct ScriptAsset {
/// The body of the script
pub content: Box<[u8]>,
/// The language of the script
pub language: Language,
}
AssetPathToScriptIdMapper Removed
No mapper is necessary between a script and a script ID. If you have a script handle, you have its script ID
let handle: Handle<ScriptAsset> = ...;
let script_id: ScriptId = handle.id(); // ScriptId = AssetId<ScriptAsset>
and vice versa.
let script_id: ScriptId = ...;
let handle: Handle<ScriptAsset> = Handle::Weak(script_id);
Contexts
Choosing how scripts run is a big policy decision. Previously BMS had two options:
- Each script ran in its own context.
- All scripts ran in one context.
This was controlled by the enable_context_sharing() method on
ConfigureScriptPlugin. That function is now deprecated. Instead use the set_context_policy method:
app.add_plugins(LuaScriptingPlugin::default().set_context_policy(
ContextPolicy::shared(),
));
The reason for this change is there are many more choices than before, namely:
ContextPolicy::shared()ContextPolicy::per_script()ContextPolicy::per_entity()ContextPolicy::per_entity_and_script()
See Contexts for more information.
ContextKey Added
Previously BMS used a ScriptId and sometimes an Entity to refer to a
context. If there was no entity then Entity::from_raw(0) was used. Instead BMS
now uses this ContextKey to look up contexts.
pub struct ContextKey {
/// Entity if there is one.
pub entity: Option<Entity>,
/// Script ID if there is one.
pub script_id: Option<Handle<ScriptAsset>>
}
This change affects the parameters for the context_pre_handling_initializers
- context_pre_handling_initializers: vec![|script_id, entity, context| {
+ context_pre_handling_initializers: vec![|context_key, context| {
and context_initializers:
- context_initializers: vec![|script_id, context| {
+ context_initializers: vec![|context_key, context| {
Recipients Changes
The Recipients enum now looks like this:
#[derive(Clone, Debug)]
pub enum Recipients {
/// The event needs to be handled by all scripts, if multiple scripts share a context, the event will be sent once per script in the context.
AllScripts,
/// The event is to be handled by all unique contexts, i.e. if two scripts share the same context, the event will be sent only once per the context.
AllContexts,
/// The event is to be handled by a specific script-entity pair
ScriptEntity(ScriptId, Entity),
/// the event is to be handled by a specific static script
StaticScript(ScriptId),
}
This aligns with how scripts are associated with contexts better.
ScriptCallbackEvent changes
The language for recipients is now controlled through the language field of the ScriptCallbackEvent. This allows for more flexibility in how callbacks are handled, especially when multiple languages are involved.
If no language is specified, the callback will apply to all languages.
#[derive(Clone, Event, Debug)]
#[non_exhaustive]
pub struct ScriptCallbackEvent {
/// The label of the callback
pub label: CallbackLabel,
/// The recipients of the callback
pub recipients: Recipients,
/// The language of the callback, if unspecified will apply to all languages
+ pub language: Option<Language>
/// The arguments to the callback
pub args: Vec<ScriptValue>,
/// Whether the callback should emit a response event
pub trigger_response: bool,
}
Bindings Changes
ScriptId
script_id is replaced with script_asset which now has a type of Handle<ScriptAsset>. This means that you can no longer use a string to refer to a script, but rather you must use a handle.
Scripts can still access the asset path of the script using:
-- prints: "my_script.lua"
print(script_asset:asset_path())
ScriptAttachment
The concept of script attachments has been introduced to describe the idea of a script instance. Previously this was muddied due to the fact script ID’s were the primary way to refer to scripts. Now the instance of a script and its mapping to a context is clearer.
This is reflected in a brand new set of bindings:
-- will create backing ScriptAttachment instances, that can be used in other bindings.
local entity_script = ScriptAttachment.new_entity_script(entity, script_asset)
local static_script = ScriptAttachment.new_static_script(script_asset)
System Builder
the system builder no longer accepts script id’s as parameters. Instead it accepts script attachments
-system_builder("my_callback", "this_script_id.lua")
+system_builder("my_callback", ScriptAttachment.new_static_script(script_asset))
0.15.0 - Asset Handles and Context Policies
This release focuses on aligning bevy_mod_scripting with modern Bevy practices, most notably by switching to Handle<ScriptAsset> for script management. This change simplifies the API, removes boilerplate, and makes script handling more idiomatic.
Summary
Asset-First Workflow
Scripts are now treated as first-class Bevy assets. The old ScriptId (which was a string) has been replaced by AssetId<ScriptAsset>, and you’ll primarily interact with scripts via Handle<ScriptAsset>.
// New way
let handle: Handle<ScriptAsset> = asset_server.load("my_script.lua");
commands.spawn(ScriptComponent(vec![handle]));
Scripts are now only evaluated when they are attached to a ScriptComponent or added to StaticScripts, which means you have more control over when and how scripts are executed.
Flexible Context Policies
You now have much finer control over how script contexts (i.e., the environment a script runs in) are created. The old enable_context_sharing() has been replaced with set_context_policy() which accepts a ContextPolicy:
ContextPolicy::shared(): All scripts run in one global contextContextPolicy::per_script(): Each script asset gets its own context (the old default.)ContextPolicy::per_entity(): Each entity with scripts gets its own context.ContextPolicy::per_entity_and_script(): A unique context for every script on every entity (the new default).
This means that each script is maximally isolated by default, but you can still opt for shared contexts if needed.
Other Changes
RecipientsEnum: TheRecipientsenum for events has been redesigned to align with the new context policies, offeringAllScriptsandAllContextsvariants, and removing some variants which don’t fit the new model. If you need the old behaviour, you can simply query the ECS first before sending events.- API Cleanup: Several types and traits were removed or simplified, including
ScriptAssetSettings,AssetPathToScriptIdMapper, andScriptMetadataStore, as they are no longer needed with the new asset-based approach.
Migration Guide
This release contains significant breaking changes. Please refer to the migration guide for detailed instructions on updating your project.
Migrating to 0.16.0
https://github.com/makspll/bevy_mod_scripting/pull/455
Replace all usages of CallbackSettings<P>.callback_handler with P::handler()(..) and P::handle(..)
https://github.com/makspll/bevy_mod_scripting/pull/456
Replace all usages of CallbackBuilder<P>.load and CallbackBuilder<P>.reload with P::load(..) and P::reload(..) or P::context_loader()(..) and P::context_reloader()(..)
https://github.com/makspll/bevy_mod_scripting/pull/463
If you were relying on BMS enabling some features in Bevy crates, your builds might be pulling in less features than you expect. Ensure you explicitly select all features you need from bevy. BMS will now only pull in strictly necessary features and crates from bevy
https://github.com/makspll/bevy_mod_scripting/pull/470
Switch all references of ContextLoadingSettings to P::readonly_config(world.id()).
https://github.com/makspll/bevy_mod_scripting/pull/471
RuntimeSettings and RuntimeContainer are removed, replace usages with P::readonly_settings(world.id()).runtime) access to initializers is no longer possible outside the plugin setup phase
https://github.com/makspll/bevy_mod_scripting/pull/472
if you implemented a scripting plugin you will need to correct your function signatures for the above aliases, and fetch the config yourself to access callbacks via Plugin::readonly_configuration(world_id) using the world id you will now receive.
https://github.com/makspll/bevy_mod_scripting/pull/473
references to StaticScripts should be replaced with appropriate resident calls on ScriptContext filtered by the attachment kind
https://github.com/makspll/bevy_mod_scripting/pull/474
- ScriptContext Access: Use
.read()and.write()to access ScriptContext (now wrapped inArc<RwLock<>>); replaceget()withget_context() - HandlerContext: Replace with direct ScriptContext access; remove any
with_handler_system_state()calls - Script Callbacks: Use new
call_context_dynamic()orcall_context()methods from the CallContext trait - Custom Context Types: Implement the new
GetPluginFortrait to provide mapping from context to plugin type - Lua Interaction: Replace
mlua::LuawithLuaContextwrapper type in all Lua code on BMS side - Script Callback Running: Replace
run_with_handler()calls withrun_with_context()orrun_with_contexts()
https://github.com/makspll/bevy_mod_scripting/pull/475
- References previously resident in
bevy_mod_scripting_core::asset/bevy_mod_scripting::core::assetwill now need to come frombevy_mod_scripting_assetorbevy_mod_scripting::asset - Adding supported extensions will now need to be done via
scripting_plugin.add_supported_extension("extension")rather than via the app directly - Plugin implementors will need to add the new crate as a dependency and should not directly rely on the top workspace crate
https://github.com/makspll/bevy_mod_scripting/pull/477
- Update imports to new crates (
bevy_mod_scripting_bindings,bevy_mod_scripting_display,bevy_mod_scripting_asset) where appropriate, if you rely on the workspace these will be re-exported underbindings,displayandassetrespectively - Replace
DisplayWithWorldusage withDisplayWithTypeInfo/DebugWithTypeInfoand useWithTypeInfo::new(value)in format strings. Ensure that the WorldGuard is in scope when printing using these utilities, or you might see raw type id’s
0.16.0
Improved printing and error ergonomics
Printing has been extracted into its own bevy_mod_scripting_display crate, and brand new traits including the reflectable DisplayWithTypeInfo were written.
There are now Debug and Display equivalent traits which receive type information from semi-static thread local objects in order to print things like TypeId’s with full information.
You can now also register ReflectDisplayWithTypeInfo against your types in the reflect registry, to customize printing.
A great re-slicing
Bindings have been split out into individual crates, for example bevy_reflect has a corresponding bevy_reflect_bms_bindings crate which contain’s its bindings. This is possible thanks to a brand new tool which allows us to calculate crate dependencies across a workspace during codegen (see bevy_mod_scripting_codegen)
At the same time more bindings are now being generated after fixing some bugs in type discovery.
Other refactorings include bevy_mod_scripting_bindings, bevy_mod_scripting_display and bevy_mod_scripting_asset being pulled out into their own crates.
This has significantly improved compile times allowing us to pack more bindings!
Getting rid of HandlerCtxt
HandlerCtxt has been removed and all of its containing resources have been put in P::readonly_configuration, which is a semi-static, WorldId parameterised static.
At the same time ScriptContext<P> has been wrapped in an Arc allowing us to run callbacks within callbacks, as long as they don’t modify the same contexts!
The great bevy minification
BMS has historically pointed at the top level bevy crate, this was handy but fairly clunky as it brought way more dependencies than necessary.
From now on all BMS crates point at bevy subcrates directly, with default features disabled, this means we pull in the minimum amount of dependencies possible (in theory, as long as we didn’t miss a feature)
Brand new scripting pipeline
A shiny new overhauled loading/unloading script pipeline which:
- Is much more customizable (want custom callbacks, or don’t like how we named our core callbacks? Just disable them and add your own!)
- More scalable, allowing you to load thousands of scripts, without hogging your framerate (by abstracting loading into tickable state machines)
See the new docs section for details.
Pre-expanding generated code
Generated code is now expanded at generation time via cargo expand saving on compilation time for consumers.
Migrating from 0.16 to 0.17
TypedThrough Changes
If you were relying on ladfiles or implementing TypedThrough manually, the interfaces will have changed. Some types have moved between crates.
Less types will appear in ladfiles
Changes to path reflection
Replace accesses to tuple structs, and tuples containing underscores, i.e. instead of my_tuple._1 use my_tuple[1]
ScriptAttachment Moved to new crate
A new crate bevy_mod_scripting_script was created, to decouple some concerns within the workspace. References will now need to use the bevy_mod_scripting::script namespace or a direct crate reference.
0.17.0 - Lua declaration files & Asset references
Lua declaration files!
On top of the ability to plug into mdbook docs, you can now generate Lua declaration files for use with the lua language server.
You can do this by simply adding the generation plugin to your app:
#![allow(unused)]
fn main() {
// this example is used to drive the generated docs on the official BMS book
app.add_plugins(BMSPlugin.set::<ScriptingFilesGenerationPlugin>(
ScriptingFilesGenerationPlugin::new(
true, // enabled, you can use a compilation feature to disable this here
PathBuf::from("assets").join("definitions"),
Some(PathBuf::from("bindings.lad.json")), // do also save the ladfile itself
"Core BMS framework bindings",
true,
true,
),
));
}
The definitions will be generated on startup!
While the generated files are not currently perfect, and not everything is yet supported, they should already make development much smoother with basic type hints and inline docs.
Improved path reflection and dictionary/set direct access!
We have decided to drop using the native Bevy reflection paths, and switched them out with custom ReferencePath and ReferencePart structures.
This works around previous limitations of not being able to reflect and modify into dictionaries as well as reference into (but not modify sets, this one is due to limitations in the native rust type).
This should also give us some minor performance benefits.
Registered Callbacks
You can now register callbacks dynamically from your scripts like so:
function on_script_loaded()
register_callback("on_test", dynamic_on_test)
end
function dynamic_on_test()
register_callback("on_test_last", dynamic_on_test_last)
return "on test: I am dynamically registered from a normal callback!"
end
This has many benefits, including allowing registering different callbacks from withing a shared global script context (where different functions are in scope depending on the last loaded script, but are predictable during loads), finally making those fully usable!
Expansion of reflection to include Asset References
The reflection system now supports a new base kind, i.e. ReflectBase::Asset
allowing us to create and send back asset references to scripts seamlessly, as well as use two new bindings (given an existing handle):
get_asset(handle_reference, registration) - Retrieves an asset by handle
has_asset(handle_reference) - Checks if an asset exists
Addition of ScriptPipelineState
A new utility has been added to allow you to check on the current batch of scripts being loaded easilly. Check it out in the new loading bar example
ScriptPath in FunctionCallContext
You can now access the last loaded script path in a script context via the FunctionCallContext::location method.
This is a lua only feature due to limitations in Rhai.
Migrating from 0.17 to 0.18
Migrate according to the official bevy migration guide. Scripts referencing native bevy bindings will also need updating accordingly.
For example in lua entity:index() will now be entity:index():index().
0.18.0 - Bevy 0.18 Support
This update only upgrades the supported version of bevy to 0.18
0.19.0
See notes for the 0.18.0 release.
Migrating from 0.19 to 0.19
Observer overhaul
TransitionListener has been deleted, use observers instead:
> app.add_observer(
> |trigger: On<LoadingCompleted>| println!("do stuff"),
> );
< active_machines.push_listener::<ReloadingInitialized<P>>(OnLoadingCompleteListener);
This allows you to use more convenient system parameter syntax to access resources and queries, but you may not use exclusive systems anymore.
If you want observers to respect ordering between themselves, you should prefer to issue commands in these instead (see related bevy issue).
Renaming Reflection Rroxies
Val<T>, Ref<T> and Mut<T> have been renamed to prevent clashes with native bevy types, as well as save a few keystrokes.
You should use: V<T>, R<T> and M<T> instead
> V<T>
< Val<T>
> R<T>
< Ref<T>
> M<T>
< Mut<T>
ScriptValue::List changes
This variant now uses VecDeque instead of Vec
Refactor of WorldAccessGuard and related types
Many functions previously living directly in WorldAccessGuard impls, now need to be accessed via the WorldExtensions trait.
Functions previously known as with_exclusive_access etc, have been split into: with_world and with_world_mut, allowing read access to the world too in some circumstances.
ReflectAccessId was removed in favour of WorldAccessRange which can be created via Into from ComponentId’s.
0.20.0 - Ergonomics, Observer overhaul
Observer overhaul
The script loading pipeline became more idiomatic with the use of observers.
What you would do previously with TransitionListener implementations you can now do with observers registered against each machine state, for example, to react to fresh scripts being loaded you can do the following:
#![allow(unused)]
fn main() {
app.add_observer(
|trigger: On<LoadingCompleted>| println!("do stuff"),
);
}
Callback command changes
Callback commands now accept a post_callback function pointer which can be set to execute some logic right after the callback runs, to make working with observers and callbacks easier in general.
Ironing out edge cases in the script lifecycle
Contexts are now stored in a Context enum which also contains the “state” of the context. Contexts which are being processed by the pipeline will be marked as loading/reloading or unloading, allowing us to have more information when trying to run callbakcs against these.
Callbacks which are loading or unloading for example, will not have callbacks issued to them generally.
Renaming Reflection Rroxies
Val<T>, Ref<T> and Mut<T> have been renamed to prevent clashes with native bevy types, as well as save a few keystrokes.
You should use: V<T>, R<T> and M<T> instead
Addition of logging bindings
Standard log_info, log_debug, log_trace, log_warn and log_error functions are now available in scripts by default
Variadic bindings & Support for multiple return values
The ArgMeta trait now includes: variadic() -> bool which if true, allows an argument in a binding to capture all remaining arguments from the call (effectively only usable as the last argument).
This is implemented by the brand new VariadicTuple type, which is an untyped wrapper for a variable amount of non-homogenous values.
New variants in the TypedThrough and LAD file format have ben added to represent variadics, and lua definition files generated from these will support them.
Two bindings have been added: pack_args and unpack_args to allow script code to directly create/unpack tuple variants if necessary. However for languages like Lua, supporting multiple return values, ScriptValue::Tuple variants (which is what we produce to represent variadic returns), are converted to many return values naturally.
New VecDeque impls
VecDeque now implements various BMS traits and can be used in bindings as a normal argument.
Improved domain boundaries - Extracted bevy_mod_scripting_world crate
The following types were extracted into their own crate:
ReflectAccessIdnow known asWorldAccessRangeClaimOwnerAccessInstanceAccessMapDynamicSystemMetaWorldGuard&WorldAccessGuard
the CachedRegistry trait was introduced to store registries such as:
AppScriptComponentRegistryAppReflectAllocatorAppScheduleRegistryAppScriptFunctionRegistry
etc. in a type-erased way.
This allowed bevy_mod_scripting_display to directly rely on world types, and removed a lot of awkward bridging code.
More Derive Macros
The following macros derive macros are now available: ArgMeta,FromScript.
This means for types you want to clone into scripts you can make convenient wrappers like so:
#![allow(unused)]
fn main() {
#[derive(Clone, TypedThrough, GetTypeDependencies, ArgMeta, IntoScript, FromScript, Reflect)]
pub struct MyThing(usize);
#[script_bindings(remote)]
impl MyThing {
// Can now be used directly without V<> wrapper, acts exactly like V<MyThing>
pub fn test(thing: MyThing) -> MyThing {
thing
}
}
}
And overriding either the into or from implementations if you wish easilly.
Migrating from 0.22 to 0.23
Scripts
Script components need a namespace
register_new_component takes a script.* namespace first:
- local Enemy = world.register_new_component("Enemy")
+ local Enemy = world.register_new_component("script.my_game", "Enemy")
Registering a name twice is still an error. If you worked around that for scripts which run more than once, you can now pass allow_existing as the third argument to get the existing registration:
local Enemy = world.register_new_component("script.my_game", "Enemy", true)
In Bevy’s component registry, script components are now named by their full path, i.e. script.my_game.Enemy.
types is deprecated
Use import_namespace with the crate that defines the type:
- local Transform = types.Transform
+ local Transform = import_namespace("bevy_transform").Transform
Script components are not added to types after a context is created. Import them from their namespace instead.
construct is stricter
construct (and the new Type.new) rejects unknown fields instead of ignoring them, and fills in missing fields from defaults.
Re-entering a running script is an error
Running a callback in a script context which is already running a callback (e.g. from an observer or a command flushed during the callback) now returns an error instead of deadlocking. Use queue_script_callback to run it once the context is free.
Rust
Messages renamed
Buffered BMS types are Bevy messages, and their names now say so:
| 0.22 | 0.23 |
|---|---|
ScriptCallbackEvent | ScriptCallbackMessage |
ScriptCallbackResponseEvent | ScriptCallbackResponseMessage |
ScriptErrorEvent | ScriptErrorMessage |
ScriptAttachedEvent | ScriptAttachedMessage |
ScriptDetachedEvent | ScriptDetachedMessage |
ScriptAssetModifiedEvent | ScriptAssetModifiedMessage |
ScriptingHandler::handle locks the context itself
Pass the context’s Arc instead of locking it:
- let mut context = context.lock();
- P::handle(args, &attachment, &label, &mut context, callbacks, world)
+ P::handle(args, &attachment, &label, &context, callbacks, world)
Pipeline progress functions renamed
| 0.22 | 0.23 |
|---|---|
num_processing_scripts | processing_script_count |
processing_batch_completed | is_processing_completed |
num_loaded_scripts | loaded_script_count |
progress | progress_fraction |
World guard cache
WorldAccessGuard::setup_cache_raw takes two new arguments, the AppScriptCallbackRunners and the AppScriptTypeCatalogue. Prefer setup_cache(world, attachment), which reads them from the world. Use CurrentScriptAttachment::empty() for guards not tied to a running script.
Other
ScriptingSystemSethas a new variant,RunQueuedCallbacks.- The script function
world.trigger_event(andWorldExtensions::trigger_event) applies all pending world commands before it returns, not only those of its observers. Recipientsmoved tobevy_mod_scripting_script, and is re-exported fromcore::event. Resolving recipients is theGetRecipientstrait.AnyTypeRegistrationhas a fourth case, bundles (ScriptBundleRegistration).ScriptComponentRegistrationhas a new public field,script_namespace.WorldExtensions::register_script_componenttakes(namespace, name, allow_existing).- LAD files have new fields:
namespaceon types,Fieldspayloads, variant function namespaces, and default metadata. Custom LAD backends may need to handle them.
0.23.0 - Scripts calling scripts, constructors, namespaces
See the migration guide for breaking changes.
Scripts calling scripts
Scripts can run each other’s callbacks, in any language:
run_script_callbackruns a callback right away and returns its result.queue_script_callbackruns it as soon as the current callback finishes, or inLastwhen called from a non-exclusive script system (ScriptingSystemSet::RunQueuedCallbacks).
Nested callbacks are now safe: re-entering a context that is already running (a script calling itself, scripts sharing a context, or a loop A → B → A) returns an error instead of freezing the app, and nesting is capped at 64. This is built on AppScriptCallbackRunners, which lets language-agnostic code run callbacks in any scripting language.
Constructors and enum variants
Every reflected type gets a new constructor, and enum variants are values:
local v = Vec3.new{ x = 1, y = 2 } -- z is filled in from the default
local all = Recipients.AllScripts:new{} -- construct a variant
if event.recipients:variant() == Recipients.AllScripts then ... end
Missing fields are filled in from defaults, and unknown fields are an error. The global construct follows the same rules. The generated LAD files and Lua language server definitions describe constructor payloads and variants, so editors complete and check them. In Rhai, call Type.new_.call(...), since new is reserved.
Events, messages and observers
world.trigger_event(type, value)andworld.write_message(type, value)send reflected Bevy events and messages.trigger_eventapplies all pending commands, including those its observers queued, before it returns.world.add_observer(event, callback, components?, entities?)runs a script callback when an event is triggered. That includes the component lifecycle events (AddEvent,InsertEvent,RemoveEvent, …), for native and script components alike. Observer callbacks never re-enter a busy script: they wait until it is free. Their errors are reported like those of other callbacks.world.register_new_event(namespace, name)lets scripts define their own events, triggered with the sameworld.trigger_event(event, payload).
See Events and Messages.
Namespaces and modules
Types now live in namespaces: the crate that defines them, or bms for BMS’ own types. Override this with ScriptNamespace type data or #[script_bindings(namespace = "...")].
import_namespace("bevy_transform")returns the types in a namespace. It replaces thetypesglobal, which is now deprecated.- Scripts register components and events into
script.*namespaces, and other scripts import them from there. export_namespace(namespace, name, callback)shares a script function with other scripts, in any language.- A script’s exports and observers are removed when it unloads or reloads.
- LAD files record each type’s namespace, and the Lua language server types
import_namespaceper namespace.
Types are indexed once in a shared, lazily rebuilt type catalogue, instead of once per script context. See Namespaces.
Script components and bundles
- Inserting a script component no longer leaks memory.
register_new_componentandregister_new_eventtake anallow_existingargument, which returns the existing registration instead of failing when the name is taken (useful for scripts which run again).world.insert_bundleandworld.spawn_bundleinsert bundles registered with#[reflect(Bundle)], all at once.
Fixes
on_script_reloadedalways runs afteron_script_loaded.- Fixed a rare ordering bug when iterating
Vec<T>from Lua. - A nested callback no longer invalidates the world of the callback that called it.
Migrating from 0.23 to 0.24
See the release notes for what’s new. Most important changes first.
Scripts
Rhai is removed
Port Rhai scripts to Lua, or to Rune (the rune feature).
Everything is imported
The only globals left are import_namespace, export_namespace and register_callback. Everything else, world and types included, is imported from a namespace, see Namespaces. Bevy types are grouped by category (math, ecs, transform, ui, …), BMS’ types and functions live in bms:
+ local bms = import_namespace("bms")
+ local world = bms.world
+ local Vec3 = import_namespace("math").Vec3
+ local Transform = import_namespace("transform").Transform
local t = Transform.from_translation(Vec3.new(1, 2, 3))
- log_info("hi")
+ bms.log_info("hi")
- world.despawn(entity)
+ world.despawn(bms.current_entity())
- script_asset
+ bms.current_script()
construct, system_builder, run_script_callback, queue_script_callback, pack_args and unpack_args moved to bms the same way. The deprecated types table is removed.
Query results are lists
The entity followed by the components, in the order they were added to the query:
for _, result in pairs(world.query():component(Transform):build()) do
- local entity, transform = result:entity(), result:components()[1]
+ local entity, transform = result[1], result[2]
end
Other changes
- The bindings are hand-written: functions of Bevy types which were generated before may be missing or named differently, check the generated docs.
world.get_type_by_nameonly takes full paths, i.e."bevy_transform::components::transform::Transform"or"script.my_game.Enemy".- Script systems:
resourceand querycomponents are writes, systems writing the same data no longer run in parallel, useresource_read/component_readwhere you only read. Sets are values (world.register_new_system_set(namespace, name),world.get_system_set_by_name) instead of names. - Asset references can’t be used in non-exclusive script systems, nor together with a mutably borrowed component in the same call.
- Lua’s
math.randomis seeded with0in new contexts, and callbacks reach scripts in attachment order, see Determinism.
Rust
Features and crates
-
The
rhaifeature andbevy_mod_scripting_rhaiare removed. -
The generated
*_bms_bindingscrates are replaced bybevy_mod_scripting_bevy_<category>_bindings. The binding features are nowbevy_{animation, asset, audio, camera, color, ecs, gizmos, input, math, render, sprite, state, text, time, transform, ui, window}_bindings:0.23 feature 0.24 bevy_reflect_bindings,bevy_curve_bindings,bevy_shape_bindingsbevy_math_bindingsbevy_image_bindings,bevy_mesh_bindings,bevy_pbr_bindingsbevy_render_bindingsbevy_input_focus_bindingsbevy_input_bindingsbevy_core_pipeline_bindings,bevy_gltf_bindings,bevy_light_bindings,bevy_picking_bindings,bevy_post_process_bindings,bevy_scene_bindings,bevy_sprite_render_bindings,bevy_ui_render_bindings,bevy_ui_widgets_bindingsremoved, reachable through reflection The default features are
core_functionsand theecs,input,math,time,transform,colorandwindowbindings. -
mluais bumped to 0.12, see its changelog if you use it directly.
Script globals are removed
AppScriptGlobalsRegistry, #[script_globals], register_static*, GlobalNamespace, FunctionScope::Global, DummyScriptFunctionRegistry and use_dummy_registry are gone. Put functions in a namespace instead:
#[script_bindings(remote, namespace = "my_game")]
impl NamespaceMembers {
/// `import_namespace("my_game").spawn_enemy(5)` in scripts
fn spawn_enemy(ctxt: FunctionCallContext, hp: usize) -> Result<(), InteropError> { .. }
}
Values go in AppScriptNamespaceMembers::register_value, made each time the namespace is imported. Types with bindings from the bevy crates are in category namespaces, move a type with app.override_script_namespace.
Borrowed arguments end with the call
FromScript::from_script takes a &CallScope instead of a WorldGuard, and R/M borrow from it, so they can’t be kept past the function call (M<'static, T> arguments no longer compile). Get the guard with scope.world(), and convert outside of script functions in guard.with_call_scope(|scope| ..), which replaces with_access_scope and releases the claims when it ends:
fn from_script<'s>(value: ScriptValue, scope: &'s CallScope<'_>) -> Result<Self::This<'s>, InteropError> {
let world = scope.world();
..
}
The allocator is removed
Values allocated for scripts are owned by the references to them and freed with the last one. ReflectAllocator, AppReflectAllocator, WorldExtensions::allocator, AllocatorDiagnosticPlugin, ScriptingSystemSet::GarbageCollection and InteropError::GarbageCollectedAllocation are gone, drop the allocator argument:
- let reference = ReflectReference::new_allocated(value, &mut world.allocator().write());
+ let reference = ReflectReference::new_allocated(value);
new_allocated_boxed and new_allocated_boxed_partial_reflect (renamed from new_allocated_boxed_parial_reflect) change the same way.
Functions
- Registering a function name twice replaces it, there are no overloads (
overwrite*,iter_overloads,remove_all_overloadsare removed). Take aUnionorScriptValuefor arguments of different types. ScriptFunctionRegistryis keyed byTypeIdinstead of a namespace:register(type_id, ..),get_function(type_id, name),iter_namespace→iter_type.#[derive(ScriptType)]implements everything a type needs to be used directly in function signatures (FromScript,IntoScript,ArgMeta,GetTypeDependencies,TypedThrough). Use#[script_type(from = custom)]/(into = custom)for a hand written conversion.- Renames:
Namespace→FunctionScope(IntoNamespaceis removed, useFunctionScope::OnType(TypeId::of::<T>())),FromScriptRef/IntoScriptRef→FromScriptErased/IntoScriptErased,try_call_overloads→call_operator. - Functions on
StaticTypeReftakeStaticTypeRefinstead ofV<StaticTypeRef>.
Script pipeline
ScriptAttachedMessage(a)/ScriptDetachedMessage(a)are one message,ScriptLifecycleMessage::Attached(a)/::Detached(a), processed in the order they were written. An attachment whose script is still loading holds back the ones after it.LoadedWithHandlesisScriptLifecycleQueue,get_readyyields(event, Option<(StrongScriptHandle, Language)>).GetScriptHandle::get_script_handlereturns anOption(None: the event doesn’t wait for its script to load).ScriptLoadingPipeline::time_budget: Option<Duration>is replaced bytick_budget: Option<usize>, the maximum amount of pipeline steps per frame, unlimited by default.ActiveMachines::budgetandRunProcessingPipelineOnce::newtake the same step count.
Script systems
- Systems are identified by attachment and callback label (adding one again replaces it) and are removed with their script. Their errors are sent as
ScriptErrorMessages instead of being logged. ScriptSystemBuilderno longer implementsIntoSystem, useScriptSystemBuilder::build.in_set,before_setandafter_settake aSystemSet.ScriptSystemSetholds a recycled slot instead of the callback label.- Rust sets are exposed to scripts with
app.register_script_system_set(namespace, name, set)(ScriptSystemSetAppExt, now inbevy_mod_scripting_bindings).ReflectSystemSetis opaque. ScriptQueryBuilder::as_query_statetakes aQueryAccess:Declaredfor queries reported to the scheduler,MatchOnlyfor queries only finding entities.ScriptQueryResultconverts to a list instead of a reference, and itscomponentsare aVec<Option<ReflectReference>>,Nonefor absent optional components.
World access
ReflectReference::new_component_ref_by_id/new_resource_ref_by_id,ScriptComponentRegistration::newandScriptResourceRegistration::newareunsafe: the type must be the type of the component or resource id.ReflectBaseType::base_idis private, read it withbase_id().WorldAccessGuard::new_non_exclusivetakes anOption<Arc<ArchetypeFilter>>, restricting component accesses to the given archetypes (Nonefor no restriction).WorldAccessRange::Externalholds the value itself (AccessOwner) instead of an id and is no longerCopy, build it from the value:(&allocation_id).into().- At most 63 accesses to the same value can be claimed at once, claims beyond fail (the count used to overflow).
- Asset references claim global access, and reading an asset no longer marks it modified.
ThreadWorldContainer::try_get_context()is an associated function (wasThreadWorldContainer.try_get_context()),set_contextis replaced byreplace_context, which restores the previous context when its guard is dropped.set_cached_registryis replaced byreplace_cached_registry.- Removed:
DynamicSystemMetaand itswith_scope/release_all_accesses(claims are released when theirCallScopeends),WorldAccessGuard::release_all_accesses,with_world_access_and_then,as_unsafe_world_cell_readonly(useas_unsafe_world_cell). ReflectReference::type_id_ofandTypeIdSourceare removed, usetail_type_id,element_type_idorkey_type_id.ReferencePath::set_is_one_indexedis removed: indexes are normalised when the path is created.
Language implementations
- Dispatch every script operation through
bevy_mod_scripting_bindings::dispatch(index,set_index,static_index,binary,unary,len,iter,display,debug), see Necessary Features.WorldExtensions::lookup_function,lookup_instance_function,lookup_type_functionandlookup_reserved_functionare private. - Convert the new
ScriptValue::Type(TypeId), a type itself (whatworldandStaticTypeRefare). - Set
bindings::builtins::builtins()(import_namespace,export_namespace) and yourregister_callbackas globals, nothing else. Don’t setworld,entityorscript_assetanymore. LuaStaticReflectReferenceisLuaTypeRef.
Documentation tooling
- The Lua language server files are split per namespace (
bindings.d.lua,bindings.<namespace>.d.lua): pointworkspace.libraryat the directory. Classes are named after their namespace (math.Vec3), and generic classes need LuaLS 3.17+. cargo xtask docgenis replaced bycargo xtask docs(all binding features,--test-bindingsfor the script test functions).cargo xtask bless-ladupdates the LAD test fixtures.ThroughTypeInfois flat (ThroughTypeInfo::Vec(..),ThroughTypeInfo::Ref(type_info), replacingTypedWrapper/UntypedWrapper),ThroughTypeInfo::TypeInfoisOpaque.#[derive(TypedThrough)]documents a type as opaque,#[typed_through(value)]as a value.generate_lad_filetakes theAppGenericTypes, seeapp.register_generic_type.- LAD format:
LadFieldOrVariableKind→LadTypeKind.Ref/Mut/Valhold aLadNamedType: a type id as before, or a generic type applied to arguments ({ "generic_type": "bevy_asset::handle::Handle", "args": [...] }).globalsis removed, builtin functions areLadFunctionNamespace::Global(the mdbook “Globals” and “Functions” pages are one “Builtins” page). Namespaces havevalues(add_instance*→add_namespace_value_of/add_namespace_instance).- Instantiations of declared generic types are recorded on the generic type (
generic_types,LadGenericType::instantiations,LadFile::get_instantiation) instead of being types of the file.polymorphizied_typesis removed. LadFunctionMetadata::is_operator→operator. Arguments are always named and never include the call context.ArgumentVisitorhas anOutputtype andvisit_*methods per kind (visit_generic,visit_type,visit_tuple_with_rest, …).
0.24.0 - Codegen removed, typed scripts, script systems, Rune
See the migration guide for breaking changes.
Codegen is gone: 4x faster builds
The codegen project, its pinned nightly toolchain and the cargo expanded binding crates are removed (see the RFC). The bindings went from 4.3MB of generated source to 0.23MB written by hand:
BMS crates, default features + lua54 | 0.23 | 0.24 | |
|---|---|---|---|
cargo build | 209s | 51s | -76% |
cargo check | 19.1s | 9.0s | -53% |
| slowest crate | bevy_reflect_bms_bindings, 193s | bevy_mod_scripting_bevy_math_bindings, 43s |
Non-incremental dev builds of the workspace crates only (dependencies cached), mean of 2 runs, 16 threads. Changing a binding is an ordinary edit, with no nightly toolchain or regeneration step.
Hand-written Bevy bindings
The Bevy bindings are written, documented and tested by hand, one crate per category, designed for scripts rather than mirrored from Rust:
local Vec3 = import_namespace("math").Vec3
local Transform = import_namespace("transform").Transform
local KeyCode = import_namespace("input").KeyCode
local Color = import_namespace("color").Color
local ui = import_namespace("ui")
local t = Transform.from_translation(Vec3.new(1, 2, 3)):looking_at(Vec3.zero(), Vec3.unit_y())
t.translation = 2 * t.translation -- numbers work on either side of operators
if KeyCode.just_pressed(KeyCode.Space) then -- no `ButtonInput<KeyCode>` resource lookups
local node = ui.Node.new({ width = ui.Val.px(100) })
local red = Color.hex("#ff0000"):mix(Color.named("rebecca_purple"), 0.5)
end
- Covers math, ecs, time, transform, color, input, window, asset, camera, render, sprite, text and ui, plus new bindings for gizmos (
Gizmos.line(a, b, color)), animation players, audio playback settings and states (world.get_state,world.set_next_state). - Things which panic in Rust are errors or
nilin scripts:normalizeof a zero vector, integer division by zero,Entity.from_bitsof an invalid id,Dir3.newof a zero vector. - No generic type paths:
world.time(),world.virtual_time(),Window.primary(),world.find_entity_by_name(name). - Everything without a binding stays reachable through reflection: fields,
Type.new{..}, variants. - The examples in the binding docs run as tests, in every language.
Everything is imported
Scripts get three globals: import_namespace, export_namespace and register_callback. Types live in short category namespaces (math, ecs, transform, ui, …) instead of globals which shadowed each other, and so does world:
local bms = import_namespace("bms")
local world = bms.world
bms.log_info("hi from " .. tostring(bms.current_entity()))
Exposing your own functions is one attribute, no globals registry:
#[script_bindings(remote, namespace = "my_game")]
impl NamespaceMembers {
/// `import_namespace("my_game").spawn_enemy(5)` in scripts
fn spawn_enemy(ctxt: FunctionCallContext, hp: usize) -> Result<(), InteropError> { .. }
}
Types, constructors and enums
A type is a value now (ScriptValue::Type), not an allocated StaticTypeRef reference. What you import from a namespace is the type: it is its registration wherever one is expected, and it carries the type’s static functions, the shared new constructor and its enum variants. Calling Vec3.new{} no longer allocates the type and clones it back out on every call.
local time = import_namespace("time")
local Timer, TimerMode = time.Timer, time.TimerMode
world.add_default_component(entity, Transform) -- the type as a registration
local timer = Timer.from_seconds(2, TimerMode.Repeating)
local image = Image.load("player.png") -- on every asset type, a typed `Handle<Image>`
if event.key_code == KeyCode.KeyA then end -- values compare against variants directly
local eased = EaseFunction.Linear:sample(0.5) -- variants have their enum's functions
- Every reflected value has
==(throughreflect_partial_eq) and:clone(), and operators a type doesn’t define fall back to the ones shared by all references. #vgoes through the type’slenfunction, so types can override it.- Asset types get
load(path),add_asset(value)andget_asset(handle), next toworld.load_asset,world.add_asset,world.is_loaded,world.load_stateandworld.asset_path. #[reflect(NoTypeFunctions)]hides the shared type functions (i.e.new) from a type.- One function per name, taking a
Unionfor different operand types (Union<R<Vec3>, f32>borrows): overloads, and the failed attempts they cost on every call, are gone. #[derive(ScriptType)]implements everything a type needs to be used directly in function signatures.
Scripts your editor understands
The Lua language server files describe what scripts actually get back. Functions are generic in the type they are given, and generic types are declared once in terms of their parameters:
local transform = world.get_component(entity, Transform) -- transform.Transform?
local image = world.load_asset("player.png", Image) -- asset.Handle<render.Image>
local state = world.get_state(GameState) -- my_game.GameState?
local t = world.get_type_by_name("bevy_transform::components::transform::Transform") -- the Transform type
- A file per namespace, classes named after their namespace (
math.Vec3), no type globals. - Type tables and values are separate classes:
Transform.from_xyzcompletes on the type, fields on the value, and passing a resource where a component is expected is flagged. - Enum variants extend their enum, so
Timer.from_seconds(2, TimerMode.Repeating)type-checks, andMyEnum.Variant:new{..}checks its fields. - Container fields are typed as what reading them gives:
integer[] | ReflectReference. - The Lua tests of BMS are type-checked against the generated files in CI, with zero diagnostics.
Declare your own generic types with app.register_generic_type::<Handle<A>>("asset", &["A"], docs), and generic functions with TypeOf<R, A> / ValueOf<A> in their signature:
fn get_component(
ctxt: FunctionCallContext,
entity: V<Entity>,
registration: TypeOf<V<ScriptComponentRegistration>, A>,
) -> Result<Option<ValueOf<A>>, InteropError>
The mdbook pages got the same treatment, and a rework: generic types show their layout and functions once, generics no longer vanish as HTML tags, rustdoc links resolve, and summaries are readable.
Script systems
Script systems grew into something you can build a mod’s logic on.
Parameters and queries
Systems declare what they read and write, so Bevy runs them in parallel with everything they don’t conflict with:
bms.system_builder("steer_enemies", attachment)
:query(world.query()
:component(Transform) -- read + write
:component_read(game.Enemy) -- read only, readers run in parallel
:optional_read(game.Shield) -- nil for entities without it
:changed(game.Target)) -- only entities whose target changed since the last run
:resource_read(game.Difficulty)
function steer_enemies(enemies, difficulty)
for _, result in ipairs(enemies) do
local entity, transform, enemy, shield = result[1], result[2], result[3], result[4]
end
end
added/changedfilters, relative to the system’s last run (or the last update inworld.query()).- Queries of a system may share components if
with/withoutmake them disjoint, like in Rust. - Query results are plain lists instead of allocated values.
Ordering and sets
Order against systems, other scripts’ systems, and sets, including Rust sets:
local propagate = import_namespace("transform.TransformSystems").Propagate
local ai = world.register_new_system_set("script.my_mod", "ai") -- other scripts import it from `script.my_mod`
builder:in_set(ai)
:before_set(propagate)
:after_script_system("on_physics", other_attachment)
The bindings register the main Bevy sets, expose your own with:
app.register_script_system_set("my_game.GameSystems", "Combat", GameSystems::Combat);
Run conditions
Evaluated in Rust, without calling into the script:
local c = bms.conditions
builder:run_if(c.any_with_component(game.Enemy))
:run_if(c.not_(c.resource_exists(game.Paused)))
:run_if(c.on_timer(0.5))
resource_exists, resource_changed, resource_added, any_with_component, on_timer, run_once, and the combinators not_, and_, or_.
Lifecycle
- A system is identified by its script and callback label: adding it again replaces it, and it is removed when its script unloads or reloads.
- Systems can be added to schedules which are running (i.e. from
on_script_loaded), the change is applied once the schedule finishes. - Errors are sent as
ScriptErrorMessages like those of other callbacks, and invalid parameters are reported once instead of every frame. - A non-exclusive system can only touch what it declared, on the entities its queries match.
See Script Systems.
Determinism
Given the same inputs, scripts load in the same order and callbacks reach scripts in the same order, on every run and machine:
- Script contexts and their residents are kept in insertion order instead of randomly seeded maps, so callback order, reload order and the “first” script of a shared context are stable.
- Attachments and detachments are one ordered
ScriptLifecycleMessagestream: removing and re-inserting a script component in the same frame no longer ends up unloaded, and a detachment waits for its attachment whose script is still loading. - The pipeline budget counts steps (
tick_budget) rather than wall clock time. - Lua’s
math.randomis seeded with0in new contexts. - Broadcast callbacks are no longer delivered twice to loaded scripts while another script is loading.
See Determinism for what BMS can’t control.
Rune
Rune is the second supported language, behind the rune feature. It replaces Rhai, which is removed:
pub fn on_script_loaded() {
let bms = import_namespace("bms");
let world = bms.world;
for result in world.query().component(life_state_type(world)).build() {
let cells = result[1].cells;
cells[0] += 255;
}
}
Operators, indexing and member lookups go through one language agnostic dispatch module, so every language resolves v.x, v:method() and 2 * v by the same rules, and adding a language is mostly converting values, see Necessary Features.
Faster interop: method calls at less than half the cost
Method calls from Lua cost less than half of what they did (cargo bench, medians of 3 runs on the same machine):
| 0.23 | 0.24 | ||
|---|---|---|---|
v:length() | 1.45µs | 0.67µs | -54% |
v:normalize() (returns a value) | 2.49µs | 1.04µs | -58% |
a + b | 1.57µs | 1.02µs | -35% |
v.x | 554ns | 426ns | -23% |
v.x = 2 | 484ns | 519ns | +7% |
| calling an empty function | 309ns | 178ns | -42% |
- Values returned to scripts are owned by the references to them and freed with the last one: the allocator, its lock and the garbage collection system are gone.
v:methodreuses one Lua function per registered function, and call locations are only looked up for errors.- Claiming the whole world (every asset access,
world.spawn, …) no longer scans every component’s claims.
Soundness
The world access machinery was reviewed and tightened:
- Borrowed arguments (
R<T>,M<T>) are tied to the function call, keeping them past it no longer compiles. - Claims are released when callbacks fail or panic, can’t overflow, and hold across guards for values reachable from several of them.
- Script systems declare exactly what they access to Bevy: written components and resources used to be declared as reads, letting writers run in parallel.
- Reading an asset no longer takes it mutably, or marks it modified (i.e. re-uploading an
Imageevery frame). - Constructors which trust the caller with a type and component id pairing are
unsafe, and registrations can’t be forged through reflection. - Converting
-1to aNonMaxU32from a script was undefined behaviour, it is an error now.
Other changes
- Cyclic Lua tables are an error instead of a stack overflow.
- Lua functions called from Rust return all of their values intact.
- Indexes are normalised when values are created, so values pass between 0 and 1 indexed languages correctly.
DynamicScriptFunctions compare equal to their clones.- The function registry is not locked while functions run, which could deadlock with a writer on another thread.
- Android and iOS builds are checked, and the script tests run on an emulator, in CI.
mlua0.12.- Only the top level
CHANGELOG.mdis maintained, it covers every crate.
Migrating from 0.24 to 0.25
See the release notes for what’s new. Most important changes first.
Rust
Documentation tooling
ThroughTypeInfohas new variants:Function { params, returns }(FunctionOf),Literal(ByName) andData(a type derivingScriptData, with aScriptDataShapeofFieldsorUnion). In the LAD file, structs are referred to byLadTypeKind::Fieldsand enums byLadTypeKind::Val.LadFile::typesholdsLadTypes:LadType::Reference(Box<LadTypeDefinition>)for the types so far (serialized as before), andLadType::Data(LadDataType)forScriptDatatypes, whoseLadDataShapeisfieldsor aunionof kinds. Useget_reference_type/reference_typeswhere aLadTypeDefinitionwas expected.- New
LadTypeKind::Function { params, returns }andLadTypeKind::Literal: implementations ofArgumentVisitoraddvisit_functionandvisit_literal.
Functions
- Conversions moved from
functiontoconversions:function::{from, into, from_ref, into_ref}areconversions::{from, into, from_ref, into_ref}(FromScript,IntoScript,V,R,M,Union,FromScriptErased,IntoScriptErased). The crate root re-exports are unchanged, i.e.bevy_mod_scripting_bindings::V. ValueOf<M>isValueOf<M, R = ReflectReference>:ValueOf<A>is unchanged,newandinto_innertake and give theR.GetFunctionInfoimplementations providefunction_info(name, namespace), which needs no value.get_function_infocalls it.Union<T1, T2>only tries the types which could convert the value, seeFromScript::could_convert. When onlyT1could, the error isT1’s rather thanT2’s. Overridecould_convertin hand-writtenFromScriptimplementations to rule out the kinds of values they never convert.
0.25.0 - Typed arguments
See the migration guide for breaking changes.
Typed arguments
Functions taking callbacks, names or tables of options are documented as exactly what they take, so the Lua language server checks the calls:
/// Spawns an enemy
#[derive(ScriptData)]
#[script_data(namespace = "game")]
struct SpawnOptions {
name: String,
speed: Option<Speed>,
on_death: Option<FunctionOf<fn(V<Entity>) -> ()>>,
}
#[derive(ScriptData)]
#[script_data(namespace = "game")]
enum Speed {
Named(ByName<Pace>), // "Slow" | "Fast"
Exact(f32), // 2.5
}
game.spawn({ name = "goblin", speed = "Fast", on_death = function(entity) end }) -- `entity` is an ecs.Entity
game.spawn({ name = "goblin", speed = "fast" }) -- not a Pace
game.spawn({ speed = 2 }) -- missing `name`
game.spawn({ name = "goblin", sped = 2 }) -- no field `sped`
FunctionOf<fn(A) -> R>: a function, documented asfun(arg1: A): R, so the parameters of a callback written inline are typed.ByName<E>: a unit variant of a reflected enum, passed by its name as in Rust and documented as the names,"Slow" | "Fast".#[derive(ScriptData)]: plain data, copied to and from scripts rather than referenced.- A struct is a map of its fields (a table in Lua, an object in Rune). Each field converts by its own type, so it can be a callback, a name or a union. Unknown, missing and mistyped fields are errors naming the field.
- An enum whose variants each hold one value is the value of any of them, and may hold itself.
- Both are data types in the book and the LAD file (
LadType::Data): a class of the fields or an alias of the union in Lua.
ValueOf<A, R>takes the conversion:ValueOf<A, ScriptValue>is any value, typed as whatever was passed, i.e.fn boxed(v: ValueOf<A, ScriptValue>) -> V<MyBox<A>>gives aMyBox<integer>forboxed(5).
See Typed arguments.
Native types
Vectors (Vec2, Vec3, Vec4, Vec3A, DVec2, DVec3, IVec2, IVec3, UVec2, UVec3) and Quat values made by functions are stored by Lua and Rune themselves, and functions read their arguments without converting them to ScriptValues. Transform components are native handles: world.get_component(e, Transform) reads and writes the component directly (t.translation.x = 5 included). Other types opt in with script_native!, see Writing Bindings. Scripts behave the same: native values are copies like the values functions return, and work wherever references to vectors do.
Other changes
- Unions only try the types which could convert a value (
FromScript::could_convert), instead of building an error for each type which can’t. - Nested unions are documented as one union,
Union<A, Union<B, C>>isA | B | C. - In the Lua language server files, function types in unions and lists are parenthesized:
fun(): a | breturns the union.