more scripting

This commit is contained in:
2026-06-04 23:52:33 -05:00
parent e0477a12b8
commit 4f21f7fa8a
8 changed files with 558 additions and 121 deletions
+17 -11
View File
@@ -92,8 +92,8 @@ An earlier design had `cells: Vec<(Glyph, usize)>` where the `usize` indexed a p
**Why `Board` is the complete unit (no wrapper struct):**
An earlier design had `GameMap { board: Board, player: Player, ... }`. This was eliminated because the split was artificial: there's no meaningful use of a `Board` without a player position, and no meaningful use of a player without a `Board`. ZZT itself treats a board as containing everything — the grid, the objects, and the player entry point. Collapsing to a single struct matches the domain model.
**`GameState`**
Owns the `Board`, the message `log: Vec<LogLine>`, and a `ScriptHost`. It keeps mutation logic (collision checking, movement) separate from the data and is where event processing/scripting dispatch lives: `try_move` for movement, `run_init()` to run object `init()` hooks once at startup, and `tick(dt)` to run object `tick(dt)` hooks every frame. After each script batch it flushes script-emitted log lines into `log`.
**`BoardState` / `GameState`**
`BoardState` is the scriptable world — currently just `{ board: Board }`, with room for runtime-only state (e.g. a shared variable blackboard). `GameState` holds it behind an `Rc<RefCell<BoardState>>`, alongside the message `log` and a `ScriptHost`. Keeping the world a **sibling** of the script host (rather than owned by it) is the key ownership move: host functions capture a clone of that `Rc` — a `'static` handle to a *different* `RefCell` than the running engine — so they can read/queue writes without aliasing the borrow that's executing scripts. Front-ends and internal logic reach the board only through `board() -> Ref<Board>` / `board_mut() -> RefMut<Board>` (no `pub board`). `try_move` moves the player; `run_init()` / `tick(dt)` run object hooks; `apply_commands()` drains the script command queue *after* each batch — the deferred apply is when `&mut` is finally free of any outstanding borrow.
---
@@ -103,11 +103,13 @@ Owns the `Board`, the message `log: Vec<LogLine>`, and a `ScriptHost`. It keeps
### `script.rs` — Rhai scripting runtime
`ScriptHost` owns the Rhai `Engine`, the scripts referenced by a board's objects (compiled once per name via `Engine::compile`), a persistent per-object `Scope`, and a shared **log sink**. Built with `ScriptHost::new(&board)`, which compiles scripts and records each object's available hooks (detected with `AST::iter_functions()` by name/arity) but **runs nothing** — compile errors and unknown-script references are reported into the log.
`ScriptHost` owns the Rhai `Engine`, the scripts referenced by a board's objects (compiled once per name via `Engine::compile`), a persistent per-object `Scope`, and a shared **command queue**. Built with `ScriptHost::new(&Rc<RefCell<BoardState>>)`, which registers the API, compiles scripts, and records each object's available hooks (detected with `AST::iter_functions()` by name/arity) but **runs nothing** — compile/unknown-script failures are queued as `GameCommand::Error`.
Two optional lifecycle hooks per object: `init()` (zero-arg, run once) and `tick(dt)` (elapsed seconds as `f64`, run per frame), driven by `run_init()` / `run_tick(dt)`. Runtime errors are logged, not fatal.
Two optional lifecycle hooks per object: `init()` (zero-arg, run once) and `tick(dt)` (elapsed seconds as `f64`, run per frame), driven by `run_init()` / `run_tick(dt)`. Runtime errors become `Error` commands, not fatal.
The one host function so far is `log(s)`, which appends an uncolored `LogLine`. The borrow problem — Rhai's registered closures must be `'static`, yet `log` must reach the game log — is solved by writing into an `Rc<RefCell<Vec<LogLine>>>` sink cloned into the closure; `GameState` drains it with `take_pending()` after each batch, so running scripts never needs a mutable borrow of `GameState`. (Default `call_fn` rewinds the scope per call, so script-local persistence across ticks is future work; the per-object `Scope` is the seam for that and for injecting object state.) `Engine`/`Scope` are not `Send` — fine for the single-threaded kiln-tui.
**Reads vs writes.** Scripts **read** the world directly: a read-only `BoardView` (a registered type with getters only — read-only by construction) is pushed into each scope as `board`, so a script writes `board.player_x`; the getter briefly borrows the shared `BoardState`. Scripts **write** by enqueuing `Command { source, kind }` where `kind: GameCommand` is `Move(Direction)` / `SetTile(u32)` / `Log(LogLine)` / `Error(String)`. The host fns `move`/`set_tile`/`log` push into a shared `Rc<RefCell<Vec<Command>>>` cloned into each closure (the same `'static`-closure trick the old log sink used, generalized); `GameState::apply_commands` drains and applies them after the batch. Reads-are-live, writes-are-deferred gives frame-coherent semantics and keeps script execution free of any `&mut GameState` borrow.
**Sender identity** (which object issued a command) rides Rhai's per-call **tag**: `run` calls `call_fn_with_options(...with_tag(object_index)...)` and the host fns read it via `NativeCallContext::tag()`, so scripts write `move(north)` without a `this` argument (`north`/`south`/`east`/`west` are `Direction` constants in scope; `impl From<Direction> for (i32,i32)` yields the delta). The object's identity is currently its index into `Board::objects` — a stopgap (a `// TODO` flags replacing it with stable unique ids that survive spawn/destroy). Default `call_fn` rewinds the scope per call, so script-local persistence across ticks is still future work; the per-object `Scope` is the seam for that. `Engine`/`Scope` are not `Send` — fine for the single-threaded kiln-tui.
---
@@ -306,8 +308,11 @@ target_entry = "west_door"
[scripts]
greeter = """
fn init() { log("hello world"); }
fn tick(dt) { }
fn init() {
log(`player at ${board.player_x}, ${board.player_y}`); # read
set_tile(2); # write
}
fn tick(dt) { move(north); } # dt = elapsed seconds; dir ∈ north/south/east/west
"""
```
@@ -331,11 +336,12 @@ A direct mapping from palette character → `(Glyph, Archetype)` means the map f
## What's not yet implemented
**Object scripting** — the runtime exists (`script.rs`): objects run optional `init()`/`tick(dt)` hooks and can call `log(s)`. Still to come:
**Object scripting** — the runtime exists (`script.rs`): objects run optional `init()`/`tick(dt)` hooks, **read** the world via `board.*`, and **write** via queued commands (`move`, `set_tile`, `log`). Still to come:
1. More event hooks beyond lifecycle — e.g. fire `on_touch` when the player moves onto an object's cell
2. Grow the Rhai API surface (movement, board queries, `send_message`, randomness) and give a script a handle to *its own* object
3. Persist script-local state across ticks (needs `call_fn_raw` so the per-object `Scope` isn't rewound each call)
4. `PortalDef` is still parsed-only — no multi-board navigation yet
2. Grow the command vocabulary and read API (`send_message`, randomness, board queries, more glyph setters)
3. **Stable object ids**`Command.source` / `ObjectRuntime.object_index` are array indices into `Board::objects`, which break under spawn/destroy/reorder; replace with monotonically-increasing unique ids and key objects by them (a `// TODO` marks this in code)
4. Persist script-local state across ticks (needs `call_fn_raw` so the per-object `Scope` isn't rewound each call)
5. `PortalDef` is still parsed-only — no multi-board navigation yet
**Object behavior from scripts**`ObjectDef.passable` and `ObjectDef.opaque` are live and editable in the editor, but they are static author-set values. Eventually they should be overridable by the object's Rhai script at runtime (e.g. a door script that flips `passable` when opened). `Board::is_passable` already has the right shape for this; the script runtime just needs to be wired in.