Skip to content

The Engine API

This is the deep API reference for the JavaScript reference engine, @patterkit/runtime. If you just want it running, start with the JavaScript & web guide; for the cross-engine model, see the play loop. The native Unity, Unreal, and Godot ports mirror this same shape.

The Engine owns the world, meaning the bundle, shared global state, and every running flow. A Flow is one independent position through the story, with its own cursor, PRNG, and per-flow state. Many flows can run at once over the same data, sharing the shared state; that’s how you’d run two NPCs from one project. One live instance, one shared state, and no whole-story copy per branch.

import { Engine } from "@patterkit/runtime";
const engine = new Engine(bundle); // bundle = parsed .patterc JSON
const flow = engine.openFlow("main", { scene: "square" });
for (;;) {
const step = flow.advance();
if (step.type === "line") render(step.character, step.speakerLabel, step.text);
else if (step.type === "text") step.action ? stage(step) : show(step.text);
else if (step.type === "gameEvent") host(step.gameData); // your side-effects
else if (step.type === "choice") flow.choose(pick(step.options).id);
else if (step.type === "end") break;
}
new Engine(bundle, options?)

options (all optional): seed (the default per-flow PRNG seed), locale (the active locale; defaults to the bundle’s default, see Localisation), replayPromptOnChoose (speak a chosen option’s authored prompt back as its first beat, exactly as the choice showed it; a prompt the choice borrowed from the option’s own first line is not repeated, since that line plays anyway), hostScopes (the scopes your game binds, such as @world), onError (see When something goes wrong), and log (the decision log). There’s also an rng override, but for resumable, save-safe runs use the built-in seeded PRNG. An option the engine doesn’t take, a mistyped key, say, is reported rather than ignored in silence.

engine.openFlow(id, { scene?, block?, seed? })

scene and block accept either a host-facing gameId/address or an internal id. With neither, the flow starts where the project starts: the scene (and block) chosen in Patterpad’s Project Settings, or the first scene when the project hasn’t chosen one. A scene on its own starts at its first block. The block is scene-scoped, as for goto: it must be in the scene you named. Re-opening an existing id replaces it. An address that does not resolve throws before anything changes, so nothing opens and a flow already open under that id carries on. Other engine methods: getFlow(id), flows(), closeFlow(id), and reset() (drop all flows and re-seed shared state).

Dropping a flow finishes it: after closeFlow(id), a reset(), or having its name re-opened, a reference you are still holding is inert (advancing reports the end, goto refuses to move it), so a forgotten reference cannot keep running scene entry effects behind your back. To set a flow aside as data and bring it back later, under the same id or another, see Taking one flow out.

engine.runFlow(name, scene?, block?) // -> the steps that played

Opens the named flow if it does not exist, moves it if it does, plays to the next stop, and returns what played. Unlike openFlow, it reuses the named flow rather than replacing it, so variation state (shuffles, once-each lists, visit counts) keeps its place across calls. An empty array means the address had nothing left to give; an address that does not resolve throws. See Host navigation.

engine.runText(scene, block?, { flow?, separator? }) // -> one string

Plays the address and returns its text beats as one string, joined with separator (a newline by default), for a letter, a book page, or a sign. It’s a convenience wrapper around runFlow that keeps only the text: game events are skipped, and for game data or tags, use runFlow and read the beats yourself. With no flow, it plays on a throwaway flow that’s never registered or saved, so the same address reads the same each time; name a flow to reuse it as runFlow does. A line of dialogue, a choice, or an address that doesn’t resolve throws. See Host navigation.

  • flow.advance(): the next step (line, text, game event, choice, or end).
  • flow.advanceToStop(): { played, stop }, collecting beats until the next choice or the end (handy when you render a whole exchange at once).
  • flow.getChoices(): the options of a pending choice, as advance() delivers them.
  • flow.stepFor(beatId): the step this flow would deliver for that line or text beat right now, as advance() would give it (in the current language, with this flow’s values filled in, closed captions applied, and the speaker’s names and label), without moving the flow or running anything. For a game that keeps lines by id and shows them again, after a load or a language switch. Undefined for an id that isn’t a beat or an option’s prompt. Every runtime has it (StepFor in C# and Blueprint, step_for in GDScript).
  • flow.choose(id): pick an eligible option by id, and the next advance() runs it. It throws if there’s no pending choice, or the id is unknown or ineligible.
  • flow.isEnded(), flow.currentScene: state for tooling that follows the story across scenes.
  • flow.reset(scene?, block?): begin this flow again at a scene (where the project starts by default), forgetting everything that is its own: its position, its own properties, its visit counts, and anything waiting to be delivered. Shared state is kept. Every runtime calls it reset (Reset in C# and Blueprint).
  • flow.goto(scene, block?): returns a boolean and moves the cursor to an address, exactly as an authored jump would (on-entry effects run, arriving counts as a visit, the call stack is replaced). It moves rather than resets, so variation and visit counts carry on; it lands immediately, abandoning any part-delivered snippet or pending choice. It returns false and leaves the cursor alone if the address does not resolve; the block is scene-scoped. See Host navigation.
  • flow.isClosed: whether this flow has been finished (see above).
step.type Fields
"line" id, text, character?, characterName?, direction?, qualifier?, qualifierName?, speakerLabel?, padAfter, spokenText?, spokenLocale?, estimateSpeed, gameData?, tags?
"text" id, text, padAfter, action?, spokenText?, spokenLocale?, estimateSpeed, gameData?, tags?
"gameEvent" id, gameData?, tags?: no text; the host-event beat
"choice" groupId, options: ChoiceOption[]
"end" reason: "ended", or "ran-dry" (see below)

text is interpolated for you (against current property values), except on voiced lines, which are static. characterName is the localised character name; if a character has none, it’s absent and you fall back to the character ID in character. qualifier is the line’s speaker qualifier, by its gameId ("vo", "os", "radio", or one of the project’s own), and qualifierName is its shown name (V.O.), localised as characterName is. Both are absent when the line has none, and on a line closed captions silence. What a qualifier means is your game’s: play a vo line from a non-positional voice, say, or put a filter on a radio one.

speakerLabel is the name to show for the speaker, localised and ready to display: You (V.O.), or the label the writer gave that character with that qualifier (“Your thoughts”), or with no qualifier the character name (the character ID when there’s none). Show it as the speaker’s name rather than putting characterName and qualifierName together yourself: how they combine is the writer’s and the translator’s (see How a qualified speaker is shown). It’s absent when the line has no speaker, on a silenced line, and in IDs-only mode.

action is true on a text step that is action: a direction for whoever stages the scene (MARA turns away.), not words for the player. A dialogue scene’s text is action unless the project localises it (see What gets translated). Use it to stage the moment, a look, a move, a camera cut, rather than show it as on-screen text. Its text is the source language in every locale, since action isn’t translated. The field is absent on shown text, and a replayed option prompt is never action.

padAfter is the writer’s pause after a line or text beat, in seconds, already resolved from the beat’s own value and the defaults above it (0.6 when nothing sets one). Negative means the next beat starts that long before this one ends, so a line or text beat straight after it cuts in on it. A snippet’s last line or text beat is never negative, since what follows it isn’t certain. A spoken option prompt’s padAfter times the reply, and is never clamped. When your game times lines itself, these are the rules the writer expects:

  • Start the next line padAfter after this one ends, but never before this line itself started.
  • Ignore the pause on the last line of a conversation, and on the line before a choice, where the player decides.
  • Start the first line, and the reply to a choice with no spoken prompt, at once.
  • Count a pause after a game event from when the event is done, so a held event doesn’t eat it.
  • Give action no time of its own: like a game event, only its padAfter separates it from the next beat.
  • Apply no pauses when the player clicks through.

A line with no recording lasts estimateLineDuration(step.spokenText, step.spokenLocale, step.estimateSpeed) seconds: about as long as it would take to say, never less than half a second or more than 18. A line is spoken in the project’s main language whatever language the player reads, so spokenText is the line in that language (interpolated as text is, with caption cues left out, and empty for the caption character’s lines) and spokenLocale is that language. A French player reading subtitles over an English line gets the English line’s timing. estimateSpeed is the project’s speed for an estimate, 1 unless the writer sets Timing for lines without audio in Project settings, from 0.5 to 2.5: higher is faster. A line with a recording always lasts as long as the recording. It’s Patter’s one rule, the same in every runtime, in Patterpad’s Play window, and in the playable HTML page, so a line your game times by it lasts as long as the writer heard it. In an IDs-only bundle there’s no text, so pass your own main-language text and locale, with estimateSpeed.

The estimate weighs the line’s characters, each code point once: a Chinese or Japanese Han character weighs 3, kana 2, a Korean Hangul syllable 2.5, a soft hyphen nothing, and anything else 1, spaces and punctuation included. A line is timed at 14 weighted characters a second times the speed. It’s meant to be close enough, not exact: a line that has to be timed exactly needs a recording. The locale is passed for the future: nothing reads it yet.

That’s how long a line takes to say, not how long its text needs to be read. If you show lines as subtitles or overhead text, keep each one up for at least SUBTITLE_READING_MIN (1.5 seconds; Unity Bundle.SubtitleReadingMin, Unreal patter::SUBTITLE_READING_MIN, Godot PatterBundle.SUBTITLE_READING_MIN) after a shorter line ends, overlapping the next line if you must. The line itself still ends when it’s said, so a quick exchange stays quick.

Patterplay doesn’t break a line into syllables or vowels to move a mouth: Patterstage, the dialogue manager over Patterplay, carries its own speech units for that, and lays them over a line’s length, a recording’s or this estimate.

A ChoiceOption is { id, prompt?, eligible, gameData? }: ineligible options are still present (greyed) unless they’re secret; pass id to choose(). Its prompt is { kind, text, padAfter }, where kind is "line" or "text" and padAfter is the pause before the reply, for a game that voices the prompts itself; a line prompt adds character, characterName, direction, qualifier, qualifierName, and speakerLabel when they’re set. With replayPromptOnChoose, the chosen prompt comes back as the first step after choose(), carrying the same padAfter. A choice is only offered when at least one option can be taken: if every remaining option is greyed out, the choice runs dry, as one with no options does, so its fallback plays if it has one and otherwise the flow moves on.

An option’s prompt is built each time the choice is delivered, in the language in use and with the current values filled in, so a pending choice follows setLocale, and a choice in a loaded save shows in the language of the engine that loaded it. The one exception is the replayed prompt: with replayPromptOnChoose, it’s spoken back exactly as the choice showed it, in that language, since that’s what the player picked.

tags is the beat’s accumulated author tags (its own plus every ancestor’s), absent when empty: see Tags at runtime.

gameData on a step, an option, or an outline entry is your game’s own copy, flags lists included, so changing it changes nothing the engine hands out next. extensions is different: it’s the bundle’s own data, handed over as it is, since an extension’s data can be large and is its runtime’s to read. Treat it as read-only.

Falling off the end of a block is a normal ending, the same as END, and the end step’s reason is "ended". The one exception is a choice that ran dry with nothing after it: the flow stops there because the choice had nothing left to offer, not because the story finished, so the reason is "ran-dry" and onError hears a dry-choice problem. An END straight after the dry choice still counts as running dry; your own goto("END") is a plain "ended". The reason survives a save and load. Unity’s step has Reason (FlowEndReason.Ended or FlowEndReason.RanDry), Unreal’s FPatterStep has EndReason (EPatterFlowEndReason::RanDry; StepResult::reason in C++), and Godot’s end Dictionary has "reason". To mark a choice as allowed to run out, give it a fallback that says what happens then.

Read and write game state from the host:

engine.getProperty("@gold"); // shared @patter globals
engine.setProperty("@gold", 10);
flow.getProperty("@scene.locked"); // @scene props live on a flow
flow.setProperty("@scene.locked", false);

@patter globals are reachable from the engine; @scene properties (and per-flow property values) are read and written on a Flow. A write must fit the property’s declaration: a number for a number, one of an enum’s values (or "" when that’s the enum’s own default), flags the property lists, one of a quality’s stages. One that doesn’t fit, or that names a property the content doesn’t declare, throws and changes nothing. The message says what the property takes: "@patter.gold" takes a number; "lots" doesn't fit. Another engine’s scope is that engine’s to check. The @patterkit/play-helpers package adds conveniences like setProperties(engine, { "@hp": 10 }).

A quality’s value is a stage name, and the order of its stages is what makes >= and advance() work. When your game holds a quality’s value and wants the same order, ask the engine by the quality’s reference rather than keeping a copy of the ladder:

engine.stageIndex("@investigation", "certain"); // 2: its position, or -1 if it isn't a stage
engine.compareStages("@investigation", "suspicious", "certain"); // -1, 0 or 1, as a condition compares them
engine.nextStage("@investigation", "suspicious"); // "certain": one rung up, as advance() does
flow.nextStage("@scene.alarm", "quiet"); // @scene qualities live on a flow

compareStages and nextStage refuse a value that isn’t one of the stages, and all three refuse a reference that isn’t a quality. They work for @patter globals, @world and other host scopes on the engine, and for @scene on a flow. Every runtime has the same three (StageIndex, CompareStages and NextStage in C# and Blueprint, stage_index, compare_stages and next_stage in Godot). Holding a ladder yourself? The JavaScript runtime also exports stageIndex, compareStages and nextStage over a plain list of stages.

Visit counts, which a story reads with visits() and seen(), are there for a debug panel too: engine.getVisitCounts() gives the counts shared across every flow and flow.getVisitCounts() a flow’s own, each by node id. Every runtime has the same call (GetVisitCounts in C# and Blueprint, get_visit_counts in Godot).

A condition or effect can fail while the story plays, in ways the compiler can’t see: a division by zero, a value from your game of an unexpected type, or the story setting a @world value your game marks read-only. The story never stops for one. A failing condition counts as false, so its line, option, or branch is skipped, and a failing effect is skipped while the rest of its list still runs. Every runtime does the same.

The engine also carries on past three other kinds of problem, and reports them the same way:

  • setup: how the engine was set up. A locale the bundle doesn’t have (it uses the nearest one), a host scope bound under a token the bundle doesn’t declare (when only the case differs, the report names the declared spelling: tokens are case-sensitive, so World is never world), or an engine option it doesn’t take. These belong to no flow, so flow is "", and node is the locale, token, or option at fault. One found while the engine is being built is reported as the constructor ends, so your handler hears it.
  • save: a load whose place has gone from the build, as after a patch that deleted the line a player saved at. The flow resumes at the nearest safe point (see Loading a save into an edited build), and node is the saved snippet, or the pending choice, that has gone.
  • dry-choice: a choice that ran dry with nothing after it, so the flow ended there: a hub whose options have all been used, say, with no fallback. node is the choice. A dry choice that play carries on past is the usual “ask until there’s nothing left, then move on”, and isn’t reported.

Each is reported, so none is silent. Pass onError to hear about it: it receives the flow, the kind (condition, effect, best-match, setup, save, or dry-choice), the node, the expression’s source when there is one, and a message. With the decision log on, each is also a diagnostic entry in it.

const engine = new Engine(bundle, {
onError: (e) => console.error(`${e.kind} on ${e.node}: ${e.message}`),
});
Runtime How to hear about it Unset
JS onError in the engine options console.warn
Unity EngineOptions.OnError (a PlayError) Debug.LogWarning
Unreal the engine’s OnError event (an FPatterPlayError); EngineOptions::onError in C++. A setup report made as the engine is created goes to the log and the decision log at once, and to OnError on the first OpenFlow, since the event is bound after the engine exists a log warning
Godot "on_error" in the options, a Callable taking a Dictionary push_warning

Patterpad’s Play window marks each failure in its transcript, and the coverage test lists every one it saw.

A step tells you what played, not why. The decision log records each decision the engine made and its reasoning:

  • each branch or sequence it chose from, with every option it looked at and why each was or wasn’t taken;
  • each choice it offered, with the options it greyed out, and the option chosen;
  • each jump;
  • each property it set, with the value it replaced;
  • each problem it reported and carried on past.

Turn it on with log: true in the engine options. engine.log() is the whole run in order, each entry naming its flow and scene. A flow’s own log() holds only that flow’s decisions. clearLog() empties a log, and entries keep counting from where they were, so two reads either side of a clear still agree on the order.

For a tool that wants the decisions as they happen, onTrace hands each one over with the flow it happened in, whether the log is on or off. It returns a function that stops it.

const stop = engine.onTrace((flow, entry) => console.log(flow, entry.type));
Runtime The log Live
JS log option; engine.log(), flow.log(), clearLog() engine.onTrace(handler), returning its stop
Unity EngineOptions.Log; Log(), ClearLog() engine.OnTrace(handler), returning its stop
Unreal bLog in FPatterEngineOptions; Log(), ClearLog() the engine’s OnTrace event; Engine::onTrace in C++
Godot "log" in the options; log(), clear_log() engine.on_trace(handler), returning its stop

Without the log, and with nothing tracing, the engine does none of this work.

Open source under the MIT licence, made by .