# Modding guide Everything you play in Stafra is built as mods: experiences, libraries, UI screens, and built-in tools like the home screen, developer tools, and AI assistant (`F3`). Built-in bootstrap mods ship in `mods/@stafra/`; your own mods go in `mods/`. A mod is a script written in [Rune](https://rune-rs.github.io/book/), a small scripting language that looks a lot like Rust. ## Quick start Make a text file `mods/my_mod.rn` (on Windows, make sure it doesn't end in `.txt`), put this in it and save: ```rust pub fn init() { let s = ui::screen("hello"); let count = #{ clicks: 0 }; let label = s.root.text("Clicks: 0"); let btn = s.root.button("Click me"); btn.when_clicked = || { count.clicks += 1; label.text = format!("Clicks: {}", count.clicks); tone("C5 E5 G5").play(); }; s.open = true; count } ``` That's a complete, self-contained mod—no external assets needed. The game picks up new files and saved changes while it's running. Press **F1** to see the log, which includes anything your mod prints with `println!`. Press **F2** to open the built-in editor: every mod and its files (long-press or right-click one to switch it on or off), and Ctrl+S (Cmd+S on a Mac) to save and reload. **F4** goes home, **F12** saves a screenshot in `saves/`. When a mod grows its own models (`.glb`), images, sounds, stylesheets (`.css`), markup (`.ui`), or shaders, give it a folder instead: `mods/my_mod/mod.rn` (or `mods/my_mod/my_mod.rn`), with the other files next to it. ## How a mod works A mod can define these functions. All of them are optional, and each one only lists the parameters it actually uses: `update()`, `update(dt)` and `update(dt, state)` all work. ```rust pub fn init() { ... } // once when loaded, and again after every save pub fn update(dt, state) { ... } // every frame pub fn on_mow(data, state) { ... } // when any mod calls emit("mow", data) ``` - Whatever `init` returns becomes your **state** and is passed back as the last parameter of the others. Return an object to keep several things: `#{ pet: pet, score: 0 }`. - `dt` is the seconds since the last frame. Multiply speeds by it: `pet.forward(2.0 * dt)` moves 2 metres per second. - **Events:** `emit("mow", data)` runs `on_mow` in every mod that has one. Pick any name. The game itself emits `"mod_loaded"` (data: the mod's name, like `"@stafra/grass"`). - **Saving reloads your mod.** Everything it created is removed and `init` runs again. In a folder mod, changing any file in the folder (a model, a shader) reloads it too. - **Errors only stop your mod.** The message appears in the top-left. Fix it and save. - **Each call has to finish.** Your functions run on the game's own thread, so while `update` (or a button's function, or a timer's) runs, nothing else does: no drawing, no input, no editor. One that runs for over 5 seconds (20 for `init`) is stopped, and your mod with it, and the error says where it was: it's usually a loop that never ends. Work that takes long anyway, like a game AI's search or generating a level, should be spread over several frames: do a slice of it in each `update` and keep where you got to in your state. Anything over a few milliseconds per frame shows as stutter. - **Assets by name, no extension.** `spawn("bear")`, `sound("roar")`, `shader = "fur"` and `texture = "bark"` find bear.glb, roar.ogg, fur.vert/.frag and bark.png in **your** mod. Each mod is a namespace: a bare name only ever means your own file. Another of your mods is `"pack/name"`, like `"trees/oak"`. The mods that come with the game are in the `@stafra` scope, so from your mods they're `"@stafra/fox/fox"` (inside @stafra they just say `"fox/fox"`). Nothing else is searched, so another mod can never take over a name; get it wrong and the error says what to write. Full file paths still work. - World units are metres, right-handed, Y up. `actor.yaw = 0` faces `+Z` (glTF standard). `camera().yaw = 0` sits at `+Z` looking toward `-Z` (`+X` is screen-right, `-Z` is screen-up/forward). Prefer `heading(go.x, go.y)`, `cam.forward()`, `cam.right()`, and `cam.position()` over hand-rolling trig from `cam.yaw`. ## Experiences What you play is an **experience**: the home screen lists them (Tutorial, Horde, Create with AI, then yours) and makes new ones. An experience is a mod folder with a `stafra.md` next to its `mod.rn`: settings between `---` lines, then what it is: ``` --- title: My game image: cover.png mods: @stafra/ground, @stafra/grass, @stafra/fox, my_enemies --- What it is, in a sentence or two: the first paragraph shows on its tile. Anything more shows when you hover over it. ``` Its `mod.rn` decides what's shown (a game, a story, a menu of other experiences); `mods` are the other mods that run with it. Names work like asset names: a bare name is a mod in the experience's own scope (yours, or in `@stafra/horde` the built-ins), `@scope/name` one in another; `*` means every mod and `*mine` all of yours. Along with those, your **always-on** mods run in every experience: any mods you like, set in Settings on the home screen (developer tools and the assistant to start with). In the editor, switching a mod on or off applies to the experience you're in, and is remembered for it, as is the editor layout (open files, panels) and the assistant's conversation. Always-on mods carry on across experiences: they hear `on_experience(name, state)` when it changes. ## Sound Sounds are objects you ask for by name, then tell what to do. No loading step: ```rust sound("hit").play(); // hit.wav or hit.ogg next to your script tone("C5 E5 G5").play(); // synthesised notes: no file needed music::play("theme"); // theme.ogg, on repeat, crossfading from the last track ``` Asking for the same name again gives back the **same** Sound, so settings stick, and they apply live, even to a sound that's already playing: ```rust let engine = sound("engine"); engine.volume = 0.5; // 0 to 1 engine.pitch = 1.5; // 1 = as recorded, 2 = an octave up engine.at = car; // comes from that actor: quieter further away, engine.repeat(); // and panned as the camera turns ``` Tones are written as notes: `"C4"`, `"F#5"`, `"Bb3"`, a frequency like `"440"`, `-` for a rest, and `:2` to hold a note for two beats. Set `wave` (`"square"`, `"triangle"`, `"saw"`, `"sine"`, `"noise"`) and `beat` (seconds per note). A short `"noise"` tone makes a good scuff, pop or hit. See `footsteps.rn`, `chimes/` and the fanfare in `horde/`. A mod's sounds stop when it reloads. Music asked for again by `init` carries on without a gap, so editing a mod doesn't restart its soundtrack. ## Buttons and movement Buttons work the same way: ask for one by name, then read it or hand it a function. The same mod works with a keyboard, a gamepad and a touch screen without asking which: ```rust button("jump").when_pressed = || fox.restart(); // Space, gamepad A, or the touch Jump button key("F").when_pressed = || drop_decoy(my); // one keyboard key if pad("rb").held() { ... } // one gamepad button let go = movement(); // WASD/arrows, the left stick, or the touch stick fox.turn_toward(heading(go.x, go.y), 8.0 * dt); fox.forward(1.4 * go.length() * dt); // a stick pushed half way gives 0.5 ``` The named buttons are `"jump"` (Space, pad A), `"action"` (E, Return, pad X), `"special"` (Q, pad Y), `"run"` (Left Shift, left bumper, or the touch stick pushed all the way), `"menu"` (Tab, Start) and `"camera"` (V, Back). Jump, action, special and camera get an on-screen button on phones and tablets, shown only while some mod has asked for them. `when_pressed` / `when_released` run on the frame it happens, just before your `update`. A function can read the variables around it but not reassign them, so keep anything it changes in an object: `|| my.score += 1` works, `|| score += 1` doesn't. See `fox/`. `held("W")` and `pressed("Space")` still work too. ## Things that carry on by themselves Start something with one line and it keeps going without your `update`: ```rust fox.walk_to(3.0, 4.0); // turns, walks there (playing Walk), then stops fox.when_arrived = || bark.play(); // and runs this when it gets there fox.animate("scale", 2.0, 0.5); // glide to scale 2 over half a second after(2.0, || fox.walk_to(0.0, 0.0)); let wander = every(3.0, || fox.walk_to(range(-5.0, 5.0), range(-5.0, 5.0))); wander.stop(); // timers keep going until stopped (or the mod reloads) ``` `walk_speed` sets how fast `walk_to` goes (from 2.5 m/s it plays Run). `animate` works on `x`, `y`, `z`, `yaw`, `scale` and `speed`. `fox.stop()` cancels both. See the decoys in `@stafra/fox/`: each pops in and then wanders about on its own. ## Drawing and the camera Draw on top of the game every frame you want it shown. A position is `(x, y)` in pixels from the top-left, an actor (just above its head, following it on screen), or `(x, y, z)` in the world. Colours are names (`"red"`, `"white"`, ...), `"#ff8800"`, or `(r, g, b)` / `(r, g, b, a)` from 0 to 1: ```rust draw::text(fox, "Fox", "white"); // a name tag that follows the fox draw::rect(ghoul, 40, 6, "red"); // a health bar over its head draw::rect((20, 20), 200, 30, (0, 0, 0, 0.6)); draw::circle((100, 100), 8, "#ffcc00"); draw::line((0, 0), fox, 2, "cyan"); ``` Text grows with the screen, so lay it out with `char_size()` (one character's width and height in pixels). See `@stafra/views.rn`. There's one camera, and it's an object like everything else: ```rust let cam = camera(); cam.top_down(); // or cam.side_on(), cam.orbit() cam.distance = 12.0; // also yaw, pitch, fov cam.follow = fox; // or () and cam.look_at(x, y, z) for a fixed spot cam.free = false; // the player can't turn it (zoom still works) ``` When the mod that changed it unloads, the camera goes back to the usual view. Press V (or the touch Camera button) to try the views. ## UI Screens Menus, HUDs and dialogs use **`ui::screen()`** — the standard accessible UI system for mods. Screens are trees of flexbox components styled with CSS that work with a mouse, touch, keyboard navigation (Tab / Enter / Space) and screen readers (VoiceOver / accessibility roles and labels), and reflow for any screen size: ```rust let s = ui::screen("hud"); // asking again gives the same screen s.style("theme.css"); // stylesheet in your mod's folder s.load("hud.ui"); // elements from markup... s.get("play").when_clicked = || start_game(); let row = s.root.row(); // ...or built in code row.text("Score: 0"); s.open = true; ``` See [docs/ui.md](../docs/ui.md) for the full component, markup, CSS and canvas reference. (`ui::panel()` is reserved for built-in `@stafra` app/editor panels like the home screen and assistant.) ## The assistant `@stafra/assistant` (F3) asks a language model about the file you're editing: ask anything, Fix error, or Explain. It asks for just the lines to change, applies them, and compiles the result (if that fails it asks again, up to three times, with the problems, for just the files that have them; the rest are kept), then shows it in the editor as a change you Accept or Reject. It never edits on its own. When it gives up, or a request fails, the conversation and `stafra.log` say why. It needs a model: pick one at the bottom of the panel, or press **+** to add one. The best results come from a large hosted model: choose a provider (OpenRouter has models from many companies with one key; or Anthropic, OpenAI, Gemini, Mistral, Groq, DeepSeek, xAI), pick or type a model, and paste your API key. Keys are kept in the system keychain, never in your files. Your code and questions go to that service, and it bills your account. Or a model server on your computer or network: Ollama (`ollama`), LM Studio (`lmstudio`), or any OpenAI-style server (`url = http://.../v1` with `model = custom:name` in `saves/ai.txt`). Conversations are saved: **History** lists them to carry on with one, **New chat** starts over. The editor's **Edited** filter lists the files changed this session. The mod is ordinary Rune, so you can change what it tells the model or add buttons. It uses these, which only the built-in (`@stafra`) mods can call for now: | | | | ------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `ai::ask(system, prompt)` / `ai::chat([#{ role, content }, ..])` | Ask the model. Returns a **Reply**: `text` (so far), `thinking` (true once the model is reasoning), `reasoning` (its reasoning so far, where the service shares it, else `""`), `error`, `done()`, `failed()` (also when the answer came back empty, was cut off at the output limit, or the connection dropped; `text` keeps what arrived), `cancel()`, `when_done`, and when done `input_tokens`, `output_tokens`, `cost` (US dollars, if the service says). | | `ai::credits()` | Dollars left on the account, for services that say (OpenRouter), or `None`. | | `ai::status()` / `ai::model()` | `"off"` (no model chosen), `"busy"` or `"ready"`; the model in use. | | `ai::save_chat(id, messages)` / `ai::chats()` / `ai::load_chat(id)` / `ai::delete_chat(id)` | Keep conversations: `save_chat` returns the id (`""` makes a new one); `chats()` is `[#{ id, title, when }]`, newest first; `delete_chat` also forgets its editor context. | | `editor::file()` | `Some(#{ path, text, folder })` for the file open in the editor (`folder`: its mod's folder, or `""` for a one-file mod), or `None`. | | `editor::errors()` | Current errors: `[#{ source, file, line, message }]`. | | `editor::context(id)` | Makes `id` (a conversation, say) the current task: the files changed and tabs opened are kept with it, and come back when it's the current one again. `""` for none. | | `editor::error_action(label, \|e\| ...)` | A button on every error in the editor; pressing it hands your function that error (`#{ source, file, line, message }`). | | `editor::files(folder)` / `editor::read(path)` | Text files in a folder of mods/ (`""` for all), as paths; a file's text, or `None`. | | `editor::changes(reply, path)` | The file changes in a reply (FIND/REPLACE, FILE and DELETE blocks; `path` for edits that don't name one): `[#{ path, text, old, whole, deleted, problems }]`. | | `editor::propose(path, text, note)` | Show a change to a file (or a new file) in the editor, to Accept or Reject. Several wait their turn. Returns a **Change**: `status` (`"waiting"`, then `"accepted"`, `"rejected"`, `"unchanged"` or `"replaced"`), `path`, `when_decided`. `editor::propose_delete(path, note)` asks to delete one. | | `code::check(text)` / `code::check_shader(text, "vert")` | Compile without running: `[#{ line, message }]`, empty if fine. | | `code::check_changes([#{ path, text, deleted }, ..])` | Compile proposed changes the way their mods load (`mod` declarations, sibling files, libraries), all together: `[#{ path, line, message }]` for errors the changes cause (ones already there aren't listed). | | `code::reference()` / `code::blocks(text)` | This guide's reference tables (for prompts); the ``` code blocks in a reply. | | `code::reads(text)` | Files a reply asks to see first (`READ path` lines). | | `code::prose(text, marker)` / `code::functions(text)` | A reply with each code block replaced by `marker`; the names of the functions a file defines. | | `code::apply_edits(text, reply)` | Applies a reply's `<<<<<<< FIND` / `=======` / `>>>>>>> REPLACE` blocks to `text`: `#{ text, edits, missed }` (`missed` lists FINDs not in the file). | ## Playing online A mod in a namespace (`@you/game`) can put players in rooms together. Rooms belong to the mod's own experience: a backgammon mod sees backgammon rooms, nothing else. The player plays as their account (the Account dialog opens if they're signed out); the connection reconnects and catches up by itself after a drop. Someone else's mod (downloaded, not one you made or work on) asks the player first, saying what it wants (the room permissions it declared when uploaded); once allowed, it plays with a token limited to that version and those permissions. Until then its requests wait; if the player says no, `on_room_error` says so. ```rune pub fn init() { let my = #{ room: (), board: [] }; key("H").when_pressed = || rooms::create("Pope's table", 2); // make one and join it key("L").when_pressed = || rooms::list(); // or find one: on_rooms my } pub fn on_rooms(list, my) { if list.len() > 0 { rooms::join(list[0].id); } } pub fn on_room_joined(event, my) { my.room = event.room; my.board = event.state; } pub fn on_room_message(event, my) { if event.kind == "moved" { /* event.data, from event.from (an account ID, or () for the room's script) */ } } // Sending: rooms::send(my.room, "move", #{ from: 8, to: 5 }); ``` If the experience ships a `room.rn`, it runs on the server and decides what happens (dice, legal moves); clients send it requests. Without one, messages go straight to everyone in the room. See `docs/multiplayer.md`. ## Testing Mark a function `#[test]` and it becomes a test: it passes unless an `assert!`, `assert_eq!` or `panic!` in it fails (or it hits an error). Put tests in any of your scripts, or in `tests.rn` (or a `tests/` folder with a `mod.rn`) beside `mod.rn`: that is only compiled for tests, so the game never loads it. Your hooks are ordinary functions there, so a test can play the game by calling them: ```rune // tests.rn use crate::{init, update, rules}; #[test] fn opening_needs_fifty() { assert_eq!(rules::initial_meld_requirement(0), 50); } #[test] fn tapping_deal_deals() { let my = init(); test::tap(640.0, 400.0); // seen by the next update in pointer::taps() update(0.016, my); test::step(0.016); // end the frame assert_eq!(my.hand.len(), 11); } ``` In the editor, **Tests** (in the bar) opens the mod's tests: **Run all**, a ▶ to run one, and where each failure happened (click it to go there). Beside every `#[test]` in the code is a mark (▶ not run, ✔ passed, ✖ failed): click it to run that test. **Run on save** runs them whenever the mod's files change, a few seconds apart at most. Each test starts afresh: a new world with a 1280×720 screen, its own empty saves, nothing online. A test that runs too long (a loop that never ends) fails rather than hanging. Inside tests, the `test` module stands in for the player: | Function | Does | | -------------------------- | ------------------------------------------------------------------ | | `test::tap(x, y)` | a tap at that screen position, seen by the next `update` | | `test::tap_world(x, y, z)` | a tap on that point in the world, through the camera | | `test::click(text)` | clicks the panel button whose text starts with `text` | | `test::panel_text()` | every widget's text in your panels | | `test::step(dt)` | ends a frame: clears taps and keys, moves time on, runs due timers | | `test::screen(w, h)` | sets the screen size (try a phone: `390.0, 844.0`) | From a terminal (for CI): `stafra test mods/@you/game` runs them all and prints each result (`stafra test mods/@you/game deals` runs one, by its name with or without its file, `tests::deals` or `deals`). It exits 0 when everything passed, 1 when a test failed (or there are none), 2 when the mod didn't compile. Tests go up with your drafts and releases like any other file, so collaborators and people remixing your mod get them too; players' games never compile them. ## Seeing your state **State** (in the editor's bar) shows a running experience's state as it plays: the value your `init()` returned and every `update` is handed, as a tree you can fold (`my.game.points[3]`). Values that just changed light up. Numbers, true/false and text can be changed right there, and your next `update` sees the change, so you can set up a situation without playing to it. Right-click a value to **Watch** it (pinned at the top) or copy its path. **Pause** stops the game where it is (time, timers and updates wait; the picture stays) and **Step** runs one frame at a time. The game only stays paused while the editor is open. `println!` output goes to the log. ## Reference ### Functions | Function | What it does | | ------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `spawn("file.glb")` / `spawn(mesh)` | Put a glTF/GLB model, or a **Mesh** you built, in the world. Returns an **Actor**. | | `instances("file.glb")` / `instances(mesh)` | Make an **Instances** set: many copies drawn at once. | | `despawn(thing)` | Remove an actor or instance set. | | `actors()` / `find("tag")` | Every actor from every mod / the first one with that `tag` (or `None`). | | `raycast(origin, dir, max_dist)` / `ground_at(x, y, z, max_step)` / `resolve_solid(pos, radius, height, max_step)` | 3D BVH collision against every `solid` actor and instance set: ray hit (`Some(#{ pos, normal, dist, tag })`), highest surface at or below `y + max_step` (`Some(#{ y, normal, tag })`), and horizontal capsule wall slide returning `(x, y, z)`. | | `follow(actor)` | Make the camera follow an actor (same as `camera().follow = actor`). | | `camera()` | The **Camera**: `yaw`, `pitch`, `distance`, `fov`, `near`, `far`, `free`, `follow`; `orbit()`, `top_down()`, `side_on()`, `look_at(x, y, z)`, `position()` (eye `(x, y, z)`), `forward()` (unit 3D look dir), `right()` (unit horizontal screen-right). | | `light()` | Scene **Lighting & atmosphere**: `sun(x, y, z)`, `sun_color(r, g, b, intensity)`, `sky(r, g, b)`, `ground(r, g, b)`, `ambient(strength)`, `rim(strength)`, `fog(r, g, b, density)`, `bloom(strength)`, `ssao(strength)`, `env("sky.jpg")` / `clear_env()`, `point(id, (x, y, z), colour, intensity)` (up to 8), `point_radius(id, radius)`, `remove_point(id)`, `clear_points()`, and presets `day()`, `golden_hour()`, `studio()`, `night()`. Resets when the mod unloads. | | `ui::panel("title")` | A **Panel** (a small window): `label(text)`, `button(text)`, `text_box(hint)`, `text_area(hint)` (several lines; Enter sends, Shift+Enter a new line), `model_picker()` (the player's model choice for `ai::`), `choice_button(["A", "B"])` (a button with a menu to switch what it does; its `text` is the choice), `code(text, lang)`, `card(title, description)`, `tile(title, image, details)` (a picture with a title, side by side with other tiles, details on hover; set `menu` to a list of words for a hold/right-click menu, and `when_chosen` runs with the pick in `chosen`), `checkbox(text)` (its `on`), `separator()`, `clear()`, `focus(widget)`, `open`, `title`, `docked`, `fill` (covering the game view, like the home screen), `modal` (a dialog over everything) (at the side of the screen, the default, or a floating window). Widgets have `text`, `visible`, `enabled`, `pinned` (in the bar at the bottom), `top` (in a row at the top), `boxed` and `small` (label styles), `markdown` (a label shown as Markdown: headings, lists, quotes, bold, italic, `code`, links), `summary` (a label folded under this line, tap to show it), `busy` (a label with a spinner before it, while something's under way), `icon` (a button drawn as an icon: `"new"`, `"history"`, `"delete"`, `"settings"`, `"plus"`, `"close"`, `"check"`, `"refresh"`; `text` is its tooltip), `inline` (on the same line as the widget before), `when_clicked`, `when_submitted`. | | `ui::screen_button("text")` | A big button in the corner of the game view (for touch screens): `text`, `on` (drawn pressed in), `visible`, `when_clicked`. | | `app::editor()` / `app::show_editor(on)`, `app::log()` / `app::show_log(on)`, `app::keyboard()` / `app::show_keyboard(on)`, `app::touch_screen()` | What the app shows; switch them from a mod. `@stafra/devtools` puts Home, Keys, Log and Editor buttons on touch screens (and F1, F2, F4 on keyboards): turn it off for a game without them. | | `app::open_panel("title")` | Opens a panel by its title (another mod's, say). | | `app::experiences()` / `app::experience()` / `app::open_experience(name)` | Every experience (`[#{ name, title, description, details, image, shipped, scope }]`), the one running, and switching to another. | | `app::always_on()` / `app::set_always_on(name, on)` / `app::mods()` / `app::show_mods()` | The mods that run in every experience; every mod there is; the app's Mods dialog. | | `app::always_on()` / `app::set_always_on(name, on)` / `app::mods()` / `app::show_mods()` / `app::workspace_mode()` / `app::trusted_namespaces()` | The mods that run in every experience; every mod there is; the app's Mods dialog; whether the app is running in workspace mode; and namespaces trusted for local mods. | | `app::pin(name, on)` / `app::update_now(name)` / `app::add_version(project, release)` / `app::remove_copy(name)` | For copies from the server: pin one at its version (it stops updating by itself) or let it update again / install the newest version over it now / keep another version beside it (`name-0-1-0`, pinned) / remove a kept version (to mods/.trash). `app::experiences()` entries say each copy's `version`, `pinned` and `project`. | | `app::remote_experiences()` / `app::download(project, release)` / `app::refresh_remote()` / `app::downloading()` | The signed-in account's projects on the server that aren't on this device, drafts included: `#{ name, title, scope, version, draft, owner, project, release, state, versions }` (`state`: "missing", "current", "updating", "changed" or "pinned"; `versions`: recent `#{ release, version, draft }`) / install one (an `experiences_changed` event follows) / ask the server again / whether a download is under way. | | `app::report_experience(release, label)` / `app::report_player(username)` / `app::report_room(room, label)` / `app::block_player(username)` | Report something: the engine asks the player for a reason from a fixed list (no text) and sends it to moderators / block a player (no shared rooms, no friend requests; works both ways). Put Report on anything players see from others (experience tiles, players at a table). | | `app::show_account()` / `app::account()` | Opens the Account dialog (sign in, create an account, namespaces); the signed-in username, or `None`. | | `app::show_account()` / `app::show_groups()` / `app::account()` | Opens the Account dialog (sign in, create an account, namespaces) or the Groups & Families dialog; the signed-in username, or `None`. | | `app::version()` / `app::update()` / `app::open_update()` | This app's version (`"0.2.1"`); a newer app for this device from the server, `#{ version, notes }`, or `None` (checked in the background at launch and every few hours); and opening its download (or store) page. | | `app::signing_in()` | True while a sign-in is under way (so a screen can say so rather than "signed out"). | | `app::recent_experiences()` | Names of the experiences opened lately, newest first (not the home screen). | | `app::public_experiences()` | Published experiences from the server: `[#{ title, scope, name, version, owner, project, release, state, published_at, changelog, staff_recommended, recommendations, recommended_by_me, recommended_by_friends, not_interested_by_me, community_score, open_rooms, active_players }]`. | | `app::recommend_experience(name, on)` / `app::not_interested_experience(name, on)` / `app::staff_recommend_experience(name, on)` | Recommend an experience, or mark it not interesting (or undo, with `on` false); staff recommendation is for moderators. Sent to the server in the background. | | `app::recommend_filters()` / `app::set_recommend_filters(exclude_liked_hidden, exclude_hated_liked, taste_boost)` | How recommendations are picked for this account: `#{ exclude_liked_hidden, exclude_hated_liked, taste_boost }`, and changing them. | | `app::cloud_error()` / `app::clear_cloud_error()` | The last error from the server (a failed publish or download, say), or `None`; and dismissing it. | | `app::show_new(experience)` | Opens the New dialog (the editor's + New, the home screen's Create): `true` for an experience, `false` for a plain mod. | | `app::create_experience(name, title)` | Makes `mods//` (or `mods/@scope//` for `"@scope/name"`, any namespace but @stafra) with a stafra.md and a mod.rn; false if the name's taken or not letters, numbers, `-` and `_` (namespaces: lowercase letters, digits and hyphens). | | `editor::open(path)` | Opens a file in the editor. | | `draw::text(pos, "text", colour)`, `draw::rect(pos, w, h, colour)`, `draw::circle(pos, r, colour)`, `draw::line(a, b, width, colour)` | Draw this frame at pixels, an actor or a world point. | | `draw::polygon([pos, ...], colour)` | Draw a filled convex polygon, useful for rotated cards and other custom shapes. | | `draw::label(pos, "text", colour, angle, size)` | Proportional text with clockwise rotation in radians and font size in game-view pixels. Rotates around its top-left position. | | `draw::center_label(pos, "text", colour, angle, size)` | Text centered on `pos` using its measured font metrics, rotated around that center. Useful for card symbols and pips. | | `button("jump")` / `action("dash", ["Left Shift", "pad:b"])` / `key("F")` / `pad("a")` | A **Button**: a built-in action, a custom named action with default bindings, one key (SDL names: `"Left Shift"`, `"Up"`, `"Return"`), or one gamepad button. | | `movement()` | Where the player is steering: `.x` right, `.y` forward, `.length()` 0..1. | | `rooms::create(name, capacity)` / `rooms::join(id)` / `rooms::leave(id)` | Make a room for this mod's experience and join it / join one / leave one. `on_room_created(event)` fires before joining a new table, identifying its `room` ID. `on_room_joined(event)`: `#{ room, name, capacity, players, names, owner, state, resumed }` (`names` maps each player to their username) (`state` from the room's script; `resumed` after a reconnect, with what was missed following). | | `rooms::close(id)` | Close a table owned by this account. Everyone receives `on_room_left` with reason `"closed"`. | | `rooms::list()` | Ask for this experience's rooms: `on_rooms(list)`, each `#{ id, name, capacity, players, owner }`. | | `rooms::send(room, kind, data)` / `rooms::send_fast(room, kind, data)` | A message to the room: reliable (in order, everyone including you) / fast (latest wins, may be dropped). `on_room_message(event)` / `on_room_fast(event)`: `#{ room, from, name, kind, data }` (`name` is the sender's username); kinds `"@joined"` and `"@left"` are players arriving and going (`from` is the player). Reliable messages arrive exactly once, also ones sent while the connection was down. | | `rooms::watch(id)` | Watch a room instead of playing: no seat, not counted against its capacity, can't send. `on_room_joined`'s `event.observer` is true, and the room's script decides what observers see (and may show it to them a little late, against peeking). | | `rooms::reconnect()` | Connect again now. The connection already comes back by itself after a drop (trying every few seconds, rejoining rooms and catching up on what was missed); this is for a "Reconnect" button while `on_room_offline` has said it's down. | | `rooms::online()` / `rooms::me()` | Whether this mod's connection is up / the player's account ID as `Some(id)` (compare `id` with `from`), or `None` signed out. Also `on_room_online`, `on_room_offline(why)`, `on_room_left(#{ room, reason })`, `on_room_error(#{ room, error })`. | | `pointer::lock()` / `pointer::unlock()` | Request mouse look locking on the next left click in the game view / release the request. The cursor is free by default; Escape, menus and focus loss release capture. Drag to orbit while unlocked. | | `pointer::enable()` / `pointer::disable()` | Opt this mod into point-and-click play (free mouse, tap-to-play touch, drag to orbit, pinch to zoom, no touch stick) / exit pointing mode to restore normal camera & stick controls. Released when the mod unloads. | | `pointer::taps()` | This frame's mouse clicks/touch taps as `(x, y)` in logical points (CSS px, matching `screen()` and `ui::screen`), excluding drags, pinches, cancelled touches and other UI. | | `pointer::enable_drag()` | Opt into mouse/touch card-style dragging instead of camera gestures. Also enables pointing; released when the mod unloads or calls `pointer::disable()`. | | `pointer::events()` | This frame's ordered `(kind, x, y)` screen gestures after `enable_drag()`: `"down"`, `"move"`, `"up"`, or `"cancel"`, in logical points (CSS px). A cancel aborts the gesture; its position is unused. Taps remain available separately. | | `pointer::ray(x, y)` / `pointer::world(x, y, height)` / `pointer::project(x, y, z)` | Cast a camera ray from logical game-view points (`Some(((ox,oy,oz), (dx,dy,dz)))` or `None`, usable with `raycast` or vertical planes), pick a horizontal `Y = height` plane (`Some((x,y,z))` or `None`), or project a world point to logical game-view points (`Some((x,y))` or `None`). | | `held("W")` / `pressed("Space")` | Key held / just pressed (the older way; same key names). | | `camera_yaw()` / `heading(x, y)` | Camera direction; turn a camera-relative stick into a world yaw. | | `share(key, value)` / `shared(key)` | Share values between mods. The fox mod shares `"player"`. | | `emit(name, data)` | Send an event to every mod's `on_` function. | | `after(seconds, f)` / `every(seconds, f)` | Run a function once later, or over and over. Returns a **Timer**: `stop()`, `active()`, `seconds`. | | `random()` / `range(lo, hi)` | Random numbers. | | `time()` | Seconds since the game started. | | `thing.texture = "bark"` / `= painted` | An image by name (bark.png/.jpg), or a **Texture** you painted. `texture(..)` gives the id, as before. | | `thing.shader = "fur"` | Custom GLSL: fur.vert and/or fur.frag (a missing one uses the default). `shader("a.vert", "b.frag")` still works. | | `screen()` / `char_size()` | Game view size, and the size of one text character, in logical points (CSS px, matching `ui::screen` and `draw::`). | | `dpi_scale()` / `safe_area()` | Physical pixels per logical point (display DPI × text zoom), and safe-area insets `(top, right, bottom, left)` in logical points for notches/home bars. | | `sound("name")` / `tone("C5 E5")` | A **Sound** from a .wav/.ogg file, or synthesised from notes. | | `music::play("name")`, `music::stop()`, `music::volume(v)` | One background track at a time, looping. | | `save(key, "text")` / `saved(key)` | Remember text between sessions. | | `save_data(key, value)` / `saved_data(key)` | Save plain objects, arrays and primitive values as structured data. Reads return `Some(value)` or `None`; actor and other native handles cannot be saved this way. | | `mods()` / `error_count()` | Loaded mod names; number of errors on screen. | | `create_mod(name, code)` | Create `mods/.rn` (never overwrites). | | `open_folder(name)` / `copy_text(text)` | Open a mod's folder; copy text to the clipboard. | ### Actor (from `spawn`) | | | | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Fields | `x`, `y`, `z`, `yaw`, `scale`, `speed` (animation rate), `fade` (crossfade seconds), `looping`, `tag`, `solid` (participates in `raycast` / `ground_at` / `resolve_solid`), `texture`, `shader`. Read-only: `time`, `size` (model size before scaling). | | `fit(metres)` | Scale it to that size, whatever size the model file is. | | `play("Walk")` | Switch animation clip, with a crossfade (matches exact name, case-insensitive, or suffix after `\|`). | | `load_clips("anim.glb")` | Retarget animation clips from another glTF/GLB onto this actor's skeleton by matching bone names. Returns imported clip names. | | `clips()`, `clip()`, `duration()`, `finished()`, `restart()` | Animation info and control. | | `bones()`, `play_layer(slot, clip, mask_bone, weight)`, `play_additive(slot, clip, mask_bone, weight)`, `stop_layer(slot)` | Masked or additive animation layers (`mask_bone = ""` for whole body, or e.g. `"Spine"` for upper body). | | `rotate_bone(bone, rx, ry, rz)`, `offset_bone(bone, dx, dy, dz)`, `bone_pos(bone)`, `clear_bones()` | Procedural bone rotations (radians), actor-space translation offsets (metres, applied before IK), and animated world-space bone position query (`Some((x, y, z))` or `None`). | | `look_at(x, y, z)`, `clear_look_at()` | Smoothly turn the character's neck and head toward a world point. | | `reach_left(x, y, z)`, `reach_right(x, y, z)`, `ik(upper, mid, end, (x, y, z))`, `ik_weight(end, weight)`, `ik_pole(end, (x, y, z))`, `clear_ik(end)`, `clear_reach()` | Analytical 2-bone IK for reaching hands, planting feet, or bending any 3-bone chain, with optional per-target weight (`0..1`), bend-hint pole, and selective clear. | | `morph(name, weight)`, `get_morph(name)`, `morphs()`, `clear_morphs()` | Drive glTF morph targets / facial blendshapes directly from script. | | `attach(parent, bone)`, `detach()` | Attach this actor (prop, weapon, hat) to a bone on `parent`; `x/y/z/yaw/scale` become local offsets. | | `forward(metres)` | Move the way it's facing. | | `turn_toward(yaw, max_step)` | Turn gradually toward a direction. | | `walk_to(x, z)`, `walking()`, `when_arrived`, `walk_speed` | Walk somewhere by itself, then run `when_arrived`. | | `animate("scale", to, seconds)`, `animating()` | Glide `x`, `y`, `z`, `yaw`, `scale` or `speed` to a value. | | `stop()` | Stop walking and animating. | | `uniform(name, [..])`, `uniform_array(name, [..])` | Values for a custom shader. | ### Instances (from `instances`) | | | | ------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------- | | `add((x, y, z), yaw, scale)` | Add a copy. `tint(r, g, b)` colours copies added after it. | | `move_to(i, (x, y, z), yaw)`, `position(i)` | Move or read copy `i`. | | `remove(i)`, `remove_within(x, z, radius)`, `clear()`, `len()` | Remove copies. | | `play(i, "Run")`, `play_all("Walk")`, `set_speed(i, s)`, `set_time(i, t)` | Per-copy animation (rigged models only). | | `shader`, `texture`, `uniform(..)`, `size`, `tag`, `solid` | Same as on Actor (`solid = true` enables `raycast` / `ground_at` / `resolve_solid` against every instance). | ### Sound (from `sound` or `tone`) | | | | ------------------------------ | ------------------------------------------------------------------------------------------------------------- | | `play()`, `repeat()`, `stop()` | Play once (again layers another copy), play over and over, stop every copy. | | `playing()`, `duration()` | Whether any copy is playing; length in seconds. | | Fields | `volume`, `pitch`, `pan` (-1 left to 1 right), `at` (an actor, or `()` for none). Tones also: `wave`, `beat`. | ### Button (from `button`, `key` or `pad`) | | | | ----------------------------------- | ------------------------------------------------------------- | | `held()`, `pressed()`, `released()` | Down now; went down this frame; came up this frame. | | `held_time()` | Seconds it's been down (0 when up). | | `when_pressed`, `when_released` | Set to a function, like `\|\| fox.restart()`, to run it then. | Gamepad buttons for `pad()`: `a b x y` (by position: a is the bottom one), `lb rb lt rt`, `l3 r3` (clicking the sticks), `start back home`, `up down left right` (the d-pad). ### Mesh, Texture, math | | | | ------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `Mesh::new()` | Then `color(r, g, b)`, `normal(x, y, z)`, `uv(u, v)` (each applies to vertices added after it), `vertex(x, y, z)` (returns an index), `triangle(a, b, c)`, `quad(a, b, c, d)`. | | `Texture::new(w, h)` | Then `set(x, y, (r, g, b))` and `fill((r, g, b))`; colours are 0 to 1. | | `math::sin`, `cos`, `tan`, `atan2`, `lerp`, `float(int)`, `int(float)`, `round(x, places)`, `PI`, `TAU` | Maths helpers (`int` rounds down; `round` to so many decimal places, for showing numbers). Floats also have `.sqrt()`, `.abs()`, `.floor()`, `.min(x)`, `.max(x)`. | ### Shaders `thing.shader = "my"` (my.vert and/or my.frag) takes GLSL written like OpenGL 3.3 (`#version 330 core`); copy `src/shaders/default.vert` / `default.frag`, or `grass/grass.vert`, to start. The game translates it for the graphics card (Metal on a Mac, Direct3D 12 on Windows), so a few rules apply: - Declare uniforms one by one (`uniform vec2 u_wind;`), not in `uniform Block { ... }`. - Textures must be `sampler2D`. - Vertex inputs need `layout(location = N)`; the numbers are listed in `default.vert`. - Fragment shaders output **linear HDR** RGB (the engine's post pass applies SSAO, bloom, ACES tonemapping, and sRGB encoding). Linearize sRGB colors/textures with `pow(c, vec3(2.2))` to avoid washed-out double-gamma output, and write `max(length(u_camera_pos - v_world), 0.01)` to `frag.a` on opaque surfaces so SSAO has linear depth (`0.0` disables SSAO on that pixel). Shader errors show up like script errors, with the line number in your file. ## Tips - **Read the other mods.** Every `mod.rn` in `@stafra/` is commented, so copy freely. - **Lists:** change an item with `list[i] = list[i] + 1.0`; Rune doesn't allow `list[i] += 1.0`. - **Lots of things?** See `horde/mod.rn`: thousands of units kept in plain lists and drawn as one instance set. - **Integers vs decimals:** Rune keeps them apart. Write `1.0`, not `1`, for positions and speeds, and use `math::float(i)` to turn a loop counter into a decimal. - **Load order** is alphabetical by name. Prefix a mod with a number (`10_mymod`) to control it. - **Logs:** `stafra.log` next to the game keeps everything, even without a console. - **Your assets, your licence:** if you include models or images made by someone else, put their licence in your mod folder (see `fox/LICENSE.md` for an example). Virtual touch controls appear after actual touch input, remain visible while fingers are down, and fade away after three seconds idle (one-second fade). ### Icon buttons Use `parent.icon_button("Action name")` for an icon-only control. It is a normal button with keyboard, touch, screen-reader activation, focus styling, disabled styling, and a hover tooltip from `label`. The default target is 44 CSS pixels (48 with a coarse pointer). Draw directly on the returned element: ```rune let undo = panel.icon_button("Undo last move"); undo.line((5.0, 11.0), (27.0, 11.0), 2.0, "currentColor"); undo.line((5.0, 11.0), (11.0, 5.0), 2.0, "currentColor"); undo.line((5.0, 11.0), (11.0, 17.0), 2.0, "currentColor"); undo.when_clicked = || undo_move(); ``` Artwork uses a square 32×32 `view_box`, centered and fitted into the button's content box every frame. CSS can resize the button without rebuilding the art. `currentColor` follows the computed text color; disabled opacity applies to the art too. Set `view_box` to another positive size for other coordinate systems; 0 uses CSS-pixel coordinates, as ordinary canvases do. `.ui` files also accept ``; retrieve it and draw on it. Keep an action name on icon buttons, and retain their identities across updates. ### Shared table mechanics Client scripts and server `room.rn` scripts both have `table::` data helpers. They manage seats, computers, readiness, reconnects, observers, and bans for 1–256 seats. They do not send messages or own hands, turns, scores, or game rules. See [the room lifecycle guide](../docs/multiplayer.md#shared-table-mechanics). ### Inspecting component layout Set `screen.inspect = true` temporarily while developing a screen. The overlay outlines element bounds and labels IDs and dimensions in CSS pixels. Overlapping unrelated controls and elements outside the viewport are marked red; ancestor containers and intentionally scrolled content are excluded from those warnings. Read `screen.layout_issues` for the current findings. The overlay never takes pointer input, and turning it off clears the report. Repeat at phone and desktop sizes using `test::screen(width, height)` in mod tests. This inspects retained UI components; board art drawn directly with `draw::` remains the mod's responsibility. Headless previews from `STAFRA_TEST_SNAPSHOT` include both board drawing and retained components, with layout and appearance transitions settled before capture: ```sh STAFRA_TEST_MOD=mods/@you/game STAFRA_TEST_VIEW=390x844 \ STAFRA_TEST_SNAPSHOT=/tmp/game-phone.png \ cargo test --workspace local_folder_mod -- --ignored ``` Use `STAFRA_TEST_CLICKS` (button labels separated by newlines) to reach the screen you want to preview. Repeat with `STAFRA_TEST_VIEW=1280x800` for desktop. ### Guides (`@stafra` built-in) Built-in `@stafra` walkthroughs (`@stafra/guide`) use `guide::` to discover `stafra-guide.json` walkthroughs, query semantic UI targets, and drive synthetic input. Any mod can author a `stafra-guide.json` walkthrough; see [docs/guides.md](../docs/guides.md). | Function | What it does | | --- | --- | | `guide::discover()` | Scans installed mods for `stafra-guide.json` and `guides/*.json` | | `guide::target(selector)` | Live logical bounds for `#id`, `screen:#id`, `text:...`, `label:...`, or `host:...` | | `guide::targets()` | Lists all currently visible named UI targets | | `guide::send(cmd)` | Sends a structured input/UI command (`click`, `tap`, `drag`, `move`, `button`, `key`, `editor`, `log`, `experience`) | | `guide::highlight(selector)` | Draws a full-window spotlight ring around a semantic UI target (`""` clears it) | | `guide::clear_input()` | Releases any guide-held movement stick, buttons, or keys |