Skip to content

armgit / 67.js

Public Imported from GitHub
0

3D engine that AI agents drive

Add game-rules: declarative game logic as a runtime system (part of #777)

Nguyen Xuan Anfedcb7da9a59
diff --git a/README.md b/README.md
index e29c7598..06c211bb 100644
--- a/README.md
+++ b/README.md
@@ -142,6 +142,7 @@ Each addon is a separate import, so a page loads only what it uses.
| Live games | `67js/addons/input` | [Input](docs/input.md): keyboard, mouse, gamepad and custom sources mapped to named actions and axes |
| Live games | `67js/addons/animation-graph` | [Animation graph](docs/animation-graph.md): states, 1D and 2D blend spaces, parameter transitions with crossfades and masked layers for any rig |
| Live games | `67js/addons/player` | [Player](docs/player.md): character controller, follow, first-person and top-down camera rigs, swappable at runtime |
+| Live games | `67js/addons/game-rules` | [Game rules](docs/game-rules.md): a JSON rule document of variables, triggers and actions, played as a runtime system |
| Modeling | `67js/addons/mesh`, `67js/addons/modeling`, `67js/addons/sculpt` | [Mesh editing](docs/mesh.md), [modeling](docs/modeling.md) and [sculpt brushes](https://67js.codepawl.com/sculpt.md) |
| Offline light | `67js/addons/path-tracer`, `67js/addons/light-bake` | [Path-traced stills](https://67js.codepawl.com/path-tracer.md) and [baked lightmaps](https://67js.codepawl.com/light-bake.md) |
| Post passes | `67js/addons/user-pass` | [Your own full-screen GLSL passes](docs/user-passes.md): dither, pixel downscale, quantise |
diff --git a/changes/777.md b/changes/777.md
new file mode 100644
index 00000000..7a4cc239
--- /dev/null
+++ b/changes/777.md
@@ -0,0 +1 @@
+- `67js/addons/game-rules` adds `createGameRules`, a runtime system that plays a bounded JSON rule document of variables, zone, contact, input, timer and variable triggers and actions, with a deterministic event log (#777)
diff --git a/docs/game-rules.md b/docs/game-rules.md
new file mode 100644
index 00000000..6333f251
--- /dev/null
+++ b/docs/game-rules.md
@@ -0,0 +1,108 @@
+# Game rules: game logic as data
+
+`67js/addons/game-rules` plays a JSON rule document in a live game. The document holds variables, triggers and actions. It is data, not code: there is no `eval`, no `Function` and no script, so an agent can create and edit the rules through a tool without running anything it wrote. Like the [runtime](runtime.md), it loads only when imported and adds no dependency.
+
+```js
+import { createRuntime } from '67js/addons/runtime';
+import { createGameRules } from '67js/addons/game-rules';
+
+const rules = createGameRules(document, {
+ input, // a createInput object, only for input triggers
+ getPartPosition: partId => positions.get(partId), // [x, y, z] or undefined, read once per part each fixed step
+ onEvent: entry => audio.handle(entry), // each event log entry, such as a sound marker
+});
+createRuntime(renderer, { systems: [input, physics, rules] }).start(); // after input and physics
+```
+
+The host tells the rules where parts are (`getPartPosition` or `rules.setPartPosition(id, [x, y, z])`) and which parts touched (`rules.reportContact(idA, idB)`, from a physics contact callback). The rules decide what that means.
+
+## The document
+
+```json
+{
+ "version": 1,
+ "variables": { "score": 0, "secondsLeft": 10 },
+ "zones": [
+ { "id": "coin-zone-1", "shape": "sphere", "center": [2, 0, 0], "radius": 0.5 },
+ { "id": "goal-zone", "shape": "box", "center": [8, 0, 0], "size": [1, 2, 2] }
+ ],
+ "parts": [
+ { "id": "player", "tags": ["player"], "position": [0, 0, 0] },
+ { "id": "coin-1", "tags": ["coin"] }
+ ],
+ "prefabs": [{ "id": "spark", "tags": ["effect"] }],
+ "rules": [
+ {
+ "id": "collect-coin-1",
+ "once": true,
+ "when": { "type": "enter", "zone": "coin-zone-1", "tag": "player" },
+ "do": [{ "type": "add", "variable": "score", "value": 1 }, { "type": "hide", "part": "coin-1" }]
+ },
+ {
+ "when": { "type": "enter", "zone": "goal-zone", "tag": "player" },
+ "if": [">=", "score", 3],
+ "do": [{ "type": "win" }]
+ }
+ ]
+}
+```
+
+Every section is optional except `version: 1`. Names (ids, tags, variables, sound and animation names) use letters, digits, `_`, `-` and `.`, up to 64 characters. A part is hidden from zones and contacts while `visible` is false, and a part without a position is outside every zone.
+
+## Triggers (`when`)
+
+| `type` | Fields | Fires when |
+| --- | --- | --- |
+| `enter` | `zone`, `tag` | a visible part with the tag moves into the zone |
+| `exit` | `zone`, `tag` | a part with the tag leaves the zone, or is hidden inside it |
+| `contact` | `between: [tagA, tagB]` | the host reported a contact between a part with `tagA` and one with `tagB` in this step |
+| `input` | `action`, `phase` (`pressed` default, `released`, `held`) | the named action of `options.input` is in that phase |
+| `timer` | `seconds`, `repeat` | game time since the start or the last restart reaches `seconds`, once, or every `seconds` with `repeat: true` |
+| `variable` | `expression` | the expression turns true. It fires on the step it becomes true, not on every step it stays true. |
+
+A rule with `once: true` fires at most once per play. `if` is an optional expression checked after the trigger; when it is 0 the rule does not fire.
+
+## Actions (`do`)
+
+| `type` | Fields | Effect |
+| --- | --- | --- |
+| `set`, `add` | `variable`, `value` | set the variable, or add to it. `value` is an expression. |
+| `show`, `hide` | `part` | change the part's `visible` |
+| `spawn` | `prefab`, `position` | add a part named `<prefab>#<n>` with the prefab's tags |
+| `animation` | `event` | log an animation event name. A game system feeds it to its [animation graph](animation-graph.md) from `onEvent`. |
+| `sound` | `name` | log a sound marker. The host plays it from `onEvent`. |
+| `win`, `lose` | none | end the game. The remaining actions and rules of the step are skipped. |
+| `restart` | none | reset variables, visibility, spawns, timers and `once` flags. The rest of the step is skipped. Part positions stay with the host. |
+
+## Expressions
+
+A number, a variable name, or `[operator, left, right]` with `+ - * /` or `< <= > >= == !=`, nested at most 4 levels. A comparison gives 1 or 0, and an expression counts as true when it is not 0. Dividing by 0 gives 0, so a variable never turns `NaN`. Booleans are 0 and 1.
+
+## Order and determinism
+
+Each fixed step does the same things in the same order:
+
+1. read part positions and work out which parts entered or left each zone;
+2. walk `rules` in document order. A rule whose trigger matches, and whose `if` holds, runs all its actions at once, so a later rule sees the variables an earlier rule changed;
+3. clear the reported contacts.
+
+After `win` or `lose`, `fixedUpdate` does nothing until `restart()`. Same inputs, same positions and same step give the same event log, byte for byte.
+
+## Reading the state
+
+`rules.state` is a copy: `status` (`playing`, `won`, `lost`), `won`, `lost`, `step`, `elapsedSeconds`, `variables` and `parts` (`id`, `tags`, `position`, `visible`, including spawned ones). `rules.eventLog` is a copy of the log. Each entry has `step`, `rule` (the index) and either `trigger` plus what matched (`part`, `parts`, `action`), or `action` plus its details (`variable` and `value`, `part`, `prefab`, `event`, `name`). `rules.restart()` restarts from game code.
+
+## Limits and errors
+
+| Limit | Value |
+| --- | --- |
+| variables, zones, parts | 32, 64, 64 |
+| prefabs, rules | 16, 64 |
+| actions per rule, tags per part | 8, 8 |
+| spawns per play | 64. A spawn past it is logged with `refused: "spawn limit"`. |
+| event log entries | 2000. Later ones are counted in `rules.droppedEvents`. |
+| expression depth | 4 |
+
+`GAME_RULES_LIMITS` exports them. `validateGameRules(document)` checks a document alone and returns a normalised copy. An error names the field and says what to pass, such as `Game rules rules[2].do[1].variable names the variable "scor", which is not declared. Use one of: score, secondsLeft.` An unknown field, an undeclared variable, zone, part, prefab or tag, and an input trigger with no `options.input` are all errors.
+
+The tool surface for an agent (MCP) comes later. It will need the agent bench before it ships.
diff --git a/package.json b/package.json
index 2767290b..6a9787ea 100644
--- a/package.json
+++ b/package.json
@@ -45,6 +45,7 @@
"docs/input.md",
"docs/animation-graph.md",
"docs/player.md",
+ "docs/game-rules.md",
"docs/scene-query.md",
"docs/user-passes.md",
"docs/skeleton-pose.md",
@@ -124,6 +125,7 @@
"./addons/input": "./build/input.js",
"./addons/animation-graph": "./build/animation-graph.js",
"./addons/player": "./build/player.js",
+ "./addons/game-rules": "./build/game-rules.js",
"./addons/update-part-vertices": "./build/update-part-vertices.js",
"./package.json": "./package.json"
},
diff --git a/src/game-rules.js b/src/game-rules.js
new file mode 100644
index 00000000..31adac18
--- /dev/null
+++ b/src/game-rules.js
@@ -0,0 +1,583 @@
+// Declarative game logic for a live game: variables, triggers and actions held in one JSON document.
+// The document is data, never code: there is no eval, no Function and no script. Expressions are arrays such as
+// ["+", "score", 1] over a fixed set of operators. Rules run in document order on every fixed step, so the same
+// inputs give the same event log. Every count is bounded, and every validation error names the field and says what
+// to pass. docs/game-rules.md describes the document and the system.
+
+export const GAME_RULES_LIMITS = Object.freeze({
+ maximumVariables: 32,
+ maximumZones: 64,
+ maximumParts: 64,
+ maximumPrefabs: 16,
+ maximumRules: 64,
+ maximumActionsPerRule: 8,
+ maximumSpawns: 64,
+ maximumTagsPerPart: 8,
+ maximumExpressionDepth: 4,
+ maximumEventLogEntries: 2000,
+ maximumNameLength: 64,
+});
+
+export const GAME_RULE_TRIGGERS = Object.freeze(['enter', 'exit', 'contact', 'input', 'timer', 'variable']);
+export const GAME_RULE_ACTIONS = Object.freeze(['set', 'add', 'show', 'hide', 'spawn', 'animation', 'sound', 'win', 'lose', 'restart']);
+export const GAME_RULE_OPERATORS = Object.freeze(['+', '-', '*', '/', '<', '<=', '>', '>=', '==', '!=']);
+
+const NAME_PATTERN = /^[A-Za-z0-9][A-Za-z0-9_.-]*$/;
+const INPUT_PHASES = ['pressed', 'released', 'held'];
+const TIMER_EPSILON = 1e-9;
+
+const COMPARISONS = {
+ '<': (left, right) => left < right,
+ '<=': (left, right) => left <= right,
+ '>': (left, right) => left > right,
+ '>=': (left, right) => left >= right,
+ '==': (left, right) => left === right,
+ '!=': (left, right) => left !== right,
+};
+
+const ARITHMETIC = {
+ '+': (left, right) => left + right,
+ '-': (left, right) => left - right,
+ '*': (left, right) => left * right,
+ '/': (left, right) => (right === 0 ? 0 : left / right), // division by zero gives 0, so a state never turns NaN
+};
+
+function fail(path, problem, fix) {
+ throw new RangeError(`Game rules ${path} ${problem}. ${fix}`);
+}
+
+function isPlainObject(value) {
+ return value !== null && typeof value === 'object' && !Array.isArray(value);
+}
+
+function requireObject(value, path, allowedFields) {
+ if (!isPlainObject(value)) fail(path, 'must be an object', `Pass { ${allowedFields.join(', ')} }.`);
+ for (const field of Object.keys(value)) {
+ if (!allowedFields.includes(field)) fail(`${path}.${field}`, 'is not a known field', `Use one of: ${allowedFields.join(', ')}.`);
+ }
+}
+
+function requireArray(value, path, maximum) {
+ if (!Array.isArray(value)) fail(path, 'must be an array', `Pass an array of at most ${maximum} items.`);
+ if (value.length > maximum) fail(path, `has ${value.length} items`, `Pass at most ${maximum}; split the game or drop some.`);
+}
+
+function requireName(value, path) {
+ const valid = typeof value === 'string'
+ && value.length <= GAME_RULES_LIMITS.maximumNameLength
+ && NAME_PATTERN.test(value);
+ if (!valid) {
+ fail(path, `is ${JSON.stringify(value)}`, `Pass a name of letters, digits, "_", "-" or "." that starts with a letter or digit, at most ${GAME_RULES_LIMITS.maximumNameLength} characters.`);
+ }
+ return value;
+}
+
+function requireNumber(value, path, minimumExclusive) {
+ if (!Number.isFinite(value) || (minimumExclusive !== undefined && value <= minimumExclusive)) {
+ const bound = minimumExclusive === undefined ? 'a finite number' : `a finite number above ${minimumExclusive}`;
+ fail(path, `is ${JSON.stringify(value)}`, `Pass ${bound}.`);
+ }
+ return value;
+}
+
+function requireVector(value, path) {
+ if (!Array.isArray(value) || value.length !== 3 || !value.every(Number.isFinite)) {
+ fail(path, `is ${JSON.stringify(value)}`, 'Pass [x, y, z] with three finite numbers.');
+ }
+ return [...value];
+}
+
+function requireBoolean(value, path) {
+ if (typeof value !== 'boolean') fail(path, `is ${JSON.stringify(value)}`, 'Pass true or false.');
+ return value;
+}
+
+function requireUniqueId(value, path, seen) {
+ requireName(value, path);
+ if (seen.has(value)) fail(path, `repeats the id "${value}"`, 'Give every entry its own id.');
+ seen.add(value);
+ return value;
+}
+
+function validateTags(tags, path) {
+ if (tags === undefined) return [];
+ requireArray(tags, path, GAME_RULES_LIMITS.maximumTagsPerPart);
+ return tags.map((tag, index) => requireName(tag, `${path}[${index}]`));
+}
+
+function requireOneOf(value, path, choices) {
+ if (!choices.includes(value)) fail(path, `is ${JSON.stringify(value)}`, `Pass one of: ${choices.join(', ')}.`);
+ return value;
+}
+
+function validateVariables(variables) {
+ if (variables === undefined) return {};
+ if (!isPlainObject(variables)) fail('variables', 'must be an object', 'Pass { "score": 0 }, a name for each number.');
+ const names = Object.keys(variables);
+ if (names.length > GAME_RULES_LIMITS.maximumVariables) {
+ fail('variables', `has ${names.length} variables`, `Pass at most ${GAME_RULES_LIMITS.maximumVariables}.`);
+ }
+ const checked = {};
+ for (const name of names) {
+ requireName(name, `variables.${name}`);
+ checked[name] = requireNumber(variables[name], `variables.${name}`);
+ }
+ return checked;
+}
+
+function validateZones(zones) {
+ if (zones === undefined) return [];
+ requireArray(zones, 'zones', GAME_RULES_LIMITS.maximumZones);
+ const seen = new Set();
+ return zones.map((zone, index) => {
+ const path = `zones[${index}]`;
+ requireObject(zone, path, ['id', 'shape', 'center', 'size', 'radius']);
+ const id = requireUniqueId(zone.id, `${path}.id`, seen);
+ const shape = requireOneOf(zone.shape, `${path}.shape`, ['box', 'sphere']);
+ const center = requireVector(zone.center, `${path}.center`);
+ if (shape === 'box') {
+ if (zone.radius !== undefined) fail(`${path}.radius`, 'does not apply to a box', 'Pass size: [x, y, z] for a box, or shape "sphere" with radius.');
+ const size = requireVector(zone.size, `${path}.size`);
+ if (!size.every(extent => extent > 0)) fail(`${path}.size`, `is ${JSON.stringify(size)}`, 'Pass three extents above 0.');
+ return { id, shape, center, size };
+ }
+ if (zone.size !== undefined) fail(`${path}.size`, 'does not apply to a sphere', 'Pass radius for a sphere, or shape "box" with size.');
+ return { id, shape, center, radius: requireNumber(zone.radius, `${path}.radius`, 0) };
+ });
+}
+
+function validateParts(parts) {
+ if (parts === undefined) return [];
+ requireArray(parts, 'parts', GAME_RULES_LIMITS.maximumParts);
+ const seen = new Set();
+ return parts.map((part, index) => {
+ const path = `parts[${index}]`;
+ requireObject(part, path, ['id', 'tags', 'position', 'visible']);
+ return {
+ id: requireUniqueId(part.id, `${path}.id`, seen),
+ tags: validateTags(part.tags, `${path}.tags`),
+ position: part.position === undefined ? null : requireVector(part.position, `${path}.position`),
+ visible: part.visible === undefined ? true : requireBoolean(part.visible, `${path}.visible`),
+ };
+ });
+}
+
+function validatePrefabs(prefabs) {
+ if (prefabs === undefined) return [];
+ requireArray(prefabs, 'prefabs', GAME_RULES_LIMITS.maximumPrefabs);
+ const seen = new Set();
+ return prefabs.map((prefab, index) => {
+ const path = `prefabs[${index}]`;
+ requireObject(prefab, path, ['id', 'tags']);
+ return { id: requireUniqueId(prefab.id, `${path}.id`, seen), tags: validateTags(prefab.tags, `${path}.tags`) };
+ });
+}
+
+function validateExpression(expression, path, context, depth = 1) {
+ if (typeof expression === 'number') return requireNumber(expression, path);
+ if (typeof expression === 'string') {
+ if (!context.variableNames.has(expression)) {
+ const declared = [...context.variableNames].join(', ') || 'none declared';
+ fail(path, `names the variable "${expression}", which is not declared`, `Declare it under "variables", or use one of: ${declared}.`);
+ }
+ return expression;
+ }
+ const shape = 'Pass a number, a variable name, or [operator, left, right].';
+ if (!Array.isArray(expression) || expression.length !== 3) fail(path, `is ${JSON.stringify(expression)}`, shape);
+ if (depth > GAME_RULES_LIMITS.maximumExpressionDepth) {
+ fail(path, 'nests deeper than the limit', `Nest at most ${GAME_RULES_LIMITS.maximumExpressionDepth} levels; compute part of it into a variable first.`);
+ }
+ const [operator, left, right] = expression;
+ requireOneOf(operator, `${path}[0]`, GAME_RULE_OPERATORS);
+ return [
+ operator,
+ validateExpression(left, `${path}[1]`, context, depth + 1),
+ validateExpression(right, `${path}[2]`, context, depth + 1),
+ ];
+}
+
+function requireKnown(value, path, knownIds, kind) {
+ requireName(value, path);
+ if (!knownIds.has(value)) {
+ const known = [...knownIds].join(', ') || `none declared; add one under "${kind}"`;
+ fail(path, `names the ${kind.replace(/s$/, '')} "${value}", which is not declared`, `Use one of: ${known}.`);
+ }
+ return value;
+}
+
+function validateTrigger(trigger, path, context) {
+ if (!isPlainObject(trigger)) fail(path, 'must be an object', `Pass { type } with type one of: ${GAME_RULE_TRIGGERS.join(', ')}.`);
+ const type = requireOneOf(trigger.type, `${path}.type`, GAME_RULE_TRIGGERS);
+ switch (type) {
+ case 'enter':
+ case 'exit':
+ requireObject(trigger, path, ['type', 'zone', 'tag']);
+ return {
+ type,
+ zone: requireKnown(trigger.zone, `${path}.zone`, context.zoneIds, 'zones'),
+ tag: requireKnown(trigger.tag, `${path}.tag`, context.tags, 'tags'),
+ };
+ case 'contact':
+ requireObject(trigger, path, ['type', 'between']);
+ requireArray(trigger.between, `${path}.between`, 2);
+ if (trigger.between.length !== 2) fail(`${path}.between`, `has ${trigger.between.length} tags`, 'Pass exactly two tags, such as ["player", "enemy"].');
+ return { type, between: trigger.between.map((tag, index) => requireKnown(tag, `${path}.between[${index}]`, context.tags, 'tags')) };
+ case 'input': {
+ requireObject(trigger, path, ['type', 'action', 'phase']);
+ if (!context.hasInput) context.usesInput = true;
+ const phase = trigger.phase === undefined ? 'pressed' : requireOneOf(trigger.phase, `${path}.phase`, INPUT_PHASES);
+ return { type, action: requireName(trigger.action, `${path}.action`), phase };
+ }
+ case 'timer': {
+ requireObject(trigger, path, ['type', 'seconds', 'repeat']);
+ const repeat = trigger.repeat === undefined ? false : requireBoolean(trigger.repeat, `${path}.repeat`);
+ return { type, seconds: requireNumber(trigger.seconds, `${path}.seconds`, 0), repeat };
+ }
+ default:
+ requireObject(trigger, path, ['type', 'expression']);
+ return { type, expression: validateExpression(trigger.expression, `${path}.expression`, context) };
+ }
+}
+
+function validateAction(action, path, context) {
+ if (!isPlainObject(action)) fail(path, 'must be an object', `Pass { type } with type one of: ${GAME_RULE_ACTIONS.join(', ')}.`);
+ const type = requireOneOf(action.type, `${path}.type`, GAME_RULE_ACTIONS);
+ switch (type) {
+ case 'set':
+ case 'add':
+ requireObject(action, path, ['type', 'variable', 'value']);
+ return {
+ type,
+ variable: requireKnown(action.variable, `${path}.variable`, context.variableNames, 'variables'),
+ value: validateExpression(action.value, `${path}.value`, context),
+ };
+ case 'show':
+ case 'hide':
+ requireObject(action, path, ['type', 'part']);
+ return { type, part: requireKnown(action.part, `${path}.part`, context.partIds, 'parts') };
+ case 'spawn':
+ requireObject(action, path, ['type', 'prefab', 'position']);
+ return {
+ type,
+ prefab: requireKnown(action.prefab, `${path}.prefab`, context.prefabIds, 'prefabs'),
+ position: requireVector(action.position, `${path}.position`),
+ };
+ case 'animation':
+ requireObject(action, path, ['type', 'event']);
+ return { type, event: requireName(action.event, `${path}.event`) };
+ case 'sound':
+ requireObject(action, path, ['type', 'name']);
+ return { type, name: requireName(action.name, `${path}.name`) };
+ default:
+ requireObject(action, path, ['type']);
+ return { type };
+ }
+}
+
+function validateRules(rules, context) {
+ if (rules === undefined) return [];
+ requireArray(rules, 'rules', GAME_RULES_LIMITS.maximumRules);
+ const seen = new Set();
+ return rules.map((rule, index) => {
+ const path = `rules[${index}]`;
+ requireObject(rule, path, ['id', 'when', 'if', 'once', 'do']);
+ requireArray(rule.do, `${path}.do`, GAME_RULES_LIMITS.maximumActionsPerRule);
+ if (rule.do.length === 0) fail(`${path}.do`, 'is empty', 'Pass at least one action, such as { "type": "add", "variable": "score", "value": 1 }.');
+ return {
+ id: rule.id === undefined ? `rule${index}` : requireUniqueId(rule.id, `${path}.id`, seen),
+ when: validateTrigger(rule.when, `${path}.when`, context),
+ condition: rule.if === undefined ? null : validateExpression(rule.if, `${path}.if`, context),
+ once: rule.once === undefined ? false : requireBoolean(rule.once, `${path}.once`),
+ actions: rule.do.map((action, actionIndex) => validateAction(action, `${path}.do[${actionIndex}]`, context)),
+ };
+ });
+}
+
+/**
+ * Check a rule document and return a normalised copy. Throws a RangeError that names the field and says what to pass.
+ * `hasInput` says whether the game will have an input source, so an input trigger without one fails here.
+ */
+export function validateGameRules(document, { hasInput = true } = {}) {
+ requireObject(document, 'document', ['version', 'variables', 'zones', 'parts', 'prefabs', 'rules']);
+ if (document.version !== 1) fail('version', `is ${JSON.stringify(document.version)}`, 'Pass version: 1.');
+ const variables = validateVariables(document.variables);
+ const zones = validateZones(document.zones);
+ const parts = validateParts(document.parts);
+ const prefabs = validatePrefabs(document.prefabs);
+ const context = {
+ variableNames: new Set(Object.keys(variables)),
+ zoneIds: new Set(zones.map(zone => zone.id)),
+ partIds: new Set(parts.map(part => part.id)),
+ prefabIds: new Set(prefabs.map(prefab => prefab.id)),
+ tags: new Set([...parts, ...prefabs].flatMap(entry => entry.tags)),
+ hasInput,
+ usesInput: false,
+ };
+ const rules = validateRules(document.rules, context);
+ if (context.usesInput) {
+ const index = rules.findIndex(rule => rule.when.type === 'input');
+ fail(`rules[${index}].when`, 'is an input trigger, and the game has no input', 'Pass options.input from createInput, or use another trigger.');
+ }
+ return { version: 1, variables, zones, parts, prefabs, rules };
+}
+
+function evaluate(expression, variables) {
+ if (typeof expression === 'number') return expression;
+ if (typeof expression === 'string') return variables[expression];
+ const [operator, left, right] = expression;
+ const leftValue = evaluate(left, variables);
+ const rightValue = evaluate(right, variables);
+ const arithmetic = ARITHMETIC[operator];
+ if (arithmetic !== undefined) return arithmetic(leftValue, rightValue);
+ return COMPARISONS[operator](leftValue, rightValue) ? 1 : 0;
+}
+
+function isInside(zone, position) {
+ if (zone.shape === 'sphere') {
+ const distanceSquared = position.reduce((sum, value, axis) => sum + (value - zone.center[axis]) ** 2, 0);
+ return distanceSquared <= zone.radius ** 2;
+ }
+ return position.every((value, axis) => Math.abs(value - zone.center[axis]) <= zone.size[axis] / 2);
+}
+
+function pairKey(zoneId, partId) {
+ return `${zoneId}\u0000${partId}`;
+}
+
+/**
+ * A runtime system that plays a rule document. Put it after input and physics in `systems`.
+ * Options: `input` (a createInput object, for input triggers), `getPartPosition(partId)` (returns [x, y, z] or undefined,
+ * read once per part on each fixed step) and `onEvent(entry)` (called for each event log entry, such as a sound marker).
+ * The host also calls `setPartPosition` and `reportContact`. Read `state` and `eventLog` from game code.
+ */
+export function createGameRules(document, options = {}) {
+ const rules = validateGameRules(document, { hasInput: options.input !== undefined });
+ const initialVariables = rules.variables;
+ const prefabTags = new Map(rules.prefabs.map(prefab => [prefab.id, prefab.tags]));
+ const eventLog = [];
+ let droppedEvents = 0;
+ let step = 0;
+ let elapsedSeconds = 0;
+ let status = 'playing';
+ let variables = { ...initialVariables };
+ let parts = [];
+ let occupied = new Set();
+ let spawnCount = 0;
+ let firedOnce = new Set();
+ let variableWasTrue = new Map();
+ let contacts = [];
+ let entered = [];
+ let exited = [];
+
+ function resetPlay() {
+ variables = { ...initialVariables };
+ parts = rules.parts.map(part => ({ ...part, tags: [...part.tags], position: part.position && [...part.position] }));
+ occupied = new Set();
+ spawnCount = 0;
+ firedOnce = new Set();
+ variableWasTrue = new Map();
+ contacts = [];
+ entered = [];
+ exited = [];
+ status = 'playing';
+ elapsedSeconds = 0;
+ }
+ resetPlay();
+
+ function record(entry) {
+ if (eventLog.length >= GAME_RULES_LIMITS.maximumEventLogEntries) {
+ droppedEvents += 1;
+ return;
+ }
+ eventLog.push(entry);
+ options.onEvent?.(entry);
+ }
+
+ function findPart(partId, label) {
+ const part = parts.find(candidate => candidate.id === partId);
+ if (part === undefined) {
+ throw new RangeError(`${label} names the part "${partId}", which the game does not have. Use one of: ${parts.map(candidate => candidate.id).join(', ') || 'none declared'}.`);
+ }
+ return part;
+ }
+
+ function trackZoneOccupancy() {
+ const nowOccupied = new Set();
+ for (const part of parts) {
+ const reported = options.getPartPosition?.(part.id);
+ if (reported !== undefined) part.position = requireVector(reported, `getPartPosition("${part.id}") result`);
+ if (!part.visible || part.position === null) continue;
+ for (const zone of rules.zones) {
+ if (isInside(zone, part.position)) nowOccupied.add(pairKey(zone.id, part.id));
+ }
+ }
+ entered = [];
+ exited = [];
+ for (const zone of rules.zones) {
+ for (const part of parts) {
+ const key = pairKey(zone.id, part.id);
+ if (nowOccupied.has(key) && !occupied.has(key)) entered.push({ zone: zone.id, part });
+ if (!nowOccupied.has(key) && occupied.has(key)) exited.push({ zone: zone.id, part });
+ }
+ }
+ occupied = nowOccupied;
+ }
+
+ function matchZoneChange(changes, trigger) {
+ const change = changes.find(candidate => candidate.zone === trigger.zone && candidate.part.tags.includes(trigger.tag));
+ return change === undefined ? null : { part: change.part.id };
+ }
+
+ function matchContact(trigger) {
+ const [firstTag, secondTag] = trigger.between;
+ for (const [first, second] of contacts) {
+ if (first.tags.includes(firstTag) && second.tags.includes(secondTag)) return { parts: [first.id, second.id] };
+ if (second.tags.includes(firstTag) && first.tags.includes(secondTag)) return { parts: [second.id, first.id] };
+ }
+ return null;
+ }
+
+ function matchInput(trigger) {
+ const { input } = options;
+ const hit = { pressed: input.wasPressed, released: input.wasReleased, held: input.isHeld }[trigger.phase](trigger.action);
+ return hit ? { action: trigger.action } : null;
+ }
+
+ function matchTimer(trigger, previousSeconds) {
+ if (trigger.repeat) {
+ const before = Math.floor(previousSeconds / trigger.seconds + TIMER_EPSILON);
+ const now = Math.floor(elapsedSeconds / trigger.seconds + TIMER_EPSILON);
+ return now > before ? {} : null;
+ }
+ const crossed = previousSeconds < trigger.seconds - TIMER_EPSILON && elapsedSeconds >= trigger.seconds - TIMER_EPSILON;
+ return crossed ? {} : null;
+ }
+
+ // A variable trigger fires when its expression turns true, not on every step it stays true.
+ function matchVariable(trigger, ruleIndex) {
+ const isTrue = evaluate(trigger.expression, variables) !== 0;
+ const wasTrue = variableWasTrue.get(ruleIndex) === true;
+ variableWasTrue.set(ruleIndex, isTrue);
+ return isTrue && !wasTrue ? {} : null;
+ }
+
+ function matchTrigger(rule, ruleIndex, previousSeconds) {
+ const trigger = rule.when;
+ switch (trigger.type) {
+ case 'enter': return matchZoneChange(entered, trigger);
+ case 'exit': return matchZoneChange(exited, trigger);
+ case 'contact': return matchContact(trigger);
+ case 'input': return matchInput(trigger);
+ case 'timer': return matchTimer(trigger, previousSeconds);
+ default: return matchVariable(trigger, ruleIndex);
+ }
+ }
+
+ function runAction(action, ruleIndex) {
+ const base = { step, rule: ruleIndex, action: action.type };
+ switch (action.type) {
+ case 'set':
+ case 'add': {
+ const value = evaluate(action.value, variables);
+ variables[action.variable] = action.type === 'set' ? value : variables[action.variable] + value;
+ record({ ...base, variable: action.variable, value: variables[action.variable] });
+ return;
+ }
+ case 'show':
+ case 'hide':
+ findPart(action.part, `rules[${ruleIndex}] action`).visible = action.type === 'show';
+ record({ ...base, part: action.part });
+ return;
+ case 'spawn':
+ if (spawnCount >= GAME_RULES_LIMITS.maximumSpawns) {
+ record({ ...base, prefab: action.prefab, refused: 'spawn limit' });
+ return;
+ }
+ spawnCount += 1;
+ parts.push({ id: `${action.prefab}#${spawnCount}`, tags: [...prefabTags.get(action.prefab)], position: [...action.position], visible: true });
+ record({ ...base, prefab: action.prefab, part: parts[parts.length - 1].id });
+ return;
+ case 'animation':
+ record({ ...base, event: action.event });
+ return;
+ case 'sound':
+ record({ ...base, name: action.name });
+ return;
+ case 'win':
+ case 'lose':
+ status = action.type === 'win' ? 'won' : 'lost';
+ record(base);
+ return;
+ default:
+ record(base);
+ resetPlay();
+ }
+ }
+
+ // Runs one rule's actions. Returns false when the rule ended the game or restarted it, which stops the step.
+ function runRule(rule, ruleIndex, match) {
+ record({ step, rule: ruleIndex, trigger: rule.when.type, ...match });
+ for (const action of rule.actions) {
+ const previousStatus = status;
+ runAction(action, ruleIndex);
+ if (action.type === 'restart' || status !== previousStatus) return false;
+ }
+ return true;
+ }
+
+ function fixedUpdate(stepSeconds) {
+ if (!Number.isFinite(stepSeconds) || stepSeconds <= 0) {
+ throw new RangeError(`fixedUpdate step must be a number above 0 seconds, got ${String(stepSeconds)}.`);
+ }
+ if (status !== 'playing') return;
+ step += 1;
+ const previousSeconds = elapsedSeconds;
+ elapsedSeconds += stepSeconds;
+ trackZoneOccupancy();
+ for (const [ruleIndex, rule] of rules.rules.entries()) {
+ if (rule.once && firedOnce.has(ruleIndex)) continue;
+ const match = matchTrigger(rule, ruleIndex, previousSeconds);
+ if (match === null) continue;
+ if (rule.condition !== null && evaluate(rule.condition, variables) === 0) continue;
+ firedOnce.add(ruleIndex);
+ if (!runRule(rule, ruleIndex, match)) break;
+ }
+ contacts = [];
+ }
+
+ function restart() {
+ record({ step, rule: null, action: 'restart' });
+ resetPlay();
+ }
+
+ return {
+ name: options.name ?? 'game-rules',
+ fixedUpdate,
+ restart,
+ /** Tell the rules where a part is. Call it from the system that owns the part, before this system's fixedUpdate. */
+ setPartPosition(partId, position) {
+ findPart(partId, 'setPartPosition').position = requireVector(position, `setPartPosition("${partId}") position`);
+ },
+ /** Tell the rules two parts touched during the coming step. Physics calls this from its contact callback. */
+ reportContact(firstPartId, secondPartId) {
+ contacts.push([findPart(firstPartId, 'reportContact'), findPart(secondPartId, 'reportContact')]);
+ },
+ get state() {
+ return {
+ status,
+ won: status === 'won',
+ lost: status === 'lost',
+ step,
+ elapsedSeconds,
+ variables: { ...variables },
+ parts: parts.map(part => ({ id: part.id, tags: [...part.tags], position: part.position && [...part.position], visible: part.visible })),
+ };
+ },
+ get eventLog() {
+ return eventLog.map(entry => ({ ...entry }));
+ },
+ get droppedEvents() {
+ return droppedEvents;
+ },
+ };
+}
diff --git a/tests/game-rules.test.js b/tests/game-rules.test.js
new file mode 100644
index 00000000..5abfb116
--- /dev/null
+++ b/tests/game-rules.test.js
@@ -0,0 +1,306 @@
+import assert from 'node:assert/strict';
+import test from 'node:test';
+import { createRuntime } from '../src/runtime.js';
+import { createGameRules, GAME_RULES_LIMITS, validateGameRules } from '../src/game-rules.js';
+
+const STEP = 1 / 60;
+
+function pickupGameDocument() {
+ const coinRule = number => ({
+ id: `collect-coin-${number}`,
+ once: true,
+ when: { type: 'enter', zone: `coin-zone-${number}`, tag: 'player' },
+ do: [
+ { type: 'add', variable: 'score', value: 1 },
+ { type: 'hide', part: `coin-${number}` },
+ { type: 'sound', name: 'coin' },
+ ],
+ });
+ return {
+ version: 1,
+ variables: { score: 0, secondsLeft: 10 },
+ zones: [
+ { id: 'coin-zone-1', shape: 'sphere', center: [2, 0, 0], radius: 0.5 },
+ { id: 'coin-zone-2', shape: 'sphere', center: [4, 0, 0], radius: 0.5 },
+ { id: 'coin-zone-3', shape: 'sphere', center: [6, 0, 0], radius: 0.5 },
+ { id: 'goal-zone', shape: 'box', center: [8, 0, 0], size: [1, 2, 2] },
+ ],
+ parts: [
+ { id: 'player', tags: ['player'], position: [0, 0, 0] },
+ { id: 'coin-1', tags: ['coin'] },
+ { id: 'coin-2', tags: ['coin'] },
+ { id: 'coin-3', tags: ['coin'] },
+ ],
+ rules: [
+ coinRule(1),
+ coinRule(2),
+ coinRule(3),
+ { id: 'tick', when: { type: 'timer', seconds: 1, repeat: true }, do: [{ type: 'add', variable: 'secondsLeft', value: -1 }] },
+ { id: 'out-of-time', when: { type: 'variable', expression: ['<=', 'secondsLeft', 0] }, do: [{ type: 'lose' }] },
+ {
+ id: 'reach-goal',
+ when: { type: 'enter', zone: 'goal-zone', tag: 'player' },
+ if: ['>=', 'score', 3],
+ do: [{ type: 'animation', event: 'celebrate' }, { type: 'win' }],
+ },
+ ],
+ };
+}
+
+// Moves the player along x at `speed` units per second, one fixed step at a time, and returns the rules.
+function playPickupGame({ speed, steps }) {
+ const rules = createGameRules(pickupGameDocument());
+ const runtimeSystem = {
+ name: 'player-mover',
+ fixedUpdate(step) {
+ const x = rules.state.parts.find(part => part.id === 'player').position[0] + speed * step;
+ rules.setPartPosition('player', [x, 0, 0]);
+ },
+ };
+ for (let index = 0; index < steps; index += 1) {
+ runtimeSystem.fixedUpdate(STEP);
+ rules.fixedUpdate(STEP);
+ }
+ return rules;
+}
+
+test('a pickup game collects three coins, reaches the goal and wins', () => {
+ const rules = playPickupGame({ speed: 2, steps: 600 });
+ const { state } = rules;
+ assert.equal(state.won, true);
+ assert.equal(state.lost, false);
+ assert.equal(state.variables.score, 3);
+ assert.deepEqual(state.parts.filter(part => part.tags.includes('coin')).map(part => part.visible), [false, false, false]);
+ const summary = rules.eventLog.map(entry => entry.action ?? `trigger:${entry.trigger}`);
+ assert.deepEqual(summary, [
+ 'trigger:enter', 'add', 'hide', 'sound',
+ 'trigger:timer', 'add',
+ 'trigger:enter', 'add', 'hide', 'sound',
+ 'trigger:timer', 'add',
+ 'trigger:enter', 'add', 'hide', 'sound',
+ 'trigger:timer', 'add',
+ 'trigger:enter', 'animation', 'win',
+ ]);
+ assert.deepEqual(rules.eventLog.at(-1), { step: state.step, rule: 5, action: 'win' });
+ assert.equal(rules.eventLog.find(entry => entry.name === 'coin').step, rules.eventLog[0].step);
+});
+
+test('the event log is byte stable for the same inputs', () => {
+ const first = JSON.stringify(playPickupGame({ speed: 2, steps: 600 }).eventLog);
+ const second = JSON.stringify(playPickupGame({ speed: 2, steps: 600 }).eventLog);
+ assert.equal(first, second);
+ assert.match(first, /^\[\{"step":\d+,"rule":0,"trigger":"enter","part":"player"\},\{"step":\d+,"rule":0,"action":"add","variable":"score","value":1\}/);
+});
+
+test('standing still loses when the timer runs out, and the game then stops', () => {
+ const rules = playPickupGame({ speed: 0, steps: 700 });
+ assert.equal(rules.state.lost, true);
+ assert.equal(rules.state.variables.secondsLeft, 0);
+ assert.equal(rules.state.variables.score, 0);
+ const lastStep = rules.state.step;
+ assert.ok(lastStep > 595 && lastStep < 605, `lost at step ${lastStep}`);
+ rules.fixedUpdate(STEP);
+ assert.equal(rules.state.step, lastStep);
+});
+
+test('reaching the goal without all coins does not win', () => {
+ const document = pickupGameDocument();
+ document.rules = document.rules.filter(rule => rule.id !== 'collect-coin-2');
+ const rules = createGameRules(document);
+ rules.setPartPosition('player', [8, 0, 0]);
+ rules.fixedUpdate(STEP);
+ assert.equal(rules.state.status, 'playing');
+});
+
+test('the rules run as a runtime system after other systems', () => {
+ const rules = createGameRules(pickupGameDocument());
+ let time = 0;
+ const frames = [];
+ let scheduled = null;
+ const runtime = createRuntime({ render: frame => frames.push(frame) }, {
+ mode: 'fixed',
+ fixedRate: 60,
+ clock: () => time,
+ scheduler: { request: callback => { scheduled = callback; return 1; }, cancel: () => {} },
+ visibility: { hidden: false, subscribe: () => () => {} },
+ systems: [
+ { name: 'mover', fixedUpdate: step => rules.setPartPosition('player', [rules.state.parts[0].position[0] + 2 * step, 0, 0]) },
+ rules,
+ ],
+ });
+ runtime.start();
+ for (let frame = 0; frame < 20; frame += 1) {
+ time += 50;
+ scheduled(time);
+ }
+ assert.ok(rules.state.step >= 55);
+ assert.equal(rules.state.variables.score, 1);
+ runtime.dispose();
+});
+
+test('exit, input, contact and variable triggers fire in rule order', () => {
+ const heldActions = new Set();
+ const pressedActions = new Set();
+ const input = {
+ wasPressed: action => pressedActions.has(action),
+ wasReleased: () => false,
+ isHeld: action => heldActions.has(action),
+ };
+ const rules = createGameRules({
+ version: 1,
+ variables: { hits: 0, jumps: 0, exits: 0, boosted: 0 },
+ zones: [{ id: 'pad', shape: 'box', center: [0, 0, 0], size: [2, 2, 2] }],
+ parts: [
+ { id: 'hero', tags: ['hero'], position: [0, 0, 0] },
+ { id: 'rock', tags: ['hazard'] },
+ ],
+ prefabs: [{ id: 'spark', tags: ['effect'] }],
+ rules: [
+ { when: { type: 'input', action: 'jump' }, do: [{ type: 'add', variable: 'jumps', value: 1 }, { type: 'spawn', prefab: 'spark', position: [0, 1, 0] }] },
+ { when: { type: 'contact', between: ['hazard', 'hero'] }, do: [{ type: 'add', variable: 'hits', value: 1 }, { type: 'show', part: 'rock' }] },
+ { when: { type: 'exit', zone: 'pad', tag: 'hero' }, do: [{ type: 'add', variable: 'exits', value: 1 }] },
+ { when: { type: 'variable', expression: ['>=', ['+', 'hits', 'jumps'], 2] }, do: [{ type: 'set', variable: 'boosted', value: ['*', 'hits', 10] }] },
+ ],
+ }, { input });
+
+ rules.fixedUpdate(STEP);
+ pressedActions.add('jump');
+ rules.reportContact('hero', 'rock');
+ rules.fixedUpdate(STEP);
+ pressedActions.clear();
+ rules.setPartPosition('hero', [5, 0, 0]);
+ rules.fixedUpdate(STEP);
+ rules.fixedUpdate(STEP);
+
+ assert.deepEqual(rules.state.variables, { hits: 1, jumps: 1, exits: 1, boosted: 10 });
+ assert.equal(rules.state.parts.at(-1).id, 'spark#1');
+ assert.deepEqual(rules.state.parts.at(-1).tags, ['effect']);
+ const triggers = rules.eventLog.filter(entry => entry.trigger).map(entry => `${entry.step}:${entry.trigger}`);
+ assert.deepEqual(triggers, ['2:input', '2:contact', '2:variable', '3:exit']);
+ assert.equal(rules.eventLog.filter(entry => entry.trigger === 'variable').length, 1);
+});
+
+test('restart resets play, onEvent sees every entry and spawns are bounded', () => {
+ const seen = [];
+ const rules = createGameRules({
+ version: 1,
+ variables: { score: 0 },
+ prefabs: [{ id: 'dot', tags: [] }],
+ rules: [
+ { id: 'spawner', when: { type: 'timer', seconds: STEP, repeat: true }, do: [{ type: 'spawn', prefab: 'dot', position: [0, 0, 0] }, { type: 'add', variable: 'score', value: 1 }] },
+ ],
+ }, { onEvent: entry => seen.push(entry) });
+ for (let index = 0; index < GAME_RULES_LIMITS.maximumSpawns + 5; index += 1) rules.fixedUpdate(STEP);
+ assert.equal(rules.state.parts.length, GAME_RULES_LIMITS.maximumSpawns);
+ assert.ok(rules.eventLog.some(entry => entry.refused === 'spawn limit'));
+ assert.equal(seen.length, rules.eventLog.length);
+ rules.restart();
+ assert.equal(rules.state.parts.length, 0);
+ assert.equal(rules.state.variables.score, 0);
+ assert.equal(rules.eventLog.at(-1).action, 'restart');
+});
+
+test('a restart action stops the step and the event log is capped', () => {
+ const rules = createGameRules({
+ version: 1,
+ variables: { score: 0 },
+ rules: [
+ { when: { type: 'timer', seconds: STEP, repeat: true }, do: [{ type: 'add', variable: 'score', value: 5 }, { type: 'restart' }, { type: 'add', variable: 'score', value: 99 }] },
+ ],
+ });
+ for (let index = 0; index < GAME_RULES_LIMITS.maximumEventLogEntries; index += 1) rules.fixedUpdate(STEP);
+ assert.equal(rules.state.variables.score, 0);
+ assert.equal(rules.eventLog.length, GAME_RULES_LIMITS.maximumEventLogEntries);
+ assert.ok(rules.droppedEvents > 0);
+});
+
+test('expressions never produce NaN: division by zero gives 0', () => {
+ const rules = createGameRules({
+ version: 1,
+ variables: { ratio: 5, zero: 0 },
+ rules: [{ when: { type: 'timer', seconds: STEP }, do: [{ type: 'set', variable: 'ratio', value: ['/', 'ratio', 'zero'] }] }],
+ });
+ rules.fixedUpdate(STEP);
+ assert.equal(rules.state.variables.ratio, 0);
+});
+
+test('host calls name the unknown part', () => {
+ const rules = createGameRules({ version: 1, parts: [{ id: 'hero', tags: ['hero'] }] });
+ assert.throws(() => rules.setPartPosition('villain', [0, 0, 0]), /part "villain".*Use one of: hero/);
+ assert.throws(() => rules.reportContact('hero', 'villain'), /part "villain"/);
+ assert.throws(() => rules.setPartPosition('hero', [0, 0]), /Pass \[x, y, z\]/);
+ assert.throws(() => rules.fixedUpdate(0), /above 0 seconds/);
+});
+
+const validBase = () => ({
+ version: 1,
+ variables: { score: 0 },
+ zones: [{ id: 'zone', shape: 'sphere', center: [0, 0, 0], radius: 1 }],
+ parts: [{ id: 'hero', tags: ['hero'] }],
+ prefabs: [{ id: 'dot', tags: ['dot'] }],
+ rules: [{ when: { type: 'enter', zone: 'zone', tag: 'hero' }, do: [{ type: 'add', variable: 'score', value: 1 }] }],
+});
+
+const invalidCases = [
+ ['a non-object document', () => 'rules', /document must be an object/],
+ ['an unknown top-level field', document => ({ ...document, scripts: [] }), /scripts is not a known field.*Use one of: version/],
+ ['a wrong version', document => ({ ...document, version: 2 }), /version is 2.*Pass version: 1/],
+ ['a non-numeric variable', document => ({ ...document, variables: { score: 'high' } }), /variables\.score is "high".*finite number/],
+ ['too many variables', document => ({ ...document, variables: Object.fromEntries(Array.from({ length: 33 }, (_, index) => [`v${index}`, 0])) }), /variables has 33 variables.*at most 32/],
+ ['a bad zone shape', document => ({ ...document, zones: [{ id: 'z', shape: 'cone', center: [0, 0, 0] }] }), /zones\[0\]\.shape is "cone".*box, sphere/],
+ ['a sphere with a size', document => ({ ...document, zones: [{ id: 'z', shape: 'sphere', center: [0, 0, 0], radius: 1, size: [1, 1, 1] }] }), /zones\[0\]\.size does not apply to a sphere/],
+ ['a zero radius', document => ({ ...document, zones: [{ id: 'z', shape: 'sphere', center: [0, 0, 0], radius: 0 }] }), /zones\[0\]\.radius is 0.*above 0/],
+ ['a short center', document => ({ ...document, zones: [{ id: 'z', shape: 'sphere', center: [0, 0], radius: 1 }] }), /zones\[0\]\.center.*\[x, y, z\]/],
+ ['a repeated part id', document => ({ ...document, parts: [{ id: 'a' }, { id: 'a' }] }), /parts\[1\]\.id repeats the id "a"/],
+ ['too many parts', document => ({ ...document, parts: Array.from({ length: 65 }, (_, index) => ({ id: `p${index}` })) }), /parts has 65 items.*at most 64/],
+ ['a bad name', document => ({ ...document, parts: [{ id: 'bad name' }] }), /parts\[0\]\.id is "bad name"/],
+ ['too many rules', document => ({ ...document, rules: Array.from({ length: 65 }, () => document.rules[0]) }), /rules has 65 items.*at most 64/],
+ ['an empty action list', document => ({ ...document, rules: [{ ...document.rules[0], do: [] }] }), /rules\[0\]\.do is empty/],
+ ['too many actions', document => ({ ...document, rules: [{ ...document.rules[0], do: Array.from({ length: 9 }, () => ({ type: 'win' })) }] }), /rules\[0\]\.do has 9 items.*at most 8/],
+ ['an unknown trigger type', document => ({ ...document, rules: [{ when: { type: 'script' }, do: [{ type: 'win' }] }] }), /rules\[0\]\.when\.type is "script".*enter, exit, contact/],
+ ['an unknown zone', document => ({ ...document, rules: [{ when: { type: 'enter', zone: 'nowhere', tag: 'hero' }, do: [{ type: 'win' }] }] }), /rules\[0\]\.when\.zone names the zone "nowhere".*Use one of: zone/],
+ ['an unknown tag', document => ({ ...document, rules: [{ when: { type: 'enter', zone: 'zone', tag: 'ghost' }, do: [{ type: 'win' }] }] }), /rules\[0\]\.when\.tag names the tag "ghost".*hero, dot/],
+ ['a contact with one tag', document => ({ ...document, rules: [{ when: { type: 'contact', between: ['hero'] }, do: [{ type: 'win' }] }] }), /rules\[0\]\.when\.between has 1 tags.*exactly two/],
+ ['a timer of zero', document => ({ ...document, rules: [{ when: { type: 'timer', seconds: 0 }, do: [{ type: 'win' }] }] }), /rules\[0\]\.when\.seconds is 0.*above 0/],
+ ['an input phase typo', document => ({ ...document, rules: [{ when: { type: 'input', action: 'jump', phase: 'down' }, do: [{ type: 'win' }] }] }), /rules\[0\]\.when\.phase is "down".*pressed, released, held/],
+ ['an unknown field in a trigger', document => ({ ...document, rules: [{ when: { type: 'timer', seconds: 1, code: 'x' }, do: [{ type: 'win' }] }] }), /rules\[0\]\.when\.code is not a known field/],
+ ['an unknown action type', document => ({ ...document, rules: [{ when: { type: 'timer', seconds: 1 }, do: [{ type: 'eval' }] }] }), /rules\[0\]\.do\[0\]\.type is "eval".*set, add, show/],
+ ['an undeclared variable in an action', document => ({ ...document, rules: [{ when: { type: 'timer', seconds: 1 }, do: [{ type: 'add', variable: 'scor', value: 1 }] }] }), /rules\[0\]\.do\[0\]\.variable names the variable "scor".*Use one of: score/],
+ ['an undeclared variable in an expression', document => ({ ...document, rules: [{ when: { type: 'timer', seconds: 1 }, do: [{ type: 'set', variable: 'score', value: ['+', 'lives', 1] }] }] }), /rules\[0\]\.do\[0\]\.value\[1\] names the variable "lives".*Declare it/],
+ ['an unknown operator', document => ({ ...document, rules: [{ when: { type: 'timer', seconds: 1 }, do: [{ type: 'set', variable: 'score', value: ['%', 'score', 2] }] }] }), /rules\[0\]\.do\[0\]\.value\[0\] is "%".*\+, -, \*, \//],
+ ['an expression of the wrong shape', document => ({ ...document, rules: [{ when: { type: 'timer', seconds: 1 }, if: ['+', 1], do: [{ type: 'win' }] }] }), /rules\[0\]\.if is \["\+",1\].*\[operator, left, right\]/],
+ ['an expression nested too deep', document => ({ ...document, rules: [{ when: { type: 'timer', seconds: 1 }, if: ['+', ['+', ['+', ['+', ['+', 1, 1], 1], 1], 1], 1], do: [{ type: 'win' }] }] }), /nests deeper than the limit/],
+ ['an unknown part to hide', document => ({ ...document, rules: [{ when: { type: 'timer', seconds: 1 }, do: [{ type: 'hide', part: 'coin' }] }] }), /rules\[0\]\.do\[0\]\.part names the part "coin".*Use one of: hero/],
+ ['an unknown prefab to spawn', document => ({ ...document, rules: [{ when: { type: 'timer', seconds: 1 }, do: [{ type: 'spawn', prefab: 'bomb', position: [0, 0, 0] }] }] }), /rules\[0\]\.do\[0\]\.prefab names the prefab "bomb".*Use one of: dot/],
+ ['a spawn without a position', document => ({ ...document, rules: [{ when: { type: 'timer', seconds: 1 }, do: [{ type: 'spawn', prefab: 'dot' }] }] }), /rules\[0\]\.do\[0\]\.position is undefined/],
+ ['a sound with a bad name', document => ({ ...document, rules: [{ when: { type: 'timer', seconds: 1 }, do: [{ type: 'sound', name: 'a b' }] }] }), /rules\[0\]\.do\[0\]\.name is "a b"/],
+ ['a once flag that is not a boolean', document => ({ ...document, rules: [{ ...document.rules[0], once: 'yes' }] }), /rules\[0\]\.once is "yes".*true or false/],
+];
+
+for (const [label, mutate, expected] of invalidCases) {
+ test(`validation rejects ${label}`, () => {
+ assert.throws(() => validateGameRules(mutate(validBase())), expected);
+ });
+}
+
+test('the second rule is named when its field is wrong', () => {
+ const document = validBase();
+ document.rules.push({ when: { type: 'timer', seconds: 1 }, do: [{ type: 'win' }, { type: 'add', variable: 'nope', value: 1 }] });
+ assert.throws(() => validateGameRules(document), /rules\[1\]\.do\[1\]\.variable/);
+});
+
+test('an input trigger needs an input source', () => {
+ const document = validBase();
+ document.rules = [{ when: { type: 'input', action: 'jump' }, do: [{ type: 'win' }] }];
+ assert.throws(() => createGameRules(document), /rules\[0\]\.when is an input trigger.*options\.input/);
+ assert.doesNotThrow(() => createGameRules(document, { input: { wasPressed: () => false } }));
+});
+
+test('the validated copy does not share memory with the document', () => {
+ const document = validBase();
+ const checked = validateGameRules(document);
+ document.variables.score = 99;
+ document.zones[0].center[0] = 99;
+ assert.equal(checked.variables.score, 0);
+ assert.equal(checked.zones[0].center[0], 0);
+});
diff --git a/vite.lib.config.js b/vite.lib.config.js
index 0bb2c083..d02da765 100644
--- a/vite.lib.config.js
+++ b/vite.lib.config.js
@@ -109,6 +109,7 @@ export default defineConfig({
input: 'src/input.js',
'animation-graph': 'src/animation-graph.js',
player: 'src/player.js',
+ 'game-rules': 'src/game-rules.js',
'update-part-vertices':'src/update-part-vertices.js',
'replace-textured-parts': 'src/replace-textured-parts.js',
// Page of the MCP preview. It imports the engine chunks above instead of bundling its own copy.