Skip to content

3D engine that AI agents drive

Harden mesh recipe ops, OBJ and STL export range and imported skin arrays (#2510)

Nguyen Xuan Anaf31f78d60a2
diff --git a/changes/2510.md b/changes/2510.md
new file mode 100644
index 00000000..372e1c21
--- /dev/null
+++ b/changes/2510.md
@@ -0,0 +1 @@
+- Fix three bad-input holes in mesh recipes, imports and exports: an edit op named like an Object.prototype key now lists the valid ops, OBJ and STL export refuse a matrix that overflows the file, and editImportedGeometry refuses short skin or morph arrays. (#2510, #2511, #2512)
diff --git a/changes/2510.size.md b/changes/2510.size.md
new file mode 100644
index 00000000..fbd83083
--- /dev/null
+++ b/changes/2510.size.md
@@ -0,0 +1,2 @@
+- entry:export-mesh: stops OBJ and STL files that hold Infinity for an overflowing vertex, +77 B.
+- scene:agent-scene+lazy: the overflow guard, the own-property op lookup and the skin and morph length check stop crashes and NaN weights, +145 B.
diff --git a/src/export-mesh.js b/src/export-mesh.js
index 2fa41c05..30ea95df 100644
--- a/src/export-mesh.js
+++ b/src/export-mesh.js
@@ -74,7 +74,17 @@ function checkParts(parts, format) {
}
}
-function worldTriangles(part) {
+// STL stores float32, so a world coordinate past that range would be written as Infinity; OBJ text needs only finite numbers.
+function checkWorldRange(world, format) {
+ const isStl = format === 'STL';
+ for (const value of world) {
+ if (!Number.isFinite(isStl ? Math.fround(value) : value)) {
+ throw new RangeError(`${format} export moves a vertex past the ${isStl ? 'float32' : 'finite'} range; scale part.matrix down.`);
+ }
+ }
+}
+
+function worldTriangles(part, format) {
const matrix = part.matrix ?? IDENTITY;
const { positions, indices } = part.geometry;
const vertexCount = positions.length / 3;
@@ -87,6 +97,7 @@ function worldTriangles(part) {
world[vertex * 3 + axis] = matrix[axis] * x + matrix[4 + axis] * y + matrix[8 + axis] * z + matrix[12 + axis];
}
}
+ checkWorldRange(world, format);
const determinant = matrix[0] * (matrix[5] * matrix[10] - matrix[9] * matrix[6])
- matrix[4] * (matrix[1] * matrix[10] - matrix[9] * matrix[2])
+ matrix[8] * (matrix[1] * matrix[6] - matrix[5] * matrix[2]);
@@ -114,7 +125,7 @@ function faceNormal(world, first, second, third) {
/** Returns a binary STL `ArrayBuffer` of every part's triangles in world space. Y stays up, units stay as authored. */
export function exportStl(parts) {
checkParts(parts, 'STL');
- const prepared = parts.map(worldTriangles);
+ const prepared = parts.map(part => worldTriangles(part, 'STL'));
const triangleCount = prepared.reduce((total, entry) => total + entry.triangles.length / 3, 0);
const buffer = new ArrayBuffer(84 + triangleCount * 50);
const view = new DataView(buffer);
@@ -196,7 +207,7 @@ export function exportObj(parts, options = {}) {
let uvBase = 1;
let normalBase = 1;
parts.forEach((part, partIndex) => {
- const { world, triangles, matrix } = worldTriangles(part);
+ const { world, triangles, matrix } = worldTriangles(part, 'OBJ');
const key = materialKey(part.material);
if (!materialNames.has(key)) {
const name = `material_${materialNames.size}`;
diff --git a/src/mesh-import.js b/src/mesh-import.js
index 3b9b8d58..a99db20b 100644
--- a/src/mesh-import.js
+++ b/src/mesh-import.js
@@ -226,6 +226,25 @@ function tagFacesOfMaterial(mesh, materialTag) {
return withFaceAttributes(mesh, { [`${TAG_PREFIX}${materialTag}`]: { data: new Uint8Array(mesh.faceCount).fill(1), size: 1 } });
}
+function requireLength(field, array, expectedLength) {
+ if (array?.length !== expectedLength) {
+ throw new RangeError(`Geometry ${field} must hold ${expectedLength} values, not ${array?.length ?? typeof array}; fix the array or remove it.`);
+ }
+}
+
+/** Skin and morph arrays are read per vertex while transferring; a short one would turn into NaN weights. */
+function checkTransferArrays(source) {
+ const vertexCount = source.positions.length / 3;
+ if (source.skinIndices || source.skinWeights) {
+ requireLength('skinIndices', source.skinIndices, vertexCount * MAX_INFLUENCES);
+ requireLength('skinWeights', source.skinWeights, vertexCount * MAX_INFLUENCES);
+ }
+ (source.morphTargets ?? []).forEach((target, index) => {
+ if (target.positions) requireLength(`morphTargets[${index}].positions`, target.positions, vertexCount * 3);
+ if (target.normals) requireLength(`morphTargets[${index}].normals`, target.normals, vertexCount * 3);
+ });
+}
+
/**
* Apply mesh edits to imported renderer geometry. `materialTag` names a face tag on every face (an imported part
* has one material). Returns the edited geometry, its polygon mesh, the per-edit results and what was transferred.
@@ -233,6 +252,7 @@ function tagFacesOfMaterial(mesh, materialTag) {
*/
export function editImportedGeometry(source, edits, { maxVertices, smoothAngle, resolveCutter, materialTag }) {
const base = tagFacesOfMaterial(meshFromGeometry(source), materialTag);
+ checkTransferArrays(source);
const outcome = applyMeshEdits(base, edits, {
maxVertices, maxFaces: maxVertices,
resolveCutter: resolveCutter && (cutter => meshFromGeometry(resolveCutter(cutter))),
diff --git a/src/mesh-recipe.js b/src/mesh-recipe.js
index 94f51f62..89fd1f73 100644
--- a/src/mesh-recipe.js
+++ b/src/mesh-recipe.js
@@ -171,7 +171,7 @@ export function normalizeMeshEdits(edits) {
if (edits.length > MAX_MESH_EDITS) throw new RangeError(`A mesh holds at most ${MAX_MESH_EDITS} edits. Apply fewer or start from a new base.`);
return edits.map((edit, index) => {
if (!edit || typeof edit !== 'object' || Array.isArray(edit)) throw invalidField(`edits[${index}]`, edit, 'an object such as { "op": "subdivide", "levels": 1 }', TypeError);
- const definition = MESH_EDIT_OPERATIONS[edit.op];
+ const definition = Object.hasOwn(MESH_EDIT_OPERATIONS, edit.op) ? MESH_EDIT_OPERATIONS[edit.op] : undefined;
if (!definition) throw editField(index, 'op', edit.op, `one of ${Object.keys(MESH_EDIT_OPERATIONS).join(', ')}`);
for (const key of Object.keys(edit)) {
if (key !== 'op' && !definition.fields.includes(key)) throw editField(index, key, edit[key], `one of the fields ${edit.op} takes: ${definition.fields.join(', ')}; remove "${key}"`);
diff --git a/tests/export-mesh.test.js b/tests/export-mesh.test.js
index 4293b765..6a2af720 100644
--- a/tests/export-mesh.test.js
+++ b/tests/export-mesh.test.js
@@ -207,3 +207,11 @@ test('OBJ rejects uvs and normals whose length does not match the vertex count',
const shortNormals = new Float32Array(vertexCount * 3 - 3);
assert.throws(() => exportObj([{ ...part, geometry: { ...part.geometry, normals: shortNormals } }]), /geometry\.normals/);
});
+
+test('exports refuse a matrix that pushes a vertex past the number range of the file', () => {
+ const triangle = { positions: new Float32Array([0, 0, 0, 100, 0, 0, 0, 1, 0]), indices: new Uint32Array([0, 1, 2]) };
+ const scaledBy = factor => [{ geometry: triangle, matrix: [factor, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1] }];
+ assert.throws(() => exportStl(scaledBy(1e39)), /STL export moves a vertex past the float32 range/);
+ assert.throws(() => exportObj(scaledBy(1e308)), /OBJ export moves a vertex past the finite range/);
+ assert.match(exportObj(scaledBy(1e39)).obj, /v 1e\+41 0 0/);
+});
diff --git a/tests/mesh-hunt-io.test.js b/tests/mesh-hunt-io.test.js
new file mode 100644
index 00000000..c167c786
--- /dev/null
+++ b/tests/mesh-hunt-io.test.js
@@ -0,0 +1,22 @@
+import './support/load-agent-scene-modules.mjs';
+import assert from 'node:assert/strict';
+import test from 'node:test';
+import { box } from '../src/geometry.js';
+import { normalizeMeshEdits } from '../src/mesh-recipe.js';
+import { editImportedGeometry } from '../src/mesh-import.js';
+
+test('an edit op named like an Object.prototype key gets the list of valid ops', () => {
+ for (const op of ['toString', 'constructor', '__proto__', 'hasOwnProperty']) {
+ assert.throws(() => normalizeMeshEdits([{ op }]), /edits\[0\]\.op.*one of extrude_face_region/s, op);
+ }
+});
+
+test('imported geometry with a short skin or morph array is refused before values transfer', () => {
+ const source = box(0, 1);
+ const options = { maxVertices: 10000, smoothAngle: 30 };
+ const edits = [{ op: 'subdivide', levels: 1 }];
+ const shortSkin = { ...source, skinIndices: new Uint16Array(4), skinWeights: new Float32Array(4) };
+ assert.throws(() => editImportedGeometry(shortSkin, edits, options), /skinIndices must hold 96 values, not 4/);
+ const shortMorph = { ...source, morphTargets: [{ positions: new Float32Array(3) }] };
+ assert.throws(() => editImportedGeometry(shortMorph, edits, options), /morphTargets\[0\]\.positions must hold 72 values, not 3/);
+});