3D engine that AI agents drive
Preserve linear glTF vertex colors and reject vertex transparency
Nguyen Xuan Ane6fafb4fc859
diff --git a/src/gltf.js b/src/gltf.jsindex d984f95f..d0d1928a 100644--- a/src/gltf.js+++ b/src/gltf.js@@ -3,8 +3,8 @@ import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';export const GLTF_CAPABILITIES = Object.freeze({formats: ['glb', 'gltf'],- supported: ['triangle meshes', 'world transforms', 'rigid node animations', 'PNG/JPEG base color textures', 'TEXCOORD_0', 'metallic roughness factors', 'emissive factors', 'KHR_mesh_quantization', 'KHR_materials_emissive_strength'],- unsupported: ['skinning', 'morph targets', 'vertex colors', 'alpha blending or masking', 'double-sided materials', 'normal/occlusion/emissive/metallic-roughness textures', 'texture transforms', 'DRACO', 'KTX2', 'GPU instancing'],+ supported: ['triangle meshes', 'world transforms', 'rigid node animations', 'PNG/JPEG base color textures', 'TEXCOORD_0', 'linear RGB vertex colors', 'metallic roughness factors', 'emissive factors', 'KHR_mesh_quantization', 'KHR_materials_emissive_strength'],+ unsupported: ['skinning', 'morph targets', 'vertex alpha below one', 'alpha blending or masking', 'double-sided materials', 'normal/occlusion/emissive/metallic-roughness textures', 'texture transforms', 'DRACO', 'KTX2', 'GPU instancing'],});const DEFAULT_MAX_BYTES = 32 * 1024 * 1024;@@ -80,12 +80,21 @@ function validateDocument(document, limits) {for (const primitive of mesh.primitives ?? []) {if ((primitive.mode ?? 4) !== 4) throw new Error('Only glTF TRIANGLES primitives are supported.');if (primitive.targets?.length) throw new Error('Morph targets are unsupported.');- if (primitive.attributes?.COLOR_0 !== undefined) throw new Error('Vertex colors are unsupported.');const position = document.accessors?.[primitive.attributes?.POSITION];if (!position || position.type !== 'VEC3' || !Number.isSafeInteger(position.count) || position.count < 3) {throw new Error('Each mesh primitive requires a valid POSITION accessor.');}vertices += position.count;+ const colorIndex = primitive.attributes?.COLOR_0;+ if (colorIndex !== undefined) {+ const color = document.accessors?.[colorIndex];+ if (!color || !['VEC3', 'VEC4'].includes(color.type) || color.count !== position.count) {+ throw new Error('COLOR_0 requires RGB or RGBA values matching the POSITION vertex count.');+ }+ if (color.componentType !== 5126 && (![5121, 5123].includes(color.componentType) || !color.normalized)) {+ throw new Error('COLOR_0 requires float or normalized unsigned integer components.');+ }+ }for (const [name, size] of [['NORMAL', 'VEC3'], ['TEXCOORD_0', 'VEC2']]) {const accessorIndex = primitive.attributes?.[name];const accessor = document.accessors?.[accessorIndex];@@ -351,9 +360,31 @@ function convertGeometry(source, mirrored) {const uv = source.getAttribute('uv');if (uv && uv.count !== position.count) throw new Error('TEXCOORD_0 and POSITION counts must match.');if (uv) geometry.uvs = copyAttribute(uv, 2);+ const color = source.getAttribute('color');+ if (color) geometry.colors = convertVertexColors(color, position.count);return geometry;}+function convertVertexColors(attribute, vertexCount) {+ if (attribute.count !== vertexCount || ![3, 4].includes(attribute.itemSize)) {+ throw new Error('COLOR_0 requires matching RGB or RGBA vertex values.');+ }+ const values = copyAttribute(attribute, attribute.itemSize);+ const colors = new Float32Array(vertexCount * 3);+ for (let vertex = 0; vertex < vertexCount; vertex++) {+ const offset = vertex * attribute.itemSize;+ if (attribute.itemSize === 4 && values[offset + 3] !== 1) {+ throw new Error('Vertex alpha is unsupported. Every COLOR_0 alpha value must equal one.');+ }+ for (let component = 0; component < 3; component++) {+ const value = values[offset + component];+ if (value < 0 || value > 1) throw new Error('COLOR_0 RGB values must be within zero and one.');+ colors[vertex * 3 + component] = value;+ }+ }+ return colors;+}+function convertMaterial(source, limits, maps) {const material = {tag: 'gltf',diff --git a/tests/gltf.test.js b/tests/gltf.test.jsindex 716d3d35..918e41c7 100644--- a/tests/gltf.test.js+++ b/tests/gltf.test.js@@ -32,7 +32,17 @@ function triangleAsset(edit = () => {}) {],bufferViews, buffers: [{ byteLength: offset }],};- edit(document);+ function appendAccessor(data, type, normalized = false) {+ chunks.push(data);+ const bufferView = bufferViews.length;+ bufferViews.push({ buffer: 0, byteOffset: offset, byteLength: data.byteLength });+ offset += Math.ceil(data.byteLength / 4) * 4;+ document.buffers[0].byteLength = offset;+ const accessor = document.accessors.length;+ document.accessors.push({ bufferView, componentType: data instanceof Uint8Array ? 5121 : 5126, count: data.length / (type === 'VEC4' ? 4 : 3), type, normalized });+ return accessor;+ }+ edit(document, appendAccessor);const json = new TextEncoder().encode(JSON.stringify(document));const jsonLength = Math.ceil(json.length / 4) * 4;const result = new ArrayBuffer(28 + jsonLength + offset);@@ -48,7 +58,7 @@ function triangleAsset(edit = () => {}) {header.setUint32(20 + jsonLength, offset, true);header.setUint32(24 + jsonLength, 0x004e4942, true);for (let index = 0; index < chunks.length; index++) {- bytes.set(new Uint8Array(chunks[index].buffer), 28 + jsonLength + bufferViews[index].byteOffset);+ bytes.set(new Uint8Array(chunks[index].buffer, chunks[index].byteOffset, chunks[index].byteLength), 28 + jsonLength + bufferViews[index].byteOffset);}return result;}@@ -128,7 +138,7 @@ test('unsupported features fail explicitly before loading resources', async () =const cases = [[document => { document.nodes[1].skin = 0; }, /Skinned/],[document => { document.meshes[0].primitives[0].targets = [{ POSITION: 0 }]; }, /Morph/],- [document => { document.meshes[0].primitives[0].attributes.COLOR_0 = 0; }, /Vertex colors/],+ [document => { document.meshes[0].primitives[0].attributes.COLOR_0 = 1; }, /COLOR_0/],[document => { document.meshes[0].primitives[0].mode = 1; }, /TRIANGLES/],[document => { document.materials[0].alphaMode = 'BLEND'; }, /alpha mode/],[document => { document.materials[0].doubleSided = true; }, /Double-sided/],@@ -193,3 +203,39 @@ test('URL loading streams within maxBytes and cancels oversized responses', asynawait assert.rejects(loadGltf('https://example.invalid/asset.glb', { maxBytes: 80 }), /maxBytes/);assert.equal(cancelled, true);});++test('linear RGB and normalized Uint8 vertex colors become shared Float32 RGB geometry', async () => {+ const inputs = [+ { colors: new Float32Array([0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9]), type: 'VEC3', normalized: false },+ { colors: new Uint8Array([0, 128, 255, 255, 64, 0, 128, 255, 64]), type: 'VEC3', normalized: true },+ { colors: new Uint8Array([0, 128, 255, 255, 255, 64, 0, 255, 128, 255, 64, 255]), type: 'VEC4', normalized: true },+ ];+ for (const input of inputs) {+ const asset = await parseGltf(triangleAsset((document, append) => {+ document.meshes[0].primitives[0].attributes.COLOR_0 = append(input.colors, input.type, input.normalized);+ }));+ const colors = asset.parts[0].geometry.colors;+ assert.ok(colors instanceof Float32Array);+ assert.equal(colors.length, 9);+ assert.equal(asset.parts[0].geometry, asset.parts[1].geometry);+ for (let vertex = 0; vertex < 3; vertex++) {+ for (let component = 0; component < 3; component++) {+ const value = input.colors[vertex * (input.type === 'VEC4' ? 4 : 3) + component];+ const expected = input.normalized ? value / 255 : value;+ assert.ok(Math.abs(colors[vertex * 3 + component] - expected) < 1e-7);+ }+ }+ asset.dispose();+ }+});++test('vertex colors reject nonopaque alpha and invalid RGB factors explicitly', async () => {+ for (const [colors, type, expected] of [+ [new Float32Array([1, 0, 0, 1, 0, 1, 0, 0.5, 0, 0, 1, 1]), 'VEC4', /Vertex alpha/],+ [new Float32Array([1, 0, 0, 0, -0.1, 0, 0, 0, 1]), 'VEC3', /COLOR_0 RGB/],+ ]) {+ await assert.rejects(parseGltf(triangleAsset((document, append) => {+ document.meshes[0].primitives[0].attributes.COLOR_0 = append(colors, type);+ })), expected);+ }+});