3D engine that AI agents drive
Add obstacle keep-out, recipe scenes and a query-only large asset path to scene_walkmap (issue #559)
Nguyen Xuan Anf04ae6b766a9
diff --git a/changes/559.md b/changes/559.mdnew file mode 100644index 00000000..0eb5d603--- /dev/null+++ b/changes/559.md@@ -0,0 +1 @@+- `scene_walkmap` and `walkMap` mark obstacles and keep clear of them (issue #559). `keepOut` (metres) with an optional `streetY` casts a down ray from 2.6 m above the street, marks a cell as an obstacle when its first hit is over 0.3 m above the lowest surface under it (kerbs stay walkable), closes one-cell seams, cuts the obstacles back out and clears every cell closer than `keepOut`; in code `walkMap({ obstacles })` and the new `walkableMask` do the same. `scene_walkmap` also works on recipe scenes, and `assetId` queries a catalog GLB above the 1,000,000 vertex render cap without rendering it (parsed in the server, textures dropped, up to 6,000,000 triangles). On the Bistro sample a 0.25 m grid with `keepOut` 1.0 takes 38 s and agrees with a Blender walk map on 99.95 percent of cells; see `docs/scene-query.md`.diff --git a/changes/559.size.md b/changes/559.size.mdnew file mode 100644index 00000000..9e9b009b--- /dev/null+++ b/changes/559.size.md@@ -0,0 +1,3 @@+- tool-total: scene_walkmap gains assetId, keepOut and streetY (171 B), the way an agent plans a path 1 m clear of poles over a world too large to render.+- tool:scene_walkmap: the same three fields on the existing tool, instead of a new tool.+- entry:scene-query: obstacle marking, the closing step and walkableMask (913 B gzip); a 1 m grid missed poles that the 0.25 m obstacle map catches.diff --git a/docs/mcp.md b/docs/mcp.mdindex 08d0a924..c655fe83 100644--- a/docs/mcp.md+++ b/docs/mcp.md@@ -127,7 +127,7 @@ Inspect or export the recipe before retrying. Context loss still permits recipe| `scene_create_asset` | `recipe` using `67js.asset` | Imported scene ID, revision, inspection and render status || `scene_inspect` | `sessionId`, optional `ids`, `limit`, `includeBounds` | Compact node records and revision || `scene_apply` | `sessionId`, `expectedRevision`, `operations` | Updated revision, inspection, and render status |-| `scene_walkmap` | `sessionId`, `min`, `max`, optional `cellSize`, `clearance`, `includeCells` | Grid rows of `.` walkable, `x` blocked and `#` no surface, with counts; ground height and headroom per cell with `includeCells`. See [scene-query.md](scene-query.md) |+| `scene_walkmap` | `sessionId` or `assetId` (query a big catalog GLB), `min`, `max`, optional `cellSize`, `clearance`, `keepOut`, `streetY`, `includeCells` | Grid rows of `.` walkable, `x` blocked and `#` no surface, with counts; ground height and headroom per cell with `includeCells`. See [scene-query.md](scene-query.md) || `mesh_inspect` | `sessionId`, optional `geometries` (up to 16 IDs) | Per geometry: polygon counts, face sizes, parts, face tags, bounds and lint problems with fixes || `mesh_edit` | `sessionId`, `expectedRevision`, `geometry`, `edits`, optional `replace` | Updated revision, render status and the mesh report with per-edit results || `mesh_stack` | `sessionId`, `expectedRevision`, `geometry`, optional `stack`, `apply` | Updated revision, render status and the mesh report with per-node results |diff --git a/docs/scene-query.md b/docs/scene-query.mdindex 26044145..bf2b607c 100644--- a/docs/scene-query.md+++ b/docs/scene-query.md@@ -54,7 +54,7 @@ Measured on a machine under load: about 8 s for the first 12,630 cells including## MCP tool-`scene_walkmap` runs the same query on the active imported asset scene (made with `scene_create_asset`; procedural recipe scenes are not supported yet) and returns text rows an agent can read.+`scene_walkmap` runs the same query on the active scene and returns text rows an agent can read.Rows follow z, columns follow x.```json@@ -70,8 +70,30 @@ Rows follow z, columns follow x.Pass `includeCells: true` for `[x, z, groundY, headroom]` per cell, up to 4,096 cells.Plan a camera path over the `.` cells, set each eye at `groundY` plus the eye height, and check it with `scene_look`.The server holds one query per session and rebuilds it when the revision or a pose changes.-The MCP asset catalog is limited to 1,000,000 vertices (see [gltf.md](gltf.md)); a larger scene such as Bistro loads through `loadGltf` and `createSceneQuery` in code.-Fields: `min` and `max` are `[x, z]` corners, x runs across the rows and z down them. `cellSize` defaults to 1 and `clearance` (headroom a walkable cell needs) to 2.The down rays start at y = 100, and the region may hold up to 65,536 cells.The tool does not take `topY`, `groundRange` or `lowerPass`: for a scene taller than 100, ground ranges or arches, call `walkMap` from code.++The tool works on the active scene, a recipe scene or an imported asset scene.++### Obstacles and keep-out++Pass `keepOut` (metres) and bollards, lamp posts, planters and tables stop being ground.+For each cell a ray goes down from 2.6 m above the street level, and when its first hit stands more than 0.3 m above the lowest surface under it, the cell is an obstacle.+A kerb is 0.15 to 0.2 m, so kerbs stay walkable.+`streetY` is the street level; it defaults to the lowest surface in a sample of the region.+A closing step fills one-cell seams (kerb faces, cracks narrower than 0.75 m), obstacles are cut back out, and a cell closer than `keepOut` to an obstacle, a wall or a gap is not walkable (`x`).+In code pass `obstacles: true` or `obstacles: { streetY, fromY, reach, minHeight }` to `walkMap`, and give the result to `walkableMask(map, { clearance, groundRange, keepOut })`, which returns one 0 or 1 per cell, `column * rows + row`.+Cells then carry a fifth value, 1 for an obstacle.+Use a small `cellSize`: a 0.25 m grid caught poles that a 1 m grid missed.++### Large worlds++Pass `assetId` (from `scene_asset_catalog`) instead of a session to query a catalog GLB without creating a scene.+The file is read and parsed in the server process, its textures are dropped before decoding, and nothing is rendered, so it can pass the 1,000,000 vertex render cap (see [gltf.md](gltf.md)).+It still has to be a file of the configured `--assets` folder, under that folder's 64 MiB file limit, and it must stay within 6,000,000 vertices, 6,000,000 triangles and 16,384 parts, with 256 MiB for each part's index.+The server keeps one such scene; asking for another `assetId` replaces it.+`assetId` and `sessionId` are mutually exclusive.++Measured on the Bistro sample (2,829,226 triangles in 224 parts, 48 MiB file) on a machine under load: parsing 1.3 s, a 0.25 m grid over x -62 to 111 and z -88 to 97 (513,513 cells; in code, since the tool caps a region at 65,536 cells) with `keepOut` 1.0 in 38 s.+Against a Blender walk map of the same grid, 99.95 percent of the 149,652 cells with a surface in both agree on obstacle or not, and all 295 pole clusters in it are excluded.diff --git a/scripts/agent-preview-browser.js b/scripts/agent-preview-browser.jsindex 9113fe7f..3a2e690f 100644--- a/scripts/agent-preview-browser.js+++ b/scripts/agent-preview-browser.js@@ -26,7 +26,7 @@ import { clipFromGltfAnimation } from '../src/skeleton-pose.js';import { sessionProblem } from '../src/agent-errors.js';import { BRANCH_LIMITS, createBranchStore, printableLabel } from '../src/agent-branches.js';import { agentAssetDecodeOptions, withCatalogLimitAdvice } from '../src/agent-asset-limits.js';-import { sceneQueryFor, summarizeWalkMap } from './agent-walkmap.js';+import { sceneQueryFor, summarizeWalkMap, walkOptionsFor } from './agent-walkmap.js';let active = null;let canvas = document.querySelector('canvas');@@ -852,14 +852,13 @@ window.__agentPreview = {if (!allAgentSceneModulesLoaded()) return loadAllAgentSceneModules().then(() => this.inspectMeshes({ sessionId, ...options }));return { sessionId, ...scene.inspectMeshes(options) };},- async walkMap({ sessionId, clearance = 2, groundRange, includeCells = false, ...options }) {+ async walkMap({ sessionId, clearance = 2, groundRange, keepOut, streetY, includeCells = false, ...options }) {const record = requireSession(sessionId);- if (typeof record.scene.queryParts !== 'function') throw new TypeError('scene_walkmap needs an imported asset scene (scene_create_asset). Procedural recipe scenes have no loaded surfaces to query yet.');if (!allAgentSceneModulesLoaded()) await loadAllAgentSceneModules();const started = performance.now();const query = sceneQueryFor(record);- const map = query.walkMap(options);- return { sessionId, revision: record.scene.revision, ...summarizeWalkMap(map, { clearance, groundRange, includeCells }), skippedParts: query.skipped.length, milliseconds: Math.round(performance.now() - started) };+ const map = query.walkMap(walkOptionsFor(options, keepOut, streetY));+ return { sessionId, revision: record.scene.revision, ...summarizeWalkMap(map, { clearance, groundRange, keepOut, includeCells }), skippedParts: query.skipped.length, milliseconds: Math.round(performance.now() - started) };},apply(input) {if (input.sequenceData) {diff --git a/scripts/agent-query-asset.mjs b/scripts/agent-query-asset.mjsnew file mode 100644index 00000000..05575edd--- /dev/null+++ b/scripts/agent-query-asset.mjs@@ -0,0 +1,98 @@+import { parseGltf } from '../src/gltf.js';+import { createSceneQuery } from '../src/scene-query.js';+import { summarizeWalkMap, walkOptionsFor } from './agent-walkmap.js';++// Query-only load path: raycasts and walk maps over a local catalog GLB that is too big to render through MCP. The file is+// read and parsed in the server process (never sent to the preview page), with its textures dropped before decoding, so+// only positions, indices and node matrices are held. Every number below is a hard ceiling the agent cannot raise.+export const QUERY_ASSET_LIMITS = Object.freeze({+ maxVertices: 6_000_000,+ maxTriangles: 6_000_000,+ maxParts: 16_384,+ // Per part BVH budget; the mesh query itself refuses a part over 1,000,000 triangles.+ memoryBudgetMiB: 256,+});++const JSON_CHUNK = 0x4e4f534a;+const TEXTURE_KEY = /Texture$/;++function withoutTextureReferences(value) {+ if (Array.isArray(value)) {+ value.forEach(withoutTextureReferences);+ return;+ }+ if (!value || typeof value !== 'object') return;+ for (const key of Object.keys(value)) {+ if (TEXTURE_KEY.test(key) && Number.isInteger(value[key]?.index)) delete value[key];+ else withoutTextureReferences(value[key]);+ }+}++/** The same GLB with no images, textures or texture references; the binary chunk is untouched. */+export function geometryOnlyGlb(bytes) {+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);+ if (bytes.byteLength < 20 || view.getUint32(0, true) !== 0x46546c67 || view.getUint32(16, true) !== JSON_CHUNK) {+ throw new Error('Query-only assets must be GLB files with a JSON chunk first.');+ }+ const jsonLength = view.getUint32(12, true);+ const document = JSON.parse(Buffer.from(bytes.subarray(20, 20 + jsonLength)).toString('utf8'));+ delete document.images;+ delete document.textures;+ delete document.samplers;+ withoutTextureReferences(document.materials);+ const padded = Buffer.from(JSON.stringify(document));+ const jsonBytes = Buffer.concat([padded, Buffer.alloc((4 - (padded.length % 4)) % 4, 0x20)]);+ const rest = bytes.subarray(20 + jsonLength);+ const header = Buffer.alloc(20);+ header.writeUInt32LE(0x46546c67, 0);+ header.writeUInt32LE(2, 4);+ header.writeUInt32LE(20 + jsonBytes.length + rest.length, 8);+ header.writeUInt32LE(jsonBytes.length, 12);+ header.writeUInt32LE(JSON_CHUNK, 16);+ return Buffer.concat([header, jsonBytes, rest]);+}++/** Parses the geometry of a catalog GLB inside the query-only limits and returns a scene query over it. */+export async function loadQueryOnlyScene(bytes) {+ const stripped = geometryOnlyGlb(bytes);+ const buffer = stripped.buffer.slice(stripped.byteOffset, stripped.byteOffset + stripped.byteLength);+ const asset = await parseGltf(buffer, { maxBytes: bytes.length + 1024, maxVertices: QUERY_ASSET_LIMITS.maxVertices, maxParts: QUERY_ASSET_LIMITS.maxParts });+ let triangles = 0;+ let vertices = 0;+ for (const part of asset.parts) {+ triangles += part.geometry.indices.length / 3;+ vertices += part.geometry.positions.length / 3;+ }+ if (triangles > QUERY_ASSET_LIMITS.maxTriangles) {+ throw new RangeError(`Query-only asset has ${triangles} triangles, over the query maxTriangles ${QUERY_ASSET_LIMITS.maxTriangles}. Split it or decimate it.`);+ }+ const parts = asset.parts.map((part, position) => ({ id: part.name ?? `part-${position}`, geometry: part.geometry, matrix: part.matrix, material: part.material?.id }));+ const query = createSceneQuery(parts, { memoryBudgetMiB: QUERY_ASSET_LIMITS.memoryBudgetMiB });+ return { query, parts: parts.length, triangles, vertices };+}++/** One loaded scene at a time, keyed by the catalog asset ID. A different asset replaces and disposes the first. */+export function createQueryOnlyCache() {+ let current = null;+ return Object.freeze({+ async walkMap({ assetId, bytes, clearance = 2, groundRange, keepOut, streetY, includeCells = false, ...options }) {+ const started = performance.now();+ if (current?.assetId !== assetId) {+ current?.scene.query.dispose();+ current = null;+ current = { assetId, scene: await loadQueryOnlyScene(await bytes()) };+ }+ const { query, parts, triangles } = current.scene;+ const map = query.walkMap(walkOptionsFor(options, keepOut, streetY));+ return {+ assetId, queryOnly: true, parts, triangles,+ ...summarizeWalkMap(map, { clearance, groundRange, keepOut, includeCells }),+ skippedParts: query.skipped.length, milliseconds: Math.round(performance.now() - started),+ };+ },+ dispose() {+ current?.scene.query.dispose();+ current = null;+ },+ });+}diff --git a/scripts/agent-runtime.mjs b/scripts/agent-runtime.mjsindex 11e9fc93..177363ab 100644--- a/scripts/agent-runtime.mjs+++ b/scripts/agent-runtime.mjs@@ -15,6 +15,7 @@ import { AGENT_SCENE_CAPABILITIES, AGENT_SCENE_DEFAULT_LIMITS, RENDER_PASS_NAMESimport { PATH_TRACER_CAPABILITIES } from '../src/path-tracer-capabilities.js';import { chooseDenoiser, finishWithOidn } from './agent-path-trace-denoise.mjs';import { createAgentAssetCatalog } from './agent-asset-catalog.mjs';+import { createQueryOnlyCache } from './agent-query-asset.mjs';import { AGENT_ASSET_LIMITS, assertCombinedAssetBytes } from '../src/agent-asset-limits.js';import { recipeAssetNeeds } from '../src/agent-scene-assets.js';import { sequenceFrameIds } from '../src/agent-texture-sequence.js';@@ -105,6 +106,7 @@ export function createAgentRuntime({ kernelWorkers = true, backend = 'gpu', browlet queue = Promise.resolve();let closing;let catalogPromise;+ const queryOnly = createQueryOnlyCache();let jobsPromise;const savedGlbPaths = [];function jobs() {@@ -195,6 +197,7 @@ export function createAgentRuntime({ kernelWorkers = true, backend = 'gpu', brow}async function shutdownResources() {+ queryOnly.dispose();try {await browserInstance?.close();} finally {@@ -637,8 +640,11 @@ export function createAgentRuntime({ kernelWorkers = true, backend = 'gpu', browinspectMeshes(input) {return enqueue(() => invoke('inspectMeshes', input));},- walkMap(input) {- return enqueue(() => invoke('walkMap', input));+ walkMap({ assetId, ...input }) {+ if (assetId === undefined) return enqueue(() => invoke('walkMap', input));+ if (input.sessionId !== undefined) return Promise.reject(new TypeError('scene_walkmap takes a sessionId or an assetId, not both.'));+ // Query-only: parsed in this process from the catalog file and never rendered, so it may pass the render vertex cap.+ return enqueue(() => queryOnly.walkMap({ ...input, assetId, bytes: async () => (await catalog()).read(assetId) }));},setMeshStack(input) {return enqueue(async () => {diff --git a/scripts/agent-walkmap.js b/scripts/agent-walkmap.jsindex 7d031479..87846535 100644--- a/scripts/agent-walkmap.js+++ b/scripts/agent-walkmap.js@@ -1,4 +1,4 @@-import { createSceneQuery } from '../src/scene-query.js';+import { createSceneQuery, walkableMask } from '../src/scene-query.js';const MAXIMUM_LISTED_CELLS = 4096;@@ -10,9 +10,15 @@ function matrixChecksum(parts) {return total;}+/** Imported asset scenes list their own surfaces; a recipe scene's parts already hold geometry, a world matrix and a material. */+function queryPartsOf(scene) {+ if (typeof scene.queryParts === 'function') return scene.queryParts();+ return scene.parts.map(part => ({ id: part.name, geometry: part.geometry, matrix: part.matrix, material: part.material?.id }));+}+/** One cached scene query per session. It is rebuilt when the revision or any part matrix (a seeked pose) changes. */export function sceneQueryFor(record) {- const parts = record.scene.queryParts();+ const parts = queryPartsOf(record.scene);const key = `${record.scene.revision}:${parts.length}:${matrixChecksum(parts)}`;if (record.sceneQueryKey !== key) {record.sceneQuery?.dispose();@@ -22,31 +28,43 @@ export function sceneQueryFor(record) {return record.sceneQuery;}+/** keepOut and streetY switch obstacle marking on; without either the map is the plain ground and headroom one. */+export function walkOptionsFor(options, keepOut, streetY) {+ if (keepOut === undefined && streetY === undefined) return options;+ return { ...options, obstacles: streetY === undefined ? true : { streetY } };+}+function rounded(value) {return Math.round(value * 100) / 100;}/** Turns the raw cells into text rows an agent can read: '.' walkable, 'x' blocked, '#' no surface. */-export function summarizeWalkMap(map, { clearance, groundRange, includeCells }) {+export function summarizeWalkMap(map, { clearance, groundRange, keepOut, includeCells }) {const { columns, rows, cellSize, min } = map;+ const mask = walkableMask(map, { clearance, groundRange, keepOut });const grid = Array.from({ length: rows }, () => Array(columns).fill('#'));- let walkable = 0;const listed = [];for (const [x, z, groundY, headroom] of map.cells) {const column = Math.round((x - min[0]) / cellSize);const row = Math.round((z - min[1]) / cellSize);- const inRange = !groundRange || (groundY >= groundRange[0] && groundY <= groundRange[1]);- const open = headroom >= clearance && inRange;- grid[row][column] = open ? '.' : 'x';- if (open) walkable++;+ grid[row][column] = 'x';listed.push([x, z, rounded(groundY), rounded(headroom)]);}+ // Closing can open a cell that had no surface (a seam), so walkable cells are marked from the mask alone.+ let walkable = 0;+ for (let column = 0; column < columns; column++) {+ for (let row = 0; row < rows; row++) {+ if (!mask[column * rows + row]) continue;+ grid[row][column] = '.';+ walkable++;+ }+ }if (includeCells && listed.length > MAXIMUM_LISTED_CELLS) {throw new RangeError(`includeCells lists at most ${MAXIMUM_LISTED_CELLS} cells and this region has ${listed.length} with a surface. Shrink the region or raise cellSize.`);}return {cellSize, min, columns, rows, surfaceCells: map.cells.length, walkableCells: walkable,- legend: { '.': 'walkable', x: 'ground with too little headroom or outside groundRange', '#': 'no surface' },+ legend: { '.': 'walkable', x: 'ground with too little headroom, an obstacle, outside groundRange or within keepOut', '#': 'no surface' },grid: grid.map(row => row.join('')),...(includeCells ? { cells: listed } : {}),};diff --git a/scripts/mcp-server.mjs b/scripts/mcp-server.mjsindex ac38f81f..c78266a0 100644--- a/scripts/mcp-server.mjs+++ b/scripts/mcp-server.mjs@@ -755,7 +755,7 @@ export function createAgentMcpServer(runtime, { version = packageMetadata.versioregister('scene_asset_catalog', 'List content-bound GLB and PNG, JPEG or WebP image 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.'), 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('scene_walkmap', 'Walkable map of an imported asset scene on a grid: rows of . walkable, x blocked, # no surface.', z.strictObject({ ...sessionFields, min: z.tuple([z.number(), z.number()]), max: z.tuple([z.number(), z.number()]), cellSize: z.number().min(0.05).default(1), clearance: z.number().min(0).default(2), includeCells: z.boolean().optional() }), readOnly, async argumentsValue => jsonResult(await runtime.walkMap(argumentsValue)));+ register('scene_walkmap', 'Walkable map on a grid: rows of . walkable, x blocked, # no surface. keepOut (m) avoids obstacles. assetId: query a big catalog GLB, no render.', z.strictObject({ ...sessionFields, assetId: z.string().regex(/^[a-f0-9]{64}$/).optional(), min: z.tuple([z.number(), z.number()]), max: z.tuple([z.number(), z.number()]), cellSize: z.number().min(0.05).default(1), clearance: z.number().min(0).default(2), keepOut: z.number().min(0).optional(), streetY: z.number().optional(), includeCells: z.boolean().optional() }), readOnly, async argumentsValue => jsonResult(await runtime.walkMap(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/scene-query.js b/src/scene-query.jsindex 754fbbcb..3f91fe29 100644--- a/src/scene-query.js+++ b/src/scene-query.js@@ -8,8 +8,14 @@ const DEFAULT_WALK_OPTIONS = Object.freeze({clearanceCap: 99,maxCells: 65_536,});-const WALK_OPTION_NAMES = new Set(['min', 'max', 'cellSize', 'topY', 'probeHeight', 'clearanceCap', 'maxCells', 'lowerPass']);+const WALK_OPTION_NAMES = new Set(['min', 'max', 'cellSize', 'topY', 'probeHeight', 'clearanceCap', 'maxCells', 'lowerPass', 'obstacles']);const LOWER_PASS_NAMES = new Set(['fromY', 'maxDistance', 'groundBelow', 'minHeadroom']);+// A kerb is about 0.15 to 0.2 m, so 0.3 m keeps kerbs walkable while bollards, lamp posts, planters and tables stand out.+const DEFAULT_OBSTACLES = Object.freeze({ reach: 2.6, minHeight: 0.3, maxDrop: 6, maxLayers: 8 });+const OBSTACLE_NAMES = new Set(['streetY', 'fromY', 'reach', 'minHeight']);+const STREET_SAMPLE_CELLS = 1024;+// Seams a closing step fills: kerb faces and cracks narrower than this many metres.+const SEAM_METRES = 0.75;function assertNumber(value, label) {if (!Number.isFinite(value)) throw new TypeError(`${label} requires a finite number.`);@@ -117,6 +123,21 @@ function faceNormal(geometry, triangle, matrix, direction) {return normal.map(value => (value / length) * facing);}+// The lowest surface among an evenly spaced sample of the region: the street level when no streetY is given.+function lowestSampledGround(settings, topHit) {+ const { columns, rows, cellSize } = settings;+ const stride = Math.max(1, Math.ceil(Math.sqrt((columns * rows) / STREET_SAMPLE_CELLS)));+ let lowest = Infinity;+ for (let column = 0; column < columns; column += stride) {+ for (let row = 0; row < rows; row += stride) {+ const top = topHit(settings.min[0] + column * cellSize, settings.min[1] + row * cellSize);+ if (top) lowest = Math.min(lowest, top.point[1]);+ }+ }+ if (lowest === Infinity) throw new RangeError('walkMap obstacles found no surface to take the street level from. Pass obstacles.streetY.');+ return lowest;+}+function readWalkOptions(options) {if (!options || typeof options !== 'object') throw new TypeError('walkMap requires an options object.');for (const name of Object.keys(options)) {@@ -138,6 +159,16 @@ function readWalkOptions(options) {settings.lowerPass = { maxDistance: 4, minHeadroom: 2.4, ...settings.lowerPass };for (const field of ['fromY', 'groundBelow']) assertNumber(settings.lowerPass[field], `walkMap lowerPass.${field}`);}+ if (settings.obstacles !== undefined) {+ const given = settings.obstacles === true ? {} : settings.obstacles;+ if (!given || typeof given !== 'object') throw new TypeError('walkMap obstacles requires true or an options object.');+ for (const name of Object.keys(given)) {+ if (!OBSTACLE_NAMES.has(name)) throw new TypeError(`Unsupported walkMap obstacles option ${name}.`);+ assertNumber(given[name], `walkMap obstacles.${name}`);+ }+ settings.obstacles = { ...DEFAULT_OBSTACLES, ...given };+ if (settings.obstacles.minHeight <= 0 || settings.obstacles.reach <= 0) throw new RangeError('walkMap obstacles minHeight and reach must be positive.');+ }settings.columns = Math.floor((settings.max[0] - settings.min[0]) / settings.cellSize + 1e-9) + 1;settings.rows = Math.floor((settings.max[1] - settings.min[1]) / settings.cellSize + 1e-9) + 1;if (settings.columns * settings.rows > settings.maxCells) {@@ -219,11 +250,37 @@ export function createSceneQuery(parts, options = {}) {const hit = raycast({ origin: [x, groundY + probeHeight, z], direction: up, maxDistance: topY - groundY });return hit ? Math.min(hit.point[1] - groundY, clearanceCap) : clearanceCap;}+ // Obstacle marking: a down ray from about `reach` metres above the street. When its first hit stands more than+ // `minHeight` above the lowest surface under it, the cell holds an obstacle. Ground and headroom come from that column.+ const obstacles = settings.obstacles;+ let obstacleFromY = obstacles?.fromY;+ if (obstacles && obstacleFromY === undefined) {+ const streetY = obstacles.streetY+ ?? lowestSampledGround(settings, (x, z) => raycast({ origin: [x, topY, z], direction: down }));+ obstacleFromY = streetY + obstacles.reach;+ }+ function obstacleCell(x, z) {+ const first = raycast({ origin: [x, obstacleFromY, z], direction: down });+ if (!first) return null;+ let groundY = first.point[1];+ for (let layer = 0; layer < obstacles.maxLayers; layer++) {+ const lower = raycast({ origin: [x, groundY - 0.01, z], direction: down, maxDistance: obstacles.maxDrop });+ if (!lower) break;+ groundY = lower.point[1];+ }+ const standing = first.point[1] - groundY > obstacles.minHeight;+ return [x, z, groundY, headroomAbove(x, z, groundY), standing ? 1 : 0];+ }const cells = [];for (let column = 0; column < columns; column++) {for (let row = 0; row < rows; row++) {const x = settings.min[0] + column * cellSize;const z = settings.min[1] + row * cellSize;+ if (obstacles) {+ const cell = obstacleCell(x, z);+ if (cell) cells.push(cell);+ continue;+ }const top = raycast({ origin: [x, topY, z], direction: down });if (!top) continue;let groundY = top.point[1];@@ -256,3 +313,78 @@ export function createSceneQuery(parts, options = {}) {},});}++/**+ * Which cells of a walkMap result an agent may walk, as a Uint8Array indexed `column * rows + row` (1 = walkable).+ * A cell is open when it has a surface, enough headroom, is not an obstacle (see walkMap `obstacles`) and sits in+ * `groundRange`. With `keepOut` (metres) the open cells go through a closing step, so one-cell seams such as kerb+ * faces do not split a street, then obstacles are cut back out, and every cell closer than `keepOut` to anything that+ * is not open (an obstacle, a wall, a gap) stops being walkable.+ */+export function walkableMask(map, { clearance = 2, groundRange, keepOut = 0 } = {}) {+ const { columns, rows, cellSize, min } = map;+ const count = columns * rows;+ const open = new Uint8Array(count);+ const obstacle = new Uint8Array(count);+ for (const [x, z, groundY, headroom, standing] of map.cells) {+ const slot = Math.round((x - min[0]) / cellSize) * rows + Math.round((z - min[1]) / cellSize);+ const inRange = !groundRange || (groundY >= groundRange[0] && groundY <= groundRange[1]);+ if (standing) obstacle[slot] = 1;+ else if (headroom >= clearance && inRange) open[slot] = 1;+ }+ if (!(keepOut > 0)) return open;+ const seam = Math.max(1, Math.round(SEAM_METRES / cellSize));+ let free = open;+ // Closing = grow the open cells, then shrink them. Outside the grid counts as the same state as the edge cell, so the+ // border never eats into the result.+ for (let step = 0; step < seam; step++) free = spread(free, columns, rows, 1);+ for (let step = 0; step < seam; step++) free = spread(free, columns, rows, 0);+ for (let slot = 0; slot < count; slot++) if (obstacle[slot]) free[slot] = 0;+ free = spread(spread(free, columns, rows, 0), columns, rows, 1);+ return keepClear(free, columns, rows, keepOut / cellSize);+}++// One 4-neighbour step: every cell next to a cell holding `value` takes `value` too.+function spread(grid, columns, rows, value) {+ const next = Uint8Array.from(grid);+ for (let column = 0; column < columns; column++) {+ for (let row = 0; row < rows; row++) {+ const slot = column * rows + row;+ if (grid[slot] === value) continue;+ const beside = (column > 0 && grid[slot - rows] === value)+ || (column < columns - 1 && grid[slot + rows] === value)+ || (row > 0 && grid[slot - 1] === value)+ || (row < rows - 1 && grid[slot + 1] === value);+ if (beside) next[slot] = value;+ }+ }+ return next;+}++// Clears every open cell within `radius` cells of a closed cell. Only closed cells that touch an open one need to spread.+function keepClear(free, columns, rows, radius) {+ const reach = Math.ceil(radius);+ const offsets = [];+ for (let dx = -reach; dx <= reach; dx++) {+ for (let dz = -reach; dz <= reach; dz++) {+ if (dx * dx + dz * dz < radius * radius) offsets.push([dx, dz]);+ }+ }+ const result = Uint8Array.from(free);+ for (let column = 0; column < columns; column++) {+ for (let row = 0; row < rows; row++) {+ if (free[column * rows + row]) continue;+ const touchesOpen = (column > 0 && free[(column - 1) * rows + row])+ || (column < columns - 1 && free[(column + 1) * rows + row])+ || (row > 0 && free[column * rows + row - 1])+ || (row < rows - 1 && free[column * rows + row + 1]);+ if (!touchesOpen) continue;+ for (const [dx, dz] of offsets) {+ const nearColumn = column + dx;+ const nearRow = row + dz;+ if (nearColumn >= 0 && nearColumn < columns && nearRow >= 0 && nearRow < rows) result[nearColumn * rows + nearRow] = 0;+ }+ }+ }+ return result;+}diff --git a/tests/agent-query-asset.test.js b/tests/agent-query-asset.test.jsnew file mode 100644index 00000000..edf3d4c3--- /dev/null+++ b/tests/agent-query-asset.test.js@@ -0,0 +1,36 @@+import test from 'node:test';+import assert from 'node:assert/strict';+import { carAsset } from './fixtures/car-glb.js';+import { createQueryOnlyCache, geometryOnlyGlb, loadQueryOnlyScene, QUERY_ASSET_LIMITS } from '../scripts/agent-query-asset.mjs';++test('geometryOnlyGlb keeps the geometry readable', async () => {+ const stripped = geometryOnlyGlb(Buffer.from(carAsset()));+ const scene = await loadQueryOnlyScene(stripped);+ assert.ok(scene.parts > 0);+ assert.ok(scene.triangles > 0);+ assert.ok(scene.triangles <= QUERY_ASSET_LIMITS.maxTriangles);+ scene.query.dispose();+});++test('the query-only cache walks a catalog asset, reuses its scene and replaces it for another asset', async () => {+ const cache = createQueryOnlyCache();+ let reads = 0;+ const bytes = async () => {+ reads++;+ return Buffer.from(carAsset());+ };+ const region = { min: [-3, -3], max: [3, 3], cellSize: 1, topY: 20, clearance: 1 };+ const first = await cache.walkMap({ assetId: 'a'.repeat(64), bytes, ...region });+ assert.equal(first.queryOnly, true);+ assert.equal(first.grid.length, 7);+ assert.ok(first.walkableCells > 0);+ await cache.walkMap({ assetId: 'a'.repeat(64), bytes, ...region, keepOut: 0.5, streetY: 0 });+ assert.equal(reads, 1);+ await cache.walkMap({ assetId: 'b'.repeat(64), bytes, ...region });+ assert.equal(reads, 2);+ cache.dispose();+});++test('a file that is not a GLB with a JSON chunk first is refused', () => {+ assert.throws(() => geometryOnlyGlb(Buffer.alloc(64)), /GLB/);+});diff --git a/tests/agent-runtime.test.js b/tests/agent-runtime.test.jsindex 2c10ca53..b8236f07 100644--- a/tests/agent-runtime.test.js+++ b/tests/agent-runtime.test.js@@ -113,6 +113,7 @@ async function reviewRuntimeHarness({ failShot, blockShot = false, oversize = faVEGETATION_CAPABILITY_NOTE, CROWD_CAPABILITY_NOTE, USER_PASS_CAPABILITIES, MESH_BLEND_CAPABILITIES, MATERIAL_SNIPPET_CAPABILITIES, AGENT_SCENE_CAPABILITIES, AGENT_SCENE_DEFAULT_LIMITS, RENDER_PASS_NAMES, RENDER_PASS_DEPTH_RANGE, VIDEO_ENCODERS, MAXIMUM_VIDEO_SECONDS, MAXIMUM_JOB_SIDE, MAXIMUM_JOB_PIXELS, MAXIMUM_MEMORY_MIB, BAKE_WORKER_MAXIMUM_SECONDS, PATH_TRACER_CAPABILITIES,recipeAssetNeeds, sequenceFrameIds, TEXTURE_SEQUENCE_CAPABILITIES, AGENT_ASSET_LIMITS, assertCombinedAssetBytes,audioInputArguments, createAudioLibrary, measureStreamSeconds, filmTimelineDuration, filmTimelineShotStarts, sampleFilmTimeline, normalizeReview, REVIEW_LIMITS, isPreviewHost, BRANCH_LIMITS, validateBranchName,+ createQueryOnlyCache: () => ({ walkMap: async () => ({}), dispose() {} }),chromium: { launch: async () => browser }, URL, Buffer, process, performance, clearTimeout,setTimeout: (callback, delay) => { deadlines.push(delay); return setTimeout(callback, delay); },});diff --git a/tests/agent-walkmap-recipe.test.js b/tests/agent-walkmap-recipe.test.jsnew file mode 100644index 00000000..7e869ae0--- /dev/null+++ b/tests/agent-walkmap-recipe.test.js@@ -0,0 +1,25 @@+import test from 'node:test';+import assert from 'node:assert/strict';+import './support/load-agent-scene-modules.mjs';+import { previewHarness } from './support/preview-harness.mjs';++test('walkMap works on a procedural recipe scene and marks its box as an obstacle', async () => {+ const { preview } = previewHarness();+ const sessionId = 'walkmap-recipe';+ preview.create({+ sessionId, backend: 'cpu', memoryBudgetMiB: 64,+ recipe: {+ format: '67js.scene', schemaVersion: 1,+ geometries: [{ id: 'cube', type: 'box', bevel: 0 }],+ materials: [{ id: 'paint', color: [0.4, 0.5, 0.6] }],+ nodes: [{ id: 'cube', geometry: 'cube', material: 'paint' }],+ },+ });+ const region = { sessionId, min: [-2, -2], max: [2, 2], cellSize: 1, topY: 20, clearance: 1 };+ const plain = await preview.walkMap(region);+ assert.equal(plain.grid.length, 5);+ assert.ok(plain.surfaceCells > 0);+ assert.equal(plain.skippedParts, 0);+ const guarded = await preview.walkMap({ ...region, keepOut: 0.5, streetY: -0.5 });+ assert.equal(guarded.grid[2][2], 'x', 'the cube is not walkable');+});diff --git a/tests/scene-query-obstacles.test.js b/tests/scene-query-obstacles.test.jsnew file mode 100644index 00000000..64e8e57d--- /dev/null+++ b/tests/scene-query-obstacles.test.js@@ -0,0 +1,87 @@+import test from 'node:test';+import assert from 'node:assert/strict';+import { createSceneQuery, walkableMask } from '../src/scene-query.js';++function quad(halfWidth, halfDepth = halfWidth) {+ return {+ positions: Float32Array.of(-halfWidth, 0, -halfDepth, halfWidth, 0, -halfDepth, halfWidth, 0, halfDepth, -halfWidth, 0, halfDepth),+ indices: Uint32Array.of(0, 2, 1, 0, 3, 2),+ };+}++function translation(x, y, z) {+ return Float32Array.of(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, x, y, z, 1);+}++// A 10 m street at y = 0, a flat pole top at 1.2 m over x = 2, a kerb top 0.15 m high over x = 3.5 to 4.5.+const street = [+ { id: 'street', geometry: quad(5), matrix: translation(0, 0, 0) },+ { id: 'pole', geometry: quad(0.2), matrix: translation(2, 1.2, 0) },+ { id: 'kerb', geometry: quad(0.5, 5), matrix: translation(4, 0.15, 0) },+];++function cellAt(map, x, z) {+ return map.cells.find(cell => cell[0] === x && cell[1] === z);+}++function walkableAt(map, mask, x, z) {+ const column = Math.round((x - map.min[0]) / map.cellSize);+ const row = Math.round((z - map.min[1]) / map.cellSize);+ return mask[column * map.rows + row] === 1;+}++test('obstacles marks things over 0.3 m and keeps a kerb walkable', () => {+ const query = createSceneQuery(street);+ const map = query.walkMap({ min: [-4, -4], max: [4, 4], cellSize: 0.5, obstacles: { streetY: 0 } });+ assert.equal(cellAt(map, 2, 0)[4], 1, 'the pole top is an obstacle');+ assert.equal(cellAt(map, 4, 0)[4], 0, 'a 0.15 m kerb is not');+ assert.equal(cellAt(map, 0, 0)[4], 0);+ assert.ok(Math.abs(cellAt(map, 4, 0)[2]) < 1e-6, 'ground is the lowest surface under the kerb top');+ query.dispose();+});++test('the street level defaults to the lowest sampled surface', () => {+ const query = createSceneQuery(street);+ const map = query.walkMap({ min: [-4, -4], max: [4, 4], cellSize: 0.5, obstacles: true });+ assert.equal(cellAt(map, 2, 0)[4], 1);+ query.dispose();+});++test('keepOut clears cells near an obstacle and a wall, and leaves the open street', () => {+ const query = createSceneQuery(street);+ const map = query.walkMap({ min: [-4, -4], max: [4, 4], cellSize: 0.5, obstacles: { streetY: 0 } });+ const mask = walkableMask(map, { clearance: 2, keepOut: 1 });+ assert.equal(walkableAt(map, mask, 2, 0), false);+ assert.equal(walkableAt(map, mask, 2.5, 0), false);+ assert.equal(walkableAt(map, mask, 1.5, 0), false);+ assert.equal(walkableAt(map, mask, 0, 0), true);+ assert.equal(walkableAt(map, mask, 4, 0), true, 'the kerb stays walkable');+ assert.equal(walkableAt(map, mask, 0, 3.5), true);+ const withoutKeepOut = walkableMask(map, { clearance: 2 });+ assert.equal(walkableAt(map, withoutKeepOut, 2.5, 0), true);+ assert.equal(walkableAt(map, withoutKeepOut, 2, 0), false, 'the obstacle cell itself is never open');+ query.dispose();+});++test('a closing step fills a one-cell seam before keepOut is applied', () => {+ const columns = 9;+ const rows = 9;+ const cells = [];+ for (let column = 0; column < columns; column++) {+ for (let row = 0; row < rows; row++) {+ if (column === 4 && row === 4) continue;+ cells.push([column * 0.25, row * 0.25, 0, 99, 0]);+ }+ }+ const map = { cellSize: 0.25, min: [0, 0], columns, rows, cells };+ assert.equal(walkableMask(map, { clearance: 2, keepOut: 0.1 })[4 * rows + 4], 1);+ cells.find(cell => cell[0] === 1 && cell[1] === 0.5)[4] = 1;+ const withObstacle = walkableMask({ ...map, cells }, { clearance: 2, keepOut: 0.1 });+ assert.equal(withObstacle[4 * rows + 2], 0, 'an obstacle is cut back out after the closing step');+});++test('walkMap rejects unknown obstacles options', () => {+ const query = createSceneQuery(street);+ assert.throws(() => query.walkMap({ min: [0, 0], max: [1, 1], obstacles: { colour: 1 } }), /Unsupported walkMap obstacles option/);+ query.dispose();+});diff --git a/tests/support/preview-harness.mjs b/tests/support/preview-harness.mjsindex a42b131a..4629dcb1 100644--- a/tests/support/preview-harness.mjs+++ b/tests/support/preview-harness.mjs@@ -13,7 +13,7 @@ import { assetCopyKey, recipeAssetNeeds } from '../../src/agent-scene-assets.js'import { BRANCH_LIMITS, createBranchStore, printableLabel } from '../../src/agent-branches.js';import { sessionProblem } from '../../src/agent-errors.js';import { agentAssetDecodeOptions, withCatalogLimitAdvice } from '../../src/agent-asset-limits.js';-import { sceneQueryFor, summarizeWalkMap } from '../../scripts/agent-walkmap.js';+import { sceneQueryFor, summarizeWalkMap, walkOptionsFor } from '../../scripts/agent-walkmap.js';// Runs the preview page's adapter code in a VM with a fault-injected renderer, the way the MCP preview runs it in a browser.const source = (await readFile(new URL('../../scripts/agent-preview-browser.js', import.meta.url), 'utf8')).replace(/^import .+;\r?$/gm, '');@@ -78,7 +78,7 @@ export function previewHarness() {// The harness loads Manifold from node_modules directly, so the preview's served-file loader is ignored.setManifoldModuleLoader: () => {},needsPhysics, loadPhysicsEngine, physicsEngineLoaded, setPhysicsModuleLoader: () => {},- sceneQueryFor, summarizeWalkMap, parseGltf, hasPatternTextures, Uint8Array, atob, sessionProblem, assetCopyKey, recipeAssetNeeds, agentAssetDecodeOptions, withCatalogLimitAdvice,+ sceneQueryFor, summarizeWalkMap, walkOptionsFor, parseGltf, hasPatternTextures, Uint8Array, atob, sessionProblem, assetCopyKey, recipeAssetNeeds, agentAssetDecodeOptions, withCatalogLimitAdvice,applyProjection, mat4, resolveAgentShadow, agentEnvironmentMap, BRANCH_LIMITS,// Line art needs a real renderer with render passes, so the fault-injected one gets a no-op install.agentSceneModule: name => (name === 'lineArt' ? { installLineArt: renderer => renderer } : name === 'userPass' ? { ...agentSceneModule(name), installUserPasses: renderer => renderer } : agentSceneModule(name)), agentSceneModuleLoaded, createBranchStore, printableLabel,