3D engine that AI agents drive
Add Poisson spacing, density, variants, per-point fields and mesh points to instances (issue #698)
Nguyen Xuan Anbca332a8b48e
diff --git a/changes/698-instancing.md b/changes/698-instancing.mdnew file mode 100644index 00000000..2201e447--- /dev/null+++ b/changes/698-instancing.md@@ -0,0 +1 @@+- Instancing: `instances` takes a `place` record with Poisson-disk `spacing`, a `density` field, `variants` of geometry and material picked at random or by a `variant` field, per-point `rotation` and `size` fields, and `at: "vertices"` or `"faces"` on a surface source to place on a mesh's own vertices and face centres. All of it is seeded (#698).diff --git a/changes/698-instancing.size.md b/changes/698-instancing.size.mdnew file mode 100644index 00000000..31992e0e--- /dev/null+++ b/changes/698-instancing.size.md@@ -0,0 +1 @@+- scene:agent-scene+lazy: the placement module (Poisson spacing, density, variants, rotation and size fields, vertex and face points) loads only with instances, so scenes without them do not pay.diff --git a/docs/agent-scene.md b/docs/agent-scene.mdindex 38de2245..665c67ec 100644--- a/docs/agent-scene.md+++ b/docs/agent-scene.md@@ -262,6 +262,23 @@ dropped. `curve` is `{ points, count, closed, fillet }`: `count` points at equalis a random uniform `[min, max]`. At most 2048 candidate points per node, and the scene's node limit still applies.The group's own scale applies to the spacing and the points, because they are in its space.+`place` shapes the points once the source made them, and every choice is seeded and repeatable:++```text+"place": { "spacing": 1.4,+ "density": { "saturate": { "sub": [1.4, { "mul": [0.1, { "length": [{ "attr": "position" }] }] }] } },+ "variants": ["rockRound", "rockTall", { "geometry": "rockBlock", "material": "moss" }],+ "size": { "vec": [1, { "add": [0.6, { "mul": [0.5, { "fract": { "mul": [{ "attr": "index" }, 0.37] } }] }] }, 1] } }+```++- `spacing`: Poisson-disk minimum distance. Points are kept in order, so a point is dropped when a kept one is closer; give enough candidates (`count`) to fill the area. Runs after `where` and `density`.+- `density`: number field, the chance (0 to 1) that a point stays. Same seed, same points.+- `variants`: 1 to 16 geometry ids or `{ geometry, material }`. Each point takes one at random, or the one `variant` (a number field, rounded down and wrapped) names. The node needs only a material when it lists variants.+- `rotation`: vector field of extra Euler angles in radians, turned after `yaw` and `alignToNormal`. `size`: number or vector field, a scale per point, multiplied by the `scale` range and kept from 0.001 to 1000.+- `at`: with a `surface` source, `"vertices"` (welded by position) or `"faces"` (centres, normal of the face) place on the mesh itself; `count` is then the most points allowed, and more is an error.++Not yet: realizing the instances into one mesh.+### Placed catalog assetsA node with an `asset` field places a GLB from the `--assets` catalog inside the recipe, so one scene holds terrain, lights, procedural meshes and imported models (`scene_create_asset` opens one asset alone). The node is a group: its transform places the asset, and its parts become generated child nodes named `<node>/<part index>` that `scene_inspect` and `scene_export_recipe` leave out.diff --git a/docs/parity.md b/docs/parity.mdindex 8e15b374..569ce9a1 100644--- a/docs/parity.md+++ b/docs/parity.md@@ -81,7 +81,7 @@ To move to a new Blender release, run `node scripts/parity-manual-snapshot.mjs`.| Modeling > Modifiers > Generate > Mirror Modifier | done | Stack node with axis and merge. | [mesh-stack](../tests/mesh-stack.test.js), [Blender results](../tests/fixtures/blender/golden.json) | || Modeling > Modifiers > Generate > Multiresolution Modifier | missing | No multiresolution. | | || Modeling > Modifiers > Generate > Remesh Modifier | partial | Voxel mode as `remesh` (voxel size or resolution), as an edit or a stack node, compared with Blender on 2 shared fixtures. Blocks, smooth and sharp modes are missing. | [blender golden](../tests/blender-golden.test.js), [decimate](../tests/mesh-decimate.test.js) | #40 |-| Modeling > Modifiers > Generate > Scatter on Surface Modifier | partial | `instances` with a `surface` source scatters a node at seeded, area-weighted points with yaw, scale and normal alignment, and `where` filters them. Its `where` can read a path mesh with `nearest` and a terrain with `raycast`. No minimum distance or density map, and `addons/clutter` and `addons/grass` still scatter in code. | [src/mesh-instances.js](../src/mesh-instances.js), [tests/mesh-fields.test.js](../tests/mesh-fields.test.js) | #42 |+| Modeling > Modifiers > Generate > Scatter on Surface Modifier | partial | `instances` with a `surface` source scatters a node at seeded, area-weighted points with yaw, scale and normal alignment, and `where` filters them. Its `where` can read a path mesh with `nearest` and a terrain with `raycast`. `place` adds Poisson spacing, a density field, variants, per-point rotation and size fields, and vertex or face-centre points. Instances are not realized into one mesh, and `addons/clutter` and `addons/grass` still scatter in code. | [src/mesh-instances.js](../src/mesh-instances.js), [tests/mesh-fields.test.js](../tests/mesh-fields.test.js), [tests/mesh-instance-placement.test.js](../tests/mesh-instance-placement.test.js) | #42, #698 || Modeling > Modifiers > Generate > Screw Modifier | partial | `screw` edit and stack node revolves every edge of the mesh about x, y or z with `angle`, `steps`, `iterations` and a `lift` along the axis; a whole number of turns closes the ring. Counts, area and positions match Blender on 2 cases (the volume of the open strips differs by winding). No merge option, no object axis, no normal calculation and no separate render steps. `lathe` stays the way to revolve a profile. | [mesh-generator-modifiers](../tests/mesh-generator-modifiers.test.js), [Blender results](../tests/fixtures/blender/golden.json) | #42 || Modeling > Modifiers > Generate > Skin Modifier | partial | `skin` edit and stack node: a square tube on every edge of the mesh, radius a number or a scalar field per vertex, closed by end caps. Simple version: tubes that meet overlap, there is no branch solver, no loose ends marking and no Blender comparison. | [mesh-generator-modifiers](../tests/mesh-generator-modifiers.test.js) | #42 || Modeling > Modifiers > Generate > Solidify Modifier | done | Stack node with thickness, offset and even thickness. | [mesh-stack](../tests/mesh-stack.test.js), [Blender results](../tests/fixtures/blender/golden.json) | |@@ -120,7 +120,10 @@ To move to a new Blender release, run `node scripts/parity-manual-snapshot.mjs`.| Modeling > Modifiers > Physics > Particle System Modifier | partial | Recipe `particles`: seeded emitters (point, box, sphere, disc) with gravity, drag, wind, a floor and size over life, and hair strands from a surface. A seek is a closed-form evaluation, so it repeats exactly. Force fields (`fields`), collision with chosen static meshes and the floor with bounce and friction, spin, color and alpha over life (a fade to black; no per-vertex alpha), no children or hair dynamics, and no comparison against Blender was run. See docs/physics.md. | [particles](../tests/particles.test.js) | #63 || Modeling > Modifiers > Physics > Soft Body Modifier | missing | Not built: a closed mesh needs volume or shape-matching constraints, closed-mesh input checks and a recipe field with schema and capability text, which was not measured to fit the 1.5 KB gzip limit. | | #62 || Modeling > Modifiers > Geometry Nodes Modifier | partial | Bounded JSON field expressions drive `set_position`, `displace`, a `field` selection rule and `instances`; they are one language, `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 > Geometry Nodes | partial | Fields over attributes, noise and math (position, normal, index, tags), Set Position, Instance on Points (grid, scatter, surface, curve, with Poisson spacing, density, variants, rotation and scale fields) 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 |+| Geometry Nodes > Distribute Points on Faces (Poisson Disk, density) | partial | `instances` `place.spacing` thins any source with a seeded Poisson-disk dart throw and `place.density` keeps points by a field. It thins random candidates, not Blender's algorithm, so counts differ from Blender for the same area. No Blender comparison. | [tests/mesh-instance-placement.test.js](../tests/mesh-instance-placement.test.js) | #698 |+| Geometry Nodes > Curve to Points, Mesh to Points, Instance on Points (pick instance, rotation, scale) | partial | Points come from a curve (count), mesh vertices and face centres (`place.at`); `place.variants` with `variant`, `place.rotation` and `place.size` are fields per point. Curve points are by count, not by length; vertices and faces are the whole mesh, filtered by `where`. | [tests/mesh-instance-placement.test.js](../tests/mesh-instance-placement.test.js) | #698 |+| Geometry Nodes > Realize Instances | missing | Instances stay child nodes drawn as one batch; they are not merged into a mesh that edits or booleans can use. | | #698 || 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. | | || Sculpting & Painting > Selection & Visibility | out of scope | Interface for a person in a paint mode. | | |diff --git a/scripts/mcp-server.mjs b/scripts/mcp-server.mjsindex 6e657d68..a20190ff 100644--- a/scripts/mcp-server.mjs+++ b/scripts/mcp-server.mjs@@ -75,6 +75,7 @@ const instanceSpec = z.strictObject({curve: z.strictObject({ points: z.array(vector3).min(2).max(256), count: instanceCount, closed: z.boolean().optional(), fillet: z.number().positive().optional() }).optional().describe('Equal steps along a polyline; fillet is a corner radius.'),seed: z.number().int().min(0).max(2147483647).optional(),where: fieldExpression.optional().describe('Number expression over the points (position, normal, index); points where it is 0 are dropped.'),+ place: z.record(z.string(), z.unknown()).optional().describe('scene_capabilities instancing.'),yaw: z.boolean().optional().describe('Random turn about up.'),alignToNormal: z.boolean().optional().describe('Surface or curve: turn up to the normal or direction.'),scale: z.tuple([z.number().min(0.001).max(1000), z.number().min(0.001).max(1000)]).optional().describe('Random uniform scale range [min, max].'),diff --git a/src/agent-scene-capabilities.js b/src/agent-scene-capabilities.jsindex 72952b94..088bc274 100644--- a/src/agent-scene-capabilities.js+++ b/src/agent-scene-capabilities.js@@ -161,18 +161,18 @@ export const MESH_MODIFIER_NOTES = Object.freeze({// Vertex colors and groups. Details stay here so the tool schemas stay small.export const MESH_ATTRIBUTE_NOTES = Object.freeze({- vertex_group: 'name (required) sets the weights 0-1 of the vertices of the selected faces; the rest keep theirs (0 in a new group). One of weight (1), field (number expression) or gradient { axis x|y|z, range [low, high], weights [atLow, atHigh] }. Max 32 groups. displace takes group: name and scales each move by the weight; cloth takes pinGroup. Put it after shape edits: a stack node that rebuilds the mesh drops groups.',+ vertex_group: 'name (required) sets the weights 0-1 of the vertices of the selected faces; the rest keep theirs. One of weight (1), field or gradient { axis x|y|z, range [low, high], weights [atLow, atHigh] }. Max 32 groups. displace takes group: name and scales each move by the weight; cloth takes pinGroup. A stack node that rebuilds the mesh drops groups.',vertex_color: 'sets the corner colors (0-1, linear, white until set) of the selected faces. One of color [r, g, b], field (vector expression of the vertex) or gradient { axis, range [low, high], colors [[r,g,b] atLow, [r,g,b] atHigh] }. Drawn, written as COLOR_0 in a GLB, and multiplies the material color.',});// Shape keys on a recipe mesh. Details stay here so the tool schemas stay small.export const MESH_SHAPE_KEY_NOTES = Object.freeze({- shapeKeys: 'On a mesh geometry, at most 16: { name, offsets, value } or { name, edits, value }. offsets is a list of { select, offset: [x,y,z], falloff } moves like the translate edit; edits are mesh edits that only move vertices run on the finished mesh, after the stack. value (0, from 0 to 1) is the weight without motion. Each key becomes a glTF morph target. Animate it with a motion track { kind: "morph", id: <key name>, property: "weight", keyframes }; a GLB export writes targets, names (mesh.extras.targetNames) and weights.',+ shapeKeys: 'On a mesh geometry, at most 16: { name, offsets, value } or { name, edits, value }. offsets is a list of { select, offset: [x,y,z], falloff } moves like the translate edit; edits are mesh edits that only move vertices run on the finished mesh, after the stack. value (0 to 1, default 0) is the weight. Each key becomes a glTF morph target. Animate it with a motion track { kind: "morph", id: <key name>, property: "weight", keyframes }; a GLB export writes them.',});// Organic shaping edits. Details stay here so the tool schemas stay small.export const MESH_SCULPT_NOTES = Object.freeze({- sculpt: 'strokes run in order on the vertices of the selected faces; other vertices stay, so a tag confines them. A stroke has type inflate (along the vertex normal), displace (along direction, needed) or smooth (strength 0 to 1), center and radius, strength in mesh units (negative pushes in). Falloff is smooth to zero at the radius.',+ sculpt: 'strokes run in order on the vertices of the selected faces; other vertices stay, so a tag confines them. A stroke has type inflate (along the vertex normal), displace (along direction, needed) or smooth (strength 0 to 1), center and radius, strength in mesh units (negative pushes in).',shrinkwrap: 'target is a primitive record placed by translation, rotation and scale. mode nearest (default) moves each selected vertex to the closest point; project moves it along direction (needed) to the first hit. offset (default 0) stands it off along the normal, on the side it came from. maxDistance limits the search; onMiss error (default) or keep. For a decal, use enough grid cells to follow the curve, then solidify.',});@@ -195,7 +195,10 @@ export const AGENT_SCENE_CAPABILITIES = Object.freeze({rotation: 'rotate [v, axis, rad]; align [dir]: Euler of +Y to dir; transform [p, move, euler, size].',surfaces: 'nearest {surface, at, read distance|point|normal}; raycast {surface, at, direction, read hit|distance|point|normal, miss}. at defaults to position; rays go forward. surface: geometry id (instances where) or record (mesh edits). attr group + name reads a vertex group.',}),- instancing: Object.freeze({ sources: INSTANCE_SOURCES, maxCandidatePoints: MAX_INSTANCE_CANDIDATES }),+ instancing: Object.freeze({+ sources: INSTANCE_SOURCES, maxCandidatePoints: MAX_INSTANCE_CANDIDATES,+ place: 'place {at vertices|faces, spacing, density 0-1, variants [id|{geometry, material}], variant, rotation Euler, size}; the last are fields.',+ }),operations: Object.freeze(['set-node', 'set-material', 'set-camera', 'add-node', 'remove-node','add-geometry', 'remove-geometry', 'add-material', 'remove-material',diff --git a/src/mesh-instance-placement.js b/src/mesh-instance-placement.jsnew file mode 100644index 00000000..9486332c--- /dev/null+++ b/src/mesh-instance-placement.js@@ -0,0 +1,156 @@+import { quat } from 'gl-matrix';+import { seededRandom } from './mesh-fields.js';++// The `place` record of an `instances` spec: what keeps, shapes and varies the points once a source made them.+//+// "place": { "at": "vertices" | "faces", surface source only: the vertices or face centres, not random points+// "spacing": 0.8, Poisson-disk minimum distance between kept points+// "density": <number field>, chance 0..1 that a point stays+// "variants": ["rockA", "rockB", { "geometry": "rockC", "material": "moss" }],+// "variant": <number field>, index into variants (rounded down, wrapped); default seeded random+// "rotation": <vector field>, extra Euler turn, radians, X then Y then Z+// "size": <number or vector field> } scale per point; multiplies the `scale` range+//+// Every choice is a pure function of the point index and the seed, so a scene builds the same way each time.++export const PLACE_FIELDS = Object.freeze(['at', 'spacing', 'density', 'variants', 'variant', 'rotation', 'size']);+export const MAX_VARIANTS = 16;+const MAX_SPACING = 1e6;+const MIN_SIZE = 0.001;+const MAX_SIZE = 1000;+const WELD_DIGITS = 1e5;++const CHANNEL_DENSITY = 40;+const CHANNEL_VARIANT = 41;++function placeError(message) {+ return new TypeError(`Instances: place ${message}`);+}++/** Check a `place` record and return it normalised; throws a TypeError that names the field. */+export function checkedPlace(place) {+ if (place === undefined) return {};+ if (!place || typeof place !== 'object' || Array.isArray(place)) throw placeError('must be an object.');+ for (const key of Object.keys(place)) {+ if (!PLACE_FIELDS.includes(key)) throw placeError(`does not take ${JSON.stringify(key.slice(0, 24))}; fields: ${PLACE_FIELDS.join(', ')}.`);+ }+ if (place.at !== undefined && place.at !== 'vertices' && place.at !== 'faces') throw placeError('at is "vertices" or "faces".');+ if (place.spacing !== undefined && !(typeof place.spacing === 'number' && place.spacing > 0 && place.spacing <= MAX_SPACING)) {+ throw placeError('spacing is a distance above 0.');+ }+ if (place.variant !== undefined && place.variants === undefined) throw placeError('variant needs a variants list.');+ const variants = place.variants === undefined ? null : variantList(place.variants);+ return { ...place, variants };+}++function variantList(entries) {+ if (!Array.isArray(entries) || entries.length < 1 || entries.length > MAX_VARIANTS) throw placeError(`variants is 1 to ${MAX_VARIANTS} entries.`);+ return entries.map(entry => {+ const record = typeof entry === 'string' ? { geometry: entry } : entry;+ const valid = record && typeof record === 'object' && !Array.isArray(record)+ && typeof record.geometry === 'string' && (record.material === undefined || typeof record.material === 'string')+ && Object.keys(record).every(key => key === 'geometry' || key === 'material');+ if (!valid) throw placeError('variants entries are a geometry id or { geometry, material }.');+ return record;+ });+}++/** Deduplicated vertices (by position) or face centres of a render geometry, with normals. */+export function meshPoints(geometry, at, limit) {+ const positions = [];+ const normals = [];+ if (at === 'vertices') {+ const seen = new Set();+ for (let vertex = 0; vertex < geometry.positions.length / 3; vertex++) {+ const offset = vertex * 3;+ const key = [0, 1, 2].map(axis => Math.round(geometry.positions[offset + axis] * WELD_DIGITS)).join(',');+ if (seen.has(key)) continue;+ seen.add(key);+ positions.push(geometry.positions[offset], geometry.positions[offset + 1], geometry.positions[offset + 2]);+ normals.push(geometry.normals[offset], geometry.normals[offset + 1], geometry.normals[offset + 2]);+ }+ } else {+ for (let triangle = 0; triangle < geometry.indices.length / 3; triangle++) {+ const corners = [0, 1, 2].map(corner => geometry.indices[triangle * 3 + corner] * 3);+ const centre = [0, 1, 2].map(axis => corners.reduce((sum, corner) => sum + geometry.positions[corner + axis], 0) / 3);+ const edgeOne = [0, 1, 2].map(axis => geometry.positions[corners[1] + axis] - geometry.positions[corners[0] + axis]);+ const edgeTwo = [0, 1, 2].map(axis => geometry.positions[corners[2] + axis] - geometry.positions[corners[0] + axis]);+ const facing = [+ edgeOne[1] * edgeTwo[2] - edgeOne[2] * edgeTwo[1],+ edgeOne[2] * edgeTwo[0] - edgeOne[0] * edgeTwo[2],+ edgeOne[0] * edgeTwo[1] - edgeOne[1] * edgeTwo[0],+ ];+ const length = Math.hypot(...facing);+ if (length === 0) continue;+ positions.push(...centre);+ normals.push(...facing.map(component => component / length));+ }+ }+ if (positions.length / 3 > limit) throw placeError(`at "${at}" found ${positions.length / 3} points; raise the surface count to ${limit} or more.`);+ return { positions: Float64Array.from(positions), normals: Float64Array.from(normals) };+}++/** Keep each point with the chance its density value gives. */+export function thinByDensity(indices, densities, seed) {+ return indices.filter(index => seededRandom(index, CHANNEL_DENSITY, seed) < densities[index]);+}++/**+ * Poisson-disk thinning by dart throwing: walk the points in order and keep one when no kept point is closer than+ * `spacing`. A hash grid with cells of the spacing keeps the check to the 27 nearby cells.+ */+export function thinBySpacing(indices, positions, spacing) {+ const cells = new Map();+ const cellOf = (index, axis) => Math.floor(positions[index * 3 + axis] / spacing);+ const kept = [];+ for (const index of indices) {+ const cell = [cellOf(index, 0), cellOf(index, 1), cellOf(index, 2)];+ if (!crowded(cells, cell, positions, index, spacing)) {+ kept.push(index);+ const key = cell.join(',');+ if (!cells.has(key)) cells.set(key, []);+ cells.get(key).push(index);+ }+ }+ return kept;+}++function crowded(cells, cell, positions, index, spacing) {+ for (let x = -1; x <= 1; x++) {+ for (let y = -1; y <= 1; y++) {+ for (let z = -1; z <= 1; z++) {+ const neighbours = cells.get(`${cell[0] + x},${cell[1] + y},${cell[2] + z}`);+ if (!neighbours) continue;+ for (const other of neighbours) {+ const distance = Math.hypot(+ positions[index * 3] - positions[other * 3],+ positions[index * 3 + 1] - positions[other * 3 + 1],+ positions[index * 3 + 2] - positions[other * 3 + 2],+ );+ if (distance < spacing) return true;+ }+ }+ }+ }+ return false;+}++/** The variant entry for a point: from the `variant` field when given, else a seeded random pick. */+export function pickVariant(variants, fieldValues, index, seed) {+ const raw = fieldValues ? Math.floor(fieldValues[index]) : Math.floor(seededRandom(index, CHANNEL_VARIANT, seed) * variants.length);+ return variants[((raw % variants.length) + variants.length) % variants.length];+}++/** Quaternion for XYZ Euler angles in radians (Rz * Ry * Rx, the node rotation order of the field language). */+export function eulerQuaternion(angleX, angleY, angleZ) {+ const turnX = quat.setAxisAngle(quat.create(), [1, 0, 0], angleX);+ const turnY = quat.setAxisAngle(quat.create(), [0, 1, 0], angleY);+ const turnZ = quat.setAxisAngle(quat.create(), [0, 0, 1], angleZ);+ return quat.multiply(quat.create(), quat.multiply(quat.create(), turnZ, turnY), turnX);+}++/** Scale triple from one number (uniform) or three (per axis), kept inside the scene's scale range. */+export function clampedSize(values, index, perAxis) {+ const pick = axis => Math.min(MAX_SIZE, Math.max(MIN_SIZE, values[perAxis ? index * 3 + axis : index]));+ return [pick(0), pick(1), pick(2)];+}diff --git a/src/mesh-instances.js b/src/mesh-instances.jsindex 4947ef2d..0809b10c 100644--- a/src/mesh-instances.js+++ b/src/mesh-instances.js@@ -5,6 +5,9 @@ import { MAX_CURVE_POINTS, filletCurve, resampleCurve } from './curve-operationsimport { createTriangleSurfaceIndex } from './mesh-query.js';import './mesh-field-surfaces.js';import './field-rotation.js';+import {+ checkedPlace, clampedSize, eulerQuaternion, meshPoints, pickVariant, thinByDensity, thinBySpacing,+} from './mesh-instance-placement.js';// Instance on points: a node with an `instances` record becomes a group node plus one child node per point, all// sharing the node's geometry and material, so the renderer draws them in one instanced call. Points come from a@@ -16,13 +19,16 @@ import './field-rotation.js';// "where": { "gt": [{ "attr": "position", "component": "x" }, 0] },// "yaw": true, "alignToNormal": false, "scale": [0.7, 1.3] } }//+// "place" adds Poisson spacing, a density field, variants, and per-point rotation and size from fields; see+// mesh-instance-placement.js. `place.at` makes a surface source give its vertices or face centres.+//// Points are in the group's own space: the group takes the node's translation, rotation and scale, and its parent.// Put the group under the node that carries the surface geometry to place instances on that node's surface.export { MAX_INSTANCE_CANDIDATES };const MAX_COORDINATE = 1e6;const SOURCES = INSTANCE_SOURCES;-const INSTANCE_FIELDS = Object.freeze([...SOURCES, 'seed', 'where', 'yaw', 'alignToNormal', 'scale']);+const INSTANCE_FIELDS = Object.freeze([...SOURCES, 'seed', 'where', 'yaw', 'alignToNormal', 'scale', 'place']);const MAX_SEED = 0x7fffffff;const CURVE_FILLET_SEGMENTS = 8;const UP = Object.freeze([0, 1, 0]);@@ -171,7 +177,7 @@ function curvePoints(source) {return { positions, normals };}-function candidatePoints(spec, seed, resolveSurface) {+function candidatePoints(spec, seed, resolveSurface, place) {const sourceName = SOURCES.filter(name => Object.hasOwn(spec, name));if (sourceName.length !== 1) throw instanceError(`give exactly one point source: ${SOURCES.join(', ')}.`);if (sourceName[0] === 'grid') return gridPoints(spec.grid);@@ -180,29 +186,32 @@ function candidatePoints(spec, seed, resolveSurface) {const source = plainRecord(spec.surface, 'surface', ['geometry', 'count']);const count = wholeNumber(source.count, 1, MAX_INSTANCE_CANDIDATES, 'surface count');if (typeof source.geometry !== 'string') throw instanceError('surface needs a geometry id.');+ if (place.at) return meshPoints(resolveSurface(source.geometry), place.at, count);return surfacePoints(resolveSurface(source.geometry), count, seed);}-function keptIndices(spec, points, resolveSurface) {+// Evaluate a field expression over every candidate point; a missing expression gives null.+function pointField(expression, points, resolveSurface, kind) {+ if (expression === undefined) return null;const count = points.positions.length / 3;- const kept = [];- if (spec.where === undefined) {- for (let index = 0; index < count; index++) kept.push(index);- return kept;- }const normals = points.normals ?? Float64Array.from({ length: count * 3 }, (unused, position) => UP[position % 3]);const loadSurface = surface => {- if (typeof surface !== 'string') throw instanceError('a where field reads a surface by its geometry id.');+ if (typeof surface !== 'string') throw instanceError('a field reads a surface by its geometry id.');return createTriangleSurfaceIndex(resolveSurface(surface));};- const { values } = evaluateField(spec.where, pointSetContext(points.positions, normals, loadSurface), { kind: 'scalar' });- for (let index = 0; index < count; index++) {- if (values[index] !== 0) kept.push(index);- }+ return evaluateField(expression, pointSetContext(points.positions, normals, loadSurface), kind ? { kind } : {});+}++function keptIndices(spec, place, points, fields, seed) {+ const count = points.positions.length / 3;+ let kept = Array.from({ length: count }, (unused, index) => index);+ if (fields.where) kept = kept.filter(index => fields.where.values[index] !== 0);+ if (fields.density) kept = thinByDensity(kept, fields.density.values, seed);+ if (place.spacing) kept = thinBySpacing(kept, points.positions, place.spacing);return kept;}-function instanceRotation(spec, seed, candidate, normals) {+function instanceRotation(spec, seed, candidate, normals, turns) {const rotation = quat.create();if (spec.alignToNormal && normals) {const normal = [normals[candidate * 3], normals[candidate * 3 + 1], normals[candidate * 3 + 2]];@@ -212,12 +221,14 @@ function instanceRotation(spec, seed, candidate, normals) {const turn = quat.setAxisAngle(quat.create(), UP, seededRandom(candidate, CHANNEL_YAW, seed) * Math.PI * 2);quat.multiply(rotation, rotation, turn);}+ if (turns) quat.multiply(rotation, rotation, eulerQuaternion(turns[candidate * 3], turns[candidate * 3 + 1], turns[candidate * 3 + 2]));return Array.from(rotation);}-function instanceScale(spec, seed, candidate) {- if (spec.scale === undefined) return 1;- return spec.scale[0] + (spec.scale[1] - spec.scale[0]) * seededRandom(candidate, CHANNEL_SCALE, seed);+function instanceScale(spec, seed, candidate, sizes) {+ const uniform = spec.scale === undefined ? 1 : spec.scale[0] + (spec.scale[1] - spec.scale[0]) * seededRandom(candidate, CHANNEL_SCALE, seed);+ if (!sizes) return [uniform, uniform, uniform];+ return clampedSize(sizes.values, candidate, sizes.kind === 'vector').map(size => size * uniform);}function checkedSpec(spec) {@@ -236,6 +247,17 @@ function checkedSpec(spec) {return seed;}+// The fields a spec reads, evaluated once over all candidate points.+function placementFields(spec, place, points, resolveSurface) {+ return {+ where: pointField(spec.where, points, resolveSurface, 'scalar'),+ density: pointField(place.density, points, resolveSurface, 'scalar'),+ variant: pointField(place.variant, points, resolveSurface, 'scalar'),+ rotation: pointField(place.rotation, points, resolveSurface, 'vector'),+ size: pointField(place.size, points, resolveSurface),+ };+}+/*** Replace each node that has an `instances` record with a group node and its instance children. `resolveSurface(id)`* returns the render geometry ({ positions, normals, indices }) for a surface source. Nodes without `instances` pass@@ -250,17 +272,20 @@ export function expandInstancedNodes(nodes, { resolveSurface, maxNodes }) {continue;}const { instances: spec, geometry, material, ...group } = node;- if (typeof geometry !== 'string' || typeof material !== 'string') throw instanceError(`node ${JSON.stringify(String(node.id).slice(0, 48))} needs geometry and material ids to instance.`);+ const place = checkedPlace(spec?.place);+ if (typeof material !== 'string' || (typeof geometry !== 'string' && !place.variants)) throw instanceError(`node ${JSON.stringify(String(node.id).slice(0, 48))} needs geometry and material ids to instance.`);const seed = checkedSpec(spec);- const points = candidatePoints(spec, seed, resolveSurface);+ if (place.at && !Object.hasOwn(spec, 'surface')) throw instanceError('place.at needs a surface source.');+ const points = candidatePoints(spec, seed, resolveSurface, place);+ const fields = placementFields(spec, place, points, resolveSurface);expanded.push(group);- for (const [slot, candidate] of keptIndices(spec, points, resolveSurface).entries()) {- const scale = instanceScale(spec, seed, candidate);+ for (const [slot, candidate] of keptIndices(spec, place, points, fields, seed).entries()) {+ const variant = place.variants ? pickVariant(place.variants, fields.variant?.values, candidate, seed) : { geometry, material };expanded.push({- id: `${node.id}.${slot}`, parent: node.id, geometry, material,+ id: `${node.id}.${slot}`, parent: node.id, geometry: variant.geometry, material: variant.material ?? material,translation: [points.positions[candidate * 3], points.positions[candidate * 3 + 1], points.positions[candidate * 3 + 2]],- rotation: instanceRotation(spec, seed, candidate, points.normals),- scale: [scale, scale, scale],+ rotation: instanceRotation(spec, seed, candidate, points.normals, fields.rotation?.values),+ scale: instanceScale(spec, seed, candidate, fields.size),});if (expanded.length > maxNodes) throw new RangeError(`Instances expand past the limit of ${maxNodes} nodes.`);}diff --git a/tests/mesh-instance-placement.test.js b/tests/mesh-instance-placement.test.jsnew file mode 100644index 00000000..d29200fe--- /dev/null+++ b/tests/mesh-instance-placement.test.js@@ -0,0 +1,122 @@+import './support/load-agent-scene-modules.mjs';+import assert from 'node:assert/strict';+import test from 'node:test';+import { box, sphere } from '../src/geometry.js';+import { expandInstancedNodes } from '../src/mesh-instances.js';++const base = { id: 'rock', geometry: 'rockA', material: 'stone' };+const surfaceGeometry = sphere(16, 8);+const options = { maxNodes: 4096, resolveSurface: () => surfaceGeometry };++function expand(instances, node = base, extra = options) {+ return expandInstancedNodes([{ ...node, instances }], extra);+}++function children(nodes) {+ return nodes.slice(1);+}++function minimumDistance(nodes) {+ let smallest = Infinity;+ const list = children(nodes);+ for (let first = 0; first < list.length; first++) {+ for (let second = first + 1; second < list.length; second++) {+ smallest = Math.min(smallest, Math.hypot(...list[first].translation.map((value, axis) => value - list[second].translation[axis])));+ }+ }+ return smallest;+}++test('a rock field with Poisson spacing has no overlaps, three variants and is deterministic', () => {+ const field = {+ scatter: { count: 600, min: [-10, 0, -10], max: [10, 0, 10] },+ seed: 11,+ yaw: true,+ place: { spacing: 1.5, variants: ['rockA', 'rockB', { geometry: 'rockC', material: 'moss' }] },+ };+ const first = expand(field);+ assert.ok(children(first).length > 40, `kept ${children(first).length}`);+ assert.ok(minimumDistance(first) >= 1.5, `closest pair ${minimumDistance(first)}`);+ const used = new Set(children(first).map(node => `${node.geometry}/${node.material}`));+ assert.deepEqual([...used].sort(), ['rockA/stone', 'rockB/stone', 'rockC/moss']);+ assert.equal(JSON.stringify(first), JSON.stringify(expand(field)));+ assert.notEqual(JSON.stringify(first), JSON.stringify(expand({ ...field, seed: 12 })));+});++test('a variant field picks the geometry by index, wrapped', () => {+ const nodes = expand({+ grid: { counts: [6, 1, 1], spacing: [1, 1, 1] },+ place: { variants: ['a', 'b', 'c'], variant: { attr: 'index' } },+ });+ assert.deepEqual(children(nodes).map(node => node.geometry), ['a', 'b', 'c', 'a', 'b', 'c']);+});++test('density keeps points by chance and a zero density drops them all', () => {+ const grid = { counts: [20, 1, 20], spacing: [1, 1, 1] };+ const half = children(expand({ grid, seed: 3, place: { density: 0.5 } })).length;+ assert.ok(half > 120 && half < 280, `kept ${half}`);+ assert.equal(children(expand({ grid, place: { density: 0 } })).length, 0);+ assert.equal(children(expand({ grid, place: { density: 1 } })).length, 400);+ const ramp = children(expand({ grid, seed: 3, place: { density: { saturate: { add: [0.5, { mul: [0.1, { attr: 'position', component: 'x' }] }] } } } }));+ const eastShare = ramp.filter(node => node.translation[0] > 0).length / ramp.length;+ assert.ok(eastShare > 0.7, `east share ${eastShare}`);+});++test('rotation and size fields turn and stretch each instance', () => {+ const nodes = children(expand({+ grid: { counts: [2, 1, 1], spacing: [1, 1, 1] },+ place: { rotation: { vec: [0, Math.PI, 0] }, size: { vec: [1, { add: [1, { attr: 'index' }] }, 1] } },+ }));+ assert.deepEqual(nodes[0].scale, [1, 1, 1]);+ assert.deepEqual(nodes[1].scale, [1, 2, 1]);+ assert.ok(Math.abs(nodes[0].rotation[1] - 1) < 1e-9 && Math.abs(nodes[0].rotation[3]) < 1e-9);+ const uniform = children(expand({ grid: { counts: [1, 1, 1], spacing: [1, 1, 1] }, scale: [2, 2], place: { size: 3 } }));+ assert.deepEqual(uniform[0].scale, [6, 6, 6]);+ const clamped = children(expand({ grid: { counts: [1, 1, 1], spacing: [1, 1, 1] }, place: { size: -4 } }));+ assert.deepEqual(clamped[0].scale, [0.001, 0.001, 0.001]);+});++test('a fence follows a curve with evenly spaced posts turned along it', () => {+ const nodes = children(expand({+ curve: { points: [[0, 0, 0], [8, 0, 0], [8, 0, 6]], count: 8 },+ alignToNormal: true,+ place: { variants: ['post', 'postWithRail'], variant: { mod: [{ attr: 'index' }, 2] } },+ }));+ assert.equal(nodes.length, 8);+ assert.deepEqual(nodes[0].translation, [0, 0, 0]);+ assert.ok(Math.abs(nodes[7].translation[0] - 8) < 1e-9 && Math.abs(nodes[7].translation[2] - 6) < 1e-9);+ assert.deepEqual(nodes.map(node => node.geometry), ['post', 'postWithRail', 'post', 'postWithRail', 'post', 'postWithRail', 'post', 'postWithRail']);+ assert.ok(nodes[0].rotation[2] !== 0, 'the first post turns to the +X direction of travel');+});++test('place.at takes the vertices or face centres of a surface, welded and bounded', () => {+ const cube = box(0, 1);+ const cubeOptions = { ...options, resolveSurface: () => cube };+ const surface = { geometry: 'crate', count: 64 };+ const vertices = children(expand({ surface, place: { at: 'vertices' } }, base, cubeOptions));+ assert.equal(vertices.length, 8);+ const faces = children(expand({ surface, place: { at: 'faces' } }, base, cubeOptions));+ assert.equal(faces.length, cube.indices.length / 3);+ assert.throws(() => expand({ surface: { geometry: 'crate', count: 4 }, place: { at: 'vertices' } }, base, cubeOptions), /raise the surface count/);+ assert.throws(() => expand({ grid: { counts: [1, 1, 1], spacing: [1, 1, 1] }, place: { at: 'vertices' } }), /needs a surface source/);+});++test('bad place records name the field', () => {+ const grid = { counts: [2, 1, 1], spacing: [1, 1, 1] };+ const bad = [+ [{ spacing: 0 }, /spacing/],+ [{ spacing: 'wide' }, /spacing/],+ [{ at: 'edges' }, /at is/],+ [{ variants: [] }, /variants/],+ [{ variants: [{ geometry: 'a', extra: 1 }] }, /variants entries/],+ [{ variant: 1 }, /needs a variants list/],+ [{ colour: 1 }, /does not take/],+ [{ density: [1, 2, 3] }, /expected a number/],+ [{ rotation: 1 }, /expected a vector/],+ [[], /must be an object/],+ ];+ for (const [place, message] of bad) {+ assert.throws(() => expand({ grid, place }), message, JSON.stringify(place));+ }+ assert.throws(() => expandInstancedNodes([{ id: 'bare', material: 'stone', instances: { grid } }], options), /geometry and material/);+});