Variables assets can keep their values from one run to the next (#166)
game-maker / suite (push) Successful in 8m21s
game-maker / gate (push) Failing after 3h5m52s

A game needs a high score or an unlocked level to survive the end of
a run. As agreed in the issue there are no save or load nodes. A
Variables asset gets a switch instead, and the existing Variables
nodes read and write the values as before.

- A "Persistent" checkbox in the Variables inspector. Toggling it is
  one undo step, and absent means not persistent.
- The behavior system loads the saved values at start and writes them
  after every frame that changed one, so a closed tab loses nothing.
- Values live in localStorage per project, not in the project file.
  Another browser or person starts fresh.
- Play and "Run in editor" save apart, so trying a behavior in the
  editor leaves the Play save alone.
- Saved values are read through the current declaration. A removed
  variable drops out, a new one starts from its default, and a changed
  kind is converted.
- "Clear saved values" in the inspector clears this asset in both
  areas. The main menu gets "Clear saved data" for the whole project.
  Clearing takes effect from the next run on.

Decisions:
- The switch covers the whole asset, not single variables. Mixing
  both means two assets.
- A changed default in the inspector shows only after the save is
  cleared. That is what persistent means.

Findings:
- The first e2e run died at "debug hook present" right after a Vulkan
  error from Chrome. The second run passed, so it was a GPU flake at
  start-up.

Tests:
- ./check.sh: 140 files, 2070 tests, exit 0 (before 138 / 2055).
- 15 new unit tests in tests/core/saved-values.test.ts and
  tests/editor/saves.test.ts.
- GM_STEPS=32,46 fresh: ALL PASSED, 24 checks. Six new checks in
  module 32 go through the UI. Module 46 knows the new menu entry.
- Counter-checks both fail as expected. Loading switched off: 2 unit
  tests and 2 e2e checks fail. Editor run writing into the Play area:
  1 e2e check fails.
- Check total 1278 (1272 measured by CI at bbbf341, plus 6).

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
adminandClaude Opus 5 committed 2026-09-22 10:23:57 +02:00
1 parent bbbf34109b
commit 41772e53f7
17 files changed
+619 -19

No files matched your search

+43 -2
View File
@@ -1,13 +1,20 @@
import { createEmptyGraph } from '../graph/Graph';
import { newId } from '../ids';
import type { Asset, FontAsset, SoundAsset, StateMachineAsset, TextureAsset } from '../model/Asset';
import type {
Asset,
FontAsset,
SoundAsset,
StateMachineAsset,
TextureAsset,
VariablesAsset,
} from '../model/Asset';
import type { AssetType } from '../model/AssetTypes';
import { isFontFile } from '../model/font';
import { DEFAULT_PALETTE, PIXEL_CANVAS_DEFAULT } from '../model/pixelart';
import { isSoundFile } from '../model/sound';
import { removeSubtrees } from '../model/hierarchy';
import type { PropertyBag, PropertyValue } from '../model/Properties';
import { objectHolders, type Project } from '../model/Project';
import { findAssetOf, objectHolders, type Project } from '../model/Project';
import { type Scope, scopeOf, setScope } from '../model/Scope';
import type { SceneObject } from '../model/SceneObject';
import { isTextureFile } from '../model/texture';
@@ -270,6 +277,40 @@ export class SetMachineScopeCommand implements Command {
}
}
/** Whether a Variables asset keeps its values past the end of the run (#166). */
export class SetVariablesPersistentCommand implements Command {
readonly label: string;
private previous = false;
constructor(
private readonly assetId: string,
private readonly persistent: boolean,
) {
this.label = persistent ? 'Make variables persistent' : 'Make variables per run';
}
execute(project: Project): void {
const asset = this.target(project);
this.previous = asset.persistent === true;
setPersistent(asset, this.persistent);
}
undo(project: Project): void {
setPersistent(this.target(project), this.previous);
}
private target(project: Project): VariablesAsset {
const asset = findAssetOf(project, this.assetId, 'variables');
if (!asset) throw new CommandError(`Variables ${this.assetId} not found`);
return asset;
}
}
function setPersistent(asset: VariablesAsset, on: boolean): void {
if (on) asset.persistent = true;
else delete asset.persistent;
}
/**
* Which state a machine starts in, as a state node's id – `''` takes the mark off again, and the
* machine is back to starting in no state. Only one state can be the start because there is only
+1
View File
@@ -8,6 +8,7 @@ export * from './nested';
export * from './NodeContext';
export * from './NodeRegistry';
export * from './propertyPorts';
export * from './savedValues';
export * from './sharedState';
export * from './stateMachine';
export * from './values';
+55
View File
@@ -0,0 +1,55 @@
import type { VariablesAsset } from '../model/Asset';
import type { PropertyBag, PropertyValue } from '../model/Properties';
import type { Project } from '../model/Project';
import { coerceValue } from '../properties/PropertySchema';
/** What a save area holds: the values of each persistent Variables asset, keyed by asset id. */
export type SavedValues = Record<string, PropertyBag>;
/**
* Where the values of persistent Variables assets outlive the run (#166). Played and editor runs
* are handed different areas, so trying a behavior in the editor leaves the player's save alone.
*/
export interface SaveArea {
read(): SavedValues;
write(saved: SavedValues): void;
}
export function isPersistent(asset: VariablesAsset): boolean {
return asset.persistent === true;
}
function persistentAssets(project: Project): VariablesAsset[] {
return project.assets.filter((a): a is VariablesAsset => a.type === 'variables' && isPersistent(a));
}
/**
* Puts what was saved over the declared start values. The declaration is the truth: a key it no
* longer has is ignored, and a value is coerced to the kind it declares now.
*/
export function restoreSaved(
project: Project,
variables: Record<string, PropertyBag>,
saved: SavedValues,
): void {
for (const asset of persistentAssets(project)) {
const stored = saved[asset.id];
const bag = variables[asset.id];
if (!stored || !bag) continue;
for (const def of asset.variables)
if (def.key in stored) bag[def.key] = coerceValue(def, stored[def.key] as PropertyValue);
}
}
/** The declared values of every persistent asset as they stand in the run – what a save writes. */
export function savedSnapshot(project: Project, variables: Record<string, PropertyBag>): SavedValues {
const saved: SavedValues = {};
for (const asset of persistentAssets(project)) {
const bag = variables[asset.id];
if (!bag) continue;
const values: PropertyBag = {};
for (const def of asset.variables) if (def.key in bag) values[def.key] = bag[def.key]!;
saved[asset.id] = values;
}
return saved;
}
+4
View File
@@ -40,10 +40,14 @@ export interface BehaviorAsset extends AssetBase {
* Declarations shared by the whole run: a `Variables` node naming this asset reads and writes one
* value per key, however many graphs point at it. Nothing is placed, so nothing overrides it –
* `props` holds the starting values, as a behavior's does for its own variables.
*
* A `persistent` asset keeps its values past the end of the run (#166): the next run starts from
* what the last one left, not from `props`. Absent is not persistent.
*/
export interface VariablesAsset extends AssetBase {
type: 'variables';
variables: PropertyDef[];
persistent?: boolean;
}
/** Placed as a child of the object it belongs to; its position is the offset from that body. */
+4 -1
View File
@@ -29,6 +29,7 @@ import type {
TextureFrame,
GradientStop,
TilemapLayer,
VariablesAsset,
VectorGradient,
VectorPaint,
VectorPoint,
@@ -169,7 +170,9 @@ export function deserializeProject(raw: unknown, fallbackId = ''): Project {
graph: normalizeGraph(a.graph),
});
} else if (type === 'variables') {
assets.push({ id, type, name, props, variables: variables.get(id) ?? [] });
const shared: VariablesAsset = { id, type, name, props, variables: variables.get(id) ?? [] };
if (a.persistent === true) shared.persistent = true;
assets.push(shared);
} else if (type === 'statemachine') {
const machine: StateMachineAsset = {
id,
+2
View File
@@ -7,6 +7,7 @@ import { Input } from '../runtime/systems/Input';
import { type ModelWrite, World } from '../runtime/World';
import { soundLibrary } from '../viewport/SoundLibrary';
import type { LiveMachineState } from './graph/GraphCanvas';
import { saveArea } from './saves';
import type { EditorState } from './state';
export interface EditorRunHooks {
@@ -123,6 +124,7 @@ export class EditorRun {
this.behaviors = addGameSystems(fresh, project, this.input, {
shouldRun: (e) => runsInEditor(e.props),
audio: soundLibrary,
saves: saveArea(project.id, 'editor'),
});
this.world = fresh;
this.hadFocus = this.hooks.focused();
+3
View File
@@ -18,6 +18,7 @@ import { Input } from '../runtime/systems/Input';
import { World } from '../runtime/World';
import { ui } from '../ui';
import { soundLibrary } from '../viewport/SoundLibrary';
import { saveArea } from './saves';
import type { GameViewport } from './viewport/GameViewport';
import type { GraphEditor } from './graph/GraphEditor';
import type { LiveMachineState } from './graph/GraphCanvas';
@@ -137,6 +138,7 @@ export class PlaySession {
audio: soundLibrary,
physics,
clock: gameClock,
saves: saveArea(runtime.id, 'play'),
});
this.host.gameView.setWorld(world);
this.host.showGame();
@@ -164,6 +166,7 @@ export class PlaySession {
carried,
physics,
clock: gameClock,
saves: saveArea(runtime.id, 'play'),
});
this.host.gameView.setWorld(world);
this.state.setNotice(this.playNotice(), 'quiet');
+10
View File
@@ -7,6 +7,7 @@ import { Dialog, Menu, type MenuEntry, type Widget } from '../ui';
import { dialogSlot } from './FormDialog';
import { OpenProjectDialog } from './OpenProjectDialog';
import { ProjectSettingsDialog, settingsChanges } from './ProjectSettingsDialog';
import { clearSaved, hasSaved } from './saves';
import type { EditorState } from './state';
export class ProjectSession {
@@ -81,10 +82,19 @@ export class ProjectSession {
{ label: 'Open project…', onSelect: () => this.openProjectPicker() },
{ separator: true },
{ label: 'Project settings…', onSelect: () => this.openProjectSettings() },
{ label: 'Clear saved data', onSelect: () => this.clearSavedData() },
];
new Menu(items).openBelow(anchor);
}
/** Forgets what persistent variables saved in this browser (#166), so the next run is a first start. */
private clearSavedData(): void {
const id = this.state.project.id;
const had = hasSaved(id);
clearSaved(id);
this.state.setNotice(had ? 'Saved data cleared' : 'Nothing saved yet');
}
private async createNext(): Promise<void> {
const list = await this.store.list();
await this.create(`Project ${list.length + 1}`);
+39 -7
View File
@@ -3,7 +3,9 @@ import {
ResetAssetPropertyCommand,
SetAssetPropertyCommand,
SetMachineScopeCommand,
SetVariablesPersistentCommand,
} from '../../core/commands/assetCommands';
import { isPersistent } from '../../core/graph/savedValues';
import { nextFieldName, nextVariableName } from '../../core/commands/naming';
import {
AddStructFieldCommand,
@@ -27,8 +29,9 @@ import {
} from '../../core/properties/PropertySchema';
import { markedAssetSchema } from '../../core/properties/deviation';
import { isModified, resolveAssetProps } from '../../core/properties/resolve';
import { Dropdown, HStack, Label, Menu, Theme } from '../../ui';
import { Button, Dropdown, HStack, Label, Menu, Theme } from '../../ui';
import { FontPreview } from '../font/FontPreview';
import { clearSaved, hasSaved } from '../saves';
import { SoundPreview } from '../sound/SoundPreview';
import { aspectActions, sizeCommand } from './aspectAction';
import { actionIf, createFieldRow, type FieldHandlers } from './fieldFactory';
@@ -49,11 +52,13 @@ export function assetSignature(project: Project, assetId: string): string {
if (!asset) return 'missing';
// A machine's own rows are none, so its scope has to be named here or switching it rebuilds nothing.
const machine = asset.type === 'statemachine' ? `|${scopeOf(asset)}` : '';
// The same for the switch that keeps shared values between runs: its notes and button depend on it.
const kept = asset.type === 'variables' ? `|${isPersistent(asset)}` : '';
// Vector art shows its shapes under its rows (#129), so a shape added or renamed is a new structure.
const shapes = asset.type === 'vectorart' ? `|${shapeListSignature(asset)}` : '';
const values = resolveAssetProps(project, asset);
const rows = schemaForAsset(project, asset).filter((def) => isRowShown(def, values));
return rows.map(defSignature).join(',') + machine + shapes;
return rows.map(defSignature).join(',') + machine + kept + shapes;
}
export function defSignature(def: PropertyDef): string {
@@ -76,11 +81,7 @@ export function buildAssetSection(host: InspectorHost, assetId: string): void {
buildProps(host, asset, markedAssetSchema(host.state.project, asset));
if (asset.type === 'behavior' || asset.type === 'variables') buildVariables(host, asset);
// Two lines rather than one: the panel is narrow enough to cut a longer note off mid-sentence.
if (asset.type === 'variables') {
addNote(host, 'One value each for the whole run.', 'small');
addNote(host, 'Every graph pointing here shares them.', 'small');
}
if (asset.type === 'variables') buildPersistence(host, asset);
if (asset.type === 'statemachine') buildMachineScope(host, asset);
// The drawing itself: its shapes are picked here as a texture's frames are picked in its tab (#129).
if (asset.type === 'vectorart') buildShapeListSection(host, asset);
@@ -206,6 +207,37 @@ function buildVariables(host: InspectorHost, asset: BehaviorAsset | VariablesAss
}
}
/** Not in the schema table either: a row there would share the bag with the declared values. */
const PERSISTENT: PropertyDef = { key: 'persistent', label: 'Persistent', kind: 'boolean', default: false };
/** Whether the values outlive the run (#166), what that means, and the way back to a first start. */
function buildPersistence(host: InspectorHost, asset: VariablesAsset): void {
const set = (value: PropertyValue): void =>
void host.state.execute(new SetVariablesPersistentCommand(asset.id, value === true));
const row = createFieldRow(host, PERSISTENT, isPersistent(asset), { onInput: set, onChange: set });
host.body.add(row.row);
// Two lines rather than one: the panel is narrow enough to cut a longer note off mid-sentence.
if (!isPersistent(asset)) {
addNote(host, 'One value each for the whole run.', 'small');
addNote(host, 'Every graph pointing here shares them.', 'small');
return;
}
addNote(host, 'Kept between runs, in this browser.', 'small');
addNote(host, 'The next run starts where one ended.', 'small');
host.body.add(
new Button('Clear saved values', {
variant: 'ghost',
onClick: () => {
const projectId = host.state.project.id;
const had = hasSaved(projectId, asset.id);
clearSaved(projectId, asset.id);
const name = findAsset(host.state.project, asset.id)?.name ?? asset.name;
host.state.setNotice(had ? `Saved values of ${name} cleared` : 'Nothing saved yet');
},
}),
);
}
/** Not in the schema table: the scope lives on the asset itself, not in its property bag. */
const MACHINE_SCOPE: PropertyDef = {
key: 'scope',
+80
View File
@@ -0,0 +1,80 @@
/**
* The saves of persistent Variables assets (#166), kept in this browser per project. Played and
* editor runs write to separate areas, so trying a behavior in the editor leaves the player's save
* alone. Like the editor settings, storage is best effort: a browser that refuses `localStorage`
* plays every run from the declared values.
*/
import type { SaveArea, SavedValues } from '../core/graph';
import type { PropertyBag } from '../core/model/Properties';
export type SaveAreaName = 'play' | 'editor';
const AREAS: readonly SaveAreaName[] = ['play', 'editor'];
type Store = Pick<Storage, 'getItem' | 'setItem' | 'removeItem'>;
function browserStore(): Store | null {
try {
return window.localStorage;
} catch {
return null;
}
}
export function saveKey(projectId: string, area: SaveAreaName): string {
return `game-maker.saves.${projectId}.${area}`;
}
function readArea(store: Store | null, key: string): SavedValues {
try {
const read: unknown = JSON.parse(store?.getItem(key) ?? 'null');
if (!read || typeof read !== 'object' || Array.isArray(read)) return {};
const saved: SavedValues = {};
for (const [assetId, bag] of Object.entries(read))
if (bag && typeof bag === 'object' && !Array.isArray(bag)) saved[assetId] = bag as PropertyBag;
return saved;
} catch {
return {};
}
}
function writeArea(store: Store | null, key: string, saved: SavedValues): void {
try {
if (Object.keys(saved).length === 0) store?.removeItem(key);
else store?.setItem(key, JSON.stringify(saved));
} catch {
// Full or refused: the run goes on with its values, it just will not find them next time.
}
}
export function saveArea(projectId: string, area: SaveAreaName, store = browserStore()): SaveArea {
const key = saveKey(projectId, area);
return {
read: () => readArea(store, key),
// Only the assets the run knows are written; one saved by another area or since switched off
// stays as it was until it is cleared.
write: (saved) => writeArea(store, key, { ...readArea(store, key), ...saved }),
};
}
/** Whether either area holds anything for the asset – or, without one, for the project. */
export function hasSaved(projectId: string, assetId?: string, store = browserStore()): boolean {
return AREAS.some((area) => {
const saved = readArea(store, saveKey(projectId, area));
return assetId === undefined ? Object.keys(saved).length > 0 : assetId in saved;
});
}
/** Forgets what both areas saved for one asset, or for the whole project without one. */
export function clearSaved(projectId: string, assetId?: string, store = browserStore()): void {
for (const area of AREAS) {
const key = saveKey(projectId, area);
if (assetId === undefined) {
writeArea(store, key, {});
continue;
}
const saved = readArea(store, key);
delete saved[assetId];
writeArea(store, key, saved);
}
}
+39 -2
View File
@@ -11,6 +11,9 @@ import {
isHandleEnabled,
type NodeContext,
type PhysicsControl,
restoreSaved,
type SaveArea,
savedSnapshot,
type SharedState,
startStates,
type TraceListener,
@@ -107,6 +110,8 @@ export interface GameSystemOptions {
* run shares the clock with the previews, and a behavior there must not slow the editor down.
*/
clock?: TimeScaled | null;
/** Where persistent Variables assets are read from at the start and written to as they change (#166). */
saves?: SaveArea | null;
}
export interface TimeScaled {
@@ -118,11 +123,19 @@ export function addGameSystems(
world: World,
project: Project,
input: Input,
{ shouldRun, audio = SILENT_AUDIO, carried = null, physics = null, clock = null }: GameSystemOptions = {},
{
shouldRun,
audio = SILENT_AUDIO,
carried = null,
physics = null,
clock = null,
saves = null,
}: GameSystemOptions = {},
): BehaviorSystem {
const collisions = physics ? new PhysicsSystem(physics) : new CollisionSystem();
const animations = new AnimationSystem();
const behaviors = new BehaviorSystem(project, input, { collisions, animations, audio, clock }, shouldRun);
const sources = { collisions, animations, audio, clock, saves };
const behaviors = new BehaviorSystem(project, input, sources, shouldRun);
if (carried) behaviors.carryOver(carried);
world.addSystem(collisions);
world.addSystem(animations);
@@ -137,6 +150,7 @@ export interface EventSources {
/** Where `Play sound` ends up. Absent is a run that plays silently, which is what a test wants. */
audio?: AudioSink | null;
clock?: TimeScaled | null;
saves?: SaveArea | null;
}
/** A behavior's `runWhilePaused` switch: whether it is ticked while Pause game holds the world. */
@@ -165,6 +179,9 @@ export class BehaviorSystem implements System {
private readonly animations: AnimationSystem | null;
private readonly audio: AudioSink;
private readonly clock: TimeScaled | null;
private readonly saves: SaveArea | null;
/** What was last written to `saves`, so a frame that changed nothing writes nothing. */
private lastSaved = '';
constructor(
private readonly project: Project,
@@ -180,6 +197,7 @@ export class BehaviorSystem implements System {
this.animations = sources.animations ?? null;
this.audio = sources.audio ?? SILENT_AUDIO;
this.clock = sources.clock ?? null;
this.saves = sources.saves ?? null;
}
/** The values `global` declarations share this run – read-only to callers, rebuilt by `start`. */
@@ -219,6 +237,9 @@ export class BehaviorSystem implements System {
this.carried = null;
// Built fresh for every run: a shared variable starts at its declared value each time Play does.
this.sharedState = carried ?? buildSharedState(this.project);
// A persistent asset picks up where the last run left it; after a scene swap it already has.
if (!carried && this.saves) restoreSaved(this.project, this.sharedState.variables, this.saves.read());
this.lastSaved = JSON.stringify(savedSnapshot(this.project, this.sharedState.variables));
this.declared = declaredVariables(this.project);
// A `global` machine is entered once for the whole run, before the first instance exists – so
// the move is queued here and every instance the first sync creates hears that one entry.
@@ -236,11 +257,26 @@ export class BehaviorSystem implements System {
this.finish(instance);
this.audio.stopOwner(instance.entity.id);
}
// After the goodbyes: what `On destroy` writes is the last thing the run did.
this.persist();
this.instances = [];
this.pending = [];
this.world = null;
}
/**
* Writes the persistent values when they differ from the last write. Every frame rather than at
* the end, because a tab closed mid-game has no end to wait for.
*/
private persist(): void {
if (!this.saves) return;
const snapshot = savedSnapshot(this.project, this.sharedState.variables);
const text = JSON.stringify(snapshot);
if (text === this.lastSaved) return;
this.lastSaved = text;
this.saves.write(snapshot);
}
/**
* One instance per behavior entity. A switched-off behavior gets its instance and `On start` only when
* switched on, which is what lets a hidden screen wake up when shown.
@@ -437,6 +473,7 @@ export class BehaviorSystem implements System {
}
this.reap(world);
this.flushStateChanges();
this.persist();
}
/**