Skip to content

3D engine that AI agents drive

Stop walkableMask and createNavmesh hanging on a huge radius (#2383, #2384)

Nguyen Xuan An1efc71ea6aae
diff --git a/changes/2383.md b/changes/2383.md
new file mode 100644
index 00000000..656b4972
--- /dev/null
+++ b/changes/2383.md
@@ -0,0 +1 @@
+- Fix `walkableMask` hanging on an infinite or huge `keepOut` (and refuse NaN or negative values), `createNavmesh` hanging on an agent radius far above the cell size, and accept only whole-number navmesh indices.
diff --git a/docs/scene-query.md b/docs/scene-query.md
index 554a3e60..ac39bd92 100644
--- a/docs/scene-query.md
+++ b/docs/scene-query.md
@@ -82,7 +82,7 @@ Pass `keepOut` (metres) and bollards, lamp posts, planters and tables stop being
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`).
+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`). `keepOut` must be a finite number of 0 or more; a value past the map clears every cell next to a closed one.
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.
diff --git a/src/navmesh.js b/src/navmesh.js
index 05db74e3..e6982c2f 100644
--- a/src/navmesh.js
+++ b/src/navmesh.js
@@ -50,8 +50,8 @@ function assertUsableGeometry(positions, indices, bounds) {
}
const vertexCount = Math.floor(positions.length / 3);
for (let offset = 0; offset < indices.length; offset++) {
- if (!(indices[offset] >= 0 && indices[offset] < vertexCount)) {
- throw new RangeError(`navmesh index ${offset} is ${indices[offset]}; use 0 to ${vertexCount - 1}.`);
+ if (!(Number.isInteger(indices[offset]) && indices[offset] >= 0 && indices[offset] < vertexCount)) {
+ throw new RangeError(`navmesh index ${offset} is ${indices[offset]}; use a whole number from 0 to ${vertexCount - 1}.`);
}
}
}
@@ -394,7 +394,8 @@ function blockFootprint(obstacle, bounds, size, columns, rows, blocked) {
// 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);
+ // A reach past the grid touches nothing more, so a huge radius over a small cell size stays bounded by the grid.
+ const reach = Math.min(Math.max(radiusInCells, 1), Math.max(columns, rows));
const limit = Math.max(radiusInCellUnits, 0.75);
for (let row = 0; row < rows; row++) {
for (let column = 0; column < columns; column++) {
diff --git a/src/scene-query.js b/src/scene-query.js
index f7e07c64..cb85cdac 100644
--- a/src/scene-query.js
+++ b/src/scene-query.js
@@ -327,6 +327,9 @@ export function createSceneQuery(parts, options = {}) {
* is not open (an obstacle, a wall, a gap) stops being walkable.
*/
export function walkableMask(map, { clearance = 2, groundRange, keepOut = 0 } = {}) {
+ if (!Number.isFinite(keepOut) || keepOut < 0) {
+ throw new RangeError(`walkableMask keepOut must be a finite number of metres, 0 or more, got ${keepOut}. Pass 0 to skip the keep-out step.`);
+ }
const { columns, rows, cellSize, min } = map;
const count = columns * rows;
const open = new Uint8Array(count);
@@ -368,7 +371,8 @@ function spread(grid, columns, rows, value) {
// 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);
+ // Nothing beyond the grid's own size can reach another cell, so a huge radius costs no more than the grid.
+ const reach = Math.min(Math.ceil(radius), Math.max(columns, rows));
const offsets = [];
for (let dx = -reach; dx <= reach; dx++) {
for (let dz = -reach; dz <= reach; dz++) {
diff --git a/tests/navmesh.test.js b/tests/navmesh.test.js
index 00a748bc..44618d34 100644
--- a/tests/navmesh.test.js
+++ b/tests/navmesh.test.js
@@ -1,5 +1,6 @@
import test from 'node:test';
import assert from 'node:assert/strict';
+import { spawnSync } from 'node:child_process';
import { createNavmesh } from '../src/navmesh.js';
import { createTerrain } from '../src/terrain.js';
import { createAgentScene, loadAllAgentSceneModules } from '../src/agent-scene.js';
@@ -102,3 +103,22 @@ test('geometry with non-finite positions or indices past the positions is refuse
brokenIndices[0] = ground.positions.length;
assert.throws(() => createNavmesh({ positions: ground.positions, indices: brokenIndices }), /index/i);
});
+
+test('an agent radius far above the cell size finishes and leaves nothing walkable around an obstacle', () => {
+ // Run in a child process: a regression loops forever, and a synchronous loop cannot be cut short by a test timeout.
+ const script = `
+ import { createNavmesh } from './src/navmesh.js';
+ const positions = Float32Array.of(0, 0, 0, 20, 0, 0, 0, 0, 20, 20, 0, 20);
+ const indices = Uint32Array.of(0, 2, 1, 1, 2, 3);
+ const navmesh = createNavmesh({ positions, indices, agentRadius: 1e6, cellSize: 0.1, obstacles: [{ min: [1, 1], max: [2, 2] }] });
+ console.log(navmesh.walkableCellCount);
+ `;
+ const run = spawnSync(process.execPath, ['--input-type=module', '-e', script], { encoding: 'utf8', timeout: 20000 });
+ assert.equal(run.error, undefined, 'createNavmesh did not finish within 20 s');
+ assert.equal(run.stdout.trim(), '0');
+});
+
+test('a fractional triangle index is refused and named', () => {
+ const positions = Float32Array.of(0, 0, 0, 10, 0, 0, 0, 0, 10, 10, 0, 10);
+ assert.throws(() => createNavmesh({ positions, indices: [0, 2, 1.5, 1, 2, 3] }), /navmesh index 2 is 1\.5; use a whole number/);
+});
diff --git a/tests/scene-query-obstacles.test.js b/tests/scene-query-obstacles.test.js
index 64e8e57d..6defeeb7 100644
--- a/tests/scene-query-obstacles.test.js
+++ b/tests/scene-query-obstacles.test.js
@@ -1,5 +1,6 @@
import test from 'node:test';
import assert from 'node:assert/strict';
+import { spawnSync } from 'node:child_process';
import { createSceneQuery, walkableMask } from '../src/scene-query.js';
function quad(halfWidth, halfDepth = halfWidth) {
@@ -85,3 +86,40 @@ test('walkMap rejects unknown obstacles options', () => {
assert.throws(() => query.walkMap({ min: [0, 0], max: [1, 1], obstacles: { colour: 1 } }), /Unsupported walkMap obstacles option/);
query.dispose();
});
+
+function openGridWithOneObstacle() {
+ const cells = [];
+ for (let column = 0; column < 20; column++) {
+ for (let row = 0; row < 20; row++) cells.push([column, row, 0, 5, column === 10 && row === 10 ? 1 : 0]);
+ }
+ return { columns: 20, rows: 20, cellSize: 1, min: [0, 0], cells };
+}
+
+test('walkableMask refuses a keepOut that is not a finite number of metres', () => {
+ for (const keepOut of [NaN, -1, '2']) {
+ assert.throws(() => walkableMask(openGridWithOneObstacle(), { keepOut }), /walkableMask keepOut must be a finite number/);
+ }
+});
+
+test('walkableMask with a keepOut far larger than the map finishes and clears every cell', () => {
+ // Run in a child process: a regression loops or allocates without end, and a test timeout cannot stop that.
+ const script = `
+ import { walkableMask } from './src/scene-query.js';
+ const cells = [];
+ for (let column = 0; column < 20; column++) {
+ for (let row = 0; row < 20; row++) cells.push([column, row, 0, 5, column === 10 && row === 10 ? 1 : 0]);
+ }
+ const mask = walkableMask({ columns: 20, rows: 20, cellSize: 1, min: [0, 0], cells }, { keepOut: 100000 });
+ console.log(mask.reduce((total, value) => total + value, 0));
+ try {
+ walkableMask({ columns: 20, rows: 20, cellSize: 1, min: [0, 0], cells }, { keepOut: Infinity });
+ } catch (error) {
+ console.log(error.message);
+ }
+ `;
+ const run = spawnSync(process.execPath, ['--input-type=module', '-e', script], { encoding: 'utf8', timeout: 20000 });
+ assert.equal(run.error, undefined, 'walkableMask did not finish within 20 s');
+ const [clearedCount, infiniteMessage] = run.stdout.trim().split(/\s*[\r\n]+\s*/);
+ assert.equal(clearedCount, '0');
+ assert.match(infiniteMessage, /walkableMask keepOut must be a finite number/);
+});