Skip to content

3D engine that AI agents drive

Bound terrain grids and validate raster sampling inputs (#2348 #2349 #2350)

Nguyen Xuan An53f49f12f39c
diff --git a/changes/2348.md b/changes/2348.md
new file mode 100644
index 00000000..fd09e003
--- /dev/null
+++ b/changes/2348.md
@@ -0,0 +1 @@
+- `createTerrain` refuses more than 64 chunks or 4096 cells per side, `sampleRasterGrid` refuses a raster whose values, box or sampling options cannot give a mean, and `createHeightfieldGeometry` gives finite normals for a one-column or one-row grid, all with errors that name the field (#2348, #2349, #2350)
diff --git a/changes/2348.size.md b/changes/2348.size.md
new file mode 100644
index 00000000..1b0755e8
--- /dev/null
+++ b/changes/2348.size.md
@@ -0,0 +1,2 @@
+- entry:heightfield: input checks that stop silent NaN, zero or wrongly weighted output from a bad raster, box or sample count (+291 bytes gzip)
+- scene:agent-scene+lazy: chunk and grid bounds in createTerrain stop an out-of-memory crash on a huge grid (+90 bytes gzip)
diff --git a/docs/terrain.md b/docs/terrain.md
index 6d8a0007..d121708b 100644
--- a/docs/terrain.md
+++ b/docs/terrain.md
@@ -78,7 +78,7 @@ Memory: three `TEXTURE_2D_ARRAY`s on units 11 to 13 (sRGB colour, normal, roughn
`createTerrain({ size = 512, resolution = 32, chunks = 8, levels = 4, height, seed = 1, material, lodDistance, eye })` returns `{ parts, heightAt, normalAt, bounds, update, triangleCount, chunkSize, chunkLevels }`.
-- The ground spans x and z from `-size / 2` to `size / 2`. `chunks` per side, each with `resolution` cells at level 0 (so `resolution` must divide by `2 ** (levels - 1)`). Level `n` uses `resolution / 2 ** n` cells.
+- The ground spans x and z from `-size / 2` to `size / 2`. `chunks` per side, each with `resolution` cells at level 0 (so `resolution` must divide by `2 ** (levels - 1)`). Level `n` uses `resolution / 2 ** n` cells. `chunks` is at most 64 and `chunks * resolution` at most 4096 cells per side; larger values throw a RangeError before any memory is allocated.
- `height` is a function `(x, z) => metres`, a square array or typed array (`Float32Array`, `Float64Array`) of metres stretched over the ground (`heightmapFromImageData(imageData, amplitude)` builds one from an image), or noise options: `amplitude` (hills, 14), `mountainAmplitude` (46), `featureSize` (160 m), `octaves`, `gain`, `lacunarity`, `warp` (domain warp in metres), `baseHeight` and `mountainMask(x, z)` (0 to 1, where ridged mountains replace hills). Hills use slope-damped octaves and mountains use ridged multifractal noise, which gives smooth flanks, sharp crests and carved valleys. The same `seed` always gives the same ground.
- `heightAt(x, z)` walks the same triangles as the level 0 mesh, so it matches the rendered surface there (coarser levels differ by their simplification). Coordinates outside the ground clamp to its edge. `normalAt` interpolates smooth grid normals.
- `update(eye)` picks a level per chunk from its distance (`lodDistance`, a positive finite number of metres, default 1.6 chunk sizes, doubling per level) and returns the parts whose geometry changed. Edges shared with a coarser neighbour are snapped onto the neighbour's edge, so there are no cracks and no skirts.
diff --git a/src/heightfield.js b/src/heightfield.js
index 72d4fd15..fd1c0912 100644
--- a/src/heightfield.js
+++ b/src/heightfield.js
@@ -51,6 +51,17 @@ function axisTaps({ count, coordinateAt, boxLow, boxHigh, pixels, reversed, cell
return { firstPixel, tapCount, tapOffset, weights };
}
+function checkSamplingInputs({ values, width, height, box }, options) {
+ const problems = [
+ [values?.length === width * height, `raster.values must hold width * height = ${width * height} values`],
+ [box.x_max > box.x_min && box.y_max > box.y_min && Number.isFinite(box.x_max - box.x_min + box.y_max - box.y_min), 'raster.box needs finite x_min below x_max and y_min below y_max'],
+ ...['columns', 'rows', 'samplesPerSide'].map(name => [Number.isInteger(options[name]) && options[name] >= 1, `${name} must be a whole number of at least 1, got ${options[name]}`]),
+ [Number.isFinite(options.cellSize) && options.cellSize >= 0, `cellSize must be a finite number of 0 or more, got ${options.cellSize}`],
+ ];
+ const failed = problems.find(([passes]) => !passes);
+ if (failed) throw new RangeError(`${failed[1]}.`);
+}
+
/**
* The mean of a raster over a square cell centred on every vertex of a regular grid, from a samplesPerSide by
* samplesPerSide pattern of bilinear samples; `cellSize` 0 with one sample reads the raster at the vertex.
@@ -60,6 +71,7 @@ function axisTaps({ count, coordinateAt, boxLow, boxHigh, pixels, reversed, cell
export function sampleRasterGrid(raster, { columns, rows, eastAt, northAt, cellSize = 0, samplesPerSide = 1, scale = 1 }) {
const { values, width, height, box } = raster;
if (width < 2 || height < 2) throw new RangeError('A raster needs at least 2 by 2 pixels.');
+ checkSamplingInputs(raster, { columns, rows, cellSize, samplesPerSide });
const east = axisTaps({ count: columns, coordinateAt: eastAt, boxLow: box.x_min, boxHigh: box.x_max, pixels: width, reversed: false, cellSize, samplesPerSide });
const north = axisTaps({ count: rows, coordinateAt: northAt, boxLow: box.y_min, boxHigh: box.y_max, pixels: height, reversed: true, cellSize, samplesPerSide });
let firstRow = height;
@@ -93,6 +105,11 @@ export function sampleRasterGrid(raster, { columns, rows, eastAt, northAt, cellS
return output;
}
+// A grid one vertex wide has no span along that axis: it has no slope there either, not NaN.
+function slopeAcross(heightDifference, span) {
+ return span === 0 ? 0 : heightDifference / span;
+}
+
function gridNormals(positions, columns, rows) {
const normals = new Float32Array(positions.length);
for (let row = 0; row < rows; row += 1) {
@@ -104,8 +121,8 @@ function gridNormals(positions, columns, rows) {
const right = row * columns + Math.min(columns - 1, column + 1);
const up = upRow + column;
const down = downRow + column;
- const normalX = -(positions[right * 3 + 1] - positions[left * 3 + 1]) / (positions[right * 3] - positions[left * 3]);
- const normalZ = -(positions[down * 3 + 1] - positions[up * 3 + 1]) / (positions[down * 3 + 2] - positions[up * 3 + 2]);
+ const normalX = -slopeAcross(positions[right * 3 + 1] - positions[left * 3 + 1], positions[right * 3] - positions[left * 3]);
+ const normalZ = -slopeAcross(positions[down * 3 + 1] - positions[up * 3 + 1], positions[down * 3 + 2] - positions[up * 3 + 2]);
const length = Math.hypot(normalX, 1, normalZ);
normals[vertex * 3] = normalX / length;
normals[vertex * 3 + 1] = 1 / length;
diff --git a/src/terrain.js b/src/terrain.js
index 31136523..69e95ccd 100644
--- a/src/terrain.js
+++ b/src/terrain.js
@@ -155,16 +155,23 @@ function resolveHeightFunction(height, size, seed) {
return createNoiseHeight(height ?? {}, seed);
}
+/** Largest chunk count per side and largest finest-grid cell count per side: 4096 cells is a 17 million sample grid. */
+export const TERRAIN_GRID_LIMITS = Object.freeze({ chunks: 64, cellsPerSide: 4096 });
+
function validateOptions({ size, resolution, chunks, levels, mirrorLevels, lodDistance }) {
if (lodDistance !== undefined && !(lodDistance > 0 && Number.isFinite(lodDistance))) {
throw new RangeError(`lodDistance must be a positive number of metres, such as ${size / 8}; got ${lodDistance}.`);
}
if (!(size > 0) || !Number.isFinite(size)) throw new RangeError('size must be a positive number of metres.');
if (!Number.isInteger(chunks) || chunks < 1) throw new RangeError('chunks must be a positive integer.');
+ if (chunks > TERRAIN_GRID_LIMITS.chunks) throw new RangeError(`chunks must be at most ${TERRAIN_GRID_LIMITS.chunks} per side; got ${chunks}.`);
if (!Number.isInteger(levels) || levels < 1) throw new RangeError('levels must be a positive integer.');
if (!Number.isInteger(resolution) || resolution < 1 || resolution % (2 ** (levels - 1)) !== 0) {
throw new RangeError(`resolution must be a positive integer divisible by 2^(levels - 1) = ${2 ** (levels - 1)}.`);
}
+ if (chunks * resolution > TERRAIN_GRID_LIMITS.cellsPerSide) {
+ throw new RangeError(`chunks * resolution must be at most ${TERRAIN_GRID_LIMITS.cellsPerSide} cells per side; got ${chunks} * ${resolution}. Lower resolution or chunks.`);
+ }
if (!Number.isInteger(mirrorLevels) || mirrorLevels < 0 || resolution % (2 ** (levels - 1 + mirrorLevels)) !== 0) {
throw new RangeError('mirrorLevels must be a whole number of extra halvings that the resolution divides by (2^(levels - 1 + mirrorLevels)).');
}
diff --git a/tests/terrain-input-bounds.test.js b/tests/terrain-input-bounds.test.js
new file mode 100644
index 00000000..d6b5ee8a
--- /dev/null
+++ b/tests/terrain-input-bounds.test.js
@@ -0,0 +1,68 @@
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import { createTerrain } from '../src/terrain.js';
+import { createHeightfieldGeometry, sampleRasterGrid } from '../src/heightfield.js';
+
+const FLAT = () => 0;
+
+test('createTerrain refuses a grid with too many cells per side before allocating it (#2348)', () => {
+ assert.throws(
+ () => createTerrain({ size: 100, resolution: 1_000_000, chunks: 1, levels: 1, height: FLAT }),
+ /resolution.*chunks|cells per side/i,
+ );
+ assert.throws(
+ () => createTerrain({ size: 100, resolution: 1024, chunks: 8, levels: 1, height: FLAT }),
+ /cells per side/,
+ );
+});
+
+test('createTerrain refuses a chunk count that would exhaust memory (#2348)', () => {
+ assert.throws(() => createTerrain({ size: 100, resolution: 1, chunks: 3000, levels: 1, height: FLAT }), /chunks must be at most/);
+});
+
+test('createTerrain still builds a grid at the bound (#2348)', () => {
+ const terrain = createTerrain({ size: 100, resolution: 16, chunks: 4, levels: 1, height: FLAT });
+ assert.equal(terrain.parts.length, 16);
+});
+
+function raster(overrides = {}) {
+ return { values: new Float32Array(16).fill(1), width: 4, height: 4, box: { x_min: 0, x_max: 4, y_min: 0, y_max: 4 }, ...overrides };
+}
+
+function sampleGrid(rasterValue, options = {}) {
+ return sampleRasterGrid(rasterValue, { columns: 2, rows: 2, eastAt: column => 1 + column, northAt: row => 1 + row, ...options });
+}
+
+test('sampleRasterGrid names the field when values do not match width * height (#2349)', () => {
+ assert.throws(() => sampleGrid(raster({ values: new Float32Array(4) })), /values.*16/);
+});
+
+test('sampleRasterGrid refuses a box with no extent or a non-finite edge (#2349)', () => {
+ assert.throws(() => sampleGrid(raster({ box: { x_min: 1, x_max: 1, y_min: 0, y_max: 4 } })), /box/);
+ assert.throws(() => sampleGrid(raster({ box: { x_min: 0, x_max: Number.NaN, y_min: 0, y_max: 4 } })), /box/);
+});
+
+test('sampleRasterGrid refuses sampling options that cannot give a mean (#2349)', () => {
+ assert.throws(() => sampleGrid(raster(), { cellSize: 1, samplesPerSide: 0 }), /samplesPerSide/);
+ assert.throws(() => sampleGrid(raster(), { cellSize: 1, samplesPerSide: 1.5 }), /samplesPerSide/);
+ assert.throws(() => sampleGrid(raster(), { rows: 0 }), /rows/);
+ assert.throws(() => sampleGrid(raster(), { columns: 2.5 }), /columns/);
+ assert.throws(() => sampleGrid(raster(), { cellSize: -1, samplesPerSide: 2 }), /cellSize/);
+});
+
+test('sampleRasterGrid keeps a flat raster flat for whole sample counts (#2349)', () => {
+ const output = sampleGrid(raster(), { cellSize: 1, samplesPerSide: 3 });
+ for (const value of output) assert.ok(Math.abs(value - 1) < 1e-12);
+});
+
+test('createHeightfieldGeometry gives unit finite normals for one column or one row (#2350)', () => {
+ const box = { x_min: 0, x_max: 1, y_min: 0, y_max: 1 };
+ const column = createHeightfieldGeometry({ columns: 1, rows: 3, eastAt: () => 0, northAt: row => row, heights: [0, 1, 0], uvBox: box });
+ const strip = createHeightfieldGeometry({ columns: 3, rows: 1, eastAt: columnIndex => columnIndex, northAt: () => 0, heights: [0, 1, 0], uvBox: box });
+ for (const geometry of [column, strip]) {
+ for (let vertex = 0; vertex < 3; vertex += 1) {
+ const length = Math.hypot(geometry.normals[vertex * 3], geometry.normals[vertex * 3 + 1], geometry.normals[vertex * 3 + 2]);
+ assert.ok(Math.abs(length - 1) < 1e-6, `normal ${vertex} has length ${length}`);
+ }
+ }
+});