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 field | Saved | Meaning |
|---|---|---|
id: u32 | yes | Stable id within the component |
script_id: String | yes | For registered (non-file) scripts; empty for a file script |
script_path: Option<PathBuf> | yes | The script file, project-relative |
enabled: bool | yes | Off entries are never called |
variables: ScriptVariables | yes | Inspector-edited values, a name-ordered BTreeMap<String, ScriptValue> |
preview: bool | no | The Inspector's per-script play button (edit-mode preview) |
runtime_state: ScriptRuntimeState | no | initialized, 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:
| Situation | ScriptsActive |
|---|---|
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 on | true, and only previewed entries run |
| Editing otherwise | false |
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:
| Set | What runs there |
|---|---|
ScriptingSet::PreScript | update_scripts_active, update_script_input, update_script_timers, scripts-folder sync, the interpreted backends' hot-reload check |
ScriptingSet::ScriptExecution | run_scripts |
ScriptingSet::CommandProcessing | apply_script_commands, then apply_reflection_sets after it |
ScriptingSet::DebugDraw | |
ScriptingSet::Cleanup | evict_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:
- 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. - Takes the
ScriptComponentoff the entity for the duration of the run and reinserts it afterwards, so scripts can be given world access without aliasing it. - Builds a
ScriptContextper entry and installs the thread-local read handlers (get_handler) that answer a script's synchronousgetcalls through reflection. - Calls the hooks:
on_readyonce (merging any props the backend reports intovariablesfirst), thenon_updateoron_fixed_update, thenon_drawfor 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. - Folds every returned command into the context (
ScriptContext::process_command) and from there intoScriptCommandQueue.
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_pressededges can appear in two ticks or none. Held buttons and axes are reliable inon_fixed_update; edges belong inon_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.
| Group | Variants |
|---|---|
| Own transform | SetPosition, SetRotation, SetScale, Translate, Rotate, LookAt, GotoCameraPreset |
| Parent / child transform | ParentSetPosition, ParentSetRotation, ParentTranslate, ChildSetPosition, ChildSetRotation, ChildTranslate |
| Environment | SetSunAngles, SetAmbientBrightness, SetAmbientColor, SetSkyTopColor, SetSkyHorizonColor, SetFog, SetFogColor, SetEv100 |
| Entities | SpawnEntity, SpawnPrimitive, SpawnPrefab, DespawnEntity, DespawnSelf, DespawnByPrefix, SetEntityName, AddTag, RemoveTag, SetVisibility |
| Audio | PlaySound, PlaySound3D, PlayMusic, StopMusic, CrossfadeMusic, StopAllSounds, SetMasterVolume, pause/resume/volume/pitch per sound or entity |
| Physics | ApplyForce, ApplyImpulse, ApplyTorque, SetVelocity, SetAngularVelocity, SetGravityScale, Raycast |
| Character controller | CharacterMove, CharacterJump, CharacterSprint |
| Animation | PlayAnimation, StopAnimation, PauseAnimation, ResumeAnimation, SetAnimationSpeed, SeekAnimation, CrossfadeAnimation, SetAnimationParam, SetAnimationBoolParam, TriggerAnimation, SetAnimationLayerWeight, PlaySpriteAnimation, SetSpriteFrame |
| Tweens | Tween, TweenPosition, TweenRotation, TweenScale |
| Particles | ParticlePlay, ParticlePause, ParticleStop, ParticleReset, ParticleBurst, ParticleSetRate, ParticleSetScale, ParticleSetTimeScale, ParticleSetTint |
| Rendering and camera | SetMaterialColor, SetLightIntensity, SetLightColor, SetCameraTarget, SetCameraZoom, ScreenShake, CameraFollow, StopCameraFollow, LockCursor, UnlockCursor |
| Health | SetHealth, SetMaxHealth, Damage, Heal, SetInvincible, Kill, Revive |
| Timers, scenes, debug | StartTimer, StopTimer, PauseTimer, ResumeTimer, LoadScene, UnloadScene, Log, DrawLine, DrawRay, DrawSphere, DrawBox, DrawPoint |
| Generic | SetProperty, 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:
- Drains
renzora_animation_api::TransformWriteQueueinto the transform writes (non-script writers use it too) and applies them. - 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 toGameEventQueuefor the next frame, so one script's event cannot re-enter a backend while another's hook is on the stack), andHttpRequest(handed toHttpInbox, answered on a background thread). - Pushes
SetComponentFieldtoScriptReflectionQueue, which the exclusiveapply_reflection_setsapplies through reflection afterwards. - Turns
Action { name, target_entity, args }into a triggeredScriptActionevent. - Converts every other command into a
ScriptActionwith a fixed name and argument map (ApplyForcebecomesapply_forcewithx/y/z,PlayAnimationbecomesplay_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:
| Resource | Filled by | Hook |
|---|---|---|
ScriptUiInbox (UiCallback) | game UI markup callbacks | on_ui / ScriptHook::Ui |
ScriptRpcInbox (IncomingRpc) | networking | on_rpc / ScriptHook::Rpc |
ScriptNetLifecycleInbox (NetPlayerEvent) | networking, server side | on_player_joined, on_player_left |
ScriptAnimEventInbox (AnimEvent) | animation clip markers | on_animation_event |
ScriptSceneInbox (SceneEvent) | scene loads | on_scene_loaded, on_scene_load_failed |
GameEventQueue (GameEvent) | emit, engine crates, plugins, the plugin bus | on_event / ScriptHook::Event |
HttpInbox (HttpResult) | http_get / http_post | on_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.
ScriptContextis 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, andextensions(), the declared bindings. - Reflection reads.
renzora_scripting_api::get_handlerholds thread-local closures the executor installs before each call:call_get(entity_name, component, field_path),call_get_component,call_get_components. A backend'sget("Health.current")goes through them and returns aPropertyValue. They are thread-local state, which is why they live in the contract and are made singular byrenzora_dylib: a backend linking a private copy would read handlers the engine never wrote, and everygetwould 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
| Item | Crate | Purpose |
|---|---|---|
ScriptingPlugin | renzora_scripting | Installs everything above |
ScriptEngine | renzora_scripting | The registered backends, routed by extension |
ScriptingSet | renzora_scripting | The system sets above |
ScriptsActive, scripts_should_run, update_scripts_active | renzora_scripting | The shared run condition |
ScriptCommandQueue, ScriptReflectionQueue | renzora_scripting::systems | Commands waiting to be applied |
ScriptComponent, ScriptEntry, ScriptVariables, ScriptValue | renzora_scripting_api::component | Attachment and inspector values |
ScriptCommand | renzora_scripting_api::command | The vocabulary |
ScriptContext | renzora_scripting_api::context | What a backend's hook receives |
ScriptAction, ScriptActionValue, inboxes | renzora_scripting_api::script_bridge | Events in and out |
ScriptBackend, AppScriptBackendExt | renzora_scripting_api::backend | Adding a language |
ScriptExtension, Bind | renzora_scripting_api::script_extension | Declaring 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.