# Liminalia Studio

## Current position (the state at each line)

The preview, the state at this line and the duration bars share the "state as in the real game" at the cursor line (the result of running from the beginning along a route).

1. **Route**: run from "New game" without a screen, and find a route that first enters that file (first runs a command in that file).
   The point of entry is just before running the first command of that file (running the inside of `@define` as a macro doesn't count as entering).
   The search is the same backtracking search as `lim build --seed` (`findRoute` in `@liminalia/runtime`). At choices, it picks the next one each time it returns to the same choice,
   and if a run ends without arriving, it changes the last choice to the next number and tries again. It also records the entry points of other files it passes on the way
   (the search order doesn't depend on the target, so the route is the same whichever file is asked for first).
   If none is found in 2 seconds, it runs from the top of that file in an empty state (`how: "file-start"`)
2. **Within the file**: from the point of entry, it runs several times, varying the choices (up to the number of choices, at most 8), and records the state when each text line and choice line is first passed.
   For other lines (effect commands, `@set`, `@if`, labels and so on), it records the state right after the line first finishes running (`Sweep.after`).
   It learns that a line has finished running just before the next command runs (`RuntimeOptions.onStep`), when the call depth is the same as or shallower than that line's.
   So `@call` and `@define` call lines get the state at the point of returning from what they called.
   When the run leaves that file (except on the way back from `@call`), that run is cut off
3. The state of a text or choice line (`Sweep.lines`) is a save that resumes just before showing that line (the screen state is `save.stage`, and game variables are `save.game`), temp,
   the line that set each variable's value (collected with `RuntimeOptions.onAssign`), and the choices made in that file.
   The state of a command line (`Sweep.after`) has no save; it has the screen state (a number into `Sweep.stages`; there are many command lines, so identical states are merged into one),
   game variables, temp, the lines that set them, and the choices made

Line states aren't stored redundantly. Large projects have hundreds of variables, and keeping all of them on every line would make tens of MB per file:

- Game variables and the lines that set their values are stored only where they changed since the point of entering the file (`Sweep.base`) (removed variables are `unset`).
  The save passed to the player is restored to the full form with `lineSave(sweep, state)`, the game variables of command lines with `afterGame(sweep, state)`,
  and the lines that set them with `lineAssigned(sweep, state)`
- The choices made within the file point to the first few entries of each run's list (`Sweep.runs`) (`lineChoices(sweep, state)`)

4. **Unreached lines**: the route in 1 is the route that first enters the file, so some lines aren't passed on that route, such as the branch of an `@if` that depends on variables set in other files
   (the hatched effect bars). Put the cursor on such a line, and it looks for a route that passes that line and redoes step 2
   (`GET /sweep/reach`, `Sweeper.entryReaching`), and shows "Route (to line N)" below the preview. While searching, and when the line isn't reached or isn't found
   in time, the line display below the preview says so (still showing the screen of the nearest earlier line that has a state). How it searches:
   - At choices, it tries first the ones that move to scenes closer to the target scene on the flowchart (the jump targets of choices are the `targets` the runner passes to the rendering side)
   - It takes as candidates the `@set` lines that set the variables in the conditions for entering that line (the `@if` around the line, and the conditions of the arrows into that line's scene) to values that meet the conditions,
     and for each candidate searches in the order "pass that line first, then go to the target line"
   - A run that enters a file once and leaves it without passing that line is cut off there and moves to the next set of choices (it doesn't run to the end of the game)
   - Up to 15 seconds. A route found is used for that file's current position data until the file changes or it searches again for another unreached line
   - The dev server doesn't stop while searching. Each time the runner sends to the rendering side and before it picks a choice (`pause` of walk in `@liminalia/runtime`),
     it lets go once every 30ms, so saves (`PUT /file`) and other requests don't have to wait (the phone app's Service Worker uses the same mechanism with its own way of letting go).
     If another line is requested, any `.lim` changes, or the request is closed, it stops searching and returns `cancelled` (not remembered; the client asks again if it is still on that line)

Routes and line states are remembered until any `.lim` changes. From the second time, they return right away.
The client fetches line states for the preview and "State at this line" only around the visible range (`from`, `to`), and the duration bars fetch the whole file with `GET /sweep/stage`.
`packages/studio/dev/measure.ts <project> [file…]` measures the size per file (before and after gzip) and the time to build it.

The performance of Studio itself is measured with `packages/studio/dev/measure-studio.ts [--out result.json] [--project <project> --file <file> [--edit <line>] [--reach-file <file> --unreachable <line>]] [shape…]`.
The shapes are projects made from the templates in `dev/shapes.ts`: `long` (one 8,000-line file), `many` (300 files in 10 folders, 3,000 variables, 1,500 syntax check warnings, 2,000 backgrounds),
and `branchy` (a line no route reaches, after 14 levels of choices). For each shape, it starts `lim studio` and reports the time to build the current position data, the wait for a save (`PUT /file`) while an unreached line is being searched for,
the time to switch to the block view (blocksOpen), the time to add one character to the text in the block view and the code view, redrawing the scene list (with every file expanded), the time until the Variables, Check and Assets screens appear, and the total of long tasks during that time.
To measure your own project, copy it first and pass the copy to `--project` (the project folder is only read; `node_modules/@liminalia` in the copy is pointed to this repository's `packages`).

## Preview (the player's interface for Studio)

Studio opens the real player in an iframe with `/?studio=1` and passes it line states with `postMessage` (only when served by the dev server).

- The player shows neither "クリックで開始" (Click to start) nor the title, and returns `{ type: "liminalia:stage-ready" }` when it opens
- On receiving `{ type: "liminalia:stage-show", save }`, it starts from that save, shows the page (or choices),
  and returns `{ type: "liminalia:stage-shown", at }` (at is the position of that page or choice; null if it ended before getting there).
  Even with system screens where `loadSave` resolves before the page appears, it waits until the page appears or it stops at choices before returning
  (up to 3 seconds; after that, the runner's current position). The client doesn't use the returned position for display
- While the preview doesn't have the focus, elements' `focus()` is suppressed. Even if choice buttons, input fields, system screens or plugin screens
  try to move the focus, what you type in Studio doesn't go into the preview. When the writer clicks the preview, the focus moves as usual
- On receiving `{ type: "liminalia:stage-still", stage }`, it stops the current play (the runner) without advancing, builds the screen for that state (`stage`) only by the rendering side's rebuilding
  (the same `restore` as loading, and plugins' `restorers`), empties the text and name box of the message window,
  and returns `{ type: "liminalia:stage-still-shown" }`. It doesn't touch system screens, so it works the same in projects that replaced them.
  Clicking the preview doesn't move it forward
- Requests to the preview (`stage-show`, `stage-still`) are handled in order, and the next doesn't start while the previous one is still rebuilding. If newer ones arrive while waiting, the older ones are skipped
- On receiving `{ type: "liminalia:stage-cast", cast }`, it replaces the characters and redraws the sprites on screen
- After showing the page requested by `stage-show` and returning `stage-shown`, each time the preview moves forward by itself and starts showing the next page (or choices),
  it returns `{ type: "liminalia:stage-progress", at: { file, line }, played }` (when the writer clicked the preview, auto, skip, or a choice).
  It isn't returned for the requested page itself or for `stage-still` screens, and when the next request arrives, it stops until that request's `stage-shown`. The client's cursor sync uses it.
  `played` (`StagePlayed`; `null` if there is no runner) is the state reached in the preview at that page:
  - `save`: a save that resumes from that page (choices) (`runtime.save()`, the same point as the save in `Sweep.lines` of the current position data). `temp`: temp at that time
  - `assigned`: variable paths that were given values after the requested page (the last `stage-show`) → their lines (collected with `SystemEnv.onAssign`; later assignments come later)
  - `choices`: the choices made after the requested page (`RouteStep`, in the order made)

  Where values came from and the choices cover only what happened after the requested page, so the client uses them on top of that page's current position data (where variables came from, and the route up to that page)
- `{ type: "liminalia:stage-pause" }` and `{ type: "liminalia:stage-resume" }` freeze the preview and let it continue.
  `{ type: "liminalia:stage-mute", muted }` silences sound and brings it back. All of these act right away without waiting their turn among requests,
  and return `{ type: "liminalia:stage-controlled", paused, muted }`. While paused, the client doesn't send `stage-show` or `stage-still`,
  and when the player reopens (`stage-ready`), it sends mute and pause again. How it pauses (`packages/web/src/studio-stage.ts`):
  - Sound: suspends the AudioContext of the rendering side's `AudioPlayer`. `<audio>` and `<video>` get `pause()` (including those that start playing after pausing)
  - Effects: `pause()` on `document.getAnimations()`. Web Animations, CSS animations and transitions that start after pausing are paused too
  - Text display, auto, `@wait`, and timers in system screens and plugins: with `?studio=1`, the player wraps the window's
    `setTimeout` and `requestAnimationFrame` in something that can be paused (`TimerGate`) before anything else. Calls whose time comes while paused are held,
    and called in the order they came on resuming (`setInterval` skips the runs while paused). The player's own waiting for requests is counted with the unwrapped timers
  - Input: while paused, the preview doesn't take clicks, keys or the wheel (Studio's keys ⌘⇧… and Esc pass through)
  - Mute is `AudioPlayer.setMuted` (sets the output volume, separate from the config volume, to 0) and `muted` on `<audio>` and `<video>`
    (only those it muted are unmuted)

  It doesn't touch system screens, so it works the same in projects where plugins replaced them. What it can't stop is
  anything that moves without timers (Web Workers, `MessageChannel`, synchronous code that keeps polling `performance.now()` and so on),
  sound from plugins that create their own `AudioContext`, and `new Audio()` played without being added to the document (mute is the same)

- On receiving `{ type: "liminalia:stage-set-var", path, value }`, it puts the value into a variable (`game.…`, `temp.…`, `system.…`) of the runner running in the preview,
  and returns `{ type: "liminalia:stage-var-set", path, value, at, played, error? }` (`at` is the line the preview is showing now, and `played` is the state at that point; the changed value is added to `played.save.game`; `error` if there is no runner or the path is wrong).
  It runs at the back of the request queue, and takes effect even while paused. It isn't saved to files or initial values, and `onAssign` isn't called (it isn't reported as a line that set the value). When `stage-show` or `stage-still` rebuilds, the runner is discarded, so `game.` and `temp.` go back,
  and `system.`, which survives across runners, is put back to its value before the change (`packages/web/src/studio-vars.ts`). It is received only inside `connectStudio`, so it works only with the dev server's `?studio=1`, and isn't included in exported games.
  `system` in `stage-shown` and `StagePlayed.system` return the `system.` variables the runner holds

Starting from a save is done by the system screens' `loadSave(save)` ([plugins.md](../plugins.md)). Projects that replace the system screens can use the preview by implementing it.

## Screenshots and performance measurement

Both open the dev server's player in a headless browser at the game's size (`screen`) and a zoom of 1 (`BrowserProvider` in `server/browser.ts`).

- **Screenshots** (`server/shot.ts`): opens the player with `/?studio=1` (opened the same way as the preview; the position display at the top right, the variable watch and the performance display don't appear),
  and requests the same characters passed to the preview (`stage-cast`) and the same thing requested from the preview (the save of `stage-show` or the state of `stage-still`).
  It waits for `stage-shown` (for text and choice pages, also until the text has finished displaying and it reaches a click wait or choices) or `stage-still-shown`; if the project holds the capture
  (`host.holdShot`), waits until it lets go; waits for fonts and images to load; and finishes moving effects before capturing (the same as `lim shot --settle`)
- **Performance measurement** (`server/profile.ts`; `lim profile` uses it too): opens the player with `?start=…&autostart=1`, and reads the numbers in `window.__liminaliaPerf`
  for each page (after waiting 0.5 seconds; at choices, the first one)
- **Browser**: `lim studio` (Studio opened in a browser) uses Playwright (`playwright-core`) with `LIMINALIA_CHROMIUM` or Playwright's chrome-headless-shell (`findChromium`).
  If none is found, the API refuses with `CHROMIUM_MISSING_STATUS` (424), and the client shows how to install it ("Run `npx playwright install chromium-headless-shell` in a terminal, then try again").
  The desktop app opens it in a hidden Electron window of the app (drawn off screen, with no sound) (the engine side asks with `page`,
  and `packages/studio-desktop/src/main/pages.ts` opens it and answers with `page-reply`; it can open only pages of that project's dev server).
  Packaged apps include neither `playwright-core` nor Chromium, so this works without Chromium. `playwright-core` is loaded when used

## Handing off production work

- **Recording script** (Project → Export → Recording script, or `lim voice-script`): exports, for each line of dialogue, the voice file (from `@voice` before the line, or
  the locked numbers and the `@voice-auto` pattern), the speaker, the line (ruby as `漢字《かんじ》`, base characters followed by the reading), acting notes (the `//!` line directly above the dialogue; plain `//` comments aren't included, and setting `voiceScript.notes` in liminalia.json to `"comments"` includes every `//` line as before), the previous line,
  the scene, the location, why it doesn't play (neither `@voice` nor `@voice-auto` applies, or the locked numbers have no number for it), whether the voice file exists, and whether it needs re-recording (it took over a number from the dialogue before it was rewritten),
  into `exports/voice-script/` as all.csv (everything), a CSV per speaker, and summary.csv (a summary of the number of lines, characters, and lines without a voice), with English headings (in the Japanese display, 全体.csv and 集計.csv with Japanese headings).
  A second `@voice` played at the same time on the same line of dialogue (`who=`, `channel=`) is a row too (its speaker is that voice's speaker), and if the dialogue belongs to another speaker, the acting notes start with "Together with Yui".
  Dialogue in packs (`packs/<id>/scenario`) comes after the main rows (the location is `packs/<id>/scenario/<file>:<line>`; whether it plays and its number are decided with the pack laid over the main scripts)
- **Script for proofreading** (Project → Export → Script for proofreading, or `lim script-export`): writes, for each file, only the text (dialogue, narration and choice text) and the scene headings,
  with speaker names, as text (ruby as `｜base《reading》`, with line numbers) or HTML (`<ruby>`, with `index.html` linking to each file) to `exports/script/`.
  To bring edited text back, use `lim prose extract` and `lim prose apply` ("Proofreading" in [format.md](../design/format.md))
- **Translation hand-off** (Project → Translation → Import and export, or `lim i18n <language> --export csv|xliff --out …` / `--import …` / `--count`):
  exports translation files as a table (CSV) or XLIFF 1.2 into `exports/translation/`, and imports files with translations written in (looked up by key; lines whose original differs from the current script
  aren't saved). `--count` gives character counts for estimates (the whole original, and what isn't translated yet).
  The context column of the table and the notes of XLIFF hold the scene, the location, the lines before and after, and a length guide, and in XLIFF the markup in the text (`{r …}`, `{br}` and so on) becomes `<ph>`, `<x/>` and `<g>`.
  On import, the markup in the text is checked, and translations that can't be read aren't saved, with the count reported (`lim i18n` also shows where and why).
  Languages other than Japanese and English also list the text of the system screens, with the English original alongside. For `--untranslated`, `--changed` and the line ID option `--stamp-ids`, see chapter 10 of [design/format.md](../design/format.md)
- **Visual check of every branch** (`lim regress [--update] [--threshold 0.05] [--pages 1] [--only text] [--dir folder]`): for each
  scene in the flowchart, starts from the top of that scene and captures `--pages` pages from the top (effects are toned down and motion is stopped, so the same script gives the same screen),
  and compares them with the baseline (`.liminalia/regress/baseline`). It reports those whose differing pixels exceed `--threshold` %, and puts images with the differences painted red in
  `.liminalia/regress/diff`. Ones without a baseline become the baseline, and `--update` makes the current ones the baseline. If anything changed, the exit code is 1.
  In Studio, "Visual check" on the Check screen does the same (`POST /regress`; `server/regress.ts`) (the first page of each scene, a difference ratio of 0.05%).
  "Check" compares, and "Use current look as baseline" makes the baseline without comparing. While capturing, it shows "n / m scenes" and "Cancel"; when done, it lists the scenes that changed
  with images of the differences painted red (`GET /regress/file?kind=diff&name=`) and the ratio; click one to go to that scene in the script. Pages are opened the same way as performance measurement
  (`browser.ts`), so the desktop app works without Chromium. It doesn't run at the same time as a measurement (409)
- **Locking voice numbers** (`lim voice-lock`): in Studio, "Lock numbers" on the Voices screen (`POST /voice-lock`; `server/voice-lock.ts`;
  shown only when some speaker uses `@voice-auto` with a pattern). Current locks don't change, and numbers are added for new lines; if there are no locks, it runs "New game" without a screen
  in 8 ways and records the numbers that play (`observeVoiceNumbers` in `@liminalia/runtime`; lim voice-lock uses the same). The previous content is kept in the change history (`.liminalia/history/@voice-lock/`).
  Lines whose numbers differ by route are listed at the top of the screen; click one to go to that line
