Skip to content

Godot

Patterplay for Godot is the pure-GDScript Patterplay runtime: no web view, no native extension to compile. It loads a .patterc bundle and plays it directly, held to the same shared test suite as every other engine.

Needs Godot 4.4 or newer; verified on 4.7, which every release is gated on. The runtime uses only plain GDScript (no scene-tree types), so it also runs headless.

Drop the addons/patterplay/ folder into your project’s addons/ directory (download it from the play-godot-v* Release: see the downloads page) and enable the plugin in Project ▸ Project Settings ▸ Plugins. The runtime works with or without the editor plugin enabled; enabling it just registers the helper classes.

Load the bundle text, build an engine, open a flow, and advance it. The play loop in GDScript: steps come back as plain dictionaries:

var json := FileAccess.get_file_as_string("res://story.patterc")
var bundle = PatterBundle.load_from_string(json)
var engine := PatterEngine.new(bundle)
var flow := engine.open_flow("main", "intro") # ("flow id", starting scene/block)
while true:
var step := flow.advance() # { "type": ..., "text": ..., "options": ... }
match step["type"]:
"line": print("%s: %s" % [step.get("speakerLabel", ""), step["text"]])
"text": print(step["text"])
"gameEvent": pass # fire step.gameData cues
"choice": flow.choose(step["options"][0]["id"]) # your UI picks
"end": break

Render each step into your own dialogue UI. A "choice" step carries the choice’s groupId and its options, each { "id", "prompt", "eligible", "gameData" } (prompt and gameData only when set): present each option’s prompt["text"], greyed when eligible is false, and call flow.choose(id) with the player’s pick. The prompt is { "kind": "line" | "text", "text" }, and a "line" prompt also carries the speaker’s character, characterName, direction, qualifier, qualifierName, and speakerLabel when set, the same shape every Patterplay runtime gives. A "line" step carries qualifier and qualifierName the same way: the line’s speaker qualifier by its gameId, and its localised shown name. Show speakerLabel as the speaker’s name: it’s localised and already puts the two together the way the writer and the translator chose (see How a qualified speaker is shown). A "line" or "text" step always carries "padAfter", the writer’s pause after it in seconds, already resolved; the timing rules say how to play it, and PatterBundle.estimate_line_duration(step.get("spokenText", ""), step.get("spokenLocale", ""), step["estimateSpeed"]) how long a line with no recording lasts: "spokenText" is the line in the project’s main language, the one it’s spoken in, whatever language is shown (absent in an IDs-only bundle), and "estimateSpeed" the project’s speed for an estimate (1 unless the writer changes it, higher is faster). A "text" step with step["action"] set to true is action, a direction for whoever stages the scene: stage it, or let it pass, but don’t show it as on-screen text. The key is absent on shown text, and a replayed prompt is never action.

open_flow returns null, with push_error, when the address does not resolve: an unknown scene, or a block that is not in the scene you named. Nothing opens, and a flow already open under that name carries on as it was. Leave the scene out (open_flow("main")) and the flow starts where the project says the story starts, or at the first scene when it doesn’t say.

GDScript has no exceptions, so a call the engine refuses tells you in its own way, and always with a push_error too. flow.advance() and flow.choose(id) keep the reason for flow.last_error() (a flow that hasn’t started, no choice pending, an option that’s unknown or greyed out), and the next of those calls that succeeds clears it; a refused advance() returns {"type": "end", "reason": "ended"}. set_property returns the reason, as below.

Problems the engine plays past go to your on_error option, a Callable taking {flow, kind, node, message} (push_warning when you set none). Beside a content error ("condition", "effect", "best-match"), it reports how the engine was set up ("setup", with flow empty: an option key it doesn’t take, a locale the bundle doesn’t have, a host scope it doesn’t declare), as the engine finishes building, a load whose place has gone from an edited build ("save"), and a choice that ran dry with nothing after it, so the flow ended there ("dry-choice"; the end Dictionary’s "reason" is then "ran-dry", otherwise "ended").

The locale option and engine.set_locale(locale) resolve a locale by one rule ("fr_FR" finds "fr-FR", then "fr", then the default); engine.locale() is the locale in use, and engine.locales() gives the bundle’s {"default", "included"}.

The Game Data and tags a step, an option, or a lookup hands you are your own copies: change them as you like. Extension values are the bundle’s own, so read them and never change them.

Two demos ship inside the addon, under addons/patterplay/demo/ (delete the folder freely): a headless play-through demo (demo.gd, the smallest possible integration) and the Tour scene (tour.tscn), which plays the full interactive Patter tour with clickable choice buttons. The tour also shows per-line audio resolution via PatterAudioResolver; audio files are not bundled (playback is your platform call), so point its audio base at a Patter audio folder to hear it, or leave it unset to play silently.

The story reads your game’s state as @world properties, and you give it that state by binding a World through the host_scopes option. The simplest World is a PatterWorld node:

  1. Add a PatterWorld node to your scene, beside your game’s own state, say.
  2. Hand it to the engine as world: {"host_scopes": {"world": $PatterWorld}}.
  3. Have your game write its state into it as it changes.
@onready var world: PatterWorld = $PatterWorld
func _ready() -> void:
world.set_value("time_of_day", "night")
world.set_value("knows_road", false)
world.set_read_only("time_of_day", true) # yours alone: a story write is refused
world.changed.connect(_on_world_changed) # (name, value, from_story)
var engine := PatterEngine.new(bundle, {"host_scopes": {"world": world}})

A condition on @world.knows_road now reads your value, and an effect that writes @world lands in the node. Names match case-insensitively, as the story’s references do. PatterBundle.declares_world(bundle) says whether the story reads @world at all. A name you haven’t set reads its declared default, and a story write to a name you’ve made read-only is refused and reported to on_error as a failed effect, and the story plays on.

host_scopes takes any object with a get_property(name) method (and a set_property(name, value) method if the story may write), so a node of your own can be the World, or you can extend PatterWorld and override those two to read your game’s state where it already lives. Without set_property, the whole of @world is read-only to the story. A set_property that returns a reason (a non-empty String) refuses that write, reported as above; one that returns nothing lets it land. It also takes a get / set pair of Callables, keyed by property name, that the story reads before every condition and writes through on an effect. Make those methods too, not GDScript lambdas: the engine keeps them, and a GDScript lambda kept until quit can crash a game on Godot .NET as it closes.

var engine := PatterEngine.new(bundle, {"host_scopes": {"world": {
"get": Callable(self, "_world_get"), # returns null when unset
"set": Callable(self, "_world_set"),
}}})

Each binding is registered as a foreign scope: the values stay in your store, and no Patterplay save holds them, so your game saves them. Leave host_scopes out and a standalone engine self-backs @world from the declared defaults, as a property it stores and saves with the rest of the run. A property declared writable: false in the project is the story’s promise, so the engine refuses the story’s write with a push_error ('@world.x' is read-only) and no write, bound or self-backed. Your own set_property isn’t refused for that, because the value is the game’s, but it is refused, changing nothing, when the value doesn’t fit what the project declared (a string for a number, a value an enum doesn’t list) or names a property the project doesn’t declare. It returns the reason, or "" when the value was written:

var refused := engine.set_property("@world.time_of_day", 7)
if refused != "":
print(refused) # "@world.time_of_day" takes text; 7 doesn't fit

A scope that declares no properties takes anything. A per-name policy of your own is yours to refuse from set. Tokens are case-sensitive: binding "World" when the project declares world is reported ("setup") and binds nothing the story reads. World Properties has the full picture.

Every property value lives in a registry, a PatterScopeRegistry. A game has one, and it holds every property from every engine in the game, except values your game keeps itself behind host_scopes. The registry is saved and loaded as one.

An engine you build without one makes its own and acts as its own game, which is why a single PatterSave.serialize_state needs no wiring. A game that runs more than one engine (Patter beside the Storylet Engine, say), or that wants to hold the properties itself, makes the registry and hands it to each engine through the registry option:

var registry := PatterScopeRegistry.new()
registry.define_owned("world", [{"name": "gold", "type": "number", "default": 0}],
{"owner": "Game"}) # @world, stored and saved
var engine := PatterEngine.new(bundle, {"registry": registry})
if engine.init_error() != "":
push_error(engine.init_error()) # a token clash: see below
# One save for the game: the registry's values once, and each engine's part.
var json := JSON.stringify({"registry": registry.save(), "patter": PatterSave.save_state(engine)})
# Load in either order: values for bags that aren't open yet wait in the registry.
var data: Dictionary = JSON.parse_string(json)
registry.load(data["registry"])
PatterSave.load_state(engine, data["patter"])

Given a registry, the engine registers @patter under patter and each flow’s and scene’s bag under a key starting patter/, which no expression can name. Its save then leaves the values out, because your game saves the registry. @world is yours to register: owned, as above, when the registry should store and save it, or bound through host_scopes, when your game keeps the values. The engine self-backs nothing on a registry you pass. Every expression can read every registered scope, so a condition can test another engine’s @story.act once that engine is in the same registry, and engine.get_property("@story.act") reads it too.

Other engines’ scopes need no setting. A Patter line can name the Storylet Engine’s @story.act (in a condition, an effect, or a {@story.act} slot) in any project, and the bundle records it in externalScopes (PatterBundle.external_scopes(bundle) reads it). That content runs only where the other engine is on the same registry. If it is not, open_flow and load_game refuse before anything changes: each push_errors this content names @story, which no engine on this registry registered: give every engine the game's one registry, then open_flow returns null and load_game returns false. If that engine takes its scope away mid-game, a write to it fails in the registry naming the scope (a push_error, unknown scope '@story') rather than landing in @patter.

A token is taken once. Two engines that both want the same one clash as you build the second: GDScript has no exceptions, so the registry push_errors a message naming who got there first, the engine’s init_error() returns it, the new engine is inert, and your registry is left as it was. Values a load left for a flow that never reopened stay in the registry, and in its next save, until you call registry.discard_parked(). Rebuilding an engine on an edited bundle (hot_swap) hands its bags to the replacement on the same registry.

The game can also decide where the story goes. run_flow plays an address in one call, which is all a bark needs:

# Reuses the "guard-42" flow, so its shuffles and once-each lists keep their place
var lines: Array = engine.run_flow("guard-42", "npc-barks", "greet")
for line in lines:
print("%s: %s" % [line.get("speakerLabel", ""), line["text"]])
# Or move a flow you are already driving, exactly as an authored jump would
var moved: bool = flow.goto("throne-room", "audience") # false = did not resolve, cursor unmoved

Give each independent speaker its own flow name. Full rules, and why open_flow behaves differently: Host navigation.

For a letter, a book page, or a sign, run_text gives you the block’s text as one string. It refuses dialogue and choices: it reports an error and returns null if it meets either, or if the address doesn’t resolve (Show a block of text):

var letter = engine.run_text("correspondence", "from-mother")
if letter != null:
letter_label.text = letter

A Godot game runs in its own process, so the live state inspector ships as an in-game overlay, PatterStatePanel, it watches and edits a running engine’s @patter properties and saves / loads the whole run:

PatterDebug.register(engine) # right after you build the engine
var panel := PatterStatePanel.new() # auto-discovers registered engines
add_child(panel) # (or set panel.engine = my_engine)

Each property gets a type-aware editor (bool / number / string / enum / flags) with a reset-to-default button; values live-refresh without clobbering the field you’re editing. The panel is a debug tool: in a release export (OS.is_debug_build() false) it stays hidden and builds nothing, so it is safe to leave in a scene that ships.

PatterDebugLink streams the running story position back to Patterpad so the editor follows the cursor like a debugger. It only opens the link in a debug build, so it is inert in a release export:

var link := PatterDebugLink.new(engine.build_id(), "My Game")
add_child(link)
link.flow_opened("main")
# ...after each advance()/choose():
link.observe("main", flow.current_scene(), step.get("id", ""), step["type"])

The protocol and the editor side are on Live refresh & debug.

PatterSave.serialize_state(engine) and deserialize_state(engine, json) round-trip the whole run: every flow’s position, visit counts, selector cursors, and the seeded random generator, as a tagged JSON envelope. An engine you built on its own also carries every property value, @patter, @scene, and a self-backed @world alike, so one call is still the whole game; an engine you gave a registry leaves them to the registry’s save. deserialize_state returns false, with a push_error, for a blob it cannot read. It is the same patter/save@0 format every Patterplay runtime uses, so a save written by a web build or by Patterpad loads here, and a save written here loads in Unity or Unreal. Saves are version 4, and a version 3 save still loads; older ones don’t. A save at a choice keeps which options were offered, not their text, so a load shows them in the language in use. A load against an edited build whose saved place has gone resumes at the nearest safe point (it offers the choice again, or carries on after what was removed) and reports it to on_error as "save". Save/load & Game Data covers the format.

To set one flow aside instead, engine.capture_flow(id) returns its part of a save as a Dictionary, and engine.restore_flow(new_id, state) opens it again later (null, with a push_error, if it is refused). See Taking one flow out.

Nothing to configure. The plugin puts your .patterc into the export itself, so an exported build has its story on every platform (desktop, mobile, and web). Export as you would any Godot project.

That is worth stating plainly because it used to be a trap. Godot packs the files it recognises as resources and can silently drop everything else, so a game ran perfectly in the editor, which reads loose project files, and shipped without its story. If you followed an older version of this page and added *.patterc to your export filters, you can leave it: it is harmless, and it still covers you if the plugin is ever disabled.

Other loose files are still yours to handle. The plugin knows about bundles and nothing else, so if you use Audio Folders add patteraudio.json under Project ▸ Export… ▸ your preset ▸ Resources ▸ “Filters to export non-resource files/folders”, since the audio files themselves are imported resources and export fine, while the manifest is plain JSON and isn’t. The same goes for any other data file you read at runtime, like a *.json save template.

To sanity-check a build before you ship it, in the EXPORTED game rather than the editor:

print(FileAccess.file_exists("res://story.patterc")) # must print true

A game written in C# with Godot’s .NET build uses this same addon. Godot runs GDScript and C# side by side, so your C# scripts call Patterplay directly. There’s nothing extra to install, and the editor half (the importer, the bundle inspector, and the export hook) works as it does for a GDScript game.

C# can’t name a GDScript class_name, so load each class you need by its script path. The calls are the GDScript ones by name, and what comes back are Godot types: a step is a Godot.Collections.Dictionary.

using Godot;
using Godot.Collections;
public partial class Story : Node
{
static readonly GDScript PatterBundle = GD.Load<GDScript>("res://addons/patterplay/runtime/bundle.gd");
static readonly GDScript PatterEngine = GD.Load<GDScript>("res://addons/patterplay/runtime/engine.gd");
GodotObject _engine;
GodotObject _flow;
public override void _Ready()
{
var bundle = PatterBundle.Call("load_from_string", FileAccess.GetFileAsString("res://story.patterc"));
_engine = PatterEngine.New(bundle).AsGodotObject();
_flow = _engine.Call("open_flow", "main", "intro").AsGodotObject();
}
// Call when the player is ready for the next beat.
public void Next()
{
var step = _flow.Call("advance").AsGodotDictionary();
switch (step["type"].AsString())
{
case "line":
GD.Print($"{(step.ContainsKey("speakerLabel") ? step["speakerLabel"] : "")}: {step["text"]}");
break;
case "text":
GD.Print(step["text"]);
break;
case "choice":
var first = step["options"].AsGodotArray()[0].AsGodotDictionary(); // your UI picks
_flow.Call("choose", first["id"]);
break;
}
}
}

Everything on this page works the same way: set_property hands back its refusal as a string, PatterSave (from res://addons/patterplay/runtime/save.gd) saves and loads, and the option keys are the GDScript ones. Errors are values and push_errors, never C# exceptions.

Your game’s own C# state goes behind host_scopes as a get / set pair of C# lambdas, so the story reads and writes your C# objects directly, with no copy kept on the GDScript side:

var world = new System.Collections.Generic.Dictionary<string, Variant> { ["time_of_day"] = "night" };
_engine = PatterEngine.New(bundle, new Dictionary
{
["host_scopes"] = new Dictionary
{
["world"] = new Dictionary
{
["get"] = Callable.From((string name) => world.TryGetValue(name, out var v) ? v : default),
["set"] = Callable.From((string name, Variant value) => { world[name] = value; }),
},
},
["on_error"] = Callable.From((Dictionary e) => GD.PushWarning($"{e["kind"]}: {e["message"]}")),
}).AsGodotObject();

Returning default (a nil Variant) means unset.

Names are strings and values are Variants, so a typo shows up when the game runs, not when it compiles. If you call Patterplay from many places, wrap the calls you use in a small typed class of your own.

Godot’s C# builds don’t export to the web yet, so a game that has to run in a browser needs GDScript.

PatterplayVersion.CURRENT is this runtime’s version, as in its plugin.cfg ("1.0.0"). An extension that ships apart from Patterplay checks it at start-up with PatterplayVersion.in_range(PatterplayVersion.CURRENT, "1.0.0", "2.0.0"): at least the first version and below the second, by semantic-version order. Every runtime has the same pair.

Open source under the MIT licence, made by .