Skip to content

armgit / 67.js

Public Imported from GitHub
0

3D engine that AI agents drive

Add walking routes over terrain with holes (Part of #64)

Nguyen Xuan An5989af134663
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 609f51ba..4c1cbd23 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -2,6 +2,8 @@
## Unreleased
+- Add walking routes over terrain with holes (part of issue #64; splat layers stay at four, see `docs/terrain.md`). `addons/navmesh` builds a walkable grid from triangles (slope limit, agent radius, holes, obstacle footprints) and `findPath` runs A* with line-of-sight string pulling, deterministic, with cell and search budgets that throw a `RangeError` naming what to raise. `scene_inspect` takes `path: { ground, from, to, avoid, ... }` and returns keyframes for a node translation track, described in `scene_capabilities` `navigation`; the `scene_capabilities` result grew by 624 bytes and the `scene_inspect` schema by one record field. The suite gets `terrain-path-walk` (two holes and a rock) and records `pathQueries`; the `walkPath` check takes several openings and `avoidNodes`. Size: `entry:navmesh` 3,257 B gzip, `agent-scene+lazy` +4.5 KB, core entries unchanged.
+
- Import `SheenChair` and score it (part of issue #51). A glTF normal map may now carry its own `KHR_texture_transform` offset and positive scale (same rotation) on top of the transform the other maps share: the importer bakes the shared one into the UVs and stores the remainder as `uvTransform` on the normal map descriptor, and the `normalMapTransform` shader feature in `addons/material-layer-shaders` applies it (a scene without such a normal map compiles the same shader as before). Any other difference between the maps of one material still fails the import, and an extension `texCoord` equal to the texture's own is no longer refused. Core grew by 25 bytes gzip (`lit-box` 60,179 to 60,204): a hook in the normal map lookup, one feature line and the `bind` argument; the glTF importer grew by about 370.
- Fix the automatic floor skipping a lone flat object (part of issue #53). A lone part never counts as the recipe's own floor, so a gear lying flat, which spans its whole scene and is the lowest geometry, now gets a floor and a contact shadow (before, `agentGroundPlacement` returned null for it). The surface judge on the six cold recipes goes from 0 before the floor, to 6 with the first rule, to 7 with this fix (gear 0 to 1; one call per task, so direction only). A flat object with a hub on it is still read as a plate. Core did not change.
diff --git a/bench/agent-modeling/README.md b/bench/agent-modeling/README.md
index e595c9f7..e4274ad5 100644
--- a/bench/agent-modeling/README.md
+++ b/bench/agent-modeling/README.md
@@ -246,3 +246,14 @@ Every note names the same gap: the three-quarter view shows a surface and a shad
| Sonnet | off | 3/3 | 3, 3, 3 | 0 | $0.88 | 0 |
Result: agents ignored branches in all 12 runs. Sonnet wrote the right shade in its first `scene_apply` and exported (3 calls, with or without branches). Haiku varied from 3 to 7 calls either way, with no sign of an effect. Calls did not drop, so the issue's first done condition is not met. The task is too easy to need a comparison: the goal is arithmetic on sizes the prompt states. A task where the right variant can only be told from a render, or where a wrong pick costs a long repair, is the next try. Until then branches have no measured benefit on this suite.
+
+## A walk around two holes and a rock (2026-11-01, issue #64)
+
+`terrain-path-walk` builds 40 m of hills with two round openings (radius 3 m at the origin, 2.5 m at [9, 9]) and a 3 m by 2 m by 3 m `rock` at [-8, -8], then walks a `walker` node from [-15, -15] to [15, 15] in 10 s. The check on the exported recipe samples 41 times: the position stays within 1.5 m of the ground height, at least 0.3 m outside both openings and at least 0.3 m from the rock's footprint, and starts and ends within 0.75 m of the two points. The `through` check confirms both openings are cut clean through. The robot GLB cannot stand on a recipe terrain (asset scenes hold no recipe geometry), so the character is a box node, like `terrain-hole-walk`. The prompt does not mention the path query: agents find it in the `scene_inspect` schema (`path`) and in `scene_capabilities` `navigation`. `pathQueries` in each record counts `scene_inspect` calls that passed `path`.
+
+| Model | Runs | Pass | Calls | Errors | Cost | `path` queries |
+| --- | --- | --- | --- | --- | --- | --- |
+| Haiku | 2 | 2/2 | 12, 13 | 2, 2 | $0.15 | 2, 3 |
+| Sonnet | 1 | 1/1 | 9 | 0 | $0.40 | 3 |
+
+Result: all three agents used the query and wrote its keyframes into a `LINEAR` walker track (29 or 30 keys with the query's three-decimal values, not a hand-drawn polyline). The four Haiku errors were unrelated schema slips (`sessionId` on `scene_create`, motion keys at the recipe top level, a node with a geometry and no material), not path errors. Nothing here shows what the query saves: the task was not run with the query hidden, and an earlier task with one hole (`terrain-hole-walk`) was walked by hand 2 of 2 times by Haiku. Three runs is too few to separate Haiku from Sonnet. Total cost $0.55, one run each of the three.
diff --git a/bench/agent-modeling/check.mjs b/bench/agent-modeling/check.mjs
index 30ee76ee..34c9921f 100644
--- a/bench/agent-modeling/check.mjs
+++ b/bench/agent-modeling/check.mjs
@@ -56,8 +56,18 @@ function checkWalkPath(check, measures) {
if (!position) return { pass: false, detail: `no drawn node ${check.node}` };
if (sample === 0 && planarDistance(position, check.from) > 0.75) problems.push(`starts ${round(planarDistance(position, check.from))} m from the start point`);
if (sample === WALK_SAMPLES - 1 && planarDistance(position, check.to) > 0.75) problems.push(`ends ${round(planarDistance(position, check.to))} m from the end point`);
- const fromOpening = planarDistance(position, check.avoid.center) - check.avoid.radius;
- if (fromOpening < check.margin) problems.push(`${round(fromOpening)} m from the opening edge at t=${round(time)}`);
+ for (const opening of [].concat(check.avoid)) {
+ const fromOpening = planarDistance(position, opening.center) - opening.radius;
+ if (fromOpening < check.margin) problems.push(`${round(fromOpening)} m from the opening edge at t=${round(time)}`);
+ }
+ for (const nodeName of check.avoidNodes ?? []) {
+ const bounds = measures.nodeBounds(nodeName);
+ if (!bounds) return { pass: false, detail: `no drawn node ${nodeName}` };
+ const outsideX = Math.max(bounds.min[0] - position[0], 0, position[0] - bounds.max[0]);
+ const outsideZ = Math.max(bounds.min[2] - position[2], 0, position[2] - bounds.max[2]);
+ const fromNode = Math.hypot(outsideX, outsideZ);
+ if (fromNode < check.margin) problems.push(`${round(fromNode)} m from ${nodeName} at t=${round(time)}`);
+ }
const groundHeight = measures.surfaceHeight(check.ground, position[0], position[2]);
if (groundHeight === null) problems.push(`no ground under it at t=${round(time)}`);
else if (Math.abs(position[1] - groundHeight) > check.heightTolerance) problems.push(`${round(position[1] - groundHeight)} m off the ground at t=${round(time)}`);
diff --git a/bench/agent-modeling/references.mjs b/bench/agent-modeling/references.mjs
index 7c3eeb07..c2b9a3a7 100644
--- a/bench/agent-modeling/references.mjs
+++ b/bench/agent-modeling/references.mjs
@@ -398,6 +398,26 @@ export const REFERENCES = {
}],
},
},
+ 'terrain-path-walk': {
+ format: '67js.scene', schemaVersion: 1,
+ geometries: [
+ { id: 'hills', type: 'terrain', size: 40, resolution: 64, seed: 3, amplitude: 1, holes: [{ center: [0, 0], radius: 3 }, { center: [9, 9], radius: 2.5 }] },
+ { id: 'body', type: 'box', bevel: 0 },
+ ],
+ materials: [{ id: 'grass', color: [0.3, 0.55, 0.2] }, { id: 'coat', color: [0.8, 0.3, 0.2] }],
+ nodes: [
+ { id: 'ground', geometry: 'hills', material: 'grass' },
+ { id: 'rock', geometry: 'body', material: 'coat', translation: [-8, 1, -8], scale: [3, 2, 3] },
+ { id: 'walker', geometry: 'body', material: 'coat', translation: [-15, 0.5, -15], scale: [0.4, 1, 0.4] },
+ ],
+ motion: {
+ duration: 10,
+ tracks: [{
+ kind: 'node', id: 'walker', property: 'translation', interpolation: 'LINEAR',
+ keyframes: [[0, [-15, 0.5, -15]], [2.5, [-4, 0.5, -12]], [4, [-4, 0.5, -5]], [5.5, [5, 0.5, -5]], [7, [5, 0.5, 13]], [10, [15, 0.5, 15]]].map(([time, value]) => ({ time, value })),
+ }],
+ },
+ },
'pillar-court': scene(
[{ id: 'pillar', type: 'box', bevel: 0 }],
[{
diff --git a/bench/agent-modeling/results/2026-11-01-07-13-haiku-haiku-path-walk-cold.json b/bench/agent-modeling/results/2026-11-01-07-13-haiku-haiku-path-walk-cold.json
new file mode 100644
index 00000000..756e78d8
--- /dev/null
+++ b/bench/agent-modeling/results/2026-11-01-07-13-haiku-haiku-path-walk-cold.json
@@ -0,0 +1,146 @@
+{
+ "run": "2026-11-01-07-13-haiku-haiku-path-walk-cold",
+ "model": "claude-haiku-5-5",
+ "date": "2026-11-01T07:16:57.767Z",
+ "skill": false,
+ "branches": "on",
+ "runsPerTask": 2,
+ "passed": 2,
+ "tasks": 2,
+ "toolCalls": 25,
+ "costUsd": 0.15,
+ "byModel": {
+ "claude-haiku-5-5": {
+ "runs": 2,
+ "passed": 2,
+ "successRate": 1,
+ "toolCalls": 25,
+ "toolErrors": 4,
+ "inputTokens": 2611760,
+ "outputTokens": 19926,
+ "costUsd": 0.15,
+ "tasks": {
+ "terrain-path-walk": {
+ "runs": 2,
+ "passed": 2,
+ "successRate": 1,
+ "toolCalls": 25,
+ "toolErrors": 4,
+ "inputTokens": 2611760,
+ "outputTokens": 19926,
+ "costUsd": 0.15
+ }
+ }
+ }
+ },
+ "records": [
+ {
+ "task": "terrain-path-walk",
+ "attempt": 1,
+ "pass": true,
+ "passed": 3,
+ "total": 3,
+ "failed": [],
+ "model": "claude-haiku-5-5",
+ "toolCalls": 12,
+ "toolErrors": 2,
+ "toolsByName": {
+ "ToolSearch": 1,
+ "scene_capabilities": 1,
+ "scene_create": 3,
+ "scene_inspect": 3,
+ "scene_dispose": 1,
+ "scene_apply": 3,
+ "scene_export_recipe": 1
+ },
+ "branchCalls": 0,
+ "pathQueries": 2,
+ "features": {
+ "geometryTypes": [
+ "terrain",
+ "box"
+ ],
+ "meshOperations": [],
+ "motionIk": [],
+ "motionTracks": 1
+ },
+ "look": {
+ "silhouette": {
+ "views": {
+ "front": 0.5679,
+ "side": 0.6711,
+ "three-quarter": 0.9577
+ },
+ "mean": 0.7322
+ },
+ "images": [
+ "artifacts/agent-modeling/2026-11-01-07-13-haiku-haiku-path-walk-cold/look/1/terrain-path-walk-front.png",
+ "artifacts/agent-modeling/2026-11-01-07-13-haiku-haiku-path-walk-cold/look/1/terrain-path-walk-side.png",
+ "artifacts/agent-modeling/2026-11-01-07-13-haiku-haiku-path-walk-cold/look/1/terrain-path-walk-three-quarter.png"
+ ]
+ },
+ "turns": 14,
+ "costUsd": 0.05969754,
+ "inputTokens": 1182557,
+ "outputTokens": 8612,
+ "wallSeconds": 78,
+ "exitCode": 0,
+ "stopped": "success"
+ },
+ {
+ "task": "terrain-path-walk",
+ "attempt": 2,
+ "pass": true,
+ "passed": 3,
+ "total": 3,
+ "failed": [],
+ "model": "claude-haiku-5-5",
+ "toolCalls": 13,
+ "toolErrors": 2,
+ "toolsByName": {
+ "ToolSearch": 1,
+ "scene_capabilities": 1,
+ "scene_create": 2,
+ "scene_inspect": 4,
+ "scene_apply": 2,
+ "scene_look": 1,
+ "scene_review": 1,
+ "scene_export_recipe": 1,
+ "scene_dispose": 1
+ },
+ "branchCalls": 0,
+ "pathQueries": 3,
+ "features": {
+ "geometryTypes": [
+ "terrain",
+ "box"
+ ],
+ "meshOperations": [],
+ "motionIk": [],
+ "motionTracks": 1
+ },
+ "look": {
+ "silhouette": {
+ "views": {
+ "front": 0.5712,
+ "side": 0.6692,
+ "three-quarter": 0.9587
+ },
+ "mean": 0.733
+ },
+ "images": [
+ "artifacts/agent-modeling/2026-11-01-07-13-haiku-haiku-path-walk-cold/look/2/terrain-path-walk-front.png",
+ "artifacts/agent-modeling/2026-11-01-07-13-haiku-haiku-path-walk-cold/look/2/terrain-path-walk-side.png",
+ "artifacts/agent-modeling/2026-11-01-07-13-haiku-haiku-path-walk-cold/look/2/terrain-path-walk-three-quarter.png"
+ ]
+ },
+ "turns": 15,
+ "costUsd": 0.08857357,
+ "inputTokens": 1429203,
+ "outputTokens": 11314,
+ "wallSeconds": 127,
+ "exitCode": 0,
+ "stopped": "success"
+ }
+ ]
+}
diff --git a/bench/agent-modeling/results/2026-11-01-07-16-sonnet-sonnet-path-walk-cold.json b/bench/agent-modeling/results/2026-11-01-07-16-sonnet-sonnet-path-walk-cold.json
new file mode 100644
index 00000000..bd6e82ac
--- /dev/null
+++ b/bench/agent-modeling/results/2026-11-01-07-16-sonnet-sonnet-path-walk-cold.json
@@ -0,0 +1,90 @@
+{
+ "run": "2026-11-01-07-16-sonnet-sonnet-path-walk-cold",
+ "model": "claude-sonnet-5-5",
+ "date": "2026-11-01T07:18:23.344Z",
+ "skill": false,
+ "branches": "on",
+ "runsPerTask": 1,
+ "passed": 1,
+ "tasks": 1,
+ "toolCalls": 9,
+ "costUsd": 0.4,
+ "byModel": {
+ "claude-sonnet-5-5": {
+ "runs": 1,
+ "passed": 1,
+ "successRate": 1,
+ "toolCalls": 9,
+ "toolErrors": 0,
+ "inputTokens": 658033,
+ "outputTokens": 3121,
+ "costUsd": 0.4,
+ "tasks": {
+ "terrain-path-walk": {
+ "runs": 1,
+ "passed": 1,
+ "successRate": 1,
+ "toolCalls": 9,
+ "toolErrors": 0,
+ "inputTokens": 658033,
+ "outputTokens": 3121,
+ "costUsd": 0.4
+ }
+ }
+ }
+ },
+ "records": [
+ {
+ "task": "terrain-path-walk",
+ "attempt": 1,
+ "pass": true,
+ "passed": 3,
+ "total": 3,
+ "failed": [],
+ "model": "claude-sonnet-5-5",
+ "toolCalls": 9,
+ "toolErrors": 0,
+ "toolsByName": {
+ "ToolSearch": 1,
+ "scene_capabilities": 1,
+ "scene_create": 1,
+ "scene_inspect": 4,
+ "scene_apply": 2,
+ "scene_export_recipe": 1
+ },
+ "branchCalls": 0,
+ "pathQueries": 3,
+ "features": {
+ "geometryTypes": [
+ "terrain",
+ "box"
+ ],
+ "meshOperations": [],
+ "motionIk": [],
+ "motionTracks": 1
+ },
+ "look": {
+ "silhouette": {
+ "views": {
+ "front": 0.5687,
+ "side": 0.6786,
+ "three-quarter": 0.9573
+ },
+ "mean": 0.7349
+ },
+ "images": [
+ "artifacts/agent-modeling/2026-11-01-07-16-sonnet-sonnet-path-walk-cold/look/1/terrain-path-walk-front.png",
+ "artifacts/agent-modeling/2026-11-01-07-16-sonnet-sonnet-path-walk-cold/look/1/terrain-path-walk-side.png",
+ "artifacts/agent-modeling/2026-11-01-07-16-sonnet-sonnet-path-walk-cold/look/1/terrain-path-walk-three-quarter.png"
+ ]
+ },
+ "turns": 11,
+ "costUsd": 0.40017120000000006,
+ "inputTokens": 658033,
+ "outputTokens": 3121,
+ "wallSeconds": 56,
+ "exitCode": 0,
+ "stopped": "success"
+ }
+ ]
+}
diff --git a/bench/agent-modeling/run.mjs b/bench/agent-modeling/run.mjs
index d64884c4..cedab3e0 100644
--- a/bench/agent-modeling/run.mjs
+++ b/bench/agent-modeling/run.mjs
@@ -102,7 +102,7 @@ function textOf(content) {
/** Tool calls, errors, the model, usage and the last exported recipe from a stream-json transcript. */
function readTranscript(output) {
- const summary = { model: null, toolCalls: 0, toolErrors: 0, toolsByName: {}, branchCalls: 0, recipe: null, result: null };
+ const summary = { model: null, toolCalls: 0, toolErrors: 0, toolsByName: {}, branchCalls: 0, pathQueries: 0, recipe: null, result: null };
const exportCalls = new Set();
for (const line of output.split('\n')) {
if (!line.trim().startsWith('{')) continue;
@@ -121,6 +121,7 @@ function readTranscript(output) {
if (block.name !== 'ToolSearch') summary.toolCalls++;
summary.toolsByName[name] = (summary.toolsByName[name] ?? 0) + 1;
if (block.input?.branch !== undefined || block.input?.shots?.some(shot => shot.branch !== undefined)) summary.branchCalls++;
+ if (name.endsWith('scene_inspect') && block.input?.path !== undefined) summary.pathQueries++;
if (block.name === EXPORT_TOOL) exportCalls.add(block.id);
}
}
@@ -186,6 +187,7 @@ async function runTask(task, attempt, systemPromptAddition) {
toolErrors: transcript.toolErrors,
toolsByName: transcript.toolsByName,
branchCalls: transcript.branchCalls,
+ pathQueries: transcript.pathQueries,
features: transcript.recipe ? recipeFeatures(transcript.recipe) : null,
look: transcript.recipe ? await scoreLookSafely(task.id, transcript.recipe, { imageDirectory: join(rawDirectory, 'look', String(attempt)) }) : null,
turns: transcript.result?.num_turns ?? null,
diff --git a/bench/agent-modeling/terrain.mjs b/bench/agent-modeling/terrain.mjs
index d3cf6b63..4c5b5c3f 100644
--- a/bench/agent-modeling/terrain.mjs
+++ b/bench/agent-modeling/terrain.mjs
@@ -23,4 +23,22 @@ starts at time 0. Keep the walker's node position within 1.5 m of the ground sur
{ kind: 'walkPath', node: 'walker', ground: 'ground', from: WALK_FROM, to: WALK_TO, duration: WALK_SECONDS, avoid: { center: OPENING_CENTER, radius: OPENING_RADIUS }, margin: 0.3, heightTolerance: 1.5 },
],
},
+ {
+ id: 'terrain-path-walk',
+ prompt: `You are working with the 67js MCP tools. Units are metres and Y is up. Build a stretch of rolling ground ${GROUND_SIZE} m by ${GROUND_SIZE} m, centred on X = 0 and Z = 0, as a node named ground:
+gentle hills whose highest and lowest points differ by about 1.2 m. Two round openings are cut clean through the ground, with no surface inside them: one of radius ${OPENING_RADIUS} m
+centred on X = 0, Z = 0, and one of radius 2.5 m centred on X = 9, Z = 9. Add a node named rock, a box 3 m by 2 m by 3 m centred on X = -8, Z = -8 and standing on the ground.
+Add a node named walker (a small body that is itself drawn, say a box 0.4 m by 1 m by 0.4 m) that walks across the ground from [X = ${WALK_FROM[0]}, Z = ${WALK_FROM[1]}] to
+[X = ${WALK_TO[0]}, Z = ${WALK_TO[1]}] over a ${WALK_SECONDS} second motion that starts at time 0. Keep the walker's node position within 1.5 m of the ground surface height, at least 0.3 m outside
+both openings' edges and at least 0.3 m from the rock's footprint for the whole walk, so it goes around them. When it is finished, call scene_export_recipe once: the exported recipe is what gets graded.`,
+ ownPreamble: true,
+ checks: [
+ { kind: 'groundRelief', node: 'ground', min: 0.6, max: 2.2 },
+ { kind: 'through', axis: 'y', open: [[0.13, 0.07], [2.5, 0.11], [9.1, 9.05], [10.9, 9.1], [9.05, 7.2]], solid: [[3.6, 0.13], [0.13, 3.6], [-3.6, 0.13], [12.2, 9.1], [9.1, 12.2], [-12.07, 12.11], [15.07, 5.11]] },
+ {
+ kind: 'walkPath', node: 'walker', ground: 'ground', from: WALK_FROM, to: WALK_TO, duration: WALK_SECONDS,
+ avoid: [{ center: OPENING_CENTER, radius: OPENING_RADIUS }, { center: [9, 9], radius: 2.5 }], avoidNodes: ['rock'], margin: 0.3, heightTolerance: 1.5,
+ },
+ ],
+ },
];
diff --git a/bench/size/budgets.json b/bench/size/budgets.json
index bfc45622..5e6a9001 100644
--- a/bench/size/budgets.json
+++ b/bench/size/budgets.json
@@ -27,6 +27,7 @@
"entry:vehicle": 14700,
"entry:vegetation": 17900,
"entry:terrain": 3400,
+ "entry:navmesh": 3300,
"entry:grass": 4400,
"entry:clutter": 5300,
"entry:light-bake": 27300,
diff --git a/bench/tool-cost-budgets.json b/bench/tool-cost-budgets.json
index 2d2c73d9..088cb2ed 100644
--- a/bench/tool-cost-budgets.json
+++ b/bench/tool-cost-budgets.json
@@ -1,5 +1,5 @@
{
- "measured": "2026-10-31, from scripts/measure-tool-cost.mjs; raised by 800 total and 150 for scene_apply for branch and labels fields (no new tool); raised by 650 total and 80 for scene_apply for clip layers, bone masks and retargeting through MCP; raised by 20 for scene_create and 20 for the scene_capabilities result after merging the expression language with the material graph; was 373388 schema bytes before shared IDs and recipe references; trimmed after the render-passes merge: material graph, depth of field, motion blur and passes details moved to scene_capabilities, budgets set to the measured value plus 0.5% (total 188267, scene_capabilities result 5167); raised by 95 for scene_apply and 690 for the scene_capabilities result for node relations; curve and text geometry entries shortened to a pointer at scene_capabilities curveText, budgets set to the measured value plus 0.5% (total 189468, scene_capabilities result 6399); then six modifier ops (weld, triangulate, edge_split, smooth, simple_deform, cast) added as one compact schema entry with details in scene_capabilities meshModifiers, entry and mesh_stack description shortened: total 190382 (budget unchanged at 190420), mesh_edit 34216 (budget 34220), scene_capabilities result 7042 (budget 7050); mesh_stack 11682 (budget 11690); after merging imported mesh topology with the modifier ops: raised the total to 190480 (measured 190471), mesh_edit to 34300 (measured 34293) and the scene_capabilities result to 7520 (measured 7512) for imported mesh edits; then cloth (recipe cloth, set-cloth, grid geometry) added with the total unchanged at 190480 (measured 189159): physics descriptions shortened and set-physics now takes the same record reference as set-motion, scene_create raised to 62150 and scene_apply lowered to 44130, scene_capabilities result raised to 8190 (measured 8176) for the cloth details; then particles and hair (recipe `particles`, set-particles) added with the total unchanged at 190480 (measured 189642, scene_create raised to 62350 and scene_apply to 44370 for the recipe particles reference and set-particles): the section is one record reference described in scene_capabilities, so the scene_capabilities result rose to 9570 (measured 9523) for the particle and hair fields; after merging the film timeline (recipe timeline, set-timeline) with particles: total 190719 (budget 190730), scene_create 62464, scene_apply 44620, scene_capabilities result 9902; then the path tracer renderer setting (drop z.int bounds, integers still checked by the job validator): total raised to 190830 (measured 190818); after merging the render limits and light bake with the path tracer: measured total 190013, scene_create raised to 62680 (measured 62667), scene_apply to 44860 (measured 44852) and the scene_capabilities result to 10620 (measured 10613) for the bake section and job size limits; then material layers anisotropy and iridescence (issue #51): the 16 layer fields take one short line each in the schema and their ranges and notes moved to scene_capabilities scene.materialLayers, so the scene_capabilities result rose to 12230 (measured 12168); then the worker bake limit added workerMaxSeconds to the bake limits (result 13361, budget raised to 13370); then the sculpt and shrinkwrap mesh edits (issue #47) with the total unchanged at 190830 (measured 190612): the face rule and tag prefix descriptions shortened (the face rule text repeats in every select field), so mesh_edit rose to 33980 (measured 33960) and mesh_stack fell to 11030 (measured 11014), and the scene_capabilities result rose to 13350 (measured 13338) for the meshSculpt notes; then recipe light links and shadow cascades (issue #52): environment fields added to the shared environment schema with the total unchanged at 190830 (measured 190507) by shortening its descriptions, and the scene_capabilities result raised to 13870 (measured 13865) for lightLinking and shadowCascades",
+ "measured": "2026-10-31, from scripts/measure-tool-cost.mjs; raised by 800 total and 150 for scene_apply for branch and labels fields (no new tool); raised by 650 total and 80 for scene_apply for clip layers, bone masks and retargeting through MCP; raised by 20 for scene_create and 20 for the scene_capabilities result after merging the expression language with the material graph; was 373388 schema bytes before shared IDs and recipe references; trimmed after the render-passes merge: material graph, depth of field, motion blur and passes details moved to scene_capabilities, budgets set to the measured value plus 0.5% (total 188267, scene_capabilities result 5167); raised by 95 for scene_apply and 690 for the scene_capabilities result for node relations; curve and text geometry entries shortened to a pointer at scene_capabilities curveText, budgets set to the measured value plus 0.5% (total 189468, scene_capabilities result 6399); then six modifier ops (weld, triangulate, edge_split, smooth, simple_deform, cast) added as one compact schema entry with details in scene_capabilities meshModifiers, entry and mesh_stack description shortened: total 190382 (budget unchanged at 190420), mesh_edit 34216 (budget 34220), scene_capabilities result 7042 (budget 7050); mesh_stack 11682 (budget 11690); after merging imported mesh topology with the modifier ops: raised the total to 190480 (measured 190471), mesh_edit to 34300 (measured 34293) and the scene_capabilities result to 7520 (measured 7512) for imported mesh edits; then cloth (recipe cloth, set-cloth, grid geometry) added with the total unchanged at 190480 (measured 189159): physics descriptions shortened and set-physics now takes the same record reference as set-motion, scene_create raised to 62150 and scene_apply lowered to 44130, scene_capabilities result raised to 8190 (measured 8176) for the cloth details; then particles and hair (recipe `particles`, set-particles) added with the total unchanged at 190480 (measured 189642, scene_create raised to 62350 and scene_apply to 44370 for the recipe particles reference and set-particles): the section is one record reference described in scene_capabilities, so the scene_capabilities result rose to 9570 (measured 9523) for the particle and hair fields; after merging the film timeline (recipe timeline, set-timeline) with particles: total 190719 (budget 190730), scene_create 62464, scene_apply 44620, scene_capabilities result 9902; then the path tracer renderer setting (drop z.int bounds, integers still checked by the job validator): total raised to 190830 (measured 190818); after merging the render limits and light bake with the path tracer: measured total 190013, scene_create raised to 62680 (measured 62667), scene_apply to 44860 (measured 44852) and the scene_capabilities result to 10620 (measured 10613) for the bake section and job size limits; then material layers anisotropy and iridescence (issue #51): the 16 layer fields take one short line each in the schema and their ranges and notes moved to scene_capabilities scene.materialLayers, so the scene_capabilities result rose to 12230 (measured 12168); then the worker bake limit added workerMaxSeconds to the bake limits (result 13361, budget raised to 13370); then the sculpt and shrinkwrap mesh edits (issue #47) with the total unchanged at 190830 (measured 190612): the face rule and tag prefix descriptions shortened (the face rule text repeats in every select field), so mesh_edit rose to 33980 (measured 33960) and mesh_stack fell to 11030 (measured 11014), and the scene_capabilities result rose to 13350 (measured 13338) for the meshSculpt notes; then recipe light links and shadow cascades (issue #52): environment fields added to the shared environment schema with the total unchanged at 190830 (measured 190507) by shortening its descriptions, and the scene_capabilities result raised to 13870 (measured 13865) for lightLinking and shadowCascades; then the path query of scene_inspect (issue #64): one record field of 205 bytes in the scene_inspect schema (total 190732, within its budget) and the navigation notes in scene_capabilities, so the result rose to 14500 (measured 14494)",
"schemaTotalBytes": 190830,
"schemaToolBytes": {
"scene_create": 62930,
@@ -10,7 +10,7 @@
},
"schemaOtherToolBytes": 4000,
"resultBytes": {
- "scene_capabilities": 13870,
+ "scene_capabilities": 14500,
"scene_create": 1400,
"scene_inspect": 1400,
"mesh_inspect": 1200,
diff --git a/docs/parity.md b/docs/parity.md
index 2779e91f..295d4b6d 100644
--- a/docs/parity.md
+++ b/docs/parity.md
@@ -246,6 +246,6 @@ The goal also needs this work, and no page in the Blender manual covers it.
| Relations between parts | partial | The agent version of snapping: node `relations` (`attach`, `gap`, `flush`, `align`, `centered`) over world bounds or a tagged region, solved again on every edit, cycles rejected. Tests in [part-relations](../tests/part-relations.test.js); suite tasks `kettle-resize` and `desk-resize` with plain twins (no gain in calls measured on Sonnet). No snapping to edges or vertices, no relation on the part's own tagged region. | #44 |
| Imported mesh editing | partial | `mesh_edit` takes an imported part ID. Skin weights, morph deltas and colours of new vertices come from the nearest original surface point, missing UVs from the nearest island; an edit that reaches too far on a skinned or morphed part is rejected. Not here: merging several parts into one mesh, tags from several material groups. Evidence: tests/agent-asset-mesh.test.js, scripts/smoke-imported-topology.mjs. | #48 |
| Rendering backend | missing | WebGL2 only. WebGPU was measured with three.js as a proxy and was slower on the RTX 3060 and on SwiftShader; decision: wait. See [webgpu-decision](webgpu-decision.md). | #56 |
-| Terrain and navigation | partial | Terrain has round holes (`addons/terrain` `holes`, recipe geometry `terrain`), still with 4 splat layers. There is no navmesh. Evidence: tests/terrain-holes.test.js, suite task terrain-hole-walk. | #64 |
+| Terrain and navigation | partial | Terrain has round holes (`addons/terrain` `holes`, recipe geometry `terrain`), still with 4 splat layers (more would need a shader change and 136 MiB at 8 layers of 1K). `addons/navmesh` builds a walkable grid from triangles with a slope limit, agent radius, holes and obstacle footprints, A* with string pulling and budgets; `scene_inspect` `path` returns walking keyframes. Evidence: tests/terrain-holes.test.js, tests/navmesh.test.js, suite tasks terrain-hole-walk and terrain-path-walk. | #64 |
| Tool cost and errors | partial | Lint and errors exist. No budget limits schema size, and not every error is checked. | #65, #66 |
| Branches and labelled images | partial | `scene_apply` `branch` forks a variant over a deduplicated snapshot store (8 branches, scene and revision untouched), `scene_review` shots take a `branch`, `scene_restore` `branch` keeps one. `labels: true` on `scene_look` and `scene_review` prints part names, tags and lint problems and returns them with pixel positions. Procedural scenes only; no suite task yet measures calls. | #67 |
diff --git a/docs/terrain.md b/docs/terrain.md
index 29f35717..3b2c3880 100644
--- a/docs/terrain.md
+++ b/docs/terrain.md
@@ -90,6 +90,24 @@ Memory: three `TEXTURE_2D_ARRAY`s on units 11 to 13 (sRGB colour, normal, roughn
In a recipe, the same ground is the `terrain` geometry (`size`, `resolution`, `seed`, `amplitude`, `holes`): see [agent-scene](agent-scene.md).
+## Navigation
+
+`addons/navmesh` finds walking routes over any triangle ground, so a character can go around holes, steep slopes and obstacles. It is pure JavaScript and gives the same path for the same input.
+
+```js
+import { createNavmesh } from '67js/addons/navmesh';
+const { positions, indices } = terrain.parts[0].geometry; // world space, Y up
+const navmesh = createNavmesh({ positions, indices, agentRadius: 0.3, maxSlopeDegrees: 40, obstacles: [{ min: [4, 4], max: [6, 6] }] });
+const { points, length, searchNodes } = navmesh.findPath([-15, -15], [15, 15], { spacing: 1.5 });
+```
+
+- **Grid:** one cell per `cellSize` metres (default the agent radius, at least 0.05 m). Each cell takes the height of the highest triangle over its centre. A cell with no triangle (a hole) or inside an `obstacles` footprint is blocked, and every blocked cell blocks the cells within `agentRadius`, so the path keeps that distance from holes and obstacles. A step to a neighbour that climbs faster than `maxSlopeDegrees` is not allowed. Features thinner than a cell can be missed, so keep `cellSize` under the thinnest wall that matters.
+- **Search:** A* over eight neighbours without corner cutting, then line-of-sight string pulling, so the route is a few straight legs rather than a staircase. `points` are `[x, y, z]`, resampled every `spacing` metres (at most 200 points) with y read from the surface.
+- **Budgets:** `maxCells` (250,000) and `maxSearchNodes` (200,000) throw a `RangeError` that says what to raise. A start or goal in a hole, outside the ground or too near an obstacle, and a goal cut off by holes, throw with the reason.
+- **Measured** (40 m rolling ground at 64 cells, one 3 m hole, agent radius 0.3, corner to corner, Node on the Windows PC): 17,956 cells built in 13 ms, a path of 43.04 m (straight line 42.43 m) in 35 ms with 4,245 search nodes and 30 points.
+
+In an agent scene, `scene_inspect` takes `path: { ground, from: [x, z], to: [x, z], avoid, radius, maxSlope, cellSize, seconds, speed, lift, spacing }` and returns keyframes for a node translation track (`LINEAR`). `ground` is a node ID, `avoid` lists node IDs whose box footprints block. It reads the authored pose and changes nothing. Details are in `scene_capabilities` under `navigation`.
+
## Measured
Windows, RTX 3060, headless Chrome, 1600x900, 4x MSAA, HDRI, shadows, bloom, 600 m terrain with 10x10 chunks at resolution 32 and about 1,000 to 1,750 trees:
@@ -103,8 +121,8 @@ Splat textures take 68 MiB of 74 MiB texture memory at 1K per layer.
## Limits
-- Up to four layers; one splat material per draw (chunks share one). More layers need a shader change and are not built.
-- No navmesh or path query yet.
+- Up to four layers; one splat material per draw (chunks share one). More layers are not built: the splat shader has 16 four-wide arrays and loops, the weight texture has four channels, and eight 1K layers would take about 136 MiB against the 74 MiB of texture memory above.
+- Routes come from a grid, not a mesh of walkable polygons: no stairs or bridges over one another (the highest surface wins), and no moving obstacles.
- Overhangs are not represented: the terrain is a heightfield.
- Changing `layers` or `splat` after the renderer exists needs a new renderer.
- The weight texture follows its descriptor's filtering (mipmapped by default); 1024 square over 600 m gives 0.6 m texels.
diff --git a/package.json b/package.json
index 93efaa7a..93aed5a7 100644
--- a/package.json
+++ b/package.json
@@ -68,6 +68,7 @@
"./addons/vehicle": "./build/vehicle.js",
"./addons/vegetation": "./build/vegetation.js",
"./addons/terrain": "./build/terrain.js",
+ "./addons/navmesh": "./build/navmesh.js",
"./addons/grass": "./build/grass.js",
"./addons/clutter": "./build/clutter.js",
"./addons/light-bake": "./build/light-bake.js",
diff --git a/scripts/mcp-server.mjs b/scripts/mcp-server.mjs
index a62b1c8a..c2b65f58 100644
--- a/scripts/mcp-server.mjs
+++ b/scripts/mcp-server.mjs
@@ -691,7 +691,7 @@ export function createAgentMcpServer(runtime, { version = packageMetadata.versio
register('scene_create', 'Create the single active render scene from a JSON recipe. Dispose an existing scene first.', z.strictObject({ recipe }), { ...edit, destructiveHint: false }, async argumentsValue => jsonResult(await runtime.create(argumentsValue)));
register('scene_asset_catalog', 'List content-bound GLB IDs from the configured local asset directory. No arbitrary paths or downloads.', z.strictObject({}), readOnly, async () => jsonResult(await runtime.assetCatalog()));
register('scene_create_asset', 'Create the active scene from a catalog GLB and editable asset recipe. Preserves supported maps, skins, morphs and clips. Dispose the existing scene first.', z.strictObject({ recipe: assetRecipe }), { ...edit, destructiveHint: false }, async argumentsValue => jsonResult(await runtime.createAsset(argumentsValue)));
- register('scene_inspect', 'Read revision, counts and selected nodes. For a recipe with physics, the result lists body final positions, resting times, contacts and sensor enter/leave events. Bounds describe authored geometry rather than shader displacement.', z.strictObject({ ...sessionFields, ids: z.array(identifier).max(4096).optional().describe('Selected node IDs. Omit to inspect scene order.'), kind: z.enum(['meshes', 'hierarchy']).optional().describe('Imported assets only: hierarchy exposes stable source-node IDs and joints.'), offset: z.number().int().min(0).max(4096).optional().describe('Imported assets only: pagination offset.'), limit: z.number().int().min(1).max(4096).optional().describe('Maximum returned node records. Defaults to 64.'), includeBounds: z.boolean().optional().describe('Include world geometry bounds. Defaults to false.') }), readOnly, async argumentsValue => jsonResult(await runtime.inspect(argumentsValue)));
+ register('scene_inspect', 'Read revision, counts and selected nodes. For a recipe with physics, the result lists body final positions, resting times, contacts and sensor enter/leave events. Bounds describe authored geometry rather than shader displacement.', z.strictObject({ ...sessionFields, ids: z.array(identifier).max(4096).optional().describe('Selected node IDs. Omit to inspect scene order.'), kind: z.enum(['meshes', 'hierarchy']).optional().describe('Imported assets only: hierarchy exposes stable source-node IDs and joints.'), offset: z.number().int().min(0).max(4096).optional().describe('Imported assets only: pagination offset.'), limit: z.number().int().min(1).max(4096).optional().describe('Maximum returned node records. Defaults to 64.'), includeBounds: z.boolean().optional().describe('Include world geometry bounds. Defaults to false.'), path: z.record(z.string(), z.unknown()).optional().describe('Walking route over a ground node, around holes: fields in scene_capabilities navigation.') }), readOnly, async argumentsValue => jsonResult(await runtime.inspect(argumentsValue)));
register('mesh_inspect', 'Check recipe geometries as polygon meshes: vertex, edge and face counts, triangles/quads/n-gons, connected and closed parts, face tags (top, bottom, side, left, right, front, back), bounds, and lint problems (non-manifold, inconsistent winding, inverted, degenerate, open, loose) with a suggested fix each. Also imported asset parts (mesh-0). Read-only and cached per geometry.', z.strictObject({ ...sessionFields, geometry: identifier.optional().describe('One geometry ID to check, as in mesh_edit.'), geometries: z.array(identifier).min(1).max(16).optional().describe('Geometry IDs to check. Omit both to check the first 16 geometries.') }), readOnly, async ({ geometry: geometryId, geometries, ...rest }) => jsonResult(await runtime.inspectMeshes({ ...rest, ...(geometries || geometryId ? { geometries: [...(geometries ?? []), ...(geometryId ? [geometryId] : [])] } : {}) })));
register('mesh_edit', 'Append edits to a recipe mesh geometry or an imported asset part such as mesh-0 (or replace its edit log), atomically like scene_apply: extrude, inset, delete, flip, translate with falloff, tag, loop cut, bevel, mirror, array, solidify, UV unwrap, set_position and displace with field expressions (math, noise, attributes), booleans with a primitive cutter, sculpt brush strokes and shrinkwrap onto a primitive. Edits that select no faces or break limits fail without changing the scene. Returns the new revision, render status and the mesh report with per-edit results.', z.strictObject({ ...sessionFields, expectedRevision, geometry: identifier.describe('ID of a geometry with type mesh, or an imported part such as mesh-0.'), edits: meshEdits.min(1), replace: z.boolean().optional().describe('Replace the whole edit log instead of appending.') }), edit, async argumentsValue => jsonResult(await runtime.editMesh(argumentsValue)));
register('mesh_stack', 'Set the non-destructive modifier stack of a recipe mesh geometry (ops and fields: scene_capabilities meshModifiers), evaluated after its edits, each prefix cached. apply: n moves the first n nodes into the edit log, as Blender\'s Apply modifier. Atomic like scene_apply. Returns the revision, render status and mesh report.', z.strictObject({ ...sessionFields, expectedRevision, geometry: identifier.describe('ID of a geometry with type mesh.'), stack: meshStack.optional().describe('The whole new stack. Omit to keep the current stack (for example with apply).'), apply: z.number().int().min(0).max(16).optional() }), edit, async argumentsValue => jsonResult(await runtime.setMeshStack(argumentsValue)));
diff --git a/src/agent-navigation.js b/src/agent-navigation.js
new file mode 100644
index 00000000..df815a7f
--- /dev/null
+++ b/src/agent-navigation.js
@@ -0,0 +1,55 @@
+// The path query of scene_inspect: a route over a ground node that goes around holes and obstacles, returned as
+// keyframes that can go straight into a node translation track. It loads on demand, so the scene entry does not carry it.
+import { createNavmesh } from './navmesh.js';
+
+export const NAVIGATION_FIELDS = ['ground', 'from', 'to', 'avoid', 'radius', 'maxSlope', 'cellSize', 'seconds', 'speed', 'lift', 'spacing'];
+
+const DEFAULT_WALKING_SPEED = 1.4;
+const MAXIMUM_LIFT = 100;
+
+function rounded(value) {
+ return Math.round(value * 1000) / 1000;
+}
+
+function numberOption(value, label, minimum, maximum) {
+ if (value === undefined) return undefined;
+ if (!Number.isFinite(value) || value < minimum || value > maximum) {
+ throw new RangeError(`path ${label} must be a number from ${minimum} to ${maximum}.`);
+ }
+ return value;
+}
+
+/**
+ * `query` is the path option of scene_inspect. `ground` is { positions, indices } in world space and `avoidBounds`
+ * the world bounds ({ min, max }) of the nodes to walk around; the scene resolves node IDs into both.
+ */
+export function queryAgentPath(query, ground, avoidBounds) {
+ const seconds = numberOption(query.seconds, 'seconds', 0.1, 600);
+ const speed = numberOption(query.speed, 'speed', 0.01, 100);
+ if (seconds !== undefined && speed !== undefined) throw new RangeError('path takes seconds or speed, not both.');
+ const lift = numberOption(query.lift, 'lift', -MAXIMUM_LIFT, MAXIMUM_LIFT) ?? 0;
+ const navmesh = createNavmesh({
+ positions: ground.positions,
+ indices: ground.indices,
+ agentRadius: numberOption(query.radius, 'radius', 0.01, 100),
+ maxSlopeDegrees: numberOption(query.maxSlope, 'maxSlope', 1, 89),
+ cellSize: numberOption(query.cellSize, 'cellSize', 0.05, 100),
+ obstacles: avoidBounds.map(bounds => ({ min: [bounds.min[0], bounds.min[2]], max: [bounds.max[0], bounds.max[2]] })),
+ });
+ const route = navmesh.findPath(query.from, query.to, { spacing: numberOption(query.spacing, 'spacing', 0.1, 100) });
+ const duration = seconds ?? route.length / (speed ?? DEFAULT_WALKING_SPEED);
+ let travelled = 0;
+ const keyframes = route.points.map((point, index) => {
+ if (index > 0) travelled += Math.hypot(point[0] - route.points[index - 1][0], point[2] - route.points[index - 1][2]);
+ const fraction = route.length > 0 ? travelled / route.length : 0;
+ return { time: rounded(duration * fraction), value: [rounded(point[0]), rounded(point[1] + lift), rounded(point[2])] };
+ });
+ return {
+ length: rounded(route.length),
+ seconds: rounded(duration),
+ cellSize: navmesh.cellSize,
+ agentRadius: navmesh.agentRadius,
+ searchNodes: route.searchNodes,
+ keyframes,
+ };
+}
diff --git a/src/agent-scene-capabilities.js b/src/agent-scene-capabilities.js
index 337f6cf5..c9ed4487 100644
--- a/src/agent-scene-capabilities.js
+++ b/src/agent-scene-capabilities.js
@@ -142,6 +142,7 @@ export const AGENT_SCENE_CAPABILITIES = Object.freeze({
format: '67js.scene', schemaVersion: 1,
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.',
+ 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 }),
meshModifiers: MESH_MODIFIER_NOTES,
diff --git a/src/agent-scene-modules.js b/src/agent-scene-modules.js
index 56e29318..2178ecd9 100644
--- a/src/agent-scene-modules.js
+++ b/src/agent-scene-modules.js
@@ -17,6 +17,7 @@ const MODULE_LOADERS = {
timeline: () => import('./film-timeline.js'),
layerShaders: () => import('./material-layer-shaders.js'),
terrain: () => import('./agent-terrain.js'),
+ navigation: () => import('./agent-navigation.js'),
lightLinking: () => import('./light-linking.js'),
cascades: () => import('./cascaded-shadows.js'),
};
@@ -41,6 +42,8 @@ const MODULE_MARKERS = {
timeline: ['"timeline":{'],
layerShaders: ['"anisotropy"', '"iridescence"'],
terrain: ['"type":"terrain"'],
+ // No recipe text asks for it, only the path option of scene_inspect does, so a host loads it with loadAllAgentSceneModules.
+ navigation: [],
lightLinking: ['"affects"', '"keyAffects"'],
cascades: ['"shadowCascades"'],
};
diff --git a/src/agent-scene.js b/src/agent-scene.js
index 774ec42c..fc432737 100644
--- a/src/agent-scene.js
+++ b/src/agent-scene.js
@@ -920,6 +920,35 @@ export function createAgentScene(input, inputLimits = {}) {
const skinCache = new Map();
const checkpoints = new Map();
+ function drawnNodeGeometry(id, label) {
+ identifier(id);
+ const node = state.recipe.nodes.find(value => value.id === id);
+ const geometry = node && state.geometries.get(node.geometry);
+ if (!geometry) throw new RangeError(`path ${label} ${id} is not a node with a drawn geometry. List node IDs with scene_inspect.`);
+ return { geometry, worldMatrix: state.graph.getNode(id).worldMatrix };
+ }
+
+ // The route is computed over the authored pose of the ground and of the nodes to avoid, like the bounds in scene_inspect.
+ function pathQuery(query) {
+ if (query === null || typeof query !== 'object' || Array.isArray(query)) throw new TypeError('path must be an object.');
+ const navigation = agentSceneModule('navigation');
+ knownKeys(query, navigation.NAVIGATION_FIELDS, 'path');
+ if (query.avoid !== undefined && (!Array.isArray(query.avoid) || query.avoid.length > 64)) throw new RangeError('path avoid must list at most 64 node IDs.');
+ const { geometry, worldMatrix } = drawnNodeGeometry(query.ground, 'ground');
+ const positions = new Float32Array(geometry.positions.length);
+ for (let offset = 0; offset < positions.length; offset += 3) {
+ for (let axis = 0; axis < 3; axis++) {
+ positions[offset + axis] = worldMatrix[axis] * geometry.positions[offset] + worldMatrix[4 + axis] * geometry.positions[offset + 1]
+ + worldMatrix[8 + axis] * geometry.positions[offset + 2] + worldMatrix[12 + axis];
+ }
+ }
+ const avoidBounds = (query.avoid ?? []).map(id => {
+ const avoided = drawnNodeGeometry(id, 'avoid');
+ return boundsFor(avoided.geometry, avoided.worldMatrix);
+ });
+ return navigation.queryAgentPath(query, { positions, indices: geometry.indices }, avoidBounds);
+ }
+
function ownedGeometryRecords() {
const records = new Set(state?.geometryRecords.values() ?? []);
for (const checkpoint of checkpoints.values()) {
@@ -1406,7 +1435,7 @@ export function createAgentScene(input, inputLimits = {}) {
return commit(stage(candidate, null, removedNodes, removedMaterials), true);
},
inspect(options = {}) {
- knownKeys(options, ['ids', 'limit', 'includeBounds'], 'inspection');
+ knownKeys(options, ['ids', 'limit', 'includeBounds', 'path'], 'inspection');
const maximum = integer(options.limit ?? Math.min(64, limits.maxNodes), 1, limits.maxNodes, 'inspection limit');
if (options.includeBounds !== undefined && typeof options.includeBounds !== 'boolean') {
throw new TypeError('includeBounds must be boolean.');
@@ -1466,6 +1495,7 @@ export function createAgentScene(input, inputLimits = {}) {
exposure: state.recipe.effects.exposure,
},
nodes, truncated: selected.length > nodes.length,
+ ...(options.path === undefined ? {} : { path: pathQuery(options.path) }),
};
},
/** Polygon counts, parts, face tags and lint problems for recipe geometries (all, or the given IDs). */
diff --git a/src/navmesh.js b/src/navmesh.js
new file mode 100644
index 00000000..be335399
--- /dev/null
+++ b/src/navmesh.js
@@ -0,0 +1,381 @@
+// Walkable-grid navigation over triangle geometry: ground with slopes, holes and obstacles in, a smooth path out.
+// The grid takes the top surface at each cell centre and blocks empty cells (holes) and obstacle footprints, then
+// grows every blocked area by the agent radius. A step between cells that climbs past the slope limit is not allowed. A* finds a route over the cells and line-of-sight string pulling
+// removes the grid zigzag. Pure JavaScript, no randomness: the same input gives the same path.
+
+export const NAVMESH_LIMITS = Object.freeze({
+ maximumCells: 250000,
+ maximumSearchNodes: 200000,
+ maximumObstacles: 64,
+ maximumPathPoints: 200,
+ defaultAgentRadius: 0.3,
+ defaultSlopeDegrees: 40,
+});
+
+const NO_SURFACE = -Infinity;
+const NEIGHBOUR_OFFSETS = [[1, 0], [-1, 0], [0, 1], [0, -1], [1, 1], [1, -1], [-1, 1], [-1, -1]];
+const LINE_OF_SIGHT_SAMPLES_PER_CELL = 4;
+const EDGE_TOLERANCE = 1e-9;
+
+function positiveNumber(value, fallback, label) {
+ const resolved = value ?? fallback;
+ if (!Number.isFinite(resolved) || resolved <= 0) throw new RangeError(`navmesh ${label} must be a positive number.`);
+ return resolved;
+}
+
+function pointXZ(value, label) {
+ if (!Array.isArray(value) || value.length !== 2 || !value.every(Number.isFinite)) {
+ throw new RangeError(`navmesh ${label} must be [x, z] in metres.`);
+ }
+ return value;
+}
+
+function geometryBounds(positions) {
+ let minimumX = Infinity;
+ let minimumZ = Infinity;
+ let maximumX = -Infinity;
+ let maximumZ = -Infinity;
+ for (let offset = 0; offset < positions.length; offset += 3) {
+ minimumX = Math.min(minimumX, positions[offset]);
+ maximumX = Math.max(maximumX, positions[offset]);
+ minimumZ = Math.min(minimumZ, positions[offset + 2]);
+ maximumZ = Math.max(maximumZ, positions[offset + 2]);
+ }
+ return { minimumX, minimumZ, maximumX, maximumZ };
+}
+
+// Binary heap ordered by cost, then by cell index, so equal costs always leave in the same order.
+function createOpenSet() {
+ const costs = [];
+ const cells = [];
+ function isBefore(first, second) {
+ return costs[first] < costs[second] || (costs[first] === costs[second] && cells[first] < cells[second]);
+ }
+ function swap(first, second) {
+ [costs[first], costs[second]] = [costs[second], costs[first]];
+ [cells[first], cells[second]] = [cells[second], cells[first]];
+ }
+ return {
+ get size() {
+ return cells.length;
+ },
+ push(cell, cost) {
+ costs.push(cost);
+ cells.push(cell);
+ let index = cells.length - 1;
+ while (index > 0) {
+ const parent = (index - 1) >> 1;
+ if (!isBefore(index, parent)) break;
+ swap(index, parent);
+ index = parent;
+ }
+ },
+ pop() {
+ const top = cells[0];
+ const lastCost = costs.pop();
+ const lastCell = cells.pop();
+ if (cells.length > 0) {
+ costs[0] = lastCost;
+ cells[0] = lastCell;
+ let index = 0;
+ for (;;) {
+ const left = index * 2 + 1;
+ const right = left + 1;
+ let smallest = index;
+ if (left < cells.length && isBefore(left, smallest)) smallest = left;
+ if (right < cells.length && isBefore(right, smallest)) smallest = right;
+ if (smallest === index) break;
+ swap(index, smallest);
+ index = smallest;
+ }
+ }
+ return top;
+ },
+ };
+}
+
+/**
+ * Builds a navigation grid from triangles (`positions` x y z, `indices`, both in world space, Y up).
+ * Options: `agentRadius` (0.3 m), `maxSlopeDegrees` (40), `cellSize` (the radius, at least 0.05 m),
+ * `obstacles` ([{ min: [x, z], max: [x, z] }] footprints that block), `maxCells` (250,000).
+ */
+export function createNavmesh({ positions, indices, agentRadius, maxSlopeDegrees, cellSize, obstacles = [], maxCells } = {}) {
+ if (!(positions?.length >= 9) || !(indices?.length >= 3)) throw new RangeError('navmesh needs positions and indices with at least one triangle.');
+ const radius = positiveNumber(agentRadius, NAVMESH_LIMITS.defaultAgentRadius, 'agentRadius');
+ const slopeDegrees = positiveNumber(maxSlopeDegrees, NAVMESH_LIMITS.defaultSlopeDegrees, 'maxSlopeDegrees');
+ if (slopeDegrees >= 90) throw new RangeError('navmesh maxSlopeDegrees must stay below 90.');
+ const size = positiveNumber(cellSize, Math.max(radius, 0.05), 'cellSize');
+ const cellBudget = positiveNumber(maxCells, NAVMESH_LIMITS.maximumCells, 'maxCells');
+ if (!Array.isArray(obstacles) || obstacles.length > NAVMESH_LIMITS.maximumObstacles) {
+ throw new RangeError(`navmesh obstacles must be a list of at most ${NAVMESH_LIMITS.maximumObstacles} footprints.`);
+ }
+
+ const bounds = geometryBounds(positions);
+ const columns = Math.max(1, Math.ceil((bounds.maximumX - bounds.minimumX) / size));
+ const rows = Math.max(1, Math.ceil((bounds.maximumZ - bounds.minimumZ) / size));
+ if (columns * rows > cellBudget) {
+ const neededSize = Math.sqrt(((bounds.maximumX - bounds.minimumX) * (bounds.maximumZ - bounds.minimumZ)) / cellBudget);
+ throw new RangeError(`navmesh needs ${columns * rows} cells at cellSize ${size} m, over the budget of ${cellBudget}. Raise cellSize to at least ${Math.ceil(neededSize * 100) / 100} m or use a smaller ground.`);
+ }
+ const maximumStep = Math.tan((slopeDegrees * Math.PI) / 180);
+
+ const heights = new Float32Array(columns * rows).fill(NO_SURFACE);
+ rasterizeTopSurface(positions, indices, bounds, size, columns, rows, heights);
+
+ const blocked = new Uint8Array(columns * rows);
+ for (let cell = 0; cell < blocked.length; cell++) {
+ if (heights[cell] === NO_SURFACE) blocked[cell] = 1;
+ }
+ for (const obstacle of obstacles) {
+ blockFootprint(obstacle, bounds, size, columns, rows, blocked);
+ }
+ const walkable = growBlockedAreas(blocked, columns, rows, Math.ceil(radius / size), radius / size);
+ const walkableCellCount = walkable.reduce((total, value) => total + value, 0);
+
+ function cellOf(worldX, worldZ) {
+ const column = Math.floor((worldX - bounds.minimumX) / size);
+ const row = Math.floor((worldZ - bounds.minimumZ) / size);
+ if (column < 0 || row < 0 || column >= columns || row >= rows) return -1;
+ return row * columns + column;
+ }
+
+ function centerOf(cell) {
+ return [bounds.minimumX + ((cell % columns) + 0.5) * size, bounds.minimumZ + (Math.floor(cell / columns) + 0.5) * size];
+ }
+
+ function isWalkable(worldX, worldZ) {
+ const cell = cellOf(worldX, worldZ);
+ return cell >= 0 && walkable[cell] === 1;
+ }
+
+ // Bilinear over the four nearest cell centres that have a surface; a cell without one adds no weight.
+ function heightAt(worldX, worldZ) {
+ const columnPosition = (worldX - bounds.minimumX) / size - 0.5;
+ const rowPosition = (worldZ - bounds.minimumZ) / size - 0.5;
+ const baseColumn = Math.floor(columnPosition);
+ const baseRow = Math.floor(rowPosition);
+ let weightedHeight = 0;
+ let totalWeight = 0;
+ for (let rowStep = 0; rowStep <= 1; rowStep++) {
+ for (let columnStep = 0; columnStep <= 1; columnStep++) {
+ const column = baseColumn + columnStep;
+ const row = baseRow + rowStep;
+ if (column < 0 || row < 0 || column >= columns || row >= rows) continue;
+ const height = heights[row * columns + column];
+ if (height === NO_SURFACE) continue;
+ const weight = (columnStep === 0 ? 1 - (columnPosition - baseColumn) : columnPosition - baseColumn)
+ * (rowStep === 0 ? 1 - (rowPosition - baseRow) : rowPosition - baseRow);
+ weightedHeight += height * weight;
+ totalWeight += weight;
+ }
+ }
+ if (totalWeight > 0) return weightedHeight / totalWeight;
+ const cell = cellOf(worldX, worldZ);
+ return cell >= 0 && heights[cell] !== NO_SURFACE ? heights[cell] : null;
+ }
+
+ function canStep(fromCell, toCell, distance) {
+ return walkable[toCell] === 1 && Math.abs(heights[toCell] - heights[fromCell]) <= maximumStep * distance;
+ }
+
+ function hasLineOfSight(fromPoint, toPoint) {
+ const length = Math.hypot(toPoint[0] - fromPoint[0], toPoint[1] - fromPoint[1]);
+ const samples = Math.max(1, Math.ceil((length / size) * LINE_OF_SIGHT_SAMPLES_PER_CELL));
+ let previousCell = cellOf(fromPoint[0], fromPoint[1]);
+ for (let sample = 1; sample <= samples; sample++) {
+ const fraction = sample / samples;
+ const cell = cellOf(fromPoint[0] + (toPoint[0] - fromPoint[0]) * fraction, fromPoint[1] + (toPoint[1] - fromPoint[1]) * fraction);
+ if (cell < 0 || walkable[cell] === 0) return false;
+ if (cell !== previousCell) {
+ const [previousX, previousZ] = centerOf(previousCell);
+ const [currentX, currentZ] = centerOf(cell);
+ if (!canStep(previousCell, cell, Math.hypot(currentX - previousX, currentZ - previousZ))) return false;
+ previousCell = cell;
+ }
+ }
+ return true;
+ }
+
+ function explainUnwalkable(worldX, worldZ, label) {
+ const cell = cellOf(worldX, worldZ);
+ if (cell < 0) return `${label} [${worldX}, ${worldZ}] is outside the ground.`;
+ if (heights[cell] === NO_SURFACE) return `${label} [${worldX}, ${worldZ}] has no ground under it (a hole).`;
+ return `${label} [${worldX}, ${worldZ}] is not walkable: it is on an obstacle or a steep slope, or within the agent radius ${radius} m of a hole or an obstacle.`;
+ }
+
+ /** Route from [x, z] to [x, z]: { points: [[x, y, z], ...], length, searchNodes }. Throws when the goal cannot be reached. */
+ function findPath(from, to, { spacing, maxSearchNodes } = {}) {
+ pointXZ(from, 'from');
+ pointXZ(to, 'to');
+ const budget = positiveNumber(maxSearchNodes, NAVMESH_LIMITS.maximumSearchNodes, 'maxSearchNodes');
+ const startCell = cellOf(from[0], from[1]);
+ const goalCell = cellOf(to[0], to[1]);
+ if (startCell < 0 || walkable[startCell] === 0) throw new RangeError(explainUnwalkable(from[0], from[1], 'Start'));
+ if (goalCell < 0 || walkable[goalCell] === 0) throw new RangeError(explainUnwalkable(to[0], to[1], 'Goal'));
+
+ const cellRoute = searchCells(startCell, goalCell, budget);
+ const corners = [from, ...cellRoute.cells.slice(1, -1).map(centerOf), to];
+ const pulled = pullString(corners);
+ const points = resample(pulled, positiveNumber(spacing, Math.max(1.5, size * 2), 'spacing'));
+ let length = 0;
+ for (let index = 1; index < pulled.length; index++) {
+ length += Math.hypot(pulled[index][0] - pulled[index - 1][0], pulled[index][1] - pulled[index - 1][1]);
+ }
+ return { points, length, searchNodes: cellRoute.searchNodes };
+ }
+
+ function searchCells(startCell, goalCell, budget) {
+ const [goalX, goalZ] = centerOf(goalCell);
+ const costSoFar = new Float32Array(columns * rows).fill(Infinity);
+ const cameFrom = new Int32Array(columns * rows).fill(-1);
+ const closed = new Uint8Array(columns * rows);
+ const open = createOpenSet();
+ const remaining = cell => {
+ const [x, z] = centerOf(cell);
+ return Math.hypot(x - goalX, z - goalZ);
+ };
+ costSoFar[startCell] = 0;
+ open.push(startCell, remaining(startCell));
+ let searchNodes = 0;
+ while (open.size > 0) {
+ const cell = open.pop();
+ if (closed[cell] === 1) continue;
+ closed[cell] = 1;
+ searchNodes++;
+ if (cell === goalCell) return { cells: traceBack(cameFrom, cell), searchNodes };
+ if (searchNodes > budget) {
+ throw new RangeError(`navmesh search used ${budget} nodes without reaching the goal. Raise cellSize, or check that the goal is on the same side of the holes and obstacles.`);
+ }
+ const column = cell % columns;
+ const row = Math.floor(cell / columns);
+ for (const [columnStep, rowStep] of NEIGHBOUR_OFFSETS) {
+ const nextColumn = column + columnStep;
+ const nextRow = row + rowStep;
+ if (nextColumn < 0 || nextRow < 0 || nextColumn >= columns || nextRow >= rows) continue;
+ const next = nextRow * columns + nextColumn;
+ const isDiagonal = columnStep !== 0 && rowStep !== 0;
+ const distance = isDiagonal ? size * Math.SQRT2 : size;
+ if (closed[next] === 1 || !canStep(cell, next, distance)) continue;
+ if (isDiagonal && (walkable[row * columns + nextColumn] === 0 || walkable[nextRow * columns + column] === 0)) continue;
+ const cost = costSoFar[cell] + Math.hypot(distance, heights[next] - heights[cell]);
+ if (cost < costSoFar[next]) {
+ costSoFar[next] = cost;
+ cameFrom[next] = cell;
+ open.push(next, cost + remaining(next));
+ }
+ }
+ }
+ throw new RangeError('navmesh found no walkable route from start to goal: holes, obstacles or steep ground cut them apart.');
+ }
+
+ function traceBack(cameFrom, goalCell) {
+ const cells = [];
+ for (let cell = goalCell; cell !== -1; cell = cameFrom[cell]) cells.push(cell);
+ return cells.reverse();
+ }
+
+ function pullString(corners) {
+ const pulled = [corners[0]];
+ let anchor = 0;
+ while (anchor < corners.length - 1) {
+ let farthest = anchor + 1;
+ for (let candidate = corners.length - 1; candidate > anchor + 1; candidate--) {
+ if (hasLineOfSight(corners[anchor], corners[candidate])) {
+ farthest = candidate;
+ break;
+ }
+ }
+ pulled.push(corners[farthest]);
+ anchor = farthest;
+ }
+ return pulled;
+ }
+
+ function resample(pulled, requestedSpacing) {
+ let length = 0;
+ for (let index = 1; index < pulled.length; index++) {
+ length += Math.hypot(pulled[index][0] - pulled[index - 1][0], pulled[index][1] - pulled[index - 1][1]);
+ }
+ const spacingUsed = Math.max(requestedSpacing, length / (NAVMESH_LIMITS.maximumPathPoints - pulled.length));
+ const points = [];
+ const addPoint = (x, z) => points.push([x, heightAt(x, z) ?? heights[cellOf(x, z)], z]);
+ addPoint(pulled[0][0], pulled[0][1]);
+ for (let index = 1; index < pulled.length; index++) {
+ const [startX, startZ] = pulled[index - 1];
+ const [endX, endZ] = pulled[index];
+ const segmentLength = Math.hypot(endX - startX, endZ - startZ);
+ const pieces = Math.max(1, Math.round(segmentLength / spacingUsed));
+ for (let piece = 1; piece <= pieces; piece++) {
+ const fraction = piece / pieces;
+ addPoint(startX + (endX - startX) * fraction, startZ + (endZ - startZ) * fraction);
+ }
+ }
+ return points;
+ }
+
+ return { cellSize: size, columns, rows, cellCount: columns * rows, walkableCellCount, agentRadius: radius, isWalkable, heightAt, findPath };
+}
+
+// The highest triangle over each cell centre wins, so a floor under a roof is not walked through the roof.
+function rasterizeTopSurface(positions, indices, bounds, size, columns, rows, heights) {
+ for (let offset = 0; offset < indices.length; offset += 3) {
+ const a = indices[offset] * 3;
+ const b = indices[offset + 1] * 3;
+ const c = indices[offset + 2] * 3;
+ const ax = positions[a];
+ const az = positions[a + 2];
+ const determinant = (positions[b + 2] - positions[c + 2]) * (ax - positions[c]) + (positions[c] - positions[b]) * (az - positions[c + 2]);
+ if (Math.abs(determinant) < 1e-12) continue;
+ const minimumColumn = Math.max(0, Math.floor((Math.min(ax, positions[b], positions[c]) - bounds.minimumX) / size - 0.5));
+ const maximumColumn = Math.min(columns - 1, Math.ceil((Math.max(ax, positions[b], positions[c]) - bounds.minimumX) / size));
+ const minimumRow = Math.max(0, Math.floor((Math.min(az, positions[b + 2], positions[c + 2]) - bounds.minimumZ) / size - 0.5));
+ const maximumRow = Math.min(rows - 1, Math.ceil((Math.max(az, positions[b + 2], positions[c + 2]) - bounds.minimumZ) / size));
+ for (let row = minimumRow; row <= maximumRow; row++) {
+ for (let column = minimumColumn; column <= maximumColumn; column++) {
+ const x = bounds.minimumX + (column + 0.5) * size;
+ const z = bounds.minimumZ + (row + 0.5) * size;
+ const weightA = ((positions[b + 2] - positions[c + 2]) * (x - positions[c]) + (positions[c] - positions[b]) * (z - positions[c + 2])) / determinant;
+ const weightB = ((positions[c + 2] - az) * (x - positions[c]) + (ax - positions[c]) * (z - positions[c + 2])) / determinant;
+ const weightC = 1 - weightA - weightB;
+ if (weightA < -EDGE_TOLERANCE || weightB < -EDGE_TOLERANCE || weightC < -EDGE_TOLERANCE) continue;
+ const height = weightA * positions[a + 1] + weightB * positions[b + 1] + weightC * positions[c + 1];
+ const cell = row * columns + column;
+ if (height > heights[cell]) heights[cell] = height;
+ }
+ }
+ }
+}
+
+function blockFootprint(obstacle, bounds, size, columns, rows, blocked) {
+ const minimum = pointXZ(obstacle?.min, 'obstacle min');
+ const maximum = pointXZ(obstacle?.max, 'obstacle max');
+ const firstColumn = Math.max(0, Math.floor((minimum[0] - bounds.minimumX) / size));
+ const lastColumn = Math.min(columns - 1, Math.floor((maximum[0] - bounds.minimumX) / size));
+ const firstRow = Math.max(0, Math.floor((minimum[1] - bounds.minimumZ) / size));
+ const lastRow = Math.min(rows - 1, Math.floor((maximum[1] - bounds.minimumZ) / size));
+ for (let row = firstRow; row <= lastRow; row++) {
+ for (let column = firstColumn; column <= lastColumn; column++) blocked[row * columns + column] = 1;
+ }
+}
+
+// Marks a cell walkable only when no blocked cell lies within the agent radius.
+function growBlockedAreas(blocked, columns, rows, radiusInCells, radiusInCellUnits) {
+ const walkable = new Uint8Array(blocked.length).fill(1);
+ const reach = Math.max(radiusInCells, 1);
+ const limit = Math.max(radiusInCellUnits, 0.75);
+ for (let row = 0; row < rows; row++) {
+ for (let column = 0; column < columns; column++) {
+ if (blocked[row * columns + column] === 0) continue;
+ for (let rowOffset = -reach; rowOffset <= reach; rowOffset++) {
+ for (let columnOffset = -reach; columnOffset <= reach; columnOffset++) {
+ if (Math.hypot(rowOffset, columnOffset) > limit) continue;
+ const nearbyRow = row + rowOffset;
+ const nearbyColumn = column + columnOffset;
+ if (nearbyRow < 0 || nearbyColumn < 0 || nearbyRow >= rows || nearbyColumn >= columns) continue;
+ walkable[nearbyRow * columns + nearbyColumn] = 0;
+ }
+ }
+ }
+ }
+ return walkable;
+}
diff --git a/tests/agent-modeling-suite.test.js b/tests/agent-modeling-suite.test.js
index 0ea75793..ec8fc13c 100644
--- a/tests/agent-modeling-suite.test.js
+++ b/tests/agent-modeling-suite.test.js
@@ -173,3 +173,16 @@ test('the terrain walk needs the opening, the hills and a walk that goes around
for (const keyframe of hoveringWalker.motion.tracks[0].keyframes) keyframe.value[1] = 4;
assert.deepEqual(failedKinds(await gradeRecipe(task, hoveringWalker)), ['walkPath']);
});
+
+test('the path walk passes its reference and fails a walk through the second opening or the rock', async () => {
+ const task = taskById('terrain-path-walk');
+ assert.deepEqual(failedKinds(await gradeRecipe(task, structuredClone(REFERENCES['terrain-path-walk']))), []);
+
+ const throughSecondOpening = structuredClone(REFERENCES['terrain-path-walk']);
+ throughSecondOpening.motion.tracks[0].keyframes = [{ time: 0, value: [-15, 0.5, -15] }, { time: 4, value: [-4, 0.5, -5] }, { time: 5.5, value: [5, 0.5, -5] }, { time: 10, value: [15, 0.5, 15] }];
+ assert.deepEqual(failedKinds(await gradeRecipe(task, throughSecondOpening)), ['walkPath']);
+
+ const throughRock = structuredClone(REFERENCES['terrain-path-walk']);
+ throughRock.motion.tracks[0].keyframes = [{ time: 0, value: [-15, 0.5, -15] }, { time: 2, value: [-8, 0.5, -8] }, { time: 3, value: [-6, 0.5, -3] }, { time: 5.5, value: [5, 0.5, -5] }, { time: 7, value: [5, 0.5, 13] }, { time: 10, value: [15, 0.5, 15] }];
+ assert.deepEqual(failedKinds(await gradeRecipe(task, throughRock)), ['walkPath']);
+});
diff --git a/tests/navmesh.test.js b/tests/navmesh.test.js
new file mode 100644
index 00000000..9b3c41be
--- /dev/null
+++ b/tests/navmesh.test.js
@@ -0,0 +1,86 @@
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import { createNavmesh } from '../src/navmesh.js';
+import { createTerrain } from '../src/terrain.js';
+import { createAgentScene, loadAllAgentSceneModules } from '../src/agent-scene.js';
+
+function flatGround(size, holes = []) {
+ const terrain = createTerrain({ size, chunks: 1, levels: 1, resolution: 64, holes, height: () => 0 });
+ const { positions, indices } = terrain.parts[0].geometry;
+ return { positions, indices };
+}
+
+function distanceToHoleCentre(point, hole) {
+ return Math.hypot(point[0] - hole.center[0], point[2] - hole.center[1]);
+}
+
+test('a path goes around a hole, keeps the agent radius and is deterministic', () => {
+ const hole = { center: [0, 0], radius: 3 };
+ const navmesh = createNavmesh({ ...flatGround(40, [hole]), agentRadius: 0.3 });
+ const first = navmesh.findPath([-15, -15], [15, 15], { spacing: 0.5 });
+ const second = createNavmesh({ ...flatGround(40, [hole]), agentRadius: 0.3 }).findPath([-15, -15], [15, 15], { spacing: 0.5 });
+ assert.deepEqual(first, second);
+ assert.deepEqual(first.points[0].map(Math.round), [-15, 0, -15]);
+ assert.deepEqual(first.points.at(-1).map(Math.round), [15, 0, 15]);
+ for (const point of first.points) assert.ok(distanceToHoleCentre(point, hole) >= hole.radius + 0.3, `point ${point} is too close to the hole`);
+ const straight = Math.hypot(30, 30);
+ assert.ok(first.length > straight && first.length < straight * 1.1, `length ${first.length}`);
+});
+
+test('string pulling leaves a straight line where nothing is in the way', () => {
+ const navmesh = createNavmesh({ ...flatGround(40) });
+ const path = navmesh.findPath([-10, -8], [12, 9], { spacing: 100 });
+ assert.equal(path.points.length, 2);
+ assert.ok(Math.abs(path.length - Math.hypot(22, 17)) < 1e-6);
+});
+
+test('a start inside a hole, outside the ground or beside an obstacle is refused with a reason', () => {
+ const navmesh = createNavmesh({ ...flatGround(40, [{ center: [0, 0], radius: 3 }]), obstacles: [{ min: [8, 8], max: [10, 10] }] });
+ assert.throws(() => navmesh.findPath([0, 0], [10, 0]), /Start .* \(a hole\)/);
+ assert.throws(() => navmesh.findPath([-30, 0], [10, 0]), /Start .* outside the ground/);
+ assert.throws(() => navmesh.findPath([-10, 0], [9, 9]), /Goal .* not walkable/);
+});
+
+test('a wall of holes that cuts the ground in two has no path', () => {
+ const wall = Array.from({ length: 11 }, (_, index) => ({ center: [0, -20 + index * 4], radius: 2.2 }));
+ const navmesh = createNavmesh({ ...flatGround(40, wall.slice(0, 11)) });
+ assert.throws(() => navmesh.findPath([-10, 0], [10, 0]), /no walkable route/);
+});
+
+test('the cell and search budgets give clear errors', () => {
+ assert.throws(() => createNavmesh({ ...flatGround(40), cellSize: 0.05, maxCells: 1000 }), /over the budget of 1000.*Raise cellSize/);
+ const navmesh = createNavmesh({ ...flatGround(40, [{ center: [0, 0], radius: 8 }]) });
+ assert.throws(() => navmesh.findPath([-15, -15], [15, 15], { maxSearchNodes: 20 }), /search used 20 nodes/);
+});
+
+test('ground that climbs faster than the slope limit blocks the way', () => {
+ const terrain = createTerrain({ size: 40, chunks: 1, levels: 1, resolution: 64, height: (x) => (x > 0 ? 6 : 0) });
+ const { positions, indices } = terrain.parts[0].geometry;
+ const steep = createNavmesh({ positions, indices, maxSlopeDegrees: 30, cellSize: 0.6 });
+ assert.throws(() => steep.findPath([-10, 0], [10, 0]), /no walkable route/);
+ const gentleTerrain = createTerrain({ size: 40, chunks: 1, levels: 1, resolution: 64, height: (x) => x * 0.2 });
+ const gentle = createNavmesh({ positions: gentleTerrain.parts[0].geometry.positions, indices: gentleTerrain.parts[0].geometry.indices, maxSlopeDegrees: 30, cellSize: 0.6 });
+ const path = gentle.findPath([-10, 0], [10, 0]);
+ assert.ok(Math.abs(path.points.at(-1)[1] - 2) < 0.1);
+});
+
+test('scene_inspect path returns translation keyframes around the hole of a recipe terrain', async () => {
+ const recipe = {
+ format: '67js.scene', schemaVersion: 1,
+ geometries: [{ id: 'ground', type: 'terrain', size: 40, resolution: 64, seed: 3, amplitude: 1.2, holes: [{ center: [0, 0], radius: 3 }] }, { id: 'rock', type: 'box' }],
+ materials: [{ id: 'grass', color: [0.3, 0.6, 0.2] }],
+ nodes: [{ id: 'ground', geometry: 'ground', material: 'grass' }, { id: 'rock', geometry: 'rock', material: 'grass', translation: [-7, 0.5, -7], scale: [3, 1, 3] }],
+ };
+ await loadAllAgentSceneModules();
+ const scene = createAgentScene(recipe);
+ const { path } = scene.inspect({ path: { ground: 'ground', from: [-15, -15], to: [15, 15], avoid: ['rock'], seconds: 10, lift: 0.5 } });
+ assert.equal(path.keyframes[0].time, 0);
+ assert.equal(path.keyframes.at(-1).time, 10);
+ for (const { value } of path.keyframes) {
+ assert.ok(Math.hypot(value[0], value[2]) >= 3.3, `${value} is inside the hole margin`);
+ assert.ok(!(value[0] > -8.8 && value[0] < -5.2 && value[2] > -8.8 && value[2] < -5.2), `${value} is inside the rock`);
+ }
+ assert.throws(() => scene.inspect({ path: { ground: 'ground', from: [0, 0], to: [15, 15] } }), /a hole/);
+ assert.throws(() => scene.inspect({ path: { ground: 'nowhere', from: [0, 0], to: [15, 15] } }), /not a node/);
+ assert.throws(() => scene.inspect({ path: { ground: 'ground', from: [-15, -15], to: [15, 15], seconds: 2, speed: 1 } }), /seconds or speed/);
+});
diff --git a/vite.lib.config.js b/vite.lib.config.js
index 7949d146..173a215b 100644
--- a/vite.lib.config.js
+++ b/vite.lib.config.js
@@ -35,6 +35,7 @@ export default defineConfig({
vehicle: 'src/vehicle.js',
vegetation: 'src/vegetation.js',
terrain: 'src/terrain.js',
+ navmesh: 'src/navmesh.js',
grass: 'src/grass.js',
clutter: 'src/clutter.js',
'light-bake': 'src/light-bake.js',