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

+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);
}
}