# Godot 4 game template

A minimal, runnable AnimStream Originals game for Godot 4.7 (typed GDScript, no
plugins or dependencies) and the reference implementation of the Originals
checklist (developer page "Originals-Checkliste" / "Originals checklist").
Viewers' gifts reach the game as actions; the game plays rounds, reports its
phase to Studio and submits scores to the global leaderboard. Add your game idea at the places marked `# GAME IDEA`.

```text
project.godot               autoload "AnimStream", main scene, portrait window settings
export_presets.cfg          Windows Desktop (x86_64, one EXE), Linux, macOS; no signing secrets
addons/animstream/          the SDK (one file, class AnimStreamGame); do not edit
scenes/main.tscn            main scene
scripts/main.gd             phases, action handlers, HUD, input
scripts/settings.gd         language and settings in user://settings.cfg
scripts/audio.gd            buses Music/Effects, shuffled playlist, generated effect sounds
scripts/pause_menu.gd       pause menu (Esc)
scripts/leaderboard_panel.gd  top list with own rank and profile pictures
scripts/ui.gd               plain Label helper for untrusted names
media/actions/              action images referenced by the manifest (has a .gdignore)
tools/art/action-prompts.json  prompts of the action images (agent kit: ART-DIRECTION.md, tools/art/)
```

The download also contains `manifest.example.json` (the template's actions,
presets, Gift Wall and leaderboard), `PROTOCOL.md` (normative protocol) and
`ANIMSTREAM-SDK.md` (publishing guide). The scripts are loaded with `preload(...)`
constants, not `class_name`; keep it that way for your own scripts and run
`godot --headless --path . --import` once after adding scripts.

## How the template works

- `project.godot` autoloads the client as `AnimStream`; it connects on start and
  lives for the whole process. Register every manifest action in the main
  scene's `_ready()`: the client handles Studio messages from the first frame on.
- Actions (`manifest.example.json`): `spawn` (mercy, `"effect": "help"`, adds
  points, stackable `count`), `double-points` (mercy, `"effect": "help"`, points
  count twice for `seconds`), `steal-points` (sabotage, `"effect": "sabotage"`,
  takes `amount` points, stackable `amount`; the score never drops below 0) and
  `shake-screen` (sabotage, `"effect": "sabotage"`, shakes the playfield for
  `seconds`). Handlers answer at once (Studio sends one action at a time);
  `double-points` has a 0.5 s warm-up that checks `context.cancelled` before the
  effect starts. Stackable actions may arrive merged (Rose ×99 → one action with
  `count` 99, `context.source.giftCount` = number of gifts); older Studio versions
  send one action per gift.
- Phases: `lobby` (15 s) → `playing` (60 s) → `round-over` (10 s) → `lobby`.
  The first state Studio receives is `set_state(true, "lobby", score)`: the lobby
  accepts actions, and every action arriving in the lobby, during `round-over` or
  while paused is kept and applied when the next round starts (`_apply_carried()`),
  never rejected (also on Studio 0.1.285 and older, which has no `state`). Round 1
  starts by itself after 15 s; Enter or Space starts it at once. `round-over`
  reports `acceptingActions: false`, so Studio holds new actions.
- Phase lengths and timed effects run on the game's own clock in `_process()`,
  which stops while the pause menu is open. The template never pauses the
  SceneTree (the AnimStream autoload must keep answering the heartbeat) and never
  uses timers for phase lengths.
- Pause menu (Esc): controls overview, language (Automatic / Deutsch / English),
  music volume, effects volume and mute. While it is open the game reports
  `set_state(false, "paused", score)`; closing it restores the previous phase's
  state and applies actions that arrived meanwhile.
- Language: German or English. Default is the session language from Studio
  (`AnimStream.language`), otherwise the operating system's locale. Switch it on
  the lobby screen (button or key L) or in the pause menu. Settings are saved in
  `user://settings.cfg` (`[game] language` "" = automatic, "de" or "en";
  `[audio] music_volume`, `effects_volume`, `muted`; `[display] fullscreen`).
- Audio: `scripts/audio.gd` creates the buses `Music` and `Effects` at runtime
  and plays `PLAYLIST` shuffled (next track when one finishes, never the same
  track twice in a row). The template ships no music and no sound files: an
  empty `PLAYLIST` plays a generated silent placeholder, and the effect sounds
  are generated in code. **Only add tracks with a commercial licence that covers
  live streaming and selling the game** (keep the licence files and receipts);
  no copyrighted music without a licence, no "free for personal use" tracks.
  Import tracks with loop disabled.
- Game over: at `round-over` the game calls `submit_score(score)` and, in its
  callback, `get_leaderboard(10)`. The top list shows rank, profile picture
  (feature `leaderboard-avatars`, loaded with `load_avatar`; the name's initial
  stays as fallback for `null`, 404 or broken pictures), name and score. The
  streamer's own entry (`data.self`) is highlighted; if it is not in the list, an
  extra "You: #rank" row follows. The gift guide shows `list_bindings` and
  refreshes on `bindings_changed`. On Studio 0.1.285 and older these calls fail
  locally with `unsupported` and the panels stay empty; the game still works.
- Window: portrait layout with a 1080×1180 viewport, a 864×944 window that fits a
  1080p screen (TikTok portrait streams crop the game into the 9:16 canvas),
  stretch mode `canvas_items` with aspect `keep`. F11 toggles windowed and
  borderless fullscreen (`WINDOW_MODE_FULLSCREEN`, saved in the settings). The
  game never uses exclusive fullscreen and never binds F7 (Studio's hotkey for
  the game control window).
- Viewer, gift and leaderboard names are shown only as plain `Label` text with
  auto-translation disabled.

## Presets and action images

`manifest.example.json` carries the store and Studio data of the checklist:
`label` and `description` (de/en, keep descriptions at most 120 characters) and an
`image` for every action, three `presets` by coin value (`small-budget` ≤ 30
coins, `medium` 99–299, `big-gifts` ≥ 500, each with two mercy and two sabotage
actions), an `effect` for every action (`help` or `sabotage`), `defaultBindings`
for older Studios (the cheap preset), `giftWall` with `"sort": "preset"` and
`"split": true` (help actions left, sabotage right) and `leaderboard`. Studio shows a preset picker before the
first start and creates the gift rules and the Gift Wall from the chosen preset.

The images are paths relative to the manifest, `media/actions/<id>.png`: square
PNG or WebP, 256–1024 px (export 512×512), at most 300 KB, transparent background.
The files shipped in `media/actions/` are generated placeholders and **must be
replaced before release** (the packer warns about them). `media/` at the project
root has a `.gdignore`, so Godot neither imports nor exports it;
`animstream-pack --all` copies the referenced images into every build ZIP and
validates them.

The real images follow the binding art direction of the agent kit
(`animstream/ART-DIRECTION.md`, installed by the kit installer). The template
ships `tools/art/action-prompts.json`, the prompt template filled for its four
actions; rewrite it for your actions and generate with the kit's tool:
`node tools/art/generate-action-images.mjs --test 2` (two approval images and
`dist/art-preview.html`), then without `--test`, and `--check` before packing.
`tools/` has a `.gdignore` as well.

To build your game: set `gameId` in your copy of `manifest.example.json`, add
your actions there and register each with `AnimStream.register_action(id,
handler)` in `_ready()`, replace the `GAME IDEA` parts, keep `acceptingActions`
false in menus, breaks and cutscenes, and submit one final score per round. To
integrate the SDK into an existing project instead, copy `addons/animstream` and
either add the same autoload or create one `AnimStreamGame.new()`, register
handlers, then `add_child` it; keep it alive for the whole session.

## Test with the mock Studio

From the agent kit (see `tools/mock-studio/README.md`), with `godot` on PATH:

```sh
node tools/mock-studio/mock-studio.mjs validate manifest.json
for s in smoke stacking pause leaderboard presets lobby; do
  node tools/mock-studio/mock-studio.mjs run --manifest manifest.json --scenario $s -- godot --headless --path .
done
node tools/mock-studio/mock-studio.mjs run --manifest manifest.json --scenario smoke --legacy -- godot --headless --path .
```

`pause` and `leaderboard` wait for the first `round-over` (about 75 s).

## SDK API (`addons/animstream/animstream_game.gd`)

- `register_action(id, handler)`: `handler(params: Dictionary, context: Dictionary)`
  may `await`; return `false` to reject. `context` has `id`, `expiresAt`, `viewer`
  (`{name, handle?}`), `source` (`{code, giftId?, giftName?, giftCoins?, giftCount?}`,
  `{}` if absent) and `cancelled`. Parameters are validated against the manifest;
  dry runs never call the handler. Studio sends the next action only after the
  result: acknowledge long effects once started, not when they end.
- `subscribe(code, callback)`: raw events (`GIFT`, `COMMENT`, …) listed in the
  manifest's `events`. Display only; see "Double triggering" below.
- Signals `session_ready(manifest)`, `session_stopped(reason)`,
  `action_cancelled(id)`, `bindings_changed`. Property `is_session_ready`.
- `features` (PackedStringArray), `has_feature(name)`, `language` (`"de"`/`"en"`
  or empty), `streamer_handle` (TikTok username without `@` if the streamer
  allowed sharing it, otherwise empty; display data only). Studio 0.1.285 and
  older announce no features; the SDK then never sends `state` or `request`.
- `set_state(accepting: bool, phase: String, score = null) -> bool` (feature
  `state`): phase `^[a-z0-9][a-z0-9-]{0,31}$`, `|score| <= 1e15`; invalid input is
  reported with `push_error` and ignored. Identical states are sent once; changes
  are coalesced to at most 10 per second (latest wins), so call it whenever the
  score changes. A state set before `session_ready` is sent first once ready.
  Returns false if invalid or unsupported.
- `submit_score(score: int, callback)`, `get_leaderboard(limit: int, callback)`,
  `list_bindings(callback)` and `request(op, params, callback)` (features
  `leaderboard`, `bindings`). `callback(result: Dictionary)` gets `{ok, data,
  error}` on the main thread. Without sending anything, local errors arrive on
  the next frame: `unsupported`, `not_ready`, `invalid`, `busy` (4 requests in
  flight); also `timeout` (15 s) and `stopped` (session ended). Studio may answer
  `rate_limited` (one submission per 2 s), `unavailable` (offline or signed out),
  `busy`, `invalid` or `unsupported`. Scores are integers 0..10^12, one per
  streamer is kept (best by the manifest's `order`); submit durations as integer
  milliseconds with `"order": "asc"`.
- Leaderboard pictures (feature `leaderboard-avatars`): `get_leaderboard` entries
  and `self` always carry `avatarUrl`, a valid picture URL or `null` (anonymous,
  not shared by the streamer, hidden by moderation, invalid, or an older Studio).
  `load_avatar(url, callback)` loads it in the background (5 s timeout, at most
  1 MiB, PNG only, cached by URL) and calls `callback(texture: Texture2D)` with
  `null` on any failure, so keep an initial or placeholder as fallback and never
  wait for it in gameplay. `is_avatar_url(value)` applies the URL rule of
  PROTOCOL.md section 8 (AnimStream CDN, plus the mock Studio's loopback server).
- `quit_on_session_end` (default true): lost heartbeat, lease expiry, disconnect
  or Studio stop quits the game. If you override it, the game must stay paused
  and must never resume a dead session; the SDK does not reconnect.

## Gift rules and the game control window

Streamers map TikTok gifts to your manifest actions in Studio's **game control
window** (DE "Spielsteuerung", EN "Game control"). It opens beside the game when
the game connects; F7 brings it above a fullscreen game. Do not bind F7, prefer
windowed or borderless fullscreen (`window/size/mode` 0 or 3, never 4: exclusive
fullscreen can hide Studio windows), and build no gift mapping UI of your own.
`defaultBindings` in the manifest suggests first rules; the streamer confirms them.

Double triggering: if the manifest lists `GIFT` in `events`, one gift can arrive
both as a raw event and as an action from a gift rule. Apply gameplay only in
action handlers; use raw events for tickers and ambient reactions.

## Run, export and package

Without Studio's launch credentials the game quits immediately
(`launch_required`). Launch the exported build from Studio and use the test
buttons of the game control window, or use the agent kit's mock Studio.

Exporting needs the Godot 4.7.2 export templates (editor: Editor → Manage Export
Templates, or extract `Godot_v4.7.2-stable_export_templates.tpz` into the user
data folder `export_templates/4.7.2.stable/`). Then, from this folder:

```sh
mkdir -p build/windows build/linux build/macos
godot --headless --path . --export-release "Windows Desktop" build/windows/Game.exe
godot --headless --path . --export-release "Linux" build/linux/Game.x86_64
godot --headless --path . --export-release "macOS" build/macos/Game.zip
```

Windows and Linux embed the PCK, so the result is one executable (the Windows
console wrapper is off). Rename `Game` as you like; the dashboard entrypoint is
the exact file name. macOS uses universal binaries with ad-hoc signing and no
notarization (no secrets); set your own `application/bundle_identifier` and
extract `Game.zip` so that `build/macos/Game.app` exists before packaging.

Package one ZIP per platform with the export folder as the ZIP root. The agent
kit's packer applies the server's rules (up to 100 GiB compressed and expanded,
ZIP64 support, no symlinks, executable bits):

```sh
node tools/package/animstream-pack.mjs --all   # build/windows|macos|linux -> dist/*.zip + dist/release.json (then: animstream-release publish dist/release.json)

# or one ZIP at a time
node tools/package/animstream-pack.mjs zip --dir build/windows --out dist/my-game-1.0.0-win32-x64.zip --platform win32 --entrypoint Game.exe --arch x64
node tools/package/animstream-pack.mjs zip --dir build/linux --out dist/my-game-1.0.0-linux-x64.zip --platform linux --entrypoint Game.x86_64 --arch x64
node tools/package/animstream-pack.mjs zip --dir build/macos --out dist/my-game-1.0.0-darwin-arm64.zip --platform darwin --entrypoint Game.app/Contents/MacOS/Game
```

Without the kit, `cd build/windows && zip -X -r ../../dist/my-game-1.0.0-win32-x64.zip .`
works too (not PowerShell 5.1 `Compress-Archive`, which writes backslashes into
entry names). Upload the ZIP with its SHA-256, platform, architecture and
entrypoint as described in `ANIMSTREAM-SDK.md`. Never upload a web export.
