Skip to content

3D engine that AI agents drive

Refuse terrain holes that cover the ground and flag holes that remove no cell (#2071)

Nguyen Xuan Anc9288ea00819
diff --git a/.github/workflows/cook-addon.yml b/.github/workflows/cook-addon.yml
index 5f31dc44..e9da9ae0 100644
--- a/.github/workflows/cook-addon.yml
+++ b/.github/workflows/cook-addon.yml
@@ -65,6 +65,7 @@ on:
- 'src/agent-clip-layers.js'
- 'src/agent-cloth.js'
- 'src/agent-crowd.js'
+ - 'src/agent-diagnostics.js'
- 'src/agent-drive-schema.js'
- 'src/agent-drive.js'
- 'src/agent-explosion.js'
@@ -321,6 +322,7 @@ on:
- 'src/subsurface-shader.js'
- 'src/sun-bounce.js'
- 'src/surface-nets.js'
+ - 'src/terrain-hole-cells.js'
- 'src/terrain-sky.js'
- 'src/terrain.js'
- 'src/text-geometry.js'
diff --git a/changes/2071.md b/changes/2071.md
new file mode 100644
index 00000000..62a87c0e
--- /dev/null
+++ b/changes/2071.md
@@ -0,0 +1 @@
+- A terrain whose holes remove every cell is refused at `scene_create` with the fix named, a hole that removes no cell returns a `terrain-hole-removes-no-cell` warning with the cell size and the smallest working radius, and `scene_export_glb` names the node whose mesh has no triangles (#2071).
diff --git a/changes/2071.size.md b/changes/2071.size.md
new file mode 100644
index 00000000..f3a5d5d1
--- /dev/null
+++ b/changes/2071.size.md
@@ -0,0 +1,3 @@
+- scene:agent-scene: three agent-facing messages (a hole cover refusal, a no-cell hole warning with the smallest radius, a named empty GLB part) replace an error that named no node, cause or fix.
+- scene:agent-scene+lazy: the same messages plus the hole cell math, loaded only with a terrain recipe.
+- goal:agent-scene: the growth is 333 bytes gzip for the same three messages.
diff --git a/docs/terrain.md b/docs/terrain.md
index c6f0f6ab..6d8a0007 100644
--- a/docs/terrain.md
+++ b/docs/terrain.md
@@ -88,7 +88,7 @@ Memory: three `TEXTURE_2D_ARRAY`s on units 11 to 13 (sRGB colour, normal, roughn
`createTerrain({ holes: [{ center: [x, z], radius }] })` (up to 64 circles, radius in metres) leaves no surface where a cell centre falls inside a circle, so a cave mouth or a shaft opens through the ground. `terrain.isHole(x, z)` tells whether a point is inside one. `heightAt` and `normalAt` ignore holes and still return the surface that would be there, so check `isHole` before standing something on it. A coarser level of detail cuts a coarser hole (its cells are bigger), so give a hole a radius of a few finest cells at least. A hole that covers a whole chunk gives that chunk empty geometry. Without `holes` the meshes are byte-identical to before (a test keeps a digest).
-In a recipe, the same ground is the `terrain` geometry (`size`, `resolution`, `seed`, `amplitude`, `holes`): see [agent-scene](agent-scene.md).
+In a recipe, the same ground is the `terrain` geometry (`size`, `resolution`, `seed`, `amplitude`, `holes`): see [agent-scene](agent-scene.md). There, holes that remove every cell are refused with an error on `geometries[i].holes` (lower a radius or move a center), and a hole that removes no cell, because it does not reach a cell centre, returns a `terrain-hole-removes-no-cell` warning with the cell size (`size / resolution`) and the smallest radius that removes one. `scene_export_glb` names the node whose mesh has no triangles.
## Terrain near water
diff --git a/src/agent-diagnostics.js b/src/agent-diagnostics.js
index ca427c1e..e57e48cb 100644
--- a/src/agent-diagnostics.js
+++ b/src/agent-diagnostics.js
@@ -4,13 +4,15 @@
* kind, a severity, a target (the material, node or asset it concerns), a message and a fix that names the next action.
* Reads of an inspected scene include them only when there is something to say, to keep default results small.
*/
+import { agentSceneModule } from './agent-scene-modules.js';
+
const PLAIN_SURFACE_TAGS = new Set(['surface', 'gltf']);
const LAYER_FIELDS = ['clearcoat', 'sheenColor', 'specular', 'specularColor', 'anisotropy', 'iridescence'];
// The pass that draws transmission is a separate shader without these layers.
const FIELDS_IGNORED_BY_TRANSMISSION = ['anisotropy', 'iridescence'];
const TRANSMISSION_DETAIL_FIELDS = ['thickness', 'attenuationColor', 'attenuationDistance'];
-function diagnostic(kind, severity, target, message, fix) {
+export function diagnostic(kind, severity, target, message, fix) {
return { kind, severity, target, message, fix };
}
@@ -72,6 +74,7 @@ export function recipeDiagnostics(recipe) {
`Geometry ${geometry.id} is used by no node, so nothing draws it.`,
'Add a node that uses it with scene_apply add-node, or remove it with remove-geometry.'));
}
+ problems.push(...recipe.geometries.filter(geometry => geometry.type === 'terrain').flatMap(geometry => agentSceneModule('terrain').terrainHoleDiagnostics(geometry)));
problems.push(...portalProblems(recipe.environment?.areaLights ?? []));
return problems;
}
diff --git a/src/agent-terrain.js b/src/agent-terrain.js
index 0d6f75fc..59c30bed 100644
--- a/src/agent-terrain.js
+++ b/src/agent-terrain.js
@@ -3,13 +3,15 @@
import './world-material-shader.js';
import { createTerrain } from './terrain.js';
import { invalidField } from './field-error.js';
+import { diagnostic } from './agent-diagnostics.js';
+import { TERRAIN_DEFAULT_SIZE, TERRAIN_DEFAULT_RESOLUTION, holesCoverWholeGround, holesRemovingNoCell } from './terrain-hole-cells.js';
export const TERRAIN_LIMITS = Object.freeze({
size: [1, 2000],
resolution: [2, 256],
amplitude: [0, 200],
- defaultSize: 40,
- defaultResolution: 64,
+ defaultSize: TERRAIN_DEFAULT_SIZE,
+ defaultResolution: TERRAIN_DEFAULT_RESOLUTION,
defaultAmplitude: 1,
maximumHoles: 16,
seed: [0, 0x7fffffff],
@@ -42,16 +44,23 @@ function terrainSeed(value) {
/** Vertex count of a terrain record, checked against the recipe limits before any ground is built. */
export function terrainVertexEstimate(value) {
const resolution = integerWithin(value.resolution, TERRAIN_LIMITS.defaultResolution, TERRAIN_LIMITS.resolution, 'resolution');
- numberWithin(value.size, TERRAIN_LIMITS.defaultSize, TERRAIN_LIMITS.size, 'size');
+ const size = numberWithin(value.size, TERRAIN_LIMITS.defaultSize, TERRAIN_LIMITS.size, 'size');
numberWithin(value.amplitude, TERRAIN_LIMITS.defaultAmplitude, TERRAIN_LIMITS.amplitude, 'amplitude');
terrainSeed(value.seed);
if (value.holes !== undefined && (!Array.isArray(value.holes) || value.holes.length > TERRAIN_LIMITS.maximumHoles)) {
throw invalidField('terrain.holes', value.holes, `a list of at most ${TERRAIN_LIMITS.maximumHoles} circles, such as [{ "center": [0, 0], "radius": 2 }]`);
}
value.holes?.forEach(checkHole);
+ checkHolesLeaveGround(value.holes, size, resolution);
return (resolution + 1) * (resolution + 1);
}
+/** Refuses holes that remove every cell: the terrain would have no surface and could not be exported. */
+function checkHolesLeaveGround(holes, size, resolution) {
+ if (!holesCoverWholeGround(holes, size, resolution)) return;
+ throw invalidField('holes', holes, 'holes that leave some ground; these cover the whole terrain, so no surface would remain. Lower a radius or move a center');
+}
+
function checkHole(hole, index) {
const center = hole?.center;
const validCenter = Array.isArray(center) && center.length === 2 && center.every(Number.isFinite);
@@ -89,3 +98,11 @@ export function generateTerrainGeometry(value, maxVertices) {
if (vertices > maxVertices) throw invalidField('terrain.resolution', value.resolution ?? TERRAIN_LIMITS.defaultResolution, `a resolution whose ${vertices} vertices fit maxVertices ${maxVertices}; lower it`);
return createRecipeTerrain(value).parts[0].geometry;
}
+
+/** Warnings for holes of a terrain record that remove no ground cell, so the terrain looks as if it had no hole. */
+export function terrainHoleDiagnostics(geometry) {
+ return holesRemovingNoCell(geometry).map(({ index, cellSize, smallestRadius }) => diagnostic('terrain-hole-removes-no-cell', 'warning',
+ `${geometry.id}.holes[${index}]`,
+ `Hole ${index} of terrain ${geometry.id} removes no ground cell, so it changes nothing: cells are ${cellSize} m wide and a hole removes a cell only when it reaches the cell's centre.`,
+ `Raise radius above ${smallestRadius} (the smallest that removes a cell here), move center onto a cell centre, or raise the terrain resolution.`));
+}
diff --git a/src/export.js b/src/export.js
index 978dcaf0..756d5fa4 100644
--- a/src/export.js
+++ b/src/export.js
@@ -48,7 +48,7 @@ function validateColor(values, label) {
for (const value of values) validateFactor(value, label);
}
-function validateGeometry(geometry) {
+function validateGeometry(geometry, partName) {
const count = geometry?.positions?.length;
if (!Number.isSafeInteger(count) || count < 3 || count % 3 !== 0) {
throw new TypeError('GLB positions require a nonempty array of XYZ vertices.');
@@ -62,7 +62,10 @@ function validateGeometry(geometry) {
if (geometry.colors !== undefined) validateFloatChannel(geometry.colors, count, 'GLB colors', true);
if (geometry.uvs !== undefined) validateFloatChannel(geometry.uvs, count / 3 * 2, 'GLB UVs');
if (geometry.lightUvs !== undefined) validateFloatChannel(geometry.lightUvs, count / 3 * 2, 'GLB lightUvs');
- if (!(geometry.indices instanceof Uint32Array) || geometry.indices.length === 0 || geometry.indices.length % 3 !== 0) {
+ if (geometry.indices instanceof Uint32Array && geometry.indices.length === 0) {
+ throw new RangeError(`GLB part ${partName} has no triangles. Terrain holes may cover the whole ground: lower a radius or move a center.`);
+ }
+ if (!(geometry.indices instanceof Uint32Array) || geometry.indices.length % 3 !== 0) {
throw new TypeError('GLB indices require a nonempty Uint32Array of triangles.');
}
for (const index of geometry.indices) {
@@ -258,7 +261,7 @@ export function exportGlb(parts, options = {}) {
const morphMetadata = new Map();
for (const part of parts) {
if (!validatedGeometries.has(part?.geometry)) {
- validateGeometry(part?.geometry);
+ validateGeometry(part?.geometry, part?.name);
validatedGeometries.add(part.geometry);
}
validatePart(part);
diff --git a/src/terrain-hole-cells.js b/src/terrain-hole-cells.js
new file mode 100644
index 00000000..36fac633
--- /dev/null
+++ b/src/terrain-hole-cells.js
@@ -0,0 +1,52 @@
+// Which ground cells a terrain's holes remove. A cell goes when its centre lies strictly inside a hole circle,
+// the same rule the terrain mesh builder uses, so these answers match the mesh without building it.
+export const TERRAIN_DEFAULT_SIZE = 40;
+export const TERRAIN_DEFAULT_RESOLUTION = 64;
+
+function cellCentre(index, cellSize, halfSize) {
+ return -halfSize + (index + 0.5) * cellSize;
+}
+
+function insideAnyHole(holes, centreX, centreZ) {
+ return holes.some(hole => Math.hypot(centreX - hole.center[0], centreZ - hole.center[1]) < hole.radius);
+}
+
+/** True when the holes remove every cell of a size by size ground cut into resolution by resolution cells. */
+export function holesCoverWholeGround(holes, size, resolution) {
+ if (!Array.isArray(holes) || holes.length === 0) return false;
+ const cellSize = size / resolution;
+ for (let row = 0; row < resolution; row++) {
+ for (let column = 0; column < resolution; column++) {
+ if (!insideAnyHole(holes, cellCentre(column, cellSize, size / 2), cellCentre(row, cellSize, size / 2))) return false;
+ }
+ }
+ return true;
+}
+
+function nearestCellIndex(coordinate, cellSize, halfSize, resolution) {
+ const index = Math.round((coordinate + halfSize) / cellSize - 0.5);
+ return Math.min(Math.max(index, 0), resolution - 1);
+}
+
+/** Distance from a hole's centre to the nearest cell centre: the hole removes a cell only with a radius above it. */
+export function distanceToNearestCellCentre(hole, size, resolution) {
+ const cellSize = size / resolution;
+ const halfSize = size / 2;
+ const nearestX = cellCentre(nearestCellIndex(hole.center[0], cellSize, halfSize, resolution), cellSize, halfSize);
+ const nearestZ = cellCentre(nearestCellIndex(hole.center[1], cellSize, halfSize, resolution), cellSize, halfSize);
+ return Math.hypot(hole.center[0] - nearestX, hole.center[1] - nearestZ);
+}
+
+/** Holes of a terrain record that remove no cell, each with the cell size and the smallest radius (to 3 decimals) that would remove one. */
+export function holesRemovingNoCell(value) {
+ const size = value.size ?? TERRAIN_DEFAULT_SIZE;
+ const resolution = value.resolution ?? TERRAIN_DEFAULT_RESOLUTION;
+ const cellSize = size / resolution;
+ const missing = [];
+ (value.holes ?? []).forEach((hole, index) => {
+ const nearest = distanceToNearestCellCentre(hole, size, resolution);
+ if (hole.radius > nearest) return;
+ missing.push({ index, cellSize, smallestRadius: Math.floor(nearest * 1000 + 1) / 1000 });
+ });
+ return missing;
+}
diff --git a/tests/terrain-hole-errors.test.js b/tests/terrain-hole-errors.test.js
new file mode 100644
index 00000000..058b2d70
--- /dev/null
+++ b/tests/terrain-hole-errors.test.js
@@ -0,0 +1,57 @@
+import './support/load-agent-scene-modules.mjs';
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import { createAgentScene } from '../src/agent-scene.js';
+import { recipeDiagnostics } from '../src/agent-diagnostics.js';
+import { exportGlb } from '../src/export.js';
+import { holesRemovingNoCell } from '../src/terrain-hole-cells.js';
+import { box } from '../src/geometry.js';
+
+function terrainRecipe(terrain) {
+ return {
+ format: 'crucible.scene', schemaVersion: 1,
+ geometries: [{ id: 'slab', type: 'box' }, { id: 'ground', type: 'terrain', ...terrain }],
+ materials: [{ id: 'stone', color: [0.5, 0.5, 0.5] }],
+ nodes: [{ id: 'land', geometry: 'ground', material: 'stone' }],
+ };
+}
+
+function holeDiagnostics(terrain) {
+ const recipe = createAgentScene(terrainRecipe(terrain)).exportRecipe();
+ return recipeDiagnostics(recipe).filter(entry => entry.kind === 'terrain-hole-removes-no-cell');
+}
+
+test('holes that remove every cell are refused with the geometry, the cause and the fix', () => {
+ assert.throws(
+ () => createAgentScene(terrainRecipe({ holes: [{ center: [0, 0], radius: 100 }] })),
+ error => /^geometries\[1\]\.holes: got \[.*cover the whole terrain.*Lower a radius or move a center/.test(error.message),
+ );
+});
+
+test('several holes that together cover the ground are refused, one that leaves a cell is accepted', () => {
+ const halves = [{ center: [-10, 0], radius: 25 }, { center: [10, 0], radius: 25 }];
+ assert.throws(() => createAgentScene(terrainRecipe({ size: 40, resolution: 8, holes: halves })), /geometries\[1\]\.holes: got \[/);
+ assert.doesNotThrow(() => createAgentScene(terrainRecipe({ size: 40, resolution: 8, holes: [{ center: [0, 0], radius: 24 }] })));
+});
+
+test('a hole smaller than a cell returns a warning with the cell size and the smallest radius that removes one', () => {
+ const [problem] = holeDiagnostics({ holes: [{ center: [0, 0], radius: 0.01 }] });
+ assert.equal(problem.severity, 'warning');
+ assert.equal(problem.target, 'ground.holes[0]');
+ assert.match(problem.message, /cells are 0\.625 m wide/);
+ // Cell centres sit half a cell from the origin on both axes: 0.3125 * sqrt(2).
+ assert.match(problem.fix, /above 0\.442 /);
+});
+
+test('the smallest radius the diagnostic names removes a cell, and a hole that removes one is not flagged', () => {
+ const terrain = { size: 40, resolution: 64, holes: [{ center: [3.3, -7.1], radius: 0.01 }] };
+ const [{ smallestRadius }] = holesRemovingNoCell(terrain);
+ assert.deepEqual(holesRemovingNoCell({ ...terrain, holes: [{ center: [3.3, -7.1], radius: smallestRadius }] }), []);
+ assert.deepEqual(holeDiagnostics({ holes: [{ center: [0, 0], radius: 2 }] }), []);
+});
+
+test('the GLB export names the part whose mesh has no triangles', () => {
+ const geometry = { ...box(), indices: new Uint32Array(0) };
+ const part = { name: 'emptyGround', geometry, material: { color: [1, 1, 1] } };
+ assert.throws(() => exportGlb([part]), /GLB part emptyGround has no triangles.*holes may cover the whole ground/);
+});