Hazel

The Scripting System

crates/renzora_scripting is the language-neutral half of scripting: the component that attaches scripts to entities, the run condition that decides when they run, the executor that calls hooks, the command vocabulary hooks answer with, and the queue that applies those commands to the world. It contains no interpreter. A language arrives as a backend registered by a plugin (see Script Backends), and the engine routes each script to the backend that claims its file extension.

Rust scripts use the attachment, the run condition and the event inboxes described here, but not the executor or the command queue: they are called directly with &mut World. See Rust Scripts.

The types that cross the boundary to a plugin (ScriptBackend, ScriptCommand, ScriptContext, ScriptComponent, the inboxes, ScriptExtension) live in the contract layer crates/api/renzora_scripting_api, because a backend is meant to be an installed plugin, and an installed plugin can only name bevy and renzora. renzora_scripting re-exports them under its own paths, so engine code may use either.

Attaching scripts: ScriptComponent

#[derive(Component, Clone, Reflect)]
#[reflect(Component)]
pub struct ScriptComponent {
    pub scripts: Vec<ScriptEntry>,
    // next_id is private
}

One component per entity, holding any number of ScriptEntrys, in any mix of languages:

ScriptEntry fieldSavedMeaning
id: u32yesStable id within the component
script_id: StringyesFor registered (non-file) scripts; empty for a file script
script_path: Option<PathBuf>yesThe script file, project-relative
enabled: boolyesOff entries are never called
variables: ScriptVariablesyesInspector-edited values, a name-ordered BTreeMap<String, ScriptValue>
preview: boolnoThe Inspector's per-script play button (edit-mode preview)
runtime_state: ScriptRuntimeStatenoinitialized, has_error, fixed_has_error, ...

ScriptVariables is ordered so the same values always serialize the same way, which keeps a saved scene stable and lets the live link compare components by their text. ScriptValue is Float(f32), Int(i32), Bool, String, Entity(String), Vec2, Vec3 or Color(Vec4).

Nothing inserts a ScriptComponent automatically. It is created on demand by the Inspector's Scripts section, by dropping a script file on an entity, by the hierarchy's create-script action, and by authored game UI that binds to an entity. The executor's query therefore only visits entities that actually carry scripts.

When scripts run

ScriptsActive(bool) is computed once per frame by update_scripts_active in ScriptingSet::PreScript, and every script system gates on the run condition scripts_should_run, which reads it:

SituationScriptsActive
No PlayModeState resource (an exported game, or Play's child process)true
PlayModeState::is_scripts_running()true
Editing, and at least one enabled entry has preview ontrue, and only previewed entries run
Editing otherwisefalse

The system only reruns when play state changes or a ScriptComponent is changed or removed, and it writes only on a real transition, so it does not mark the resource changed every frame. It is computed once and shared rather than recalculated per system because four systems (three here and the Rust dispatcher) gate on it, and Bevy evaluates run conditions per system.

Frame order

ScriptingPlugin chains five sets in Update:

SetWhat runs there
ScriptingSet::PreScriptupdate_scripts_active, update_script_input, update_script_timers, scripts-folder sync, the interpreted backends' hot-reload check
ScriptingSet::ScriptExecutionrun_scripts
ScriptingSet::CommandProcessingapply_script_commands, then apply_reflection_sets after it
ScriptingSet::DebugDraw
ScriptingSet::Cleanupevict_despawned_scripts

PreScript is ordered after PhysicsSet::Read, so scripts see this frame's velocities and contacts rather than last frame's.

In FixedUpdate, ScriptExecution (running run_fixed_scripts) and CommandProcessing are chained and placed before PhysicsSet::Commands, so a force or velocity set in on_fixed_update reaches the physics step that follows it.

The executor

run_scripts and run_fixed_scripts are one exclusive pass (run_pass) with a frame and a fixed mode, so the context a fixed hook sees cannot drift from the one on_update sees.

For each entity with something to run, the pass:

  1. Snapshots the frame's shared state once: Time, ScriptInput, finished timers, the input action map (ActionState), the parent and children transforms, and (frame pass only) the event inboxes.
  2. Takes the ScriptComponent off the entity for the duration of the run and reinserts it afterwards, so scripts can be given world access without aliasing it.
  3. Builds a ScriptContext per entry and installs the thread-local read handlers (get_handler) that answer a script's synchronous get calls through reflection.
  4. Calls the hooks: on_ready once (merging any props the backend reports into variables first), then on_update or on_fixed_update, then on_draw for entities with a canvas surface, then, in the frame pass, each pending event: on_rpc, on_ui, on_animation_event, on_http, on_player_joined / on_player_left, on_event, on_scene_loaded / on_scene_load_failed.
  5. Folds every returned command into the context (ScriptContext::process_command) and from there into ScriptCommandQueue.

Before building a context, the pass asks the backend defines_hook(path, hook). Building a context is the expensive part of a call (an input snapshot, name maps, read handlers), so a backend that answers Some(false) is skipped entirely. That is how a Rust script, which is dispatched elsewhere, costs the executor nothing.

The fixed pass deliberately does less:

  • It never drains the inboxes. A drain has one consumer; draining in a fixed tick would hand an event to whichever pass ran first, and a frame with no fixed tick would hand it to nobody.
  • It skips entries that have not had on_ready, so the first fixed tick of play arrives a frame late rather than before setup.
  • Input is sampled once per frame, so just_pressed edges can appear in two ticks or none. Held buttons and axes are reliable in on_fixed_update; edges belong in on_update.

An Err from a hook is logged once (has_error latches until the hook next succeeds) and the script keeps being called. A backend should return errors rather than panic; nothing in the executor catches a panic.

The command vocabulary

A hook does not touch the world. It returns Vec<ScriptCommand>, and the engine applies them after the hook has finished. That indirection is what lets an interpreter run without &mut World, and what makes backends interchangeable: every language produces the same values.

ScriptCommand (in renzora_scripting_api::command) groups roughly as follows. Vectors are [f32; 3] and colours [f32; 4], converted where the command is applied rather than at every construction site.

GroupVariants
Own transformSetPosition, SetRotation, SetScale, Translate, Rotate, LookAt, GotoCameraPreset
Parent / child transformParentSetPosition, ParentSetRotation, ParentTranslate, ChildSetPosition, ChildSetRotation, ChildTranslate
EnvironmentSetSunAngles, SetAmbientBrightness, SetAmbientColor, SetSkyTopColor, SetSkyHorizonColor, SetFog, SetFogColor, SetEv100
EntitiesSpawnEntity, SpawnPrimitive, SpawnPrefab, DespawnEntity, DespawnSelf, DespawnByPrefix, SetEntityName, AddTag, RemoveTag, SetVisibility
AudioPlaySound, PlaySound3D, PlayMusic, StopMusic, CrossfadeMusic, StopAllSounds, SetMasterVolume, pause/resume/volume/pitch per sound or entity
PhysicsApplyForce, ApplyImpulse, ApplyTorque, SetVelocity, SetAngularVelocity, SetGravityScale, Raycast
Character controllerCharacterMove, CharacterJump, CharacterSprint
AnimationPlayAnimation, StopAnimation, PauseAnimation, ResumeAnimation, SetAnimationSpeed, SeekAnimation, CrossfadeAnimation, SetAnimationParam, SetAnimationBoolParam, TriggerAnimation, SetAnimationLayerWeight, PlaySpriteAnimation, SetSpriteFrame
TweensTween, TweenPosition, TweenRotation, TweenScale
ParticlesParticlePlay, ParticlePause, ParticleStop, ParticleReset, ParticleBurst, ParticleSetRate, ParticleSetScale, ParticleSetTimeScale, ParticleSetTint
Rendering and cameraSetMaterialColor, SetLightIntensity, SetLightColor, SetCameraTarget, SetCameraZoom, ScreenShake, CameraFollow, StopCameraFollow, LockCursor, UnlockCursor
HealthSetHealth, SetMaxHealth, Damage, Heal, SetInvincible, Kill, Revive
Timers, scenes, debugStartTimer, StopTimer, PauseTimer, ResumeTimer, LoadScene, UnloadScene, Log, DrawLine, DrawRay, DrawSphere, DrawBox, DrawPoint
GenericSetProperty, SetComponentField, Action, Emit, HttpRequest

The exhaustive list is the enum itself; this table is a map of it.

How commands are applied

ScriptContext::process_command sorts commands as they come back. Own-, parent- and child-transform and environment commands become fields on the context (new_position, child_changes, env_fog_color, ...) and turn into transform writes and environment requests; everything else is pushed to ctx.commands and lands in ScriptCommandQueue.

apply_script_commands (in CommandProcessing) then:

  1. Drains renzora_animation_api::TransformWriteQueue into the transform writes (non-script writers use it too) and applies them.
  2. Handles a small core directly: entity spawning and despawning, visibility, names, timers, logging, camera presets, scene loads (pushed to PendingSceneLoad), prefab spawning, the character controller queue (CharacterCommandQueue), cursor lock, Emit (queued to GameEventQueue for the next frame, so one script's event cannot re-enter a backend while another's hook is on the stack), and HttpRequest (handed to HttpInbox, answered on a background thread).
  3. Pushes SetComponentField to ScriptReflectionQueue, which the exclusive apply_reflection_sets applies through reflection afterwards.
  4. Turns Action { name, target_entity, args } into a triggered ScriptAction event.
  5. Converts every other command into a ScriptAction with a fixed name and argument map (ApplyForce becomes apply_force with x/y/z, PlayAnimation becomes play_animation, and so on) and triggers it.

That last step is why scripting depends on none of the domain crates. Physics, animation, audio and particles each observe the ScriptActions they understand; a stripped export without one of them simply has no observer, and the action does nothing. It is also the same event a declared binding fires, so a domain crate handles "the command" and "the function" with one observer.

Event inboxes

Producers outside scripting never call into it. Each pushes plain data into a resource in renzora_scripting_api::script_bridge, and the frame pass drains it:

ResourceFilled byHook
ScriptUiInbox (UiCallback)game UI markup callbackson_ui / ScriptHook::Ui
ScriptRpcInbox (IncomingRpc)networkingon_rpc / ScriptHook::Rpc
ScriptNetLifecycleInbox (NetPlayerEvent)networking, server sideon_player_joined, on_player_left
ScriptAnimEventInbox (AnimEvent)animation clip markerson_animation_event
ScriptSceneInbox (SceneEvent)scene loadson_scene_loaded, on_scene_load_failed
GameEventQueue (GameEvent)emit, engine crates, plugins, the plugin buson_event / ScriptHook::Event
HttpInbox (HttpResult)http_get / http_poston_http

Events are broadcast: every running script's hook is called for every event, and the script filters by name. The Rust hook dispatcher reads these (except HttpInbox) before ScriptExecution and leaves them in place, so the interpreted executor's drain still sees them.

The plugin bus

renzora_scripting::bus_bridge joins GameEventQueue to the plugin bus: every script event is re-emitted on the bus under its name, every bus event is queued for scripts, and an action(name, ...) whose name is a bus service calls it, answering with an event named by the callback argument. Each direction marks what it relays so the two do not echo each other forever.

Built-in actions

A few ScriptAction names are handled inside scripting itself, for scripts that reach them through a generic action(...) call rather than a command: despawn_self, despawn (by name, or self when no target), lock_cursor, unlock_cursor, and http_get / http_post (arguments url, callback, and body for a post).

Reading state from a script

An interpreted script reads through two channels:

  • The context. ScriptContext is a snapshot built per call: time (ScriptTime), own transform (ScriptTransform), keyboard, mouse, gamepads and touch, the input action map (action_pressed, action_axis_2d, ...), parent and children, collisions, timers that just finished, raycast results, a few component mirrors (health, light, material colour), network role, and extensions(), the declared bindings.
  • Reflection reads. renzora_scripting_api::get_handler holds thread-local closures the executor installs before each call: call_get(entity_name, component, field_path), call_get_component, call_get_components. A backend's get("Health.current") goes through them and returns a PropertyValue. They are thread-local state, which is why they live in the contract and are made singular by renzora_dylib: a backend linking a private copy would read handlers the engine never wrote, and every get would quietly return nothing.

Writes go the other way, as SetComponentField commands, so they apply after the hook returns.

Backend state and hot reload

evict_despawned_scripts tells every backend (ScriptBackend::evict) when a scripted entity is gone, so a backend that keeps a VM per (entity, script) does not grow forever. It checks that the entity really lost its ScriptComponent: the executor's take-and-reinsert registers as a removal every frame, and evicting then would reset every script's state.

check_script_hot_reload asks each backend needs_reload every 0.5 s and calls reload on stale scripts, resetting their initialized flag so on_ready runs again, then triggers renzora_shell_api::ScriptsReloaded. Rust scripts do not use this path; they rebuild on ProjectFileChanged instead.

Key types

ItemCratePurpose
ScriptingPluginrenzora_scriptingInstalls everything above
ScriptEnginerenzora_scriptingThe registered backends, routed by extension
ScriptingSetrenzora_scriptingThe system sets above
ScriptsActive, scripts_should_run, update_scripts_activerenzora_scriptingThe shared run condition
ScriptCommandQueue, ScriptReflectionQueuerenzora_scripting::systemsCommands waiting to be applied
ScriptComponent, ScriptEntry, ScriptVariables, ScriptValuerenzora_scripting_api::componentAttachment and inspector values
ScriptCommandrenzora_scripting_api::commandThe vocabulary
ScriptContextrenzora_scripting_api::contextWhat a backend's hook receives
ScriptAction, ScriptActionValue, inboxesrenzora_scripting_api::script_bridgeEvents in and out
ScriptBackend, AppScriptBackendExtrenzora_scripting_api::backendAdding a language
ScriptExtension, Bindrenzora_scripting_api::script_extensionDeclaring script functions

ScriptingPlugin is behind renzora_runtime's strippable scripting feature. A lean export of a game with no interpreted scripts drops it; Rust scripts keep working because RustScriptPlugin installs the run condition itself when the host is absent.