3D engine that AI agents drive
Grow and scatter trees from recipes, with foliage tags, wind and seasons (issue #321)
Nguyen Xuan Aneaccb98ebeaf
diff --git a/changes/321.md b/changes/321.mdnew file mode 100644index 00000000..8568668b--- /dev/null+++ b/changes/321.md@@ -0,0 +1 @@+- Add the `vegetation` recipe node (issue #321): one tree, or a seeded scatter over a terrain node with density, slope limit and exclusions, with levels chosen from the recipe camera, `season` (summer, autumn, bare), `foliage` and `grass` recipe material tags, `environment.wind` strength and direction, a `tag` override for placed asset materials so imported trees sway, and `scene_inspect` `vegetation` counts per species and level. The scatter gives the same instances as `scatterVegetation` for the same options.diff --git a/docs/agent-scene.md b/docs/agent-scene.mdindex b8813ed4..32ccb329 100644--- a/docs/agent-scene.md+++ b/docs/agent-scene.md@@ -249,13 +249,29 @@ A node with an `asset` field places a GLB from the `--assets` catalog inside the"clip": { "index": 0, "start": 0.5, "speed": 1, "loop": true } } }```-- `id` is an id from `scene_asset_catalog`. `materials` override source materials by glTF material name (`color`, `metallic`, `roughness`, `opacity`, `emission`, `emissiveColor`); `scene_inspect` lists the names. Placements with the same overrides share one material.+- `id` is an id from `scene_asset_catalog`. `materials` override source materials by glTF material name (`color`, `metallic`, `roughness`, `opacity`, `emission`, `emissiveColor`, and `tag`: `foliage` or `grass` makes the leaves of an imported tree sway in `environment.wind` and cast moving shadows, like grown ones); `scene_inspect` lists the names. Placements with the same overrides share one material.- Placements of the same asset share geometry and materials, so they draw as one instanced batch per material (`drawBatches` in the render status stays flat as copies are added). Skins and morphs keep working.- `clip` plays that clip, held at its first frame until scene time `start`, then at `speed`, looping unless `loop` is false. Each placement that plays a clip gets a decoded copy of its own (its geometry is not shared), because a pose is state of one decoded asset. A seek gives the same frame as playing to that time. `set-motion` tracks still move the node itself, so a walking figure is a clip plus a motion track on the same node.- Bounds: 512 placements, 16 different assets, 16 placements playing a clip, and `maxNodes` for the generated parts. Placed geometry does not count against `maxVertices`; each asset keeps the decoder limits of the catalog.- `scene_inspect` adds `assets`: per placement the asset id, part count, world bounds, clips (index, name, duration), material names and the playing clip.- Not yet: render jobs refuse a scene with placed assets (`scene_look` draws them), and a scene created without any placed asset cannot add the first one with `scene_apply`.+### Vegetation++A node with a `vegetation` field is a group that grows trees from the addon in [Vegetation](/vegetation.md). Its parts become generated child nodes like placed assets (`<node>/<instance>/<bark|foliage>`), left out of `scene_inspect` nodes and `scene_export_recipe`.++```json+{ "id": "forest", "vegetation": { "mix": { "broadleaf": 3, "conifer": 2, "bush": 2 }, "seed": 11, "season": 0.4,+ "scatter": { "ground": "hills", "density": 0.014, "slopeLimit": 30, "exclude": [{ "center": [0, 0], "radius": 8 }, { "node": "cabin", "radius": 3 }] } } }+```++- One tree: `{ "species": "conifer", "seed": 2, "height": 9, "leaves": "cards" }` grows at the node transform. A scatter takes `mix` (species weights, also `grass` and `flowers`) and `scatter`: `ground` (a node drawing a terrain geometry; give the group the same transform), `density` per square metre, `slopeLimit` degrees, `area` `{min,max}` in `[x,z]`, `exclude` (circles, boxes or a node and radius; terrain holes always stay clear), `variants` and `scale`.+- The same options give the same instances as `scatterVegetation` from `67js/addons/vegetation`: the recipe path calls it with the terrain's `heightAt` and `isHole`.+- Levels of detail come from the recipe camera `eye` when the scene is built or edited (`distanceScale`, `cullDistance`), never from the frame being drawn, so a seek, a camera track or a shot cannot change them. Edit the camera with `set-camera` to regrow the levels for another viewpoint.+- `season` runs 0 summer, 0.35 gold, 0.6 orange, 0.85 brown; 0.9 and above drops the leaves of broadleaf, birch and bush, while conifer and palm stay green. Cards recolour their leaf sprite and mesh leaves and grass blades recolour the material.+- Materials with tag `foliage` or `grass` sway. `environment.wind` is `{ "strength": 0.3, "direction": 0 }` (strength 0 to 4; direction in degrees, 0 toward +x and 90 toward +z, turning the sway and the grass gusts). The wind clock is the render time, so a render job or `scene_review` `rendererTime` gives the same frame at the same time.+- At most 1000 instances (a scatter whose area times density is above 4000 is refused first), and `maxNodes` for the generated parts. `scene_inspect` adds `vegetation`: per node the instances, culled count, triangles, and per species the instances and the count at each level.+### Relations between partsA mesh node can list `relations` that place it against other mesh nodes, so a resized body keeps its handle where itdiff --git a/docs/vegetation.md b/docs/vegetation.mdindex 772fbe38..641388a7 100644--- a/docs/vegetation.md+++ b/docs/vegetation.md@@ -116,6 +116,11 @@ When `changed` is true, build a new renderer from the new parts. Grass switches`vegetationParts(variant, matrix, level, name)` places one tree or clump yourself.+## Recipes and MCP++A recipe node with a `vegetation` field grows and scatters these trees, with wind, seasons and imported trees; see "Vegetation" in [Agent scenes](/agent-scene.md). `scatterVegetation` is called with the terrain's own `heightAt`, so the instances match the addon for the same options.+`levelForDistance(distance, variant, { distanceScale, cullDistance })` is the stateless form of `selectLevels`: no hysteresis, so the level is a pure function of the distance.+## MeasuredOn the demo clearing (125 trees and bushes, 1,941 grass clumps and 129 flower patches, camera at the clearing edge), headless Chrome with GPU:@@ -126,4 +131,5 @@ Meshes and textures are built in plain JavaScript, so tests run in Node.- Cards need the renderer's alpha mask to look right. Without `leafTextures` the leaf textures are 128 px procedural sprigs that look flat from under a few metres; the scanned cards hold up to about 1 m. Palm fronds have no scanned card yet. The conifer card is a cedar spray, so it reads as a flat branch tip rather than separate needles.- Level changes pop; there is no cross-fade. Level 2 crowns are blobs or crossed cards, not baked imposters.-- Species are fixed presets; there is no seasonal color, wind-bent skeleton or collision with other trees.+- Species are fixed presets; there is no wind-bent skeleton or collision with other trees. Seasonal colour exists only in recipes (the `season` field), not in the addon call.+- In recipes, tags `foliage` and `grass` accept a `tag` override on placed assets, so an imported tree sways; its leaf shading and alpha coverage stay those of the renderer.diff --git a/package.json b/package.jsonindex aefc8f21..323e7822 100644--- a/package.json+++ b/package.json@@ -124,6 +124,7 @@"smoke:agent-look": "node scripts/smoke-agent-look.mjs","smoke:view-transform": "node scripts/smoke-view-transform.mjs","smoke:agent-assets": "node scripts/smoke-agent-assets.mjs",+ "smoke:agent-vegetation": "node scripts/smoke-agent-vegetation.mjs","smoke:agent-render-jobs": "node scripts/smoke-agent-render-jobs.mjs","smoke:render-passes": "node scripts/smoke-render-passes.mjs","smoke:path-tracer": "node scripts/smoke-path-tracer.mjs",diff --git a/scripts/agent-preview-browser.js b/scripts/agent-preview-browser.jsindex ec22598e..7a747bc8 100644--- a/scripts/agent-preview-browser.js+++ b/scripts/agent-preview-browser.js@@ -173,7 +173,7 @@ function draw(record, time = 0, camera = record.scene.camera, frameOptions = {})record.shadowKey = shadowKey;}record.renderer.world = environment.world;- record.renderer.render({ ...camera, environment: litEnvironment(record.scene.parts, environment, Boolean(record.renderer.groundPart)), effects, exposure: effects.exposure, time, lines: environment.lines, ...frameOptions });+ record.renderer.render({ ...camera, environment: litEnvironment(record.scene.parts, environment, Boolean(record.renderer.groundPart)), effects, exposure: effects.exposure, time, lines: environment.lines, ...windFrame(environment), ...frameOptions });const error = record.renderer.context.getError();if (error !== 0) {throw new Error(`WebGL render failed with error ${error}.`);@@ -233,6 +233,12 @@ function cascadeCountFor(scene) {return agentSceneModule('cascades').effectiveShadowCascades(scene.environment, scene.shadow);}+// Wind strength and heading (degrees, 0 toward +x, turning toward +z) of the recipe; absent keeps the renderer default.+function windFrame(environment) {+ if (!environment.wind) return {};+ return { wind: environment.wind.strength, windHeading: environment.wind.direction * Math.PI / 180 };+}+function cascadesFor(scene) {const count = cascadeCountFor(scene);return count > 0 ? agentSceneModule('cascades').createCascadedShadows({ count }) : null;diff --git a/scripts/mcp-server.mjs b/scripts/mcp-server.mjsindex 3724319a..7373b180 100644--- a/scripts/mcp-server.mjs+++ b/scripts/mcp-server.mjs@@ -29,9 +29,11 @@ const skinSpec = z.strictObject({}).describe('Bind this mesh node to an armature with automatic weights: each vertex follows its nearest bones, by distance to the bone segments. Needs the armature at rest where the mesh is.');const relationList = z.array(z.record(z.string(), z.unknown())).max(8).describe('Relations against other mesh nodes; fields in scene_capabilities relations. [] removes them.').meta({ id: 'Relations' });const placedAsset = z.record(z.string(), z.unknown()).describe('Catalog GLB placed at this group node: {id,materials,clip}; see scene_capabilities placedAssets.').meta({ id: 'PlacedAsset' });+const placedVegetation = z.record(z.string(), z.unknown()).describe('Trees at this group node: {species} for one, or {mix, scatter:{ground,...}} over a terrain node; see scene_capabilities vegetation.').meta({ id: 'PlacedVegetation' });const nodeFields = {relations: relationList.optional(),asset: placedAsset.optional(),+ vegetation: placedVegetation.optional(),skin: skinSpec.optional(),label: z.string().max(256).optional().describe('Human-readable label. Identity remains the node ID.'),parent: identifier.nullable().optional().describe('Parent node ID, or null for a root. Local transforms stay unchanged.'),@@ -113,7 +115,7 @@ const materialFields = {alphaMode: z.enum(['opaque', 'blend']).optional().describe('blend draws after opaque geometry, sorted back to front.'),doubleSided: z.boolean().optional().describe('Draw and light both faces (thin sheets, leaves, cloth).'),};-const materialTag = z.enum(['surface', 'unlit', 'liquid', 'foam']).optional().describe('liquid refracts what lies behind it and absorbs by thickness: color is the light one metre lets through. foam is soft blended whitewater.');+const materialTag = z.enum(['surface', 'unlit', 'liquid', 'foam', 'foliage', 'grass']).optional().describe('liquid refracts what lies behind it and absorbs by thickness: color is the light one metre lets through. foam is soft blended whitewater. foliage and grass sway in environment.wind.');const liquidOptics = z.strictObject({thickness: z.number().min(0).max(100).optional().describe('Metres of liquid where it faces the camera.'),ior: z.number().min(1).max(3).optional(),@@ -200,6 +202,7 @@ const environment = z.strictObject({volumeFog: volumeFog.optional().describe('Directional scattering; needs HDR.'),liquid: liquidOptics.optional().describe('Optics for materials tagged liquid or foam.'),lines: lines.nullable().optional(),+ wind: z.strictObject({ strength: bounded(0, 4).optional(), direction: bounded(-360, 360).optional().describe('Degrees: 0 toward +x, 90 toward +z.') }).optional().describe('Sway of foliage and grass materials; strength defaults to 0.3.'),});const effects = z.strictObject({exposure: bounded(0.01, 16).optional(),diff --git a/scripts/smoke-agent-vegetation.mjs b/scripts/smoke-agent-vegetation.mjsnew file mode 100644index 00000000..9833e8d5--- /dev/null+++ b/scripts/smoke-agent-vegetation.mjs@@ -0,0 +1,103 @@+// Through MCP on the CPU backend: a forest clearing grown by the vegetation node on terrain, an imported tree whose leaf+// material is tagged foliage, and wind. Checks the inspected counts, that wind moves the frame and that a seek reproduces it.+import assert from 'node:assert/strict';+import { mkdir, writeFile } from 'node:fs/promises';+import { constants, setPriority } from 'node:os';+import { resolve } from 'node:path';+import { Client } from '@modelcontextprotocol/client';+import { StdioClientTransport } from '@modelcontextprotocol/client/stdio';+import { createTree } from '../src/vegetation.js';+import { exportGlb } from '../src/export.js';++setPriority(0, constants.priority.PRIORITY_BELOW_NORMAL);+const proofFolder = 'artifacts/vegetation-proof';+await mkdir(proofFolder, { recursive: true });++// exportGlb writes no material names, so name the materials in the GLB JSON chunk, in order of first use.+function nameGlbMaterials(glb, names) {+ const bytes = Buffer.from(glb);+ const jsonLength = bytes.readUInt32LE(12);+ const document = JSON.parse(bytes.subarray(20, 20 + jsonLength).toString('utf8'));+ document.materials.forEach((material, index) => { material.name = names[index]; });+ const padded = Buffer.from(JSON.stringify(document).padEnd(Math.ceil(JSON.stringify(document).length / 4) * 4, ' '));+ const rest = bytes.subarray(20 + jsonLength);+ const header = Buffer.alloc(20);+ header.write('glTF', 0, 'latin1');+ header.writeUInt32LE(2, 4);+ header.writeUInt32LE(20 + padded.length + rest.length, 8);+ header.writeUInt32LE(padded.length, 12);+ header.write('JSON', 16, 'latin1');+ return Buffer.concat([header, padded, rest]);+}++// An imported tree: the addon's mesh-leaf tree written as a GLB, so its materials are plain named glTF materials.+const tree = createTree({ species: 'broadleaf', leaves: 'mesh', height: 8 }, 4);+const importedParts = tree.levels[1].parts.map(part => ({+ name: part.role, geometry: { ...part.geometry, colors: part.geometry.colors?.map(channel => Math.min(1, channel)) }, matrix: new Float32Array([1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]),+ material: { ...part.material, tag: 'surface' },+}));+await writeFile(`${proofFolder}/imported-tree.glb`, nameGlbMaterials(exportGlb(importedParts), ['Bark', 'Leaves']));++const transport = new StdioClientTransport({+ command: process.execPath,+ args: [resolve('scripts/mcp-server.mjs'), '--backend', 'cpu', '--memory', '192', '--assets', resolve(proofFolder)],+ stderr: 'pipe', cwd: process.cwd(),+});+let diagnostics = '';+transport.stderr.on('data', chunk => { diagnostics += chunk.toString(); });+const client = new Client({ name: '67js-vegetation-proof', version: '1' }, {+ versionNegotiation: { mode: { pin: '2026-07-28' }, probe: { timeoutMs: 180000 } },+});+async function call(name, argumentsValue = {}) {+ const result = await client.callTool({ name, arguments: argumentsValue }, { timeout: 180000 });+ assert.equal(result.isError, undefined, result.content?.find(item => item.type === 'text')?.text);+ return result;+}+// The wind clock is the renderer time, so a review at one renderer time is the frame a render job draws at that time.+async function look(sessionId, revision, label, rendererTime) {+ const result = await call('scene_review', { sessionId, expectedRevision: revision, width: 480, height: 270, labels: false, shots: [{ rendererTime }] });+ const bytes = Buffer.from(result.content.find(item => item.type === 'image').data, 'base64');+ await writeFile(`artifacts/vegetation-${label}.png`, bytes);+ return bytes;+}+try {+ await client.connect(transport, { timeout: 180000 });+ assert.equal((await client.listTools()).tools.length, 22);+ const catalog = (await call('scene_asset_catalog')).structuredContent;+ const imported = catalog.assets.find(asset => asset.name === 'imported-tree.glb').assetId;+ const created = (await call('scene_create', { recipe: {+ format: '67js.scene', schemaVersion: 1,+ geometries: [{ id: 'hills', type: 'terrain', size: 50, resolution: 64, amplitude: 1.2, seed: 4 }, { id: 'beacon', type: 'sphere' }],+ materials: [{ id: 'turf', tag: 'grass', color: [0.2, 0.34, 0.1], roughness: 0.95 }, { id: 'lamp', color: [1, 0.8, 0.3], emission: 2 }],+ nodes: [+ { id: 'ground', geometry: 'hills', material: 'turf' },+ { id: 'forest', vegetation: { mix: { broadleaf: 3, birch: 1.5, conifer: 2, bush: 2 }, seed: 11, leaves: 'cards', season: 0.4,+ scatter: { ground: 'ground', density: 0.014, slopeLimit: 30, exclude: [{ center: [0, 0], radius: 8 }, { node: 'imported', radius: 3 }], variants: 2 } } },+ { id: 'imported', translation: [2.5, 0.3, 1], asset: { id: imported, materials: [{ name: 'Leaves', tag: 'foliage', color: [0.2, 0.5, 0.12] }] } },+ { id: 'beacon', geometry: 'beacon', material: 'lamp', translation: [-3, 0.4, 1], scale: [0.3, 0.3, 0.3] },+ ],+ environment: { wind: { strength: 2.5, direction: 20 } },+ camera: { eye: [0, 3, 13], target: [0, 3.5, 0], fov: 55 },+ } })).structuredContent;+ const sessionId = created.sessionId;+ const inspection = (await call('scene_inspect', { sessionId })).structuredContent;+ const forest = inspection.vegetation[0];+ assert.equal(forest.mode, 'scatter');+ assert.ok(forest.instances > 20 && forest.triangles > 0);+ assert.ok(Object.values(forest.species).every(species => species.levels.length > 0));+ assert.equal(inspection.assets.length, 1);+ const first = await look(sessionId, created.revision, 'wind-start', 0.4);+ const later = await look(sessionId, created.revision, 'wind-later', 2.3);+ assert.notDeepEqual(first, later, 'the wind moves the leaves');+ assert.deepEqual(await look(sessionId, created.revision, 'wind-later-again', 2.3), later, 'a seek reproduces its frame');+ assert.deepEqual(await look(sessionId, created.revision, 'wind-start-again', 0.4), first);+ await call('scene_dispose', { sessionId });+ const report = { backend: 'cpu', instances: forest.instances, species: forest.species, triangles: forest.triangles, seekExact: true };+ await writeFile('artifacts/vegetation-cpu.json', JSON.stringify(report, null, 2));+ console.log(JSON.stringify(report));+} catch (error) {+ console.error(diagnostics);+ throw error;+} finally {+ await client.close();+}diff --git a/src/agent-look.js b/src/agent-look.jsindex 8d6489b2..47857b09 100644--- a/src/agent-look.js+++ b/src/agent-look.js@@ -13,7 +13,7 @@ const MAX_LOOK_ARRAY_ENTRIES = Math.max(MAX_POINT_LIGHTS, MAX_SPOT_LIGHTS, MAX_Aconst ENVIRONMENT_FIELDS = ['world', 'ground', 'setup', 'environmentIntensity', 'environmentRotation', 'lightDirection', 'keyColor', 'keyIntensity', 'fillIntensity', 'ambientIntensity',- 'daylight', 'pointLights', 'spotLights', 'areaLights', 'skyTop', 'skyBottom', 'fogColor', 'fogDensity', 'volumeFog', 'liquid', 'shadowCascades', 'keyAffects', 'objectReflections', 'lines', 'resolveCoplanar', 'viewTransform', 'look',+ 'daylight', 'pointLights', 'spotLights', 'areaLights', 'skyTop', 'skyBottom', 'fogColor', 'fogDensity', 'volumeFog', 'liquid', 'shadowCascades', 'keyAffects', 'objectReflections', 'lines', 'resolveCoplanar', 'viewTransform', 'look', 'wind',];const LIQUID_FIELDS = ['thickness', 'ior', 'refraction', 'scattering', 'foamOpacity', 'foamSoftness'];const EFFECT_FIELDS = ['exposure', 'saturation', 'contrast', 'temperature', 'vignette', 'grain', 'ambientOcclusion', 'ambientOcclusionRadius', 'bloom', 'depthOfField', 'motionBlur'];@@ -292,6 +292,13 @@ function environmentFrom(input = {}) {if (input.shadowCascades !== undefined) {environment.shadowCascades = shadowCascadesFrom(input.shadowCascades);}+ if (input.wind !== undefined && input.wind !== null) {+ knownKeys(input.wind, ['strength', 'direction'], 'wind');+ environment.wind = {+ strength: numberInRange(fallback(input.wind.strength, 0.3), 0, 4, 'wind.strength'),+ direction: numberInRange(fallback(input.wind.direction, 0), -360, 360, 'wind.direction'),+ };+ }if (input.viewTransform !== undefined) {if (!VIEW_TRANSFORM_NAMES.includes(input.viewTransform)) {throw new RangeError(`environment.viewTransform must be one of ${VIEW_TRANSFORM_NAMES.join(', ')}.`);diff --git a/src/agent-scene-assets.js b/src/agent-scene-assets.jsindex b11a0a0c..6eabf2be 100644--- a/src/agent-scene-assets.js+++ b/src/agent-scene-assets.js@@ -13,7 +13,9 @@ const PLACEMENT_FIELDS = ['id', 'materials', 'clip'];const CLIP_FIELDS = ['index', 'start', 'speed', 'loop'];const COLOR_FIELDS = ['color', 'emissiveColor'];const UNIT_FIELDS = ['metallic', 'roughness', 'opacity'];-const OVERRIDE_FIELDS = ['name', ...COLOR_FIELDS, ...UNIT_FIELDS, 'emission'];+const OVERRIDE_FIELDS = ['name', 'tag', ...COLOR_FIELDS, ...UNIT_FIELDS, 'emission'];+// A tag an override may set: foliage and grass make an imported tree sway in the wind and shade like a grown one.+const OVERRIDE_TAGS = ['surface', 'foliage', 'grass'];function knownKeys(value, allowed, label) {if (!value || typeof value !== 'object' || Array.isArray(value)) {@@ -39,6 +41,10 @@ function normalizeMaterialOverride(override) {throw new TypeError('An asset material override needs the source material name. scene_inspect lists the names under assets.');}const result = { name: override.name };+ if (override.tag !== undefined) {+ if (!OVERRIDE_TAGS.includes(override.tag)) throw new RangeError(`asset material override tag must be one of ${OVERRIDE_TAGS.join(', ')}.`);+ result.tag = override.tag;+ }for (const field of COLOR_FIELDS) {if (override[field] !== undefined) result[field] = colorVector(override[field], field);}@@ -138,6 +144,7 @@ function jsonMaterial(source) {function overrideFields(override) {const fields = {};+ if (override?.tag !== undefined) fields.tag = override.tag;for (const field of [...COLOR_FIELDS, ...UNIT_FIELDS, 'emission']) {if (override?.[field] !== undefined) fields[field] = override[field];}diff --git a/src/agent-scene-capabilities.js b/src/agent-scene-capabilities.jsindex 15eb2cb0..2cc3e92a 100644--- a/src/agent-scene-capabilities.js+++ b/src/agent-scene-capabilities.js@@ -156,6 +156,7 @@ export const AGENT_SCENE_CAPABILITIES = Object.freeze({geometryTypes: Object.freeze(['box', 'cylinder', 'sphere', 'torus', 'lathe', 'extrude', 'tube', 'curve', 'text', 'grid', 'terrain', 'mesh']),terrain: 'One mesh, x and z from -size/2 to size/2, hills about y = 0. size 40 m (1-2000), resolution 64 cells (2-256), seed 1, amplitude 1 m (0-200), holes up to 16 of {center:[x,z],radius} with no surface inside; radius a few cells or more.',placedAssets: 'Node field asset:{id,materials?,clip?} turns a group node into a catalog GLB (id from asset_catalog; scene_create_asset is one asset alone). Its transform places it. materials:[{name,color,metallic,roughness,opacity,emission,emissiveColor}] override source materials by name. clip:{index,start=0,speed=1,loop=true} plays that clip from scene time start, on a decoded copy of its own; scene_apply set-motion tracks move the node as usual and scene time seeks the clip. Copies of one asset share geometry and materials and draw as one batch. scene_inspect assets lists id, bounds, clips and material names. At most 512 placements, 16 assets, 16 playing a clip. Render jobs do not draw placed assets yet; scene_look does.',+ vegetation: "Node field vegetation turns a group node into trees (src/vegetation.js). One tree: {species: broadleaf|birch|conifer|palm|bush, seed=1, height?, leaves: cards|mesh}, grown at the node transform. A scatter: {mix:{species:weight, also grass and flowers}, seed, leaves, scatter:{ground: terrain node ID, density=0.012 per m2, slopeLimit=32 degrees, area?:{min:[x,z],max:[x,z]}, exclude?:[{center:[x,z],radius}|{min,max}|{node,radius}], variants=3 (1-4), scale?:[min,max]}}; terrain holes stay clear. Instances sit in the ground node frame, so give the group the ground transform. Levels (0 full to 3 far) come from the recipe camera eye at each edit, never from a frame, plus optional cullDistance m and distanceScale, so a seek cannot change them. season 0 summer, 0.35 gold, 0.6 orange, 0.85 brown, 0.9 and up bare for broadleaf, birch and bush (conifer and palm stay green). scatterVegetation from 67js/addons/vegetation gives the same instances for the same options. At most 1000 instances. scene_inspect vegetation lists instances per species and level, culled and triangles. Tags foliage and grass sway with environment.wind {strength 0-4 (0.3), direction degrees, 0 toward +x and 90 toward +z}; a recipe material may use them, and asset materials:[{name, tag:\"foliage\"}] makes the leaves of an imported tree sway and cast moving shadows.",navigation: 'scene_inspect path:{ground,from:[x,z],to:[x,z]} returns a route over the ground node around its holes, steep slopes and the nodes in avoid:[ids] (box footprints), as keyframes [{time,value:[x,y,z]}] for a node translation track with interpolation LINEAR. radius 0.3 m is how far the walker position stays from holes and avoided nodes; maxSlope 40 degrees; cellSize defaults to radius; give seconds for the whole walk or speed (1.4 m/s); lift raises y, such as half the walker height. Ground and avoided nodes are read at their authored pose. Errors name an unwalkable start or goal, or one that cannot be reached.',meshEdits: Object.freeze({ operations: Object.freeze(Object.keys(MESH_EDIT_OPERATIONS)), maxEdits: MAX_MESH_EDITS }),meshStack: Object.freeze({ operations: STACK_OPERATIONS, maxNodes: MAX_STACK_NODES }),@@ -171,7 +172,7 @@ export const AGENT_SCENE_CAPABILITIES = Object.freeze({'add-geometry', 'remove-geometry', 'add-material', 'remove-material','set-environment', 'set-effects', 'set-shadow', 'set-motion', 'set-armatures', 'set-physics', 'set-cloth', 'set-timeline', 'set-particles', 'set-bake', 'edit-mesh', 'set-mesh-stack',]),- materialTags: Object.freeze(['surface', 'unlit', 'liquid', 'foam']),+ materialTags: Object.freeze(['surface', 'unlit', 'liquid', 'foam', 'foliage', 'grass']),materialLayers: Object.freeze(Object.fromEntries(MATERIAL_LAYER_FIELDS.map(field => [field, Object.freeze({range: MATERIAL_LAYER_SCALAR_RANGES[field] ?? MATERIAL_LAYER_COLOR_RANGES[field] ?? 'above 0',note: MATERIAL_LAYER_NOTES[field],diff --git a/src/agent-scene-modules.js b/src/agent-scene-modules.jsindex 7c8b355d..10e9d276 100644--- a/src/agent-scene-modules.js+++ b/src/agent-scene-modules.js@@ -24,6 +24,7 @@ const MODULE_LOADERS = {lightLinking: () => import('./light-linking.js'),cascades: () => import('./cascaded-shadows.js'),assets: () => import('./agent-scene-assets.js'),+ vegetation: () => import('./agent-vegetation.js'),lineArt: () => import('./line-art.js'),viewTransform: () => import('./view-transform-shader.js'),coplanar: () => import('./coplanar-overlap.js'),@@ -58,6 +59,7 @@ const MODULE_MARKERS = {lightLinking: ['"affects"', '"keyAffects"'],cascades: ['"shadowCascades"'],assets: ['"asset":{'],+ vegetation: ['"vegetation":{'],lineArt: ['"lines":{', '"toon":'],viewTransform: ['"viewTransform":"agx"', '"viewTransform":"neutral"', '"look":"'],// The coplanar-overlap warning in scene_inspect appears only once this is loaded, which loadAllAgentSceneModules does; a recipe with resolveCoplanar needs it.diff --git a/src/agent-scene.js b/src/agent-scene.jsindex e255d4d9..734f7fda 100644--- a/src/agent-scene.js+++ b/src/agent-scene.js@@ -23,7 +23,7 @@ const MAX_MESH_REPORTS = 16;// Terrain meshes carry one more float for each vertex (sky visibility) than the 56 bytes the budget estimates.const TERRAIN_SKY_VISIBILITY_BYTES = 4;const CAMERA_DEFAULTS = Object.freeze({ eye: [4, 3, 5], target: [0, 0, 0], up: [0, 1, 0], fov: 45, near: 0.1, far: 1000 });-const NODE_FIELDS = ['translation', 'rotation', 'scale', 'parent', 'label', 'geometry', 'material', 'skin', 'relations', 'asset', 'decal', 'depthLayer'];+const NODE_FIELDS = ['translation', 'rotation', 'scale', 'parent', 'label', 'geometry', 'material', 'skin', 'relations', 'asset', 'vegetation', 'decal', 'depthLayer'];const MATERIAL_FIELDS = ['color', 'metallic', 'roughness', 'emission', 'emissiveColor', 'opacity', 'alphaMode', 'doubleSided', 'pattern', ...MATERIAL_LAYER_FIELDS];const PATTERN_TEXTURE_FIELDS = ['map', 'normalMap', 'metallicRoughnessMap', 'emissiveMap', 'boxMapScale', 'boxMapAxis'];const CAMERA_FIELDS = Object.keys(CAMERA_DEFAULTS);@@ -291,6 +291,12 @@ function nodeFrom(value) {}result.asset = agentSceneModule('assets').normalizeAssetPlacement(value.asset);}+ if (value.vegetation !== undefined) {+ if (value.geometry !== undefined || value.skin !== undefined || value.asset !== undefined) {+ throw new TypeError(`Node ${value.id}: a node that grows vegetation is a group; drop geometry, material, skin and asset.`);+ }+ result.vegetation = agentSceneModule('vegetation').normalizeVegetation(value.vegetation);+ }if (value.decal !== undefined && typeof value.decal !== 'boolean') {throw new TypeError('decal must be boolean.');}@@ -794,6 +800,15 @@ function assetMaterialHandle(snapshot, output, ...candidates) {return reusable ?? { holder: { snapshot }, output };}+function mergedRuntime(placed, vegetation) {+ return {+ ...placed,+ geometryParts: new Map([...placed.geometryParts, ...vegetation.geometryParts]),+ materialOutputs: new Map([...placed.materialOutputs, ...vegetation.materialOutputs]),+ partExtras: new Map([...placed.partExtras, ...vegetation.partExtras]),+ };+}+function retainedMatrices(parts) {for (const part of parts) {if (part.matrix.length !== 16 || part.matrix.byteLength !== 64) {@@ -962,6 +977,7 @@ function removeNode(candidate, operation) {export function createAgentScene(input, inputLimits = {}, options = {}) {const limits = resolveLimits(inputLimits);const assetOutputCache = new Map();+ let vegetationCache = null;let state = null;let revision = 0;let topologyRevision = 0;@@ -1015,9 +1031,14 @@ export function createAgentScene(input, inputLimits = {}, options = {}) {function stage(inputRecipe, preferred = null, removedNodes = new Set(), removedMaterials = new Set()) {const recipe = normalizeRecipe(inputRecipe, limits);- const assetRuntime = recipe.nodes.some(node => node.asset)+ const placedRuntime = recipe.nodes.some(node => node.asset)? agentSceneModule('assets').expandAssetPlacements(recipe, options.assets, limits, assetOutputCache): NO_ASSETS;+ // Grown vegetation travels the placed-asset channel: generated geometries, materials and part nodes.+ const vegetationRuntime = recipe.nodes.some(node => node.vegetation)+ ? agentSceneModule('vegetation').expandVegetation(recipe, limits, vegetationCache ??= agentSceneModule('vegetation').createVegetationCache())+ : null;+ const assetRuntime = vegetationRuntime ? mergedRuntime(placedRuntime, vegetationRuntime) : placedRuntime;if (state) {retainedMatrices(state.parts);}@@ -1137,6 +1158,7 @@ export function createAgentScene(input, inputLimits = {}, options = {}) {stats: geometryStats(geometryRecords.values()),};stagedState.assetRuntime = assetRuntime;+ stagedState.vegetationReport = vegetationRuntime?.report ?? [];stagedState.localBounds = localBounds;stagedState.skinBindings = skinBindings;stagedState.skinStages = createSkinStages(skinBindings);@@ -1595,6 +1617,7 @@ export function createAgentScene(input, inputLimits = {}, options = {}) {physics: state.physicsSampler ? state.physicsSampler.report() : null,...(state.clothSampler ? { cloth: state.clothSampler.report() } : {}),...(state.particleSampler ? { particles: state.particleSampler.report() } : {}),+ ...(state.vegetationReport?.length ? { vegetation: state.vegetationReport } : {}),...(state.assetRuntime.placements.length ? { assets: agentSceneModule('assets').describeAssetPlacements(state.assetRuntime, state.graph, geometry => state.localBounds.get(geometry)) } : {}),...(state.bakeReport ? { bake: state.bakeReport } : {}),...(state.reflectionReport ? { reflections: state.reflectionReport } : {}),diff --git a/src/agent-terrain.js b/src/agent-terrain.jsindex 81e688c0..57f38bc8 100644--- a/src/agent-terrain.js+++ b/src/agent-terrain.js@@ -38,13 +38,11 @@ export function terrainVertexEstimate(value) {return (resolution + 1) * (resolution + 1);}-/** Render geometry of a terrain record: ground from -size / 2 to size / 2 on X and Z, hills of the given amplitude, holes cut out. */-export function generateTerrainGeometry(value, maxVertices) {- const vertices = terrainVertexEstimate(value);- if (vertices > maxVertices) throw new RangeError(`Terrain needs ${vertices} vertices, exceeding maxVertices ${maxVertices}. Lower resolution.`);+/** The terrain addon object of a terrain record: render parts plus heightAt, isHole and bounds. Vegetation scatters over the same ground. */+export function createRecipeTerrain(value) {const size = value.size ?? TERRAIN_LIMITS.defaultSize;const seed = Number.isInteger(value.seed) ? value.seed : 1;- const terrain = createTerrain({+ return createTerrain({size,chunks: 1,levels: 1,@@ -58,5 +56,11 @@ export function generateTerrainGeometry(value, maxVertices) {mountainMask: () => 0,},});- return terrain.parts[0].geometry;+}++/** Render geometry of a terrain record: ground from -size / 2 to size / 2 on X and Z, hills of the given amplitude, holes cut out. */+export function generateTerrainGeometry(value, maxVertices) {+ const vertices = terrainVertexEstimate(value);+ if (vertices > maxVertices) throw new RangeError(`Terrain needs ${vertices} vertices, exceeding maxVertices ${maxVertices}. Lower resolution.`);+ return createRecipeTerrain(value).parts[0].geometry;}diff --git a/src/agent-vegetation.js b/src/agent-vegetation.jsnew file mode 100644index 00000000..42914e2f--- /dev/null+++ b/src/agent-vegetation.js@@ -0,0 +1,328 @@+import { mat4 } from 'gl-matrix';+import { leafTextureDescriptor } from './vegetation-textures.js';+import { SPECIES, createTree, scatterVegetation, levelForDistance } from './vegetation.js';+import { createRecipeTerrain } from './agent-terrain.js';++// Recipe vegetation: a group node with a `vegetation` field grows one tree, or scatters trees over a terrain node. The+// result reuses the placed-asset channel of agent-scene.js: generated geometries (type "asset"), materials (assetSource)+// and part nodes (assetPart), so exports and edits already skip them. Everything is a pure function of the recipe: the+// same seed grows the same trees, and levels of detail come from the recipe camera, never from the frame being drawn.++export const VEGETATION_LIMITS = Object.freeze({+ maxInstances: 1000, maxVariants: 4, maxExclusions: 32, maxCandidates: 4000, maxCachedSets: 4,+});+const SCATTER_SPECIES = [...Object.keys(SPECIES), 'grass', 'flowers'];+const VEGETATION_FIELDS = ['species', 'mix', 'seed', 'height', 'leaves', 'season', 'cullDistance', 'distanceScale', 'scatter'];+const SCATTER_FIELDS = ['ground', 'density', 'slopeLimit', 'area', 'exclude', 'variants', 'scale'];+const EXCLUSION_FIELDS = ['center', 'radius', 'min', 'max', 'node'];+const GROUND_EDGE_MARGIN = 0.5;+const SEASON_TARGETS = Object.freeze([[0.35, [196, 150, 40]], [0.6, [186, 84, 26]], [0.85, [112, 66, 34]]]);+const GRASS_CARD_COLOR = [80, 128, 40];+const BARE_SEASON = 0.9;+const DECIDUOUS_SPECIES = new Set(['broadleaf', 'birch', 'bush']);++function knownKeys(value, allowed, label) {+ if (!value || typeof value !== 'object' || Array.isArray(value)) throw new TypeError(`${label} must be an object.`);+ for (const key of Object.keys(value)) {+ if (!allowed.includes(key)) throw new TypeError(`Unknown ${label} field: ${key}. Allowed fields: ${allowed.join(', ')}.`);+ }+}++function numberWithin(value, minimum, maximum, label) {+ if (!Number.isFinite(value) || value < minimum || value > maximum) {+ throw new RangeError(`${label} must be a number from ${minimum} to ${maximum}.`);+ }+ return value;+}++function planePoint(value, label) {+ if (!Array.isArray(value) || value.length !== 2 || value.some(component => !Number.isFinite(component))) {+ throw new TypeError(`${label} must be [x, z] in metres.`);+ }+ return [...value];+}++function normalizeExclusion(value) {+ knownKeys(value, EXCLUSION_FIELDS, 'vegetation exclusion');+ if (value.min !== undefined || value.max !== undefined) {+ const min = planePoint(value.min, 'exclusion min');+ const max = planePoint(value.max, 'exclusion max');+ if (max[0] <= min[0] || max[1] <= min[1]) throw new RangeError('exclusion max must be above min on both axes.');+ return { min, max };+ }+ const radius = numberWithin(value.radius, 0.01, 2000, 'exclusion radius');+ if (value.node !== undefined) {+ if (typeof value.node !== 'string' || !value.node) throw new TypeError('exclusion node must be a node ID.');+ return { node: value.node, radius };+ }+ return { center: planePoint(value.center, 'exclusion center'), radius };+}++function normalizeScatter(value) {+ knownKeys(value, SCATTER_FIELDS, 'vegetation scatter');+ if (typeof value.ground !== 'string' || !value.ground) throw new TypeError('vegetation scatter needs ground: the ID of a terrain node.');+ const result = {+ ground: value.ground,+ density: numberWithin(value.density ?? 0.012, 0.0001, 4, 'scatter density'),+ slopeLimit: numberWithin(value.slopeLimit ?? 32, 0, 90, 'scatter slopeLimit'),+ variants: numberWithin(value.variants ?? 3, 1, VEGETATION_LIMITS.maxVariants, 'scatter variants'),+ exclude: [],+ };+ if (!Number.isInteger(result.variants)) throw new RangeError('scatter variants must be a whole number.');+ if (value.exclude !== undefined) {+ if (!Array.isArray(value.exclude) || value.exclude.length > VEGETATION_LIMITS.maxExclusions) {+ throw new RangeError(`scatter exclude lists at most ${VEGETATION_LIMITS.maxExclusions} areas.`);+ }+ result.exclude = value.exclude.map(normalizeExclusion);+ }+ if (value.area !== undefined) {+ knownKeys(value.area, ['min', 'max'], 'scatter area');+ result.area = { min: planePoint(value.area.min, 'area min'), max: planePoint(value.area.max, 'area max') };+ if (result.area.max[0] <= result.area.min[0] || result.area.max[1] <= result.area.min[1]) {+ throw new RangeError('scatter area max must be above min on both axes.');+ }+ }+ if (value.scale !== undefined) {+ if (!Array.isArray(value.scale) || value.scale.length !== 2) throw new TypeError('scatter scale must be [min, max].');+ result.scale = [numberWithin(value.scale[0], 0.1, 10, 'scatter scale min'), numberWithin(value.scale[1], 0.1, 10, 'scatter scale max')];+ if (result.scale[1] < result.scale[0]) throw new RangeError('scatter scale max must not be below min.');+ }+ return result;+}++/** Validate the `vegetation` field of a node. Returns the canonical form kept in the recipe. */+export function normalizeVegetation(value) {+ knownKeys(value, VEGETATION_FIELDS, 'vegetation');+ const result = {};+ if ((value.species === undefined) === (value.mix === undefined)) {+ throw new TypeError('vegetation needs exactly one of species (one tree) or mix (a scatter, species weights).');+ }+ if (value.species !== undefined) {+ if (!SCATTER_SPECIES.includes(value.species) || (!value.scatter && !SPECIES[value.species])) {+ throw new RangeError(`vegetation species must be one of ${(value.scatter ? SCATTER_SPECIES : Object.keys(SPECIES)).join(', ')}.`);+ }+ result.species = value.species;+ } else {+ if (!value.scatter) throw new TypeError('vegetation mix needs scatter. A single tree takes species.');+ if (!value.mix || typeof value.mix !== 'object' || Array.isArray(value.mix)) throw new TypeError('vegetation mix must map species to weights.');+ result.mix = {};+ for (const [name, weight] of Object.entries(value.mix)) {+ if (!SCATTER_SPECIES.includes(name)) throw new RangeError(`vegetation mix species must be among ${SCATTER_SPECIES.join(', ')}; got ${name}.`);+ result.mix[name] = numberWithin(weight, 0, 100, `mix ${name}`);+ }+ if (!Object.values(result.mix).some(weight => weight > 0)) throw new RangeError('vegetation mix needs one positive weight.');+ }+ result.seed = numberWithin(value.seed ?? 1, -2147483648, 2147483647, 'vegetation seed');+ if (value.height !== undefined) result.height = numberWithin(value.height, 0.2, 80, 'vegetation height');+ result.leaves = value.leaves ?? 'cards';+ if (result.leaves !== 'cards' && result.leaves !== 'mesh') throw new RangeError('vegetation leaves must be cards or mesh.');+ result.season = numberWithin(value.season ?? 0, 0, 1, 'vegetation season');+ if (value.cullDistance !== undefined) result.cullDistance = numberWithin(value.cullDistance, 1, 100_000, 'vegetation cullDistance');+ result.distanceScale = numberWithin(value.distanceScale ?? 1, 0.1, 10, 'vegetation distanceScale');+ if (value.scatter !== undefined) result.scatter = normalizeScatter(value.scatter);+ return result;+}++/** A leaf colour (0 to 255 sRGB) for a season: summer keeps the species colour, then 0.35 gold, 0.6 orange and 0.85 brown. */+export function seasonLeafColor(base, season) {+ const stops = [[0, base], ...SEASON_TARGETS];+ if (season >= stops[stops.length - 1][0]) return [...stops[stops.length - 1][1]];+ let index = 0;+ while (season > stops[index + 1][0]) index++;+ const [startSeason, startColor] = stops[index];+ const [endSeason, endColor] = stops[index + 1];+ const fraction = (season - startSeason) / (endSeason - startSeason);+ return startColor.map((channel, axis) => Math.round(channel + (endColor[axis] - channel) * fraction));+}++// Cards recolour their procedural leaf sprite, because a colour factor cannot turn a green leaf orange; mesh leaves and grass blades recolour the material.+function seasonalMaterial(material, variant, species, season) {+ if (material.map) {+ const preset = SPECIES[species];+ const kind = species === 'grass' ? 'grass' : material === variant.materials.crown ? 'clump' : preset.leaf.texture;+ const base = species === 'grass' ? GRASS_CARD_COLOR : preset.leaf.color;+ return { ...material, map: leafTextureDescriptor(kind, seasonLeafColor(base, season)) };+ }+ const base = material.color.map(channel => channel ** (1 / 2.2) * 255);+ return { ...material, color: seasonLeafColor(base, season).map(channel => (channel / 255) ** 2.2) };+}++function nodeWorldMatrix(nodes, node) {+ const byId = new Map(nodes.map(candidate => [candidate.id, candidate]));+ let matrix = mat4.fromRotationTranslationScale(mat4.create(), node.rotation, node.translation, node.scale);+ let parent = node.parent === null ? null : byId.get(node.parent);+ for (let depth = 0; parent && depth < 256; depth++) {+ const local = mat4.fromRotationTranslationScale(mat4.create(), parent.rotation, parent.translation, parent.scale);+ matrix = mat4.multiply(mat4.create(), local, matrix);+ parent = parent.parent === null ? null : byId.get(parent.parent);+ }+ return matrix;+}++function groundTerrain(recipe, scatter) {+ const ground = recipe.nodes.find(node => node.id === scatter.ground);+ const definition = ground && recipe.geometries.find(geometry => geometry.id === ground.geometry);+ if (definition?.type !== 'terrain') {+ throw new RangeError(`vegetation scatter ground ${JSON.stringify(scatter.ground.slice(0, 48))} must be a node drawing a terrain geometry. Give the group node the same transform as the ground.`);+ }+ return { definition, terrain: createRecipeTerrain(definition) };+}++function scatterArea(scatter, definition) {+ const half = (definition.size ?? 40) / 2 - GROUND_EDGE_MARGIN;+ const area = scatter.area ?? { min: [-half, -half], max: [half, half] };+ return {+ minX: Math.max(area.min[0], -half), maxX: Math.min(area.max[0], half),+ minZ: Math.max(area.min[1], -half), maxZ: Math.min(area.max[1], half),+ };+}++function exclusionTest(recipe, scatter, terrain) {+ const areas = scatter.exclude.map(entry => {+ if (entry.min) return (x, z) => x >= entry.min[0] && x <= entry.max[0] && z >= entry.min[1] && z <= entry.max[1];+ let center = entry.center;+ if (entry.node) {+ const target = recipe.nodes.find(node => node.id === entry.node);+ if (!target) throw new RangeError(`vegetation exclusion names node ${JSON.stringify(entry.node.slice(0, 48))}, which is not in the recipe.`);+ center = [target.translation[0], target.translation[2]];+ }+ return (x, z) => Math.hypot(x - center[0], z - center[1]) <= entry.radius;+ });+ return (x, z) => terrain.isHole(x, z) || areas.some(test => test(x, z));+}++/** The options `scatterVegetation` gets for a scatter node: the same call an addon user makes, so both give the same instances. */+export function scatterOptionsFor(recipe, vegetation) {+ const { scatter } = vegetation;+ const { definition, terrain } = groundTerrain(recipe, scatter);+ const area = scatterArea(scatter, definition);+ const candidates = (area.maxX - area.minX) * (area.maxZ - area.minZ) * scatter.density;+ if (candidates > VEGETATION_LIMITS.maxCandidates) {+ throw new RangeError(`This scatter would try about ${Math.round(candidates)} trees. Lower density or give a smaller area; the limit is ${VEGETATION_LIMITS.maxInstances} placed instances.`);+ }+ return {+ area, density: scatter.density, terrainHeight: terrain.heightAt, slopeLimit: scatter.slopeLimit,+ exclusion: exclusionTest(recipe, scatter, terrain), seed: vegetation.seed, mix: vegetation.mix ?? { [vegetation.species]: 1 },+ variants: scatter.variants, leaves: vegetation.leaves, ...(scatter.scale ? { scale: scatter.scale } : {}),+ };+}++function grow(recipe, vegetation) {+ if (!vegetation.scatter) {+ const tree = createTree({ species: vegetation.species, leaves: vegetation.leaves, ...(vegetation.height ? { height: vegetation.height } : {}) }, vegetation.seed);+ return { variants: [tree], instances: [{ variant: tree, matrix: mat4.create(), species: vegetation.species }] };+ }+ const scattered = scatterVegetation(scatterOptionsFor(recipe, vegetation));+ if (scattered.instances.length > VEGETATION_LIMITS.maxInstances) {+ throw new RangeError(`This scatter placed ${scattered.instances.length} instances; the limit is ${VEGETATION_LIMITS.maxInstances}. Lower density or give a smaller area.`);+ }+ return { variants: Object.values(scattered.variants).flat(), instances: scattered.instances };+}++function cacheKey(recipe, node) {+ const { vegetation } = node;+ const ground = vegetation.scatter ? recipe.geometries.find(geometry => geometry.id === recipe.nodes.find(candidate => candidate.id === vegetation.scatter.ground)?.geometry) : null;+ const named = vegetation.scatter?.exclude.filter(entry => entry.node).map(entry => recipe.nodes.find(candidate => candidate.id === entry.node)?.translation);+ const { season, cullDistance, distanceScale, ...growth } = vegetation;+ return JSON.stringify([growth, ground, named]);+}++function materialJson(material) {+ return {+ tag: material.tag ?? 'surface', color: [...material.color], metallic: material.metallic ?? 0, roughness: material.roughness ?? 0.5,+ emission: material.emission ?? 0, opacity: 1, alphaMode: material.alphaMode ?? 'opaque',+ doubleSided: Boolean(material.doubleSided),+ };+}++/**+ * Generate the geometries, materials and part nodes of every vegetation node into a normalized recipe, in place.+ * `cache` (kept by the scene) holds grown trees across edits, so a camera or season edit does not grow them again.+ * Returns the runtime maps the scene merges with the placed-asset ones, and a report for scene_inspect.+ */+export function expandVegetation(recipe, limits, cache) {+ const planted = recipe.nodes.filter(node => node.vegetation);+ const runtime = { geometryParts: new Map(), materialOutputs: new Map(), partExtras: new Map(), report: [] };+ const generatedNodes = [];+ const geometryIds = new Set();+ const eye = recipe.camera?.eye ?? [0, 0, 0];+ for (const node of planted) {+ const { vegetation } = node;+ const key = cacheKey(recipe, node);+ if (!cache.has(key)) {+ if (cache.size >= VEGETATION_LIMITS.maxCachedSets) cache.delete(cache.keys().next().value);+ cache.set(key, { serial: ++cache.serial, grown: grow(recipe, vegetation), outputs: new Map() });+ }+ const entry = cache.get(key);+ const bare = vegetation.season >= BARE_SEASON;+ const world = nodeWorldMatrix(recipe.nodes, node);+ const variantIds = new Map(entry.grown.variants.map((variant, index) => [variant, index]));+ const materialIds = new Map();+ const bySpecies = {};+ let triangles = 0;+ let culled = 0;+ entry.grown.instances.forEach((instance, instanceIndex) => {+ const position = [instance.matrix[12], instance.matrix[13], instance.matrix[14]];+ const worldPosition = [+ world[0] * position[0] + world[4] * position[1] + world[8] * position[2] + world[12],+ world[1] * position[0] + world[5] * position[1] + world[9] * position[2] + world[13],+ world[2] * position[0] + world[6] * position[1] + world[10] * position[2] + world[14],+ ];+ const distance = Math.hypot(eye[0] - worldPosition[0], eye[1] - worldPosition[1], eye[2] - worldPosition[2]);+ const level = levelForDistance(distance, instance.variant, { distanceScale: vegetation.distanceScale, cullDistance: vegetation.cullDistance });+ const counts = bySpecies[instance.species] ??= { instances: 0, levels: [] };+ counts.instances++;+ if (level < 0) {+ culled++;+ return;+ }+ counts.levels[level] = (counts.levels[level] ?? 0) + 1;+ const leafless = bare && DECIDUOUS_SPECIES.has(instance.species);+ const seasonal = DECIDUOUS_SPECIES.has(instance.species) || instance.species === 'grass';+ instance.variant.levels[level].parts.forEach((part, partIndex) => {+ if (leafless && part.tintable) return;+ const geometryId = `vegetation:${entry.serial}:${variantIds.get(instance.variant)}:${level}:${partIndex}`;+ if (!geometryIds.has(geometryId)) {+ geometryIds.add(geometryId);+ recipe.geometries.push({ id: geometryId, type: 'asset', vegetation: entry.serial });+ runtime.geometryParts.set(geometryId, part.geometry);+ }+ const tinted = part.tintable && seasonal && vegetation.season > 0;+ if (!materialIds.has(part.material)) materialIds.set(part.material, materialIds.size);+ const materialId = `vegetation:${entry.serial}:${variantIds.get(instance.variant)}:${materialIds.get(part.material)}:${tinted ? `s${vegetation.season}` : 'plain'}`;+ if (!runtime.materialOutputs.has(materialId)) {+ if (!entry.outputs.has(materialId)) {+ entry.outputs.set(materialId, Object.freeze(tinted ? seasonalMaterial(part.material, instance.variant, instance.species, vegetation.season) : { ...part.material }));+ }+ runtime.materialOutputs.set(materialId, entry.outputs.get(materialId));+ recipe.materials.push({ id: materialId, ...materialJson(entry.outputs.get(materialId)), assetSource: true });+ }+ const partNodeId = `${node.id}/${instanceIndex}/${part.role}`;+ generatedNodes.push({+ id: partNodeId, parent: node.id, label: `${instance.species} ${part.role}`,+ translation: [0, 0, 0], rotation: [0, 0, 0, 1], scale: [1, 1, 1],+ geometry: geometryId, material: materialId, assetPart: { placement: node.id, index: instanceIndex, matrix: Array.from(instance.matrix) },+ });+ if (part.shadowLods) runtime.partExtras.set(partNodeId, { shadowLods: part.shadowLods });+ triangles += part.geometry.indices.length / 3;+ });+ });+ runtime.report.push({+ node: node.id, mode: vegetation.scatter ? 'scatter' : 'tree', instances: entry.grown.instances.length, culled,+ season: vegetation.season, bare, triangles,+ species: Object.fromEntries(Object.entries(bySpecies).map(([name, counts]) => [name, { instances: counts.instances, levels: Array.from(counts.levels, count => count ?? 0) }])),+ });+ }+ if (recipe.nodes.length + generatedNodes.length > limits.maxNodes) {+ throw new RangeError(`Vegetation expands to ${generatedNodes.length} part nodes, which with the ${recipe.nodes.length} authored nodes exceeds maxNodes ${limits.maxNodes}. Lower density or cull far trees with cullDistance.`);+ }+ recipe.nodes.push(...generatedNodes);+ return runtime;+}++/** The cache a scene keeps for grown vegetation; a Map with a serial counter so geometry IDs never repeat. */+export function createVegetationCache() {+ const cache = new Map();+ cache.serial = 0;+ return cache;+}diff --git a/src/renderer.js b/src/renderer.jsindex a12bcbc1..19362a21 100644--- a/src/renderer.js+++ b/src/renderer.js@@ -527,7 +527,7 @@ export class Renderer67 {this.splatResources = new Map();this.textureBytes = 4;this.shadowsDirty = true;- this.windState = { time: 0, strength: 0.3 };+ this.windState = { time: 0, strength: 0.3, heading: 0 };// The shadow map the constructor draws uses no assembly, so a first frame with none does not draw it again.this.assemblyAmount = 0;const groups = groupParts(this.groundPart ? [...parts, this.groundPart] : parts, batching);@@ -632,7 +632,7 @@ export class Renderer67 {this.depthAlphaUniforms = Object.fromEntries(DEPTH_ALPHA_UNIFORMS.map(name => [name, this.context.getUniformLocation(this.depthProgram, name)]));this.depthUniform = this.context.getUniformLocation(this.depthProgram, 'lightProjection');this.depthAssemblyUniform = this.context.getUniformLocation(this.depthProgram, 'assemblyAmount');- this.depthWindUniforms = { time: this.context.getUniformLocation(this.depthProgram, 'time'), wind: this.context.getUniformLocation(this.depthProgram, 'wind') };+ this.depthWindUniforms = { time: this.context.getUniformLocation(this.depthProgram, 'time'), wind: this.context.getUniformLocation(this.depthProgram, 'wind'), heading: this.context.getUniformLocation(this.depthProgram, 'windHeading') };this.partCount = parts.length;this.triangles = parts.reduce((total, part) => total + part.geometry.indices.length / 3, 0);this.whiteTexture = this.createTexture(null);@@ -707,7 +707,7 @@ export class Renderer67 {finishMainProgram(pendingProgram) {this.program = finishProgram(this.context, pendingProgram);- this.uniforms = Object.fromEntries(['materialDielectric', 'materialCoat', 'materialSheen', 'materialAnisotropy', 'materialIridescence', 'lightLinkMask', 'boxMapScale', 'boxMapAxis', 'lightMap', 'lightMapScale', 'hasLightMap', 'viewProjection', 'lightProjection', 'eye', 'armorColor', 'armorSurface', 'exposure', 'inspection', 'shadowMap', 'shadowBiasPerSlope', ...MAP_UNIFORMS, ...MAP_FLAGS, ...SKIN_UNIFORMS, ...MORPH_UNIFORMS, 'normalScale', 'occlusionStrength', 'materialMoss', ...SPLAT_UNIFORMS, 'hdrEnabled', 'time', 'wind', 'worldMode', 'daylight', 'fogColor', 'lightDirection', 'fogDensity', 'waterRipple', 'rippleTime', 'explosionProgress', 'explosionCenter', 'assemblyAmount', 'renderPassMode', 'renderPassDepthRange', 'renderPassObjectBase', ...ALPHA_UNIFORMS].map((name) => [name, this.context.getUniformLocation(this.program, name)]));+ this.uniforms = Object.fromEntries(['materialDielectric', 'materialCoat', 'materialSheen', 'materialAnisotropy', 'materialIridescence', 'lightLinkMask', 'boxMapScale', 'boxMapAxis', 'lightMap', 'lightMapScale', 'hasLightMap', 'viewProjection', 'lightProjection', 'eye', 'armorColor', 'armorSurface', 'exposure', 'inspection', 'shadowMap', 'shadowBiasPerSlope', ...MAP_UNIFORMS, ...MAP_FLAGS, ...SKIN_UNIFORMS, ...MORPH_UNIFORMS, 'normalScale', 'occlusionStrength', 'materialMoss', ...SPLAT_UNIFORMS, 'hdrEnabled', 'time', 'wind', 'windHeading', 'worldMode', 'daylight', 'fogColor', 'lightDirection', 'fogDensity', 'waterRipple', 'rippleTime', 'explosionProgress', 'explosionCenter', 'assemblyAmount', 'renderPassMode', 'renderPassDepthRange', 'renderPassObjectBase', ...ALPHA_UNIFORMS].map((name) => [name, this.context.getUniformLocation(this.program, name)]));for (const name of LIGHT_UNIFORMS) {this.uniforms[name] = this.context.getUniformLocation(this.program, name);}@@ -1342,6 +1342,7 @@ export class Renderer67 {context.uniform1f(this.depthAssemblyUniform, this.assemblyAmount ?? 0);context.uniform1f(this.depthWindUniforms.time, this.windState.time);context.uniform1f(this.depthWindUniforms.wind, this.windState.strength);+ context.uniform1f(this.depthWindUniforms.heading, this.windState.heading);// The base map sampler must not alias the shadow texture on unit 0 while that texture is the render target.context.uniform1i(this.depthAlphaUniforms.baseMap, 1);context.enable(context.POLYGON_OFFSET_FILL);@@ -1413,10 +1414,10 @@ export class Renderer67 {/** Stores the wind time and strength the shadow pass must use; true when swaying batches need a new shadow map. */updateWindState(frame) {- const next = { time: frame.time ?? 0, strength: frame.wind ?? 0.3 };+ const next = { time: frame.time ?? 0, strength: frame.wind ?? 0.3, heading: frame.windHeading ?? 0 };const previous = this.windState;this.windState = next;- if (previous.time === next.time && previous.strength === next.strength) return false;+ if (previous.time === next.time && previous.strength === next.strength && previous.heading === next.heading) return false;return this.batches.some(batch => batch.castShadow && SWAYING_TAGS.has(batch.parts[0].material.tag));}@@ -2124,6 +2125,7 @@ export class Renderer67 {context.uniform1f(this.uniforms.ambientIntensity, this.lighting.ambientIntensity);context.uniform1f(this.uniforms.time, frame.time ?? 0);context.uniform1f(this.uniforms.wind, frame.wind ?? 0.3);+ context.uniform1f(this.uniforms.windHeading, frame.windHeading ?? 0);context.uniform1f(this.uniforms.worldMode, this.world ? 1 : 0);context.uniform1f(this.uniforms.daylight, environment.daylight);context.uniform3fv(this.uniforms.lightDirection, environment.lightDirection);diff --git a/src/vegetation.js b/src/vegetation.jsindex b2dccda6..17580aac 100644--- a/src/vegetation.js+++ b/src/vegetation.js@@ -767,6 +767,11 @@ export function selectLevels(instances, eye, { distanceScale = 1, hysteresis = 0return { parts, changed, levelCounts: Array.from(levelCounts, count => count ?? 0), culled, triangles };}+/** The level of detail for one distance, without hysteresis: a pure function of the distance, or -1 past cullDistance. */+export function levelForDistance(distance, variant, { distanceScale = 1, cullDistance = Infinity } = {}) {+ return nextLevel(-1, distance, variant.distances.map(threshold => threshold * distanceScale), 0, cullDistance);+}+/** Renderer parts for one tree (or clump) placed by `matrix`, at a level of detail. */export function vegetationParts(variant, matrix, levelIndex = 0, name = variant.species) {return variant.levels[levelIndex].parts.map(part => ({ name: `${name} ${part.role}`, geometry: part.geometry, shadowLods: part.shadowLods, matrix, material: part.material }));diff --git a/src/world-material-shader.js b/src/world-material-shader.jsindex e3d1c779..557179ae 100644--- a/src/world-material-shader.js+++ b/src/world-material-shader.js@@ -16,10 +16,15 @@ export const worldMaterialSlots = {worldVertexWind: `// Grass bends by how far up the blade a vertex is (uv.y is 1 at the root), so it ignores terrain height.// Gusts roll across the field as a travelling wave along the wind direction, like the rolling bands in a meadow.+// windHeading turns the wind about the vertical axis, in radians; 0 is the default heading toward +x.+uniform float windHeading;+vec3 grassWind(vec3 worldPoint, vec2 leafUv, float seconds, float strength) {float tip = clamp(1.0 - leafUv.y, 0.0, 1.0);float bendWeight = tip * tip;- vec2 windDirection = vec2(0.94, 0.34);+ float headingCos = cos(windHeading);+ float headingSin = sin(windHeading);+ vec2 windDirection = vec2(0.94 * headingCos - 0.34 * headingSin, 0.94 * headingSin + 0.34 * headingCos);float along = dot(worldPoint.xz, windDirection);float gust = 0.5 + 0.5 * sin(along * 0.32 - seconds * 1.7 + 2.0 * sin(worldPoint.x * 0.05 - worldPoint.z * 0.04 + seconds * 0.23));float push = (0.3 + 0.7 * gust * gust) * strength;@@ -37,7 +42,9 @@ vec3 windOffset(vec3 localPosition, vec3 worldPoint, vec2 leafUv, float surfaceTfloat sway = sin(seconds * 1.2 + worldPoint.z * 0.31 + worldPoint.x * 0.17) * strength * 0.10 * heightReach * branchReach;float tip = clamp(1.0 - leafUv.y, 0.0, 1.0);float flutter = sin(seconds * 3.1 + worldPoint.x * 1.7 + worldPoint.z * 1.3 + localPosition.y * 2.0) * strength * 0.08 * tip;- return vec3(sway + flutter, 0.0, flutter * 0.6);+ vec2 heading = vec2(cos(windHeading), sin(windHeading));+ vec2 push = heading * (sway + flutter) + vec2(-heading.y, heading.x) * (flutter * 0.6);+ return vec3(push.x, 0.0, push.y);}`,worldFunctions: `float terrainHash(vec2 position) {diff --git a/tests/agent-scene-vegetation.test.js b/tests/agent-scene-vegetation.test.jsnew file mode 100644index 00000000..07ab9b68--- /dev/null+++ b/tests/agent-scene-vegetation.test.js@@ -0,0 +1,166 @@+import test from 'node:test';+import assert from 'node:assert/strict';+import { parseGltf } from '../src/gltf.js';+import { createAgentScene, loadAllAgentSceneModules } from '../src/agent-scene.js';+import { assetCopyKey } from '../src/agent-scene-assets.js';+import { createTerrain } from '../src/terrain.js';+import { scatterVegetation } from '../src/vegetation.js';+import { seasonLeafColor } from '../src/agent-vegetation.js';+import { skinnedStripAsset } from './fixtures/skinned-strip.js';++await loadAllAgentSceneModules();++const GROUND = { id: 'ground', type: 'terrain', size: 60, resolution: 48, seed: 3, amplitude: 2 };+const CLEARING = { center: [0, 0], radius: 9 };+const SCATTER = { ground: 'hills', density: 0.02, slopeLimit: 30, exclude: [CLEARING], variants: 2 };++function forestRecipe(overrides = {}) {+ return {+ format: '67js.scene', schemaVersion: 1,+ geometries: [GROUND, { id: 'marker', type: 'box' }],+ materials: [{ id: 'grass', tag: 'grass', color: [0.2, 0.4, 0.1] }, { id: 'steel', color: [0.6, 0.6, 0.6] }],+ nodes: [+ { id: 'hills', geometry: 'ground', material: 'grass' },+ { id: 'forest', vegetation: { mix: { broadleaf: 3, birch: 1, conifer: 2 }, seed: 11, scatter: SCATTER, ...overrides } },+ { id: 'marker', geometry: 'marker', material: 'steel', translation: [0, 1, 0] },+ ],+ camera: { eye: [0, 6, 40], target: [0, 4, 0] },+ environment: { wind: { strength: 0.8, direction: 30 } },+ motion: { duration: 2, tracks: [{ kind: 'node', id: 'marker', property: 'translation', keyframes: [{ time: 0, value: [0, 1, 0] }, { time: 2, value: [3, 1, 0] }] }] },+ };+}++function stillRecipe() {+ const { motion, ...still } = forestRecipe();+ return still;+}++function vegetationMatrices(scene) {+ return scene.parts.filter(part => part.name.startsWith('forest/')).map(part => [part.name, Array.from(part.matrix)]);+}++test('a forest clearing grows on terrain through the recipe, keeps the clearing clear, and a seek gives the same frame', () => {+ const scene = createAgentScene(forestRecipe());+ const report = scene.inspect().vegetation[0];+ assert.equal(report.mode, 'scatter');+ assert.ok(report.instances > 20, `placed ${report.instances}`);+ const parts = scene.parts.filter(part => part.name.startsWith('forest/'));+ assert.ok(parts.length >= report.instances, 'bark and foliage parts for the instances');+ for (const part of parts) {+ assert.ok(Math.hypot(part.matrix[12], part.matrix[14]) > CLEARING.radius, `${part.name} stands outside the clearing`);+ }+ const counted = Object.values(report.species).reduce((total, species) => total + species.instances, 0);+ assert.equal(counted, report.instances);+ const drawnLevels = Object.values(report.species).flatMap(species => species.levels).reduce((total, count) => total + count, 0);+ assert.equal(drawnLevels + report.culled, report.instances);+ assert.ok(report.triangles > 0);+ assert.ok(parts.some(part => part.material.tag === 'foliage'));++ const before = vegetationMatrices(scene);+ const levelsBefore = JSON.stringify(report.species);+ scene.sampleMotion(1.5);+ assert.equal(scene.parts.find(part => part.name === 'marker').matrix[12], 2.25, 'the motion did move the scene');+ assert.deepEqual(vegetationMatrices(scene), before);+ scene.sampleMotion(0);+ assert.deepEqual(vegetationMatrices(scene), before);+ assert.equal(JSON.stringify(scene.inspect().vegetation[0].species), levelsBefore);+});++test('the same scatter through the recipe and through the addon gives the same instances for a seed', () => {+ const scene = createAgentScene(forestRecipe());+ const terrain = createTerrain({+ size: 60, chunks: 1, levels: 1, resolution: 48, seed: 3,+ height: { amplitude: 2, featureSize: 15, warp: 0, mountainMask: () => 0 },+ });+ const addon = scatterVegetation({+ area: { minX: -29.5, maxX: 29.5, minZ: -29.5, maxZ: 29.5 },+ density: 0.02, terrainHeight: terrain.heightAt, slopeLimit: 30,+ exclusion: (x, z) => Math.hypot(x - CLEARING.center[0], z - CLEARING.center[1]) <= CLEARING.radius,+ seed: 11, mix: { broadleaf: 3, birch: 1, conifer: 2 }, variants: 2, leaves: 'cards',+ });+ const recipePlaced = new Map();+ for (const part of scene.parts.filter(candidate => candidate.name.startsWith('forest/'))) {+ recipePlaced.set(Number(part.name.split('/')[1]), Array.from(part.matrix));+ }+ assert.equal(scene.inspect().vegetation[0].instances, addon.instances.length);+ assert.ok(addon.instances.length > 20);+ addon.instances.forEach((instance, index) => {+ assert.deepEqual(recipePlaced.get(index), Array.from(instance.matrix), `instance ${index} (${instance.species})`);+ });+ assert.deepEqual(scene.inspect().vegetation[0].species, Object.fromEntries(Object.entries(addon.counts).map(([name, count]) => [name, { instances: count, levels: scene.inspect().vegetation[0].species[name].levels }])));+});++test('levels follow the recipe camera and are not changed by time', () => {+ const near = createAgentScene(forestRecipe()).inspect().vegetation[0];+ const far = createAgentScene({ ...forestRecipe(), camera: { eye: [0, 6, 400], target: [0, 4, 0] } }).inspect().vegetation[0];+ const meanLevel = report => {+ const levels = Object.values(report.species).flatMap(species => species.levels.map((count, level) => [count, level]));+ return levels.reduce((total, [count, level]) => total + count * level, 0) / Math.max(1, levels.reduce((total, [count]) => total + count, 0));+ };+ assert.ok(meanLevel(far) > meanLevel(near));+ const culled = createAgentScene(forestRecipe({ cullDistance: 20 })).inspect().vegetation[0];+ assert.ok(culled.culled > 0 && culled.culled < culled.instances);+});++test('season tints leaves, and bare season drops deciduous foliage but keeps conifers green', () => {+ const leafMap = scene => scene.parts.find(part => part.material.tag === 'foliage').material.map;+ const stand = season => createAgentScene({ ...stillRecipe(), nodes: [+ { id: 'hills', geometry: 'ground', material: 'grass' },+ { id: 'forest', vegetation: { mix: { broadleaf: 1 }, seed: 5, season, scatter: SCATTER } },+ ] });+ const summer = stand(0);+ const autumn = stand(0.5);+ assert.notEqual(leafMap(autumn), leafMap(summer), 'autumn recolours the leaf sprite');+ assert.deepEqual(seasonLeafColor([64, 110, 36], 0), [64, 110, 36]);+ assert.deepEqual(seasonLeafColor([64, 110, 36], 0.35), [196, 150, 40]);+ const bare = createAgentScene(forestRecipe({ season: 1 }));+ const roles = bare.parts.filter(part => part.name.startsWith('forest/')).map(part => part.name.split('/')[2]);+ assert.ok(roles.includes('foliage'), 'conifer foliage stays');+ const deciduousOnly = stand(1);+ assert.ok(deciduousOnly.parts.filter(part => part.name.startsWith('forest/')).every(part => part.name.endsWith('/bark')));+});++test('one tree grows at the node transform and validation names the problem', () => {+ const single = createAgentScene({+ format: '67js.scene', schemaVersion: 1,+ nodes: [{ id: 'oak', translation: [4, 0, 2], vegetation: { species: 'broadleaf', seed: 2, height: 9 } }],+ camera: { eye: [4, 4, 20], target: [4, 4, 2] },+ });+ assert.equal(single.inspect().vegetation[0].mode, 'tree');+ assert.equal(single.parts.length, 2);+ assert.equal(single.parts[0].matrix[12], 4);+ const bad = (vegetation, pattern) => assert.throws(() => createAgentScene({ ...stillRecipe(), nodes: [{ id: 'hills', geometry: 'ground', material: 'grass' }, { id: 'marker', geometry: 'marker', material: 'steel' }, { id: 'forest', vegetation }] }), pattern);+ bad({ mix: { broadleaf: 1 }, scatter: { ground: 'marker' } }, /terrain/);+ bad({ mix: { oak: 1 }, scatter: { ground: 'hills' } }, /species/);+ bad({ species: 'broadleaf', mix: { birch: 1 } }, /exactly one/);+ bad({ species: 'grass' }, /species must be/);+ bad({ mix: { grass: 1 }, scatter: { ground: 'hills', density: 4 } }, /try about/);+});++test('environment.wind validates and survives export', () => {+ const scene = createAgentScene(forestRecipe());+ assert.deepEqual(scene.environment.wind, { strength: 0.8, direction: 30 });+ assert.deepEqual(scene.exportRecipe().environment.wind, { strength: 0.8, direction: 30 });+ assert.throws(() => createAgentScene({ ...forestRecipe(), environment: { wind: { strength: 9 } } }), /strength/);+ assert.throws(() => createAgentScene({ ...forestRecipe(), environment: { wind: { speed: 1 } } }), /Unknown wind field/);+});++test('an imported tree with a foliage override gets the swaying tag and shares it between placements', async () => {+ const id = 'ef'.repeat(32);+ const asset = await parseGltf(skinnedStripAsset(document => { document.materials[0].name = 'Leaves'; }));+ const assets = new Map([[assetCopyKey(id, 0), asset]]);+ const recipe = {+ format: '67js.scene', schemaVersion: 1,+ nodes: [+ { id: 'a', asset: { id, materials: [{ name: 'Leaves', tag: 'foliage', color: [0.2, 0.5, 0.1] }] } },+ { id: 'b', translation: [3, 0, 0], asset: { id, materials: [{ name: 'Leaves', tag: 'foliage', color: [0.2, 0.5, 0.1] }] } },+ { id: 'plain', translation: [6, 0, 0], asset: { id } },+ ],+ };+ const scene = createAgentScene(recipe, {}, { assets });+ const material = name => scene.parts.find(part => part.name === `${name}/0`).material;+ assert.equal(material('a').tag, 'foliage');+ assert.equal(material('a'), material('b'));+ assert.notEqual(material('plain').tag, 'foliage');+ assert.throws(() => createAgentScene({ ...recipe, nodes: [{ id: 'a', asset: { id, materials: [{ name: 'Leaves', tag: 'water' }] } }] }, {}, { assets }), /tag must be one of/);+});