3D engine that AI agents drive
Use one expression module for field and motion expressions (issue #98)
Nguyen Xuan Anc4d587eba494
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 7a5eda19..851627a3 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -2,6 +2,8 @@## Unreleased+- Use one expression language for fields and drivers (issue #98). `src/expression.js` now holds what `src/mesh-fields.js` and `src/motion-expression.js` shared by copy: the node and depth limits, number literals, the table of math operators with their operand counts, and the lifting of an operator over numbers or vectors. Each file is now a dialect that adds only its own sources (attributes, noise and vectors for fields; `time` and node reads for motion). Recipe syntax is unchanged. 160,000 random expressions, plus hostile and malformed ones, give the same values, reads and error messages as before, except that the operator list in a field's "unknown operator" message is in a new order. The two languages still differ where they did: a field turns `div` by zero, a negative `sqrt` and an overflowing `pow` into 0, a motion expression keeps them as a non-finite error; `if` is true above 0 in motion and not 0 in fields; `smoothstep` with equal edges is a step in fields. Fixed-arity calls keep field evaluation at the old speed (about 70 ms for 200,000 elements). The bundle did not shrink: `entry:agent-scene+lazy` grew by about 385 bytes gzip, because the two copies compressed against each other.+- Add `decimate`, `remesh` and generated levels of detail (issue #40). `decimate` (a `ratio` of triangles) is a quadric edge collapse of our own that keeps open boundaries, the borders between tags and the tags themselves; it measured 0.25 to 0.85 of the Hausdorff error of meshoptimizer 1.3.0 on the same meshes and adds no dependency, but takes about 2.5 s on 100k triangles where meshoptimizer takes 0.09 s. `remesh` (`voxelSize` or `resolution`, at most 192 per side and 4,194,304 cells, checked before allocation) builds a closed quad surface from a BVH signed distance with surface nets. Both are edits and stack nodes, in the MCP schemas, and load on demand with the mesh code. `generateMeshLods`, `generateGeometryLods` and `generateAssetLods` (also in `67js/addons/mesh`) return levels with a measured error for runtime selection (issue #37). Four decimate and two remesh cases join the Blender comparison, compared by volume, area and Hausdorff distance because face counts differ.- Make the default look good without tuning. Recipes get an image-based environment: `environment.setup` (`daylight` by default, `overcast`, `sunset`, `studio`) selects a small procedural sky map generated in code, plus its key light, with `environmentIntensity` and `environmentRotation`; no URLs or files from tool input. `effects.ambientOcclusion` (0 to 1) and `ambientOcclusionRadius` add screen-space ambient occlusion from the depth texture. It is off by default: measured with `npm run reference -- --ambient-occlusion`, it improved no score by more than 0.002 (strength 0.8: -0.0019 in foliage, +0.0047 in lit-interior; strength 0.4, radius 0.3: within +0.0013 everywhere). When used it compiles and allocates on first use and costs about 16 ms on a 190 ms SwiftShader frame (8 percent). `scene_capabilities` lists `lightingSetups`, `defaultLightingSetup` and `ambientOcclusion`. **This changes the look of every existing recipe that sets no lighting**: it now has an environment map, a key color of `[3, 2.8, 2.5]` instead of `[5.2, 4.7, 4.1]`, and a fill intensity of `0` instead of `1`. The engine default is unchanged (occlusion off, no map) so code scenes keep their pixels. Screen-space reflections are not part of this. The `scene:lit-box` size budget rises by 100 bytes gzip for the environment and occlusion code. The reference suite gets `--ambient-occlusion`, and its Blender renderer drops triangles that repeat a vertex, which crashed Blender on the skinned characterdiff --git a/docs/agent-motion.md b/docs/agent-motion.mdindex c86571ed..ba83869a 100644--- a/docs/agent-motion.md+++ b/docs/agent-motion.md@@ -170,7 +170,10 @@ An expression is JSON data and is never run as code: a number, the string `"time`mul`, `min`, `max` (2 to 8 operands), `sub`, `div`, `pow`, `mod`, `atan2`, `gt`, `lt`, `neg`, `abs`, `sin`, `cos` (radians),`sqrt`, `floor`, `fract`, `saturate`, `clamp(x, low, high)`, `mix(a, b, t)`, `smoothstep(low, high, x)` and`if(condition, then, otherwise)`. An expression has at most 64 parts and 8 levels, and a result that is not finite is an-error. The operator names follow the field expressions of the mesh addon where they overlap.+error. It is the motion dialect of the one expression language in `src/expression.js`: the operator names, operand counts, limits and+hostile-input checks are shared with the field expressions of the mesh addon. Two edge cases differ on purpose. A motion expression+keeps plain arithmetic, so `div` by zero, a negative `sqrt` and `pow` overflow give a non-finite result that is an error, where a+field gives 0. And `if` takes `then` when the condition is above 0, where a field takes it when the condition is not 0.### Evaluation orderdiff --git a/docs/mesh.md b/docs/mesh.mdindex c1481ac5..7b585e83 100644--- a/docs/mesh.md+++ b/docs/mesh.md@@ -210,7 +210,8 @@ as Blender's Apply modifier, which leaves the result unchanged.A field expression is plain JSON that computes one number, or one vector, for each point or face of a mesh. It isdata and never code: `src/mesh-fields.js` reads it against a fixed table of operators, compiles it once into-closures over typed arrays, and checks the limits before it evaluates anything. No string is executed, and no input+closures over typed arrays, and checks the limits before it evaluates anything. It is the field dialect of the one+expression language in `src/expression.js`, which motion drivers share (see [agent motion](agent-motion.md)). No string is executed, and no inputstring is used as a property name, so a recipe written by an agent that follows injected instructions cannot run codeor reach `__proto__` or `constructor`. The same expression gives the same bytes on every run.diff --git a/docs/parity.md b/docs/parity.mdindex 9215afbe..375de635 100644--- a/docs/parity.md+++ b/docs/parity.md@@ -117,7 +117,7 @@ To move to a new Blender release, run `node scripts/parity-manual-snapshot.mjs`.| Modeling > Modifiers > Physics > Particle Instance Modifier | missing | No particle system. | | #63 || Modeling > Modifiers > Physics > Particle System Modifier | missing | No particle system. | | #63 || Modeling > Modifiers > Physics > Soft Body Modifier | missing | No soft bodies. | | #62 |-| Modeling > Modifiers > Geometry Nodes Modifier | partial | Bounded JSON field expressions drive `set_position`, `displace`, a `field` selection rule and `instances`. There is no node graph, no loops, no custom node groups, and no realize, curve or volume nodes. | [src/mesh-fields.js](../src/mesh-fields.js), [tests/mesh-fields.test.js](../tests/mesh-fields.test.js), [tests/blender-golden.test.js](../tests/blender-golden.test.js), [pillar-court task](../bench/agent-modeling/tasks.mjs) | #43 |+| Modeling > Modifiers > Geometry Nodes Modifier | partial | Bounded JSON field expressions drive `set_position`, `displace`, a `field` selection rule and `instances`; they share one evaluator, `src/expression.js`, with motion drivers. There is no node graph, no loops, no custom node groups, and no realize, curve or volume nodes. | [src/mesh-fields.js](../src/mesh-fields.js), [tests/mesh-fields.test.js](../tests/mesh-fields.test.js), [tests/blender-golden.test.js](../tests/blender-golden.test.js), [pillar-court task](../bench/agent-modeling/tasks.mjs) | #43 || Modeling > Geometry Nodes | partial | Fields over attributes, noise and math (position, normal, index, tags), Set Position, Instance on Points (grid, scatter, surface) and Displace. Noise is not Blender's noise function, and there is no Blender comparison for instancing. Issue #43 chose bounded JSON expressions and not a visual editor. | [src/mesh-fields.js](../src/mesh-fields.js), [tests/mesh-fields.test.js](../tests/mesh-fields.test.js), [tests/blender-golden.test.js](../tests/blender-golden.test.js) | #43 || Modeling > Transform | partial | Node transforms, and `translate` on a selection with falloff. There is no rotate or scale on a selection. | | || Sculpting & Painting > Brushes | out of scope | Brush settings for a hand. Strokes have explicit parameters. | | |@@ -139,7 +139,7 @@ To move to a new Blender release, run `node scripts/parity-manual-snapshot.mjs`.| Animation & Rigging > Lattice | missing | No lattice. | | #42 || Animation & Rigging > Constraints > Interface | out of scope | Interface for a mouse. | | || Animation & Rigging > Constraints > Motion Tracking | out of scope | Motion tracking is out of scope in issue #23. | | |-| Animation & Rigging > Constraints > Transform > Copy Location Constraint | partial | `copy_location` in `motion.constraints`: axes, invert, offset, world or local space, influence. Matches Blender where tested. | [agent-motion-constraints](../tests/agent-motion-constraints.test.js) | #58 |+| Animation & Rigging > Constraints > Transform > Copy Location Constraint | partial | `copy_location` in `motion.constraints`: axes, invert, offset, world or local space, influence. Matches Blender where tested. | [agent-motion-constraints](../tests/agent-motion-constraints.test.js), [src/expression.js](../src/expression.js) | #58, #98 || Animation & Rigging > Constraints > Transform > Copy Rotation Constraint | partial | `copy_rotation`: Euler axes, invert, replace or add, world or local. World matrices match Blender 5.2 in 2 cases. | [blender-constraints](../tests/blender-constraints.test.js) | #58 || Animation & Rigging > Constraints > Transform > Copy Scale Constraint | partial | `copy_scale`: axes and offset, world or local. | [agent-motion-constraints](../tests/agent-motion-constraints.test.js) | #58 || Animation & Rigging > Constraints > Transform > Copy Transforms Constraint | missing | No constraint. | | #58 |diff --git a/src/expression.js b/src/expression.jsnew file mode 100644index 00000000..a4eff30c--- /dev/null+++ b/src/expression.js@@ -0,0 +1,105 @@+// One bounded expression language, two dialects. An expression is JSON data, never code: it is read by walking plain+// objects against a fixed table of operators held in a Map, compiled once into closures and checked against its limits+// before anything runs. No string is executed or used as a property name.+//+// This module owns what both dialects share: the limits check, number literals, the walk, and the table of math+// operators with their operand counts. A dialect adds what only it has:+// - `src/mesh-fields.js`: element attributes, noise and vectors, evaluated once per mesh element.+// - `src/motion-expression.js`: motion time and node reads, evaluated once per sampled time.+//+// A compiled value is { kind: 'scalar', evaluate(argument) } or { kind: 'vector', parts: [evaluateX, evaluateY,+// evaluateZ] }. The argument is whatever the dialect evaluates over: an element index or a motion context. Only the+// field dialect makes vectors.+//+// A dialect is { maxNodes, maxDepth, messages: { nodes, depth, number }, reject(message, state), compileOther(node,+// state, depth) }. `reject` returns the Error to throw for a message. `state` holds `dialect` and `nodeCount` plus+// anything the dialect needs while compiling.++export const MAX_LITERAL = 1e6;+export const MAX_OPERANDS = 8;+export const COMPONENTS = Object.freeze({ x: 0, y: 1, z: 2 });++export const scalarValue = evaluate => ({ kind: 'scalar', evaluate });+export const constantScalar = number => scalarValue(() => number);+export const vectorValue = (partX, partY, partZ) => ({ kind: 'vector', parts: [partX, partY, partZ] });++export function partsOf(value) {+ return value.kind === 'vector' ? value.parts : [value.evaluate, value.evaluate, value.evaluate];+}++export function isBoundedNumber(value) {+ return typeof value === 'number' && Number.isFinite(value) && Math.abs(value) <= MAX_LITERAL;+}++/** Compile one node. Counts it, checks the limits and number literals, and hands every other node to the dialect. */+export function compileNode(node, state, depth) {+ const { dialect } = state;+ state.nodeCount += 1;+ if (state.nodeCount > dialect.maxNodes) throw dialect.reject(dialect.messages.nodes, state);+ if (depth > dialect.maxDepth) throw dialect.reject(dialect.messages.depth, state);+ if (typeof node === 'number') {+ if (!isBoundedNumber(node)) throw dialect.reject(dialect.messages.number, state);+ return constantScalar(node);+ }+ return dialect.compileOther(node, state, depth);+}++/**+ * The math operators both languages have, as pure functions of numbers with the operand counts they take. The two+ * languages disagree on the edge cases of a few of them, so each dialect passes its own `semantics`: divide, modulo,+ * power, squareRoot and smoothstep. A comparison gives 1 or 0. `if` is not here: what counts as true differs.+ */+export function createMathOperators({ divide, modulo, power, squareRoot, smoothstep }) {+ const entry = (min, max, compute) => ({ min, max, compute });+ return new Map([+ ['add', entry(2, MAX_OPERANDS, (left, right) => left + right)],+ ['mul', entry(2, MAX_OPERANDS, (left, right) => left * right)],+ ['min', entry(2, MAX_OPERANDS, Math.min)],+ ['max', entry(2, MAX_OPERANDS, Math.max)],+ ['sub', entry(2, 2, (left, right) => left - right)],+ ['div', entry(2, 2, divide)],+ ['mod', entry(2, 2, modulo)],+ ['pow', entry(2, 2, power)],+ ['clamp', entry(3, 3, (input, low, high) => Math.min(high, Math.max(low, input)))],+ ['mix', entry(3, 3, (start, end, fraction) => start + (end - start) * fraction)],+ ['smoothstep', entry(3, 3, smoothstep)],+ ['neg', entry(1, 1, number => -number)],+ ['abs', entry(1, 1, Math.abs)],+ ['sqrt', entry(1, 1, squareRoot)],+ ['sin', entry(1, 1, Math.sin)],+ ['cos', entry(1, 1, Math.cos)],+ ['floor', entry(1, 1, Math.floor)],+ ['fract', entry(1, 1, number => number - Math.floor(number))],+ ['lt', entry(2, 2, (left, right) => (left < right ? 1 : 0))],+ ['gt', entry(2, 2, (left, right) => (left > right ? 1 : 0))],+ ]);+}++/**+ * Turn an operator's pure function of numbers into a builder over compiled operands. A number operand gives a number.+ * Where an operand is a vector, the function runs on each component and a number is spread to all three.+ * Operators with more than three operands fold left to right: add, mul, min, max.+ */+export function buildLifted({ max, compute }) {+ const lifted = lift(compute);+ if (max <= 3) return lifted;+ return operands => operands.slice(1).reduce((total, next) => lifted([total, next]), operands[0]);+}++// Fixed-arity calls, not a spread: fields run this once per mesh element.+function applyAcross(compute, evaluators) {+ const [first, second, third] = evaluators;+ if (evaluators.length === 1) return argument => compute(first(argument));+ if (evaluators.length === 2) return argument => compute(first(argument), second(argument));+ return argument => compute(first(argument), second(argument), third(argument));+}++function lift(compute) {+ return operands => {+ if (operands.every(operand => operand.kind === 'scalar')) {+ return scalarValue(applyAcross(compute, operands.map(operand => operand.evaluate)));+ }+ const vectorPart = axis => applyAcross(compute, operands.map(operand => partsOf(operand)[axis]));+ return vectorValue(vectorPart(0), vectorPart(1), vectorPart(2));+ };+}diff --git a/src/mesh-fields.js b/src/mesh-fields.jsindex a5f074e5..dc85154d 100644--- a/src/mesh-fields.js+++ b/src/mesh-fields.js@@ -1,6 +1,10 @@import { TAG_PREFIX, meshTags } from './mesh-data.js';import { MAX_FIELD_NODES, MAX_FIELD_DEPTH, MAX_FIELD_ELEMENTS, MAX_FIELD_WORK, FIELD_ATTRIBUTES } from './mesh-operations.js';import { faceCentroids, faceNormals, vertexNormals } from './mesh-normals.js';+import {+ COMPONENTS, MAX_LITERAL, MAX_OPERANDS, buildLifted, compileNode, constantScalar, createMathOperators, isBoundedNumber, partsOf,+ scalarValue, vectorValue,+} from './expression.js';// Bounded field expressions: a small JSON language that computes one value per mesh element (a number, or a vector// of three numbers) from attributes, noise and math. Agents may be following instructions injected into their input,@@ -16,14 +20,12 @@ import { faceCentroids, faceNormals, vertexNormals } from './mesh-normals.js';// A number is a constant, true and false are 1 and 0, and an array of three numbers is a constant vector.// Scalar operators accept vectors and work on each component, with a scalar spread to all three.-const MAX_LITERAL = 1e6;const MAX_NOISE_OCTAVES = 4;const MAX_NOISE_SCALE = 1000;const MAX_SEED = 0x7fffffff;const MAX_REPORTED_KEY_LENGTH = 24;const TAG_NAME_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]{0,47}$/;const KIND_NAMES = Object.freeze({ scalar: 'number', vector: 'vector' });-const COMPONENTS = Object.freeze({ x: 0, y: 1, z: 2 });function fieldError(message) {return new TypeError(`Field expression: ${message}`);@@ -86,15 +88,8 @@ function fractalNoise(x, y, z, seed, octaves) {}// ----------------------------------------------------------------------------------------------------------------// Compiled values: { kind: 'scalar', evaluate(index) } or { kind: 'vector', parts: [evaluateX, evaluateY, evaluateZ] }.--const scalarValue = evaluate => ({ kind: 'scalar', evaluate });-const vectorValue = (partX, partY, partZ) => ({ kind: 'vector', parts: [partX, partY, partZ] });-const constantScalar = number => scalarValue(() => number);--function partsOf(value) {- return value.kind === 'vector' ? value.parts : [value.evaluate, value.evaluate, value.evaluate];-}+// Field operators: the math operators come from expression.js, lifted to vectors. What is here is the part only+// fields have: vectors, comparisons and logic that need numbers, and the safe edge cases that keep a value finite.function requireScalar(value, label) {if (value.kind !== 'scalar') throw fieldError(`${label} needs a number, not a vector.`);@@ -106,48 +101,26 @@ function requireVector(value, label) {return value.parts;}-function liftUnary(compute) {- return ([operand]) => {- if (operand.kind === 'scalar') return scalarValue(index => compute(operand.evaluate(index)));- const [partX, partY, partZ] = operand.parts;- return vectorValue(index => compute(partX(index)), index => compute(partY(index)), index => compute(partZ(index)));- };-}--function liftBinary(compute) {+function compareScalars(compute) {return ([left, right]) => {- if (left.kind === 'scalar' && right.kind === 'scalar') {- return scalarValue(index => compute(left.evaluate(index), right.evaluate(index)));- }- const [leftX, leftY, leftZ] = partsOf(left);- const [rightX, rightY, rightZ] = partsOf(right);- return vectorValue(- index => compute(leftX(index), rightX(index)),- index => compute(leftY(index), rightY(index)),- index => compute(leftZ(index), rightZ(index)),- );- };-}--function liftTernary(compute) {- return ([first, second, third]) => {- if (first.kind === 'scalar' && second.kind === 'scalar' && third.kind === 'scalar') {- return scalarValue(index => compute(first.evaluate(index), second.evaluate(index), third.evaluate(index)));- }- const [firstX, firstY, firstZ] = partsOf(first);- const [secondX, secondY, secondZ] = partsOf(second);- const [thirdX, thirdY, thirdZ] = partsOf(third);- return vectorValue(- index => compute(firstX(index), secondX(index), thirdX(index)),- index => compute(firstY(index), secondY(index), thirdY(index)),- index => compute(firstZ(index), secondZ(index), thirdZ(index)),- );+ const leftEvaluate = requireScalar(left, 'a comparison');+ const rightEvaluate = requireScalar(right, 'a comparison');+ return scalarValue(index => (compute(leftEvaluate(index), rightEvaluate(index)) ? 1 : 0));};}-function foldBinary(compute) {- const combine = liftBinary(compute);- return args => args.slice(1).reduce((total, next) => combine([total, next]), args[0]);+function branch([condition, whenTrue, whenFalse]) {+ const test = requireScalar(condition, 'if');+ const [trueX, trueY, trueZ] = partsOf(whenTrue);+ const [falseX, falseY, falseZ] = partsOf(whenFalse);+ if (whenTrue.kind === 'scalar' && whenFalse.kind === 'scalar') {+ return scalarValue(index => (test(index) !== 0 ? trueX(index) : falseX(index)));+ }+ return vectorValue(+ index => (test(index) !== 0 ? trueX(index) : falseX(index)),+ index => (test(index) !== 0 ? trueY(index) : falseY(index)),+ index => (test(index) !== 0 ? trueZ(index) : falseZ(index)),+ );}function finiteOrZero(number) {@@ -160,14 +133,6 @@ function smoothstep(edgeStart, edgeEnd, input) {return fraction * fraction * (3 - 2 * fraction);}-function compareScalars(compute) {- return ([left, right]) => {- const leftEvaluate = requireScalar(left, 'a comparison');- const rightEvaluate = requireScalar(right, 'a comparison');- return scalarValue(index => (compute(leftEvaluate(index), rightEvaluate(index)) ? 1 : 0));- };-}-function combineLogic(isAnd) {return args => {const evaluators = args.map(argument => requireScalar(argument, 'a logic operator'));@@ -231,73 +196,54 @@ function selectComponent(componentIndex) {return ([operand]) => scalarValue(requireVector(operand, 'a component read')[componentIndex]);}-function branch([condition, whenTrue, whenFalse]) {- const test = requireScalar(condition, 'if');- const [trueX, trueY, trueZ] = partsOf(whenTrue);- const [falseX, falseY, falseZ] = partsOf(whenFalse);- if (whenTrue.kind === 'scalar' && whenFalse.kind === 'scalar') {- return scalarValue(index => (test(index) !== 0 ? trueX(index) : falseX(index)));- }- return vectorValue(- index => (test(index) !== 0 ? trueX(index) : falseX(index)),- index => (test(index) !== 0 ? trueY(index) : falseY(index)),- index => (test(index) !== 0 ? trueZ(index) : falseZ(index)),- );-}+// Where the two dialects disagree, a field expression stays finite: a division by zero or the square root of a+// negative number gives 0 rather than an error.+const fieldSemantics = Object.freeze({+ divide: (left, right) => (right === 0 ? 0 : left / right),+ modulo: (left, right) => (right === 0 ? 0 : left - right * Math.floor(left / right)),+ power: (base, exponent) => finiteOrZero(Math.pow(base, exponent)),+ squareRoot: number => (number < 0 ? 0 : Math.sqrt(number)),+ smoothstep,+});++const fieldOperator = (min, max, build) => ({ min, max, build });+const unaryOperator = build => fieldOperator(1, 1, build);-// name -> { arguments: 'list' with min and max, or 'single', build(compiledArguments) }.// Operators live in a Map so that input keys such as "__proto__" or "constructor" are plain unknown names.-const LIST = 'list';-const SINGLE = 'single';-const OPERATORS = new Map([- ['add', { form: LIST, min: 2, max: 8, build: foldBinary((left, right) => left + right) }],- ['mul', { form: LIST, min: 2, max: 8, build: foldBinary((left, right) => left * right) }],- ['min', { form: LIST, min: 2, max: 8, build: foldBinary(Math.min) }],- ['max', { form: LIST, min: 2, max: 8, build: foldBinary(Math.max) }],- ['sub', { form: LIST, min: 2, max: 2, build: liftBinary((left, right) => left - right) }],- ['div', { form: LIST, min: 2, max: 2, build: liftBinary((left, right) => (right === 0 ? 0 : left / right)) }],- ['mod', { form: LIST, min: 2, max: 2, build: liftBinary((left, right) => (right === 0 ? 0 : left - right * Math.floor(left / right))) }],- ['pow', { form: LIST, min: 2, max: 2, build: liftBinary((base, exponent) => finiteOrZero(Math.pow(base, exponent))) }],- ['clamp', { form: LIST, min: 3, max: 3, build: liftTernary((input, low, high) => Math.min(high, Math.max(low, input))) }],- ['mix', { form: LIST, min: 3, max: 3, build: liftTernary((start, end, fraction) => start + (end - start) * fraction) }],- ['smoothstep', { form: LIST, min: 3, max: 3, build: liftTernary(smoothstep) }],- ['neg', { form: SINGLE, build: liftUnary(number => -number) }],- ['abs', { form: SINGLE, build: liftUnary(Math.abs) }],- ['sqrt', { form: SINGLE, build: liftUnary(number => (number < 0 ? 0 : Math.sqrt(number))) }],- ['sin', { form: SINGLE, build: liftUnary(Math.sin) }],- ['cos', { form: SINGLE, build: liftUnary(Math.cos) }],- ['floor', { form: SINGLE, build: liftUnary(Math.floor) }],- ['ceil', { form: SINGLE, build: liftUnary(Math.ceil) }],- ['round', { form: SINGLE, build: liftUnary(Math.round) }],- ['fract', { form: SINGLE, build: liftUnary(number => number - Math.floor(number)) }],- ['sign', { form: SINGLE, build: liftUnary(Math.sign) }],- ['lt', { form: LIST, min: 2, max: 2, build: compareScalars((left, right) => left < right) }],- ['lte', { form: LIST, min: 2, max: 2, build: compareScalars((left, right) => left <= right) }],- ['gt', { form: LIST, min: 2, max: 2, build: compareScalars((left, right) => left > right) }],- ['gte', { form: LIST, min: 2, max: 2, build: compareScalars((left, right) => left >= right) }],- ['eq', { form: LIST, min: 2, max: 2, build: compareScalars((left, right) => left === right) }],- ['and', { form: LIST, min: 2, max: 8, build: combineLogic(true) }],- ['or', { form: LIST, min: 2, max: 8, build: combineLogic(false) }],- ['not', { form: SINGLE, build: ([operand]) => {- const evaluate = requireScalar(operand, 'not');- return scalarValue(index => (evaluate(index) === 0 ? 1 : 0));- } }],- ['if', { form: LIST, min: 3, max: 3, build: branch }],- ['vec', { form: LIST, min: 3, max: 3, build: buildVector }],- ['dot', { form: LIST, min: 2, max: 2, build: dotValues }],- ['cross', { form: LIST, min: 2, max: 2, build: crossValues }],- ['distance', { form: LIST, min: 2, max: 2, build: distanceValues }],- ['length', { form: SINGLE, build: lengthValue }],- ['normalize', { form: SINGLE, build: normalizeValue }],- ['x', { form: SINGLE, build: selectComponent(0) }],- ['y', { form: SINGLE, build: selectComponent(1) }],- ['z', { form: SINGLE, build: selectComponent(2) }],-]);+const OPERATORS = new Map();+for (const [name, { min, max, compute }] of createMathOperators(fieldSemantics)) {+ const isComparison = name === 'lt' || name === 'gt';+ const build = isComparison ? compareScalars(compute) : buildLifted({ max, compute });+ OPERATORS.set(name, fieldOperator(min, max, build));+}+OPERATORS.set('if', fieldOperator(3, 3, branch));+for (const [name, compute] of [['ceil', Math.ceil], ['round', Math.round], ['sign', Math.sign]]) {+ OPERATORS.set(name, unaryOperator(buildLifted({ max: 1, compute })));+}+OPERATORS.set('lte', fieldOperator(2, 2, compareScalars((left, right) => left <= right)));+OPERATORS.set('gte', fieldOperator(2, 2, compareScalars((left, right) => left >= right)));+OPERATORS.set('eq', fieldOperator(2, 2, compareScalars((left, right) => left === right)));+OPERATORS.set('and', fieldOperator(2, MAX_OPERANDS, combineLogic(true)));+OPERATORS.set('or', fieldOperator(2, MAX_OPERANDS, combineLogic(false)));+OPERATORS.set('not', unaryOperator(([operand]) => {+ const evaluate = requireScalar(operand, 'not');+ return scalarValue(index => (evaluate(index) === 0 ? 1 : 0));+}));+OPERATORS.set('vec', fieldOperator(3, 3, buildVector));+OPERATORS.set('dot', fieldOperator(2, 2, dotValues));+OPERATORS.set('cross', fieldOperator(2, 2, crossValues));+OPERATORS.set('distance', fieldOperator(2, 2, distanceValues));+OPERATORS.set('length', unaryOperator(lengthValue));+OPERATORS.set('normalize', unaryOperator(normalizeValue));+OPERATORS.set('x', unaryOperator(selectComponent(0)));+OPERATORS.set('y', unaryOperator(selectComponent(1)));+OPERATORS.set('z', unaryOperator(selectComponent(2)));export { MAX_FIELD_NODES, MAX_FIELD_DEPTH, MAX_FIELD_ELEMENTS, MAX_FIELD_WORK };const SOURCE_KEYS = Object.freeze(['attr', 'noise', 'random']);export const FIELD_OPERATORS = Object.freeze([...OPERATORS.keys(), ...SOURCE_KEYS]);+// ---------------------------------------------------------------------------------------------------------------// Compiling an expression against an element context: { count, positions(), normals(), tag(name) }.@@ -365,7 +311,7 @@ function compileRandom(node) {function compileOperator(operator, name, operand, state, depth) {let compiledArguments;- if (operator.form === SINGLE) {+ if (operator.max === 1) {compiledArguments = [compileNode(operand, state, depth + 1)];} else {if (!Array.isArray(operand) || operand.length < operator.min || operand.length > operator.max) {@@ -376,17 +322,10 @@ function compileOperator(operator, name, operand, state, depth) {return operator.build(compiledArguments);}-function compileNode(node, state, depth) {- state.nodeCount++;- if (state.nodeCount > MAX_FIELD_NODES) throw fieldError(`more than ${MAX_FIELD_NODES} nodes.`);- if (depth > MAX_FIELD_DEPTH) throw fieldError(`nesting deeper than ${MAX_FIELD_DEPTH}.`);- if (typeof node === 'number') {- if (!Number.isFinite(node) || Math.abs(node) > MAX_LITERAL) throw fieldError(`numbers must be finite and within ${MAX_LITERAL}.`);- return constantScalar(node);- }+function compileOther(node, state, depth) {if (typeof node === 'boolean') return constantScalar(node ? 1 : 0);if (Array.isArray(node)) {- if (node.length !== 3 || !node.every(component => typeof component === 'number' && Number.isFinite(component) && Math.abs(component) <= MAX_LITERAL)) {+ if (node.length !== 3 || !node.every(isBoundedNumber)) {throw fieldError('a vector literal is three finite numbers; build one from expressions with "vec".');}const [literalX, literalY, literalZ] = node;@@ -404,13 +343,25 @@ function compileNode(node, state, depth) {return compileOperator(operator, name, node[name], state, depth);}+const FIELD_DIALECT = Object.freeze({+ maxNodes: MAX_FIELD_NODES,+ maxDepth: MAX_FIELD_DEPTH,+ messages: Object.freeze({+ nodes: `more than ${MAX_FIELD_NODES} nodes.`,+ depth: `nesting deeper than ${MAX_FIELD_DEPTH}.`,+ number: `numbers must be finite and within ${MAX_LITERAL}.`,+ }),+ reject: fieldError,+ compileOther,+});+/*** Compile an expression against a context. The context is { count, positions(), normals(), tag(name) }, or null to* only validate. Limits on nodes, depth and elements are enforced here, before any element is evaluated.* Returns { kind, nodeCount, evaluate(index), parts }.*/export function compileField(expression, context = null) {- const state = { nodeCount: 0, context: context ?? VALIDATION_CONTEXT };+ const state = { dialect: FIELD_DIALECT, nodeCount: 0, context: context ?? VALIDATION_CONTEXT };const compiled = compileNode(expression, state, 0);if (context) {if (context.count > MAX_FIELD_ELEMENTS) throw new RangeError(`Field expression: ${context.count} elements is over the limit of ${MAX_FIELD_ELEMENTS}.`);diff --git a/src/motion-expression.js b/src/motion-expression.jsindex 7af2215a..3ad11596 100644--- a/src/motion-expression.js+++ b/src/motion-expression.js@@ -1,8 +1,12 @@import { denseArray, knownKeys } from './motion-validation.js';+import {+ COMPONENTS, MAX_LITERAL, MAX_OPERANDS, buildLifted, compileNode, createMathOperators, scalarValue,+} from './expression.js';// Bounded motion expressions: a small JSON language for drivers and constraint influence. An expression is data, never// code. It is read by walking plain objects against a fixed table of operators, compiled once into closures and checked// against its limits before anything runs. No string is executed, and operator names come from a Map.+// This is the motion dialect of the one expression language in expression.js; mesh-fields.js is the field dialect.//// { "mul": [{ "node": "wheel", "property": "rotation", "component": "x" }, 0.01] }// { "clamp": [{ "mul": ["time", 0.5] }, 0, 1] }@@ -15,98 +19,86 @@ import { denseArray, knownKeys } from './motion-validation.js';export const MAX_EXPRESSION_NODES = 64;export const MAX_EXPRESSION_DEPTH = 8;-const MAX_LITERAL = 1e6;-const MAX_OPERANDS = 8;-const COMPONENTS = Object.freeze({ x: 0, y: 1, z: 2 });const READ_PROPERTIES = ['translation', 'rotation', 'scale'];+const OPERAND_COUNT_TEXT = new Map([[1, 'one operand'], [2, 'two operands'], [3, 'three operands']]);-const smoothstep = (low, high, value) => {- const fraction = Math.min(1, Math.max(0, (value - low) / (high - low)));- return fraction * fraction * (3 - 2 * fraction);-};+// Where the two dialects disagree, a motion expression keeps plain arithmetic: a division by zero or the square root+// of a negative number gives a non-finite value, which `evaluate` rejects instead of hiding it as the field dialect does.+const motionSemantics = Object.freeze({+ divide: (left, right) => left / right,+ modulo: (left, right) => left - right * Math.floor(left / right),+ power: Math.pow,+ squareRoot: Math.sqrt,+ smoothstep: (low, high, value) => {+ const fraction = Math.min(1, Math.max(0, (value - low) / (high - low)));+ return fraction * fraction * (3 - 2 * fraction);+ },+});-const UNARY = new Map([- ['neg', value => -value], ['abs', Math.abs], ['sin', Math.sin], ['cos', Math.cos], ['sqrt', Math.sqrt],- ['floor', Math.floor], ['fract', value => value - Math.floor(value)], ['saturate', value => Math.min(1, Math.max(0, value))],-]);-const VARIADIC = new Map([- ['add', (left, right) => left + right], ['mul', (left, right) => left * right], ['min', Math.min], ['max', Math.max],-]);-const BINARY = new Map([- ['sub', (left, right) => left - right], ['div', (left, right) => left / right], ['pow', Math.pow],- ['mod', (left, right) => left - right * Math.floor(left / right)], ['atan2', Math.atan2],- ['gt', (left, right) => (left > right ? 1 : 0)], ['lt', (left, right) => (left < right ? 1 : 0)],-]);-const TERNARY = new Map([- ['clamp', (value, low, high) => Math.min(high, Math.max(low, value))],- ['mix', (start, end, fraction) => start + (end - start) * fraction],- ['smoothstep', smoothstep],- ['if', (condition, thenValue, otherwiseValue) => (condition > 0 ? thenValue : otherwiseValue)],-]);+const OPERATORS = createMathOperators(motionSemantics);+OPERATORS.set('saturate', { min: 1, max: 1, compute: value => Math.min(1, Math.max(0, value)) });+OPERATORS.set('atan2', { min: 2, max: 2, compute: Math.atan2 });+OPERATORS.set('if', { min: 3, max: 3, compute: (condition, thenValue, otherwiseValue) => (condition > 0 ? thenValue : otherwiseValue) });-function compileRead(input, state, label) {+function describeOperandCount(operator) {+ if (operator.min === operator.max) return OPERAND_COUNT_TEXT.get(operator.min);+ return `${operator.min} to ${operator.max} operands`;+}++function compileRead(input, state) {+ const { label, nodeIds } = state;knownKeys(input, ['node', 'property', 'component', 'space'], `${label} node read`);- if (!state.nodeIds.has(input.node)) throw new RangeError(`${label}: node ${JSON.stringify(input.node)} is not in this scene.`);+ if (!nodeIds.has(input.node)) throw new RangeError(`${label}: node ${JSON.stringify(input.node)} is not in this scene.`);if (!READ_PROPERTIES.includes(input.property)) throw new RangeError(`${label}: property must be translation, rotation or scale.`);if (!Object.hasOwn(COMPONENTS, input.component)) throw new RangeError(`${label}: component must be x, y or z.`);const space = input.space ?? 'local';if (space !== 'local' && space !== 'world') throw new RangeError(`${label}: space must be local or world.`);state.reads.add(input.node);const component = COMPONENTS[input.component];- return context => context.read(input.node, input.property, component, space);+ return scalarValue(context => context.read(input.node, input.property, component, space));}-function compileOperator(input, state, depth, label) {+function compileOperator(input, state, depth) {+ const { label } = state;const keys = Object.keys(input);if (keys.length !== 1) throw new TypeError(`${label}: an operator object has exactly one key, such as {"add": [1, 2]}.`);const [name] = keys;- const operands = denseArray(input[name], MAX_OPERANDS, `${label} ${name} operands`).map(operand => compile(operand, state, depth + 1, label));- const arity = (count, text) => {- if (operands.length !== count) throw new RangeError(`${label}: ${name} takes ${text}.`);- };- if (UNARY.has(name)) {- arity(1, 'one operand');- const compute = UNARY.get(name);- return context => compute(operands[0](context));- }- if (VARIADIC.has(name)) {- if (operands.length < 2) throw new RangeError(`${label}: ${name} takes 2 to ${MAX_OPERANDS} operands.`);- const compute = VARIADIC.get(name);- return context => operands.slice(1).reduce((total, operand) => compute(total, operand(context)), operands[0](context));+ const operands = denseArray(input[name], MAX_OPERANDS, `${label} ${name} operands`).map(operand => compileNode(operand, state, depth + 1));+ const operator = OPERATORS.get(name);+ if (!operator) throw new RangeError(`${label}: unknown operator ${JSON.stringify(name.slice(0, 24))}.`);+ if (operands.length < operator.min || operands.length > operator.max) {+ throw new RangeError(`${label}: ${name} takes ${describeOperandCount(operator)}.`);}- if (BINARY.has(name)) {- arity(2, 'two operands');- const compute = BINARY.get(name);- return context => compute(operands[0](context), operands[1](context));- }- if (TERNARY.has(name)) {- arity(3, 'three operands');- const compute = TERNARY.get(name);- return context => compute(operands[0](context), operands[1](context), operands[2](context));- }- throw new RangeError(`${label}: unknown operator ${JSON.stringify(name.slice(0, 24))}.`);+ return buildLifted(operator)(operands);}-function compile(input, state, depth, label) {- state.count += 1;- if (state.count > MAX_EXPRESSION_NODES) throw new RangeError(`${label} has more than ${MAX_EXPRESSION_NODES} parts.`);- if (depth > MAX_EXPRESSION_DEPTH) throw new RangeError(`${label} nests deeper than ${MAX_EXPRESSION_DEPTH} levels.`);- if (typeof input === 'number') {- if (!Number.isFinite(input) || Math.abs(input) > MAX_LITERAL) throw new RangeError(`${label}: a number must be finite and within ${MAX_LITERAL}.`);- return () => input;+function compileOther(input, state, depth) {+ if (input === 'time') return scalarValue(context => context.time);+ if (!input || Object.getPrototypeOf(input) !== Object.prototype) {+ throw new TypeError(`${state.label}: use a number, "time", a node read or an operator object.`);}- if (input === 'time') return context => context.time;- if (!input || Object.getPrototypeOf(input) !== Object.prototype) throw new TypeError(`${label}: use a number, "time", a node read or an operator object.`);- return Object.hasOwn(input, 'node') ? compileRead(input, state, label) : compileOperator(input, state, depth, label);+ return Object.hasOwn(input, 'node') ? compileRead(input, state) : compileOperator(input, state, depth);}+const MOTION_DIALECT = Object.freeze({+ maxNodes: MAX_EXPRESSION_NODES,+ maxDepth: MAX_EXPRESSION_DEPTH,+ messages: Object.freeze({+ nodes: ` has more than ${MAX_EXPRESSION_NODES} parts.`,+ depth: ` nests deeper than ${MAX_EXPRESSION_DEPTH} levels.`,+ number: `: a number must be finite and within ${MAX_LITERAL}.`,+ }),+ reject: (message, state) => new RangeError(`${state.label}${message}`),+ compileOther,+});+/*** Compile an expression. `evaluate({ time, read })` returns a finite number; `read(id, property, component, space)`* supplies node values. `reads` lists the node IDs the expression looks at.*/export function compileMotionExpression(input, nodeIds, label) {- const state = { count: 0, reads: new Set(), nodeIds };- const evaluateTree = compile(input, state, 0, label);+ const state = { dialect: MOTION_DIALECT, nodeCount: 0, label, nodeIds, reads: new Set() };+ const { evaluate: evaluateTree } = compileNode(input, state, 0);return Object.freeze({reads: [...state.reads],evaluate(context) {