Hazel

Rust Scripts

A Rust script is a .rs file in a project that the editor compiles into a native library and calls once per frame for every entity it is attached to, with the same &mut World an exclusive Bevy system gets. This page is the reference: the API a script sees, how it is built, loaded and dispatched, and how it ships. For the step-by-step version aimed at game developers, see Rust Scripts.

The implementation lives in crates/renzora_rust_script (dispatch, building, loading), crates/api/renzora_scripting_api (ScriptCtx, ScriptHook, the script! macro) and crates/renzora_plugin_build (the compiler driver).

The smallest script

use bevy::prelude::*;
use renzora::ScriptCtx;

fn update(ctx: &mut ScriptCtx) {
    let dt = ctx.delta();
    if let Some(mut transform) = ctx.get_mut::<Transform>() {
        transform.rotate_y(dt);
    }
}

renzora::script!(update);

That is also what the editor writes when you create a new Rust script (renzora_scripting::starter_rust): the use lines and the script! call are always included, because a .rs without the macro compiles, loads, and then fails with "exports no entry point".

A script can only name two crates: bevy and renzora. It is compiled against the staged SDK (see How a script is built), which offers exactly those, so third-party crates and mod declarations are not available. renzora here is renzora_sdk, the whole contract re-exported under one name, so renzora::ScriptCtx, renzora::ScriptHook, renzora::bus, renzora::grid, renzora::serde_json and the rest all resolve.

script!

renzora::script!(update);                  // per-frame entry point only
renzora::script!(update, hooks = hooks);   // plus the lifecycle entry point

Both arguments are paths, so the functions may have any name and live in a module of the file (renzora::script!(behaviour::update)).

The macro does not call your function directly across the library boundary. It emits a plain function that builds the ScriptCtx on the script's side and calls yours:

SymbolSignatureEmitted by
renzora_script_updatefn(&mut World, Entity)every script! call
renzora_script_hookfn(&mut World, Entity, &ScriptHook)the hooks = form only

Keeping the boundary to plain function pointers is deliberate: nothing with a lifetime crosses it, and it is sound only because the script and the engine link one shared bevy_dylib and one renzora_dylib, so World is the same type on both sides.

The hook symbol is optional on purpose. Its absence is how the dispatcher tells "this script wants no lifecycle events" from "this script ignores the one it was given", and it keeps scripts written before hooks existed working unchanged.

Under the static_scripts feature (lean exports, below) the macro emits the same functions without #[no_mangle], because fifty scripts compiled into one binary cannot all export a symbol of the same name. The exporter names each by module path instead.

ScriptCtx

ScriptCtx is the script's own entity plus the world. The common case, touching your own entity, takes no entity argument; everything else goes through world(), which hands back the whole &mut World. Nothing is withheld: it is a shortcut, not a sandbox.

MethodReturns
entity()This script's entity
world()&mut World
delta() / elapsed()Seconds since the last frame / since startup (0.0 if there is no Time)
get::<T>() / get_mut::<T>()A component on this entity
has::<T>()Whether this entity has T
insert(bundle) / remove::<B>()Add or remove components on this entity; a no-op once it is despawned
name()This entity's Name, if any
get_on::<T>(e) / get_mut_on::<T>(e)A component on another entity
get_resource::<T>() / get_resource_mut::<T>()A resource, or None; never panics
children() / parent()The hierarchy around this entity
painter() / surface_size()Immediate-mode drawing (see Drawing)

get_mut, get_mut_on and get_resource_mut carry Bevy's Mutability = Mutable bound, so an immutable component or resource is rejected at compile time rather than at the call.

insert and remove silently do nothing if the entity has been despawned (by an earlier script this frame, or by this one), so a script does not have to check it still exists before every write. get_resource returns Option rather than panicking because a script may ask for something a lean export stripped.

Spawning, querying and asset access go through world():

use bevy::prelude::*;
use renzora::ScriptCtx;

fn update(ctx: &mut ScriptCtx) {
    let me = ctx.entity();
    let world = ctx.world();
    world.spawn((Name::new("spawned by a script"), ChildOf(me)));
}

renzora::script!(update);

An entity that a script spawns is only written into the scene file if it has a Name; see Scenes.

Lifecycle hooks

update runs every frame. Everything else arrives at the optional second entry point as a ScriptHook:

use bevy::prelude::*;
use renzora::{ScriptCtx, ScriptHook};

fn update(_ctx: &mut ScriptCtx) {}

fn hooks(ctx: &mut ScriptCtx, hook: &ScriptHook) {
    match hook {
        ScriptHook::Ready => info!("{:?} is ready", ctx.entity()),
        ScriptHook::SceneLoaded { path, error: None } => info!("loaded {path}"),
        ScriptHook::PlayerJoined { id } => info!("player {id} joined"),
        _ => {}
    }
}

renzora::script!(update, hooks = hooks);

ScriptHook is #[non_exhaustive], so the _ => {} arm is required. That is what makes a new hook an additive change: it is a new variant, not a new symbol every script has to grow.

VariantDeliveredPayload
ReadyOnce per (entity, script), before its first updatenone
FixedUpdate { delta }Once per fixed tick, from FixedUpdate, only after Readythe fixed step in seconds
Draw { width, height }Each frame, only to entities that own a canvas surfacesurface size in pixels
Ui { name, args, source }A game UI markup callback fired (on_press and friends)callback name, decoded arguments, the UI node
SceneLoaded { path, error }A scene load finished; error is Some on failureproject-relative path
AnimationEvent { name, source }Playback crossed a clip markermarker name, the animator entity
Event { name, args, from }A game event: a script's emit, an engine crate, a plugin, or the plugin busfrom is the emitting script's entity, None from engine or plugin code
Rpc { name, args, from }A networked RPC arrivedsender's peer id, 0 for the server or a local call
PlayerJoined { id } / PlayerLeft { id }A peer connected or left; host or server onlypeer id
Http { callback, status, body }Declared, but not delivered to Rust scripts yet (see below)

Ready, FixedUpdate and Draw are per-entity. The rest are broadcast: every attached script with a hook entry point receives every event of the frame, and filters by name itself.

SceneLoaded only reaches scripts the load did not destroy. Everything in the outgoing scene is despawned partway through a load, so in practice the listeners are scripts in a global (autoload) scene. That is the hook a loading screen is built on.

Ordering

The dispatchers are ordinary Bevy systems, gated on the same run condition as every other script (renzora_scripting::scripts_should_run, see The Scripting System):

SystemSchedulePlacement
renzora_rust_script::dispatch (calls update)Updateafter ScriptingSet::PreScript
hooks::dispatch_hooks (Ready, Draw, broadcast events)Updateafter PreScript, before ScriptingSet::ScriptExecution
hooks::dispatch_fixed_hooks (FixedUpdate)FixedUpdatein ScriptingSet::ScriptExecution, which runs before PhysicsSet::Commands

PreScript runs after PhysicsSet::Read, so a script reads this frame's velocities and contacts. dispatch_hooks runs before ScriptExecution because that is where an interpreted backend drains the event inboxes with mem::take; the Rust dispatcher reads them without emptying them, so both kinds of script hear the same frame's events once each. The events are copied out before any script runs, since a script holding &mut World may replace the resources they came from.

Readiness is tracked per (Entity, file name) in hooks::ReadiedScripts and pruned against live entities every frame, so a scene change that frees and reuses entity ids cannot suppress the next scene's Ready.

HTTP

http_get and http_post are reachable from Rust as actions, handled by renzora_scripting::http::on_http_action:

use renzora::{ScriptAction, ScriptCtx};

fn update(ctx: &mut ScriptCtx) {
    let me = ctx.entity();
    ScriptAction::new("http_get", me)
        .arg("url", "https://example.com/api/leaderboard")
        .arg("callback", "leaderboard")
        .send(ctx.world());
}

The request runs on a background thread and its result lands in HttpInbox. The Rust hook dispatcher does not read that inbox today, so the Http hook never reaches a Rust script even though the variant exists. Until it does, a Rust script that needs the response has to fetch it another way.

Calling functions other crates declare

A script function that an engine crate or a plugin declares (see Script Extensions) is a ScriptAction underneath. A Rust script calls it by sending that action with the same argument names:

use renzora::ScriptAction;

ScriptAction::new("set_bus_volume", ctx.entity())
    .arg("bus", "Music")
    .arg("volume", 0.5_f32)
    .send(ctx.world());

send triggers the action as an observer event, so whoever handles it has run before send returns. .on("Door") aims it at another entity by name or id. Argument values convert from f32, f64, i32, i64, bool, &str, String and Vec3 into ScriptActionValue.

A function that does slow work cannot return a result. It answers later with an event named by the caller, which arrives as ScriptHook::Event:

use renzora::{ScriptActionValue, ScriptCtx, ScriptHook};

fn hooks(_ctx: &mut ScriptCtx, hook: &ScriptHook) {
    if let ScriptHook::Event { name: "on_added", args, .. } = hook {
        if let Some(ScriptActionValue::String(id)) = args.get("id") {
            bevy::log::info!("added {id}");
        }
    }
}

For anything a declared function only wraps, a Rust script can usually skip the action and write the component or resource directly, since it has the world.

The plugin bus

Script events and the plugin bus share one event space (renzora_scripting::bus_bridge): every script event is emitted on the bus under the same name, and every bus event is queued for scripts. A Rust script can also call a bus service directly and get the answer back in the same call:

use bevy::prelude::*;
use renzora::bus::prelude::*;
use renzora::ScriptCtx;

fn update(ctx: &mut ScriptCtx) {
    match ctx.world().call("inventory.add_item", BusValue::map().with("id", "sword")) {
        Ok(answer) => info!("added: {answer:?}"),
        Err(err) => warn!("{err}"),
    }
}

renzora::script!(update);

Drawing

ctx.painter() returns a Painter for the entity's draw surface. It appends DrawCmds to the ScriptDrawBuffer resource, which renzora_ember::game_ui::script_canvas reconciles into a pool of UI shape entities under the canvas node. A surface exists only where game UI markup has a node with the canvas attribute (<node canvas width="300px" height="300px">), owned by the entity the markup is bound to; ctx.surface_size() returns its size, and ScriptHook::Draw carries it.

MethodDraws
line(x1, y1, x2, y2, color, thickness)A stroke
arc(cx, cy, r, start, end, color, thickness)A stroked arc; degrees, 0 = +x, clockwise
circle(cx, cy, r, color)A filled circle
rect(x, y, w, h, color) / rect_outline(x, y, w, h, color, thickness)A filled or outlined rectangle
triangle(x1, y1, x2, y2, x3, y3, color)A filled triangle
poly(&[(x, y)], color)A filled convex polygon, fanned from the first point; fewer than three points draws nothing
text(x, y, text, size, color)Text, baseline at y, centred on x

Coordinates are surface pixels with the origin at the top left and y down, matching the UI the canvas sits in. Colours are sRGB [r, g, b, a] in 0..1.

It is immediate mode. The first painter taken in a frame clears the entity's list, so draw the whole picture every frame inside the Draw hook; something you stop drawing simply disappears.

fn hooks(ctx: &mut ScriptCtx, hook: &ScriptHook) {
    if let ScriptHook::Draw { width, height } = *hook {
        let mut g = ctx.painter();
        g.rect(0.0, 0.0, width, height, [0.0, 0.0, 0.0, 0.5]);
        g.circle(width * 0.5, height * 0.5, 40.0, [1.0, 0.8, 0.2, 1.0]);
    }
}

Tile grid maths

renzora::grid::TileGrid (defined in renzora_scene_api::grid) is the square, isometric and hexagonal grid maths the tilemap and the 2D view's grid use, available to scripts for picking and placement.

use bevy::prelude::*;
use renzora::grid::TileGrid;

let grid = TileGrid::isometric(32.0, 16.0);   // diamonds 32 wide, 16 tall
let cell = grid.cell_at(Vec2::new(40.0, 25.0));
let centre = grid.cell_center(cell);
let foot = grid.cell_bottom(cell);              // where a sprite stands
MethodReturns
TileGrid::square(size), TileGrid::isometric(w, h), TileGrid::new(shape, w, h)A grid; shape is a GridShape (Square, Isometric, HexPointy, HexFlat)
cell_at(p)The cell (IVec2) containing a position
cell_center(cell) / cell_bottom(cell)A cell's centre, or its lowest point
cell_polygon(cell)Its corners: four, or six on a hex grid
neighbours(cell)Cells sharing an edge
cell_outline(min, max)The four corners around a block of square or diamond cells
region_edges(min, max) / grid_edges(min, max)Line segments outlining a block, or every cell edge in it
snap(p, half_steps)The nearest corner, or with half_steps also centres and edge midpoints
corner(c) / to_cell_space(p)Between positions and fractional cell coordinates

When scripts run

A script does nothing while a scene is being edited. dispatch runs when ScriptsActive is true, which is the case in a game process (Play starts the game as a separate process, and an exported game has no PlayModeState, which counts as running) or in the editor when a script's own preview button in the Inspector is on. In preview, only the previewed scripts run (ScriptEntry::preview), so the rest of the scene stays still.

Each entity's scripts are read from its ScriptComponent; entries are enabled .rs paths, resolved by file name. The calls are collected before any runs, because a script may insert, remove or despawn anything, including its own entity; an entity despawned earlier in the frame is skipped.

A panic in a script is caught (through renzora_crash_api::catch) and reported to the Console with the message and the line in the script's own file, not the staged copy the compiler read. The panic ends that call; the next script and the next frame carry on. A script that panics every frame reports every frame, and the Console folds the repeats into a count. A segfault in a script is still fatal.

info!, warn! and error! from a script reach the Console under the script's crate name (the file stem, hyphens as underscores). The loader registers that target with renzora_log_api::register_script_log_target when it maps the library.

How a script is built

A script is a native plugin with a per-entity convention on top: same compiler driver, same SDK, same loading rules. The differences are only that it exports a per-entity function instead of a Plugin, and that it lives in the project instead of beside the editor.

Which files are scripts. renzora_rust_script::collect_project_scripts walks the whole project (skipping target, .git, .renzora, node_modules, dist, .svn, .hg and any dot-directory) and keeps every .rs whose text contains renzora::script! or script!(. A script can live anywhere, not only in scripts/. The marker is required because the lean exporter compiles every file this returns into the game; a helper .rs that was never meant to be a script would otherwise fail the whole export. The test is a substring match, not a parse, so the macro name in a comment is enough to count.

When it builds.

  • On project open, one walk on a task pool finds every script; each builds on its own task and loads on the main thread as it finishes.
  • On save, ProjectFileChanged for a .rs that declares itself a script starts a rebuild. A save that lands while the previous build is still running is queued and built when it finishes.
  • A failed build is not retried until the file changes again, so one compile error does not become a scrolling wall. The exception is a failure caused by a file another process had open (the editor and Play's game process building the same script at once): that is retried up to eight times, 250 ms apart, before it is reported.

When a companion process is connected, builds are submitted to it as rust_script jobs instead of running in the editor process.

Where the output goes. renzora_plugin_build::script::build_to_path stages the source as <project>/.renzora/scripts/<stem>/src/lib.rs, generates a Cargo.toml there (Bevy's proc macros read it; nothing runs cargo), and invokes rustc against the SDK. The library is named <stem>-<key>.<dll|so|dylib>, where the key is an FNV-1a hash of the SDK stamp and the source. So:

  • a script whose source and SDK have not changed finds its library on disk and skips rustc entirely, which is what makes reopening a project cheap;
  • a rebuild always writes a new file rather than overwriting the one that is mapped (Windows cannot replace a loaded DLL, and overwriting a mapped image elsewhere is a later crash);
  • the build is written under a .partial name and renamed into place, so an interrupted build never leaves a file the cache check would trust.

.renzora/ holds derived files only. Nothing in it needs committing.

Errors. A compile error goes to the Console and to the Problems panel, keyed on the script's project-relative path, with the line taken from rustc's first --> <script>:LINE:COL. Paths in the message are rewritten from the staged copy to the script you edit. A successful build clears the problem.

Loading. load_library maps the library, looks up renzora_script_update (required) and renzora_script_hook (optional), and inserts them into LoadedScripts under the file name. A library missing the update symbol is reported as "exports no entry point" and is leaked rather than unloaded. No script image is ever unloaded: a reload maps a new image and repoints the entry, and the old one stays mapped for the life of the process, because a schedule or a captured closure may still hold pointers into it and unmapping a Rust dylib has deadlocked in FreeLibrary here before. A script is a couple of hundred kilobytes; a restart reclaims them.

The SDK and the compiler

Scripts compile against the SDK staged beside the editor (renzora_plugin_build::install::sdk_dir), the same one native plugins use. A release ships it as sdk.tar.zst, unpacked once on first launch before the App is built (renzora_native_plugin::prebuild); a source build stages dist/<platform>/sdk/ on every cargo renzora dist.

The SDK records the exact rustc it was cut with. renzora_rust_script::toolchain checks for that toolchain when the editor starts and publishes the answer as renzora::RustToolchain (Unknown, Checking, Ready, Missing { .. }, Installing { .. }, Installed { .. }, Declined, Failed(..)). While it is unknown, missing or installing, the editor holds script builds instead of failing each one; the splash screen and an in-project prompt (renzora_scripting_editor) offer to install it, through rustup if present and through rustup's own installer otherwise. "Not now" releases the held builds, which then fail with an error naming the install command. A game process (Play's child, or an exported game) never asks and never holds; it builds straight away.

An editor cross-built for another operating system carries an SDK for that target, which cannot compile scripts on this machine; the symptom is every bevy::prelude name reported missing at once.

In an exported game

Scripts run in exports, and the player needs neither a compiler nor the SDK.

BuildHow scripts get inLoaded by
Editor and PlayCompiled from source on open and on savewatch
Copy-based exportThe newest library under .renzora/scripts/<stem>/ is copied to <game>/scripts/script_<i>.<ext>, with a scripts.index mapping keys to filesload_prebuilt_scripts
Lean exportEach script becomes a module of a generated renzora_static_scripts crate compiled into the binary, with static_scripts onload_static_scripts

A copy-based export works because it ships the same bevy_dylib and renzora_dylib the scripts were built against. scripts.index is two tab-separated columns, key<TAB>file; each script is listed by its project-relative path and, when the leaf name is unique, by its file name. A script with no compiled library at export time is skipped with a warning to open the project so it builds, then export again.

Those libraries are host-shaped, so a copy-based export for another platform ships no scripts. A lean export compiles them in and has no such limit, including on the web. Every script in the project is included, not only those a scene references, because a scene can be loaded and a script attached at run time.

Limits

  • No inspector properties. RustScriptBackend::get_script_props returns nothing. Put tunables in your own reflected component on the entity, which the Inspector already edits.
  • One file, two crates. No mod files and no third-party dependencies. If you need either, write a native plugin.
  • File names must be unique. Libraries, build folders and dispatch are all keyed by the script's file name, so two player.rs in different folders collide.
  • No unloading, and no REPL. Reloads leak the previous image until restart; eval_expression is refused.
  • No Http hook yet, as described above.

Why it bypasses the command queue

The scripting system's model is that a backend returns ScriptCommands and a queue applies them (see The Scripting System). That keeps interpreted backends safe and interchangeable, and it is exactly what a Rust script does not want: the reason to write one is &mut World, which no command vocabulary can stand in for.

So renzora_rust_script splits the two jobs a backend normally does together. RustScriptBackend registers with the ScriptEngine and claims .rs, so the Scripts component accepts the file, the picker lists it, and the executor does not report No backend for Some("rs"); it answers defines_hook with Some(false), so the executor never builds a context for it. The real calls come from dispatch and the hook dispatchers above, with the world in hand. RustScriptPlugin::finish also installs ScriptsActive and its updater itself when ScriptingPlugin is absent (a lean export with the scripting feature stripped), so .rs scripts stay gated rather than panicking on a missing resource.