3D engine that AI agents drive
Validate OBJ UVs, normals and materials and write opacity to the MTL (#747)
Nguyen Xuan Ane0845a0727a4
diff --git a/docs/export-glb.md b/docs/export-glb.mdindex 13790054..787549d7 100644--- a/docs/export-glb.md+++ b/docs/export-glb.md@@ -152,13 +152,13 @@ const stl = exportStl(parts);| Format | Written | Not written || --- | --- | --- || OBJ | One `o` object per part, positions, UVs and normals when the geometry has them, faces as triangles | Textures, lights, cameras, animation, skins, morph weights |-| MTL | One material per distinct base color, emission, roughness and metallic: `Kd`, `Ke` (when emission is positive), `Pr`, `Pm` | Texture maps, layers, patterns |+| MTL | One material per distinct base color, emission, roughness and metallic: `Kd`, `Ke` (when emission is positive), `Pr`, `Pm`, and `d` (opacity) for mask, blend and add materials | Texture maps, alpha cutoff, layers, patterns || STL | Triangles with face normals, 80 byte header, no color | Everything but shape |Y stays up and units stay as authored (67js uses meters); set the axis and unit in the importer or slicer.A mirrored part (negative scale) has its winding swapped so faces still point outward.A skinned part exports its bind shape.-Export stops with an error past `MAX_MESH_EXPORT_TRIANGLES` (1,000,000), and names the field it rejected: positions, indices or `part.matrix`.+Export stops with an error past `MAX_MESH_EXPORT_TRIANGLES` (1,000,000), and names the field it rejected: positions, indices, `part.matrix`, and for OBJ also `geometry.uvs`, `geometry.normals` and the `material` fields.Colors in the MTL are the linear base colors of the parts.Blender 5.2 imports both files with the same triangle count (`File > Import > Wavefront (.obj)` and `STL (.stl)`).These two functions are library calls; the `scene_export_glb` tool still writes GLB only.diff --git a/src/export-mesh.js b/src/export-mesh.jsindex dec59b70..1307e8e7 100644--- a/src/export-mesh.js+++ b/src/export-mesh.js@@ -4,8 +4,45 @@export const MAX_MESH_EXPORT_TRIANGLES = 1_000_000;const MAX_NAME_LENGTH = 64;const STL_HEADER_TEXT = '67js binary STL';+const ALPHA_MODES = ['opaque', 'mask', 'blend', 'add'];const IDENTITY = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1];+function checkFinite(values, label) {+ for (const value of values) {+ if (!Number.isFinite(value)) throw new RangeError(`OBJ export requires finite ${label}.`);+ }+}++function checkFactor(value, label, maximum = 1) {+ if (!Number.isFinite(value) || value < 0 || value > maximum) {+ throw new RangeError(`OBJ export requires ${label} to be a finite number ${maximum === 1 ? 'within [0,1]' : 'of at least 0'}.`);+ }+}++function checkColor(values, label) {+ if (!values || values.length !== 3) throw new TypeError(`OBJ export requires ${label} as three linear RGB components.`);+ for (const value of values) checkFactor(value, label);+}++// Only the OBJ writer reads UVs, normals and materials. Each is optional, and one that is present must be well formed.+function checkObjAttributes(part, vertexCount) {+ const { uvs, normals } = part.geometry;+ if (uvs?.length === vertexCount * 2) checkFinite(uvs, 'geometry.uvs');+ if (normals?.length === vertexCount * 3) checkFinite(normals, 'geometry.normals');+ const material = part.material;+ if (material === undefined) return;+ if (material === null || typeof material !== 'object') throw new TypeError('OBJ export requires part.material to be an object.');+ if (material.color !== undefined) checkColor(material.color, 'material.color');+ if (material.emissiveColor !== undefined) checkColor(material.emissiveColor, 'material.emissiveColor');+ if (material.roughness !== undefined) checkFactor(material.roughness, 'material.roughness');+ if (material.metallic !== undefined) checkFactor(material.metallic, 'material.metallic');+ if (material.emission !== undefined) checkFactor(material.emission, 'material.emission', Infinity);+ if (material.alphaMode !== undefined && !ALPHA_MODES.includes(material.alphaMode)) {+ throw new TypeError("OBJ export requires material.alphaMode to be 'opaque', 'mask', 'blend' or 'add'.");+ }+ if (material.opacity !== undefined) checkFactor(material.opacity, 'material.opacity');+}+function checkParts(parts, format) {if (!Array.isArray(parts) || parts.length === 0) throw new TypeError(`${format} export requires a nonempty parts array.`);let triangleCount = 0;@@ -27,6 +64,7 @@ function checkParts(parts, format) {if (part.matrix !== undefined && (part.matrix.length !== 16 || Array.from(part.matrix).some(value => !Number.isFinite(value)))) {throw new RangeError(`${format} export requires part.matrix with 16 finite components.`);}+ if (format === 'OBJ') checkObjAttributes(part, vertexCount);triangleCount += indices.length / 3;if (triangleCount > MAX_MESH_EXPORT_TRIANGLES) {throw new RangeError(`${format} export is limited to ${MAX_MESH_EXPORT_TRIANGLES} triangles. Simplify the scene or export fewer parts.`);@@ -114,7 +152,13 @@ function safeName(name, fallback) {}function materialKey(material) {- return JSON.stringify([material?.color, material?.emissiveColor, material?.emission, material?.metallic, material?.roughness]);+ return JSON.stringify([material?.color, material?.emissiveColor, material?.emission, material?.metallic, material?.roughness, dissolve(material)]);+}++// An opaque material ignores opacity, as in the GLB export; mask, blend and add write it as the MTL dissolve value.+function dissolve(material) {+ const alphaMode = material?.alphaMode ?? 'opaque';+ return alphaMode === 'opaque' ? 1 : material.opacity ?? 1;}function mtlBlock(name, material) {@@ -124,13 +168,14 @@ function mtlBlock(name, material) {const emissive = (material.emissiveColor ?? color).map(value => value * Math.min(material.emission, 1));lines.push(`Ke ${emissive.map(formatNumber).join(' ')}`);}- lines.push(`Pr ${formatNumber(material?.roughness ?? 0.5)}`, `Pm ${formatNumber(material?.metallic ?? 0)}`, 'd 1');+ lines.push(`Pr ${formatNumber(material?.roughness ?? 0.5)}`, `Pm ${formatNumber(material?.metallic ?? 0)}`, `d ${formatNumber(dissolve(material))}`);return lines.join('\n');}/*** Returns `{ obj, mtl }` as text. The OBJ names the MTL by `mtlFilename` (default `model.mtl`); save both files side by side.- * Colors in the MTL are the linear base colors of the parts, with roughness and metallic as `Pr` and `Pm`.+ * Colors in the MTL are the linear base colors of the parts, with roughness and metallic as `Pr` and `Pm`+ * and the opacity of a mask, blend or add material as `d`.*/export function exportObj(parts, options = {}) {checkParts(parts, 'OBJ');diff --git a/tests/export-mesh.test.js b/tests/export-mesh.test.jsindex c6686632..ed20a361 100644--- a/tests/export-mesh.test.js+++ b/tests/export-mesh.test.js@@ -149,6 +149,50 @@ test('invalid input names the field and what to pass', () => {assert.equal(exportObj(parts, { mtlFilename: 'scene.mtl' }).obj.includes('mtllib scene.mtl'), true);});+test('OBJ rejects non-finite UVs and normals and names the field', () => {+ const [part] = sceneParts();+ const uvs = new Float32Array(part.geometry.positions.length / 3 * 2);+ uvs[1] = NaN;+ assert.throws(() => exportObj([{ ...part, geometry: { ...part.geometry, uvs } }]), /finite geometry\.uvs/);+ const normals = new Float32Array(part.geometry.positions.length);+ normals[2] = Infinity;+ assert.throws(() => exportObj([{ ...part, geometry: { ...part.geometry, normals } }]), /finite geometry\.normals/);+});++test('OBJ rejects malformed material fields and STL ignores them', () => {+ const [part] = sceneParts();+ const bad = [+ [{ color: [0.5, 0.5] }, /material\.color/],+ [{ color: [0.5, undefined, 0.5] }, /material\.color/],+ [{ emissiveColor: [1, 2, 0] }, /material\.emissiveColor/],+ [{ roughness: NaN }, /material\.roughness/],+ [{ metallic: 2 }, /material\.metallic/],+ [{ emission: -1 }, /material\.emission/],+ [{ alphaMode: 'glass' }, /material\.alphaMode/],+ [{ alphaMode: 'blend', opacity: 1.5 }, /material\.opacity/],+ ];+ for (const [material, message] of bad) {+ assert.throws(() => exportObj([{ ...part, material }]), message);+ }+ assert.doesNotThrow(() => exportStl([{ ...part, material: bad[0][0] }]));+ assert.match(exportObj([{ ...part, material: undefined }]).mtl, /Kd 0\.8 0\.8 0\.8/);+});++test('MTL writes opacity for mask, blend and add materials and keeps them as separate materials', () => {+ const [part] = sceneParts();+ const parts = [+ part,+ { ...part, material: { ...redMaterial, alphaMode: 'blend', opacity: 0.25 } },+ { ...part, material: { ...redMaterial, alphaMode: 'mask', opacity: 0.6 } },+ { ...part, material: { ...redMaterial, alphaMode: 'opaque', opacity: 0.1 } },+ ];+ const blocks = exportObj(parts).mtl.trim().split('\n\n');+ assert.equal(blocks.length, 3);+ assert.match(blocks[0], /\nd 1$/);+ assert.match(blocks[1], /\nd 0\.25$/);+ assert.match(blocks[2], /\nd 0\.6$/);+});+test('the triangle limit is enforced before any output is built', () => {const geometry = { positions: new Float32Array(9), indices: new Uint32Array(MAX_MESH_EXPORT_TRIANGLES * 3 + 3) };assert.throws(() => exportStl([{ geometry }]), /limited to 1000000 triangles/);