Skip to content

armgit / 67.js

Public Imported from GitHub
0

3D engine that AI agents drive

Center studio projection at any width, repair canceled vertex normals, and use Metal on macOS (#517, #521, #507)

Nguyen Xuan An235ef1d99444
diff --git a/changes/507.md b/changes/507.md
new file mode 100644
index 00000000..4b5e20ef
--- /dev/null
+++ b/changes/507.md
@@ -0,0 +1 @@
+- `scripts/render-media.mjs` now launches Google Chrome with `--use-angle=metal` on macOS when `--backend gpu` is selected, avoiding a SwiftShader fallback (issue #507).
diff --git a/changes/517.md b/changes/517.md
new file mode 100644
index 00000000..bceff0f6
--- /dev/null
+++ b/changes/517.md
@@ -0,0 +1 @@
+- `Renderer67.resize` no longer shifts the studio projection right on canvases wider than 700 px (issue #517); `render({ eye, target })` now keeps `target` centred at any canvas width, and the studio demo sets its own sidebar offset.
diff --git a/changes/521.md b/changes/521.md
new file mode 100644
index 00000000..16c7af57
--- /dev/null
+++ b/changes/521.md
@@ -0,0 +1 @@
+- `loadGltf` and `parseGltf` now fall back to a touching face normal or `[0, 1, 0]` with a warning when a generated vertex normal cancels out or a vertex touches only zero-area triangles (issue #521).
diff --git a/scripts/render-media.mjs b/scripts/render-media.mjs
index 9adff56a..0ce2e3dd 100644
--- a/scripts/render-media.mjs
+++ b/scripts/render-media.mjs
@@ -122,7 +122,9 @@ export async function renderMedia(values = process.argv.slice(2)) {
const root = fileURLToPath(new URL('..', import.meta.url));
const ffmpeg = process.platform === 'win32' ? resolve(process.env.USERPROFILE, '.local/bin/ffmpeg.exe') : 'ffmpeg';
const encoderBackend = kind === 'video' ? await selectEncoderBackend(plan.encoderBackend, () => probeNvenc(ffmpeg)) : null;
- const chrome = 'C:/Program Files/Google/Chrome/Application/chrome.exe';
+ const chrome = process.platform === 'darwin'
+ ? '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome'
+ : 'C:/Program Files/Google/Chrome/Application/chrome.exe';
const serverPort = await freePort();
const server = spawn(process.execPath, ['node_modules/vite/bin/vite.js', '--config', 'scripts/render-vite.config.mjs', '--host', '127.0.0.1', '--port', String(serverPort), '--strictPort'], { cwd: root, windowsHide: true, stdio: 'pipe' });
let browser;
@@ -150,6 +152,7 @@ export async function renderMedia(values = process.argv.slice(2)) {
});
const args = ['--enable-webgl', '--ignore-gpu-blocklist'];
if (backend === 'cpu') args.push('--use-angle=swiftshader', '--enable-unsafe-swiftshader');
+ else if (process.platform === 'darwin') args.push('--use-angle=metal', '--enable-gpu');
browser = await chromium.launch({ headless: true, ...(existsSync(chrome) ? { executablePath: chrome } : {}), args });
const page = await browser.newPage({ viewport: { width, height }, deviceScaleFactor: 1 });
const errors = [];
diff --git a/src/gltf.js b/src/gltf.js
index 855e1e64..bbe2c046 100644
--- a/src/gltf.js
+++ b/src/gltf.js
@@ -813,10 +813,20 @@ function triangleAt(positions, indices, corner) {
function computeVertexNormals(positions, indices) {
const normals = new Float32Array(positions.length);
+ const firstFace = new Float32Array(positions.length);
for (let corner = 0; corner < indices.length; corner += 3) {
const { corners, cross } = triangleAt(positions, indices, corner);
+ const area = Math.hypot(...cross);
for (const vertexOffset of corners) {
for (let axis = 0; axis < 3; axis++) normals[vertexOffset + axis] += cross[axis];
+ if (area > 1e-8 && !firstFace[vertexOffset] && !firstFace[vertexOffset + 1] && !firstFace[vertexOffset + 2]) {
+ for (let axis = 0; axis < 3; axis++) firstFace[vertexOffset + axis] = cross[axis] / area;
+ }
+ }
+ }
+ for (let offset = 0; offset < normals.length; offset += 3) {
+ if (Math.hypot(...normals.subarray(offset, offset + 3)) < 1e-8 && (firstFace[offset] || firstFace[offset + 1] || firstFace[offset + 2])) {
+ for (let axis = 0; axis < 3; axis++) normals[offset + axis] = firstFace[offset + axis];
}
}
return normals;
@@ -848,11 +858,6 @@ function convertGeometry(source, mirrored, primitive, secondUvSet, onIgnoredVert
const repairedNormals = [];
for (let offset = 0; offset < normals.length; offset += 3) {
const length = Math.hypot(...normals.subarray(offset, offset + 3));
- if (length < 1e-8 && !normal) {
- // A vertex that no triangle with area touches has no generated normal; it draws nothing, so any unit vector will do.
- normals[offset + 1] = 1;
- continue;
- }
if (length < 1e-8) {
repairedNormals.push(offset);
continue;
@@ -860,8 +865,8 @@ function convertGeometry(source, mirrored, primitive, secondUvSet, onIgnoredVert
for (let axis = 0; axis < 3; axis++) normals[offset + axis] /= length;
}
if (repairedNormals.length) {
- // An authored normal of zero length cannot light anything: use the face normal of the triangles at that vertex, or up.
- const faceNormals = computeVertexNormals(positions, indices);
+ // A vertex normal of zero length cannot light anything: use the face normal of the triangles at that vertex, or up.
+ const faceNormals = normal ? computeVertexNormals(positions, indices) : normals;
for (const offset of repairedNormals) {
const length = Math.hypot(...faceNormals.subarray(offset, offset + 3));
for (let axis = 0; axis < 3; axis++) normals[offset + axis] = length > 1e-8 ? faceNormals[offset + axis] / length : axis === 1 ? 1 : 0;
diff --git a/src/renderer.js b/src/renderer.js
index 6a30be86..9ff6666d 100644
--- a/src/renderer.js
+++ b/src/renderer.js
@@ -1467,7 +1467,6 @@ export class Renderer67 {
if (!this.benchmark) this.allocateFrameTargets(width, height);
}
mat4.perspective(this.projection, this.world ? Math.PI / 4 : Math.PI / 5.5, width / height, 0.1, this.world ? 600 : 100);
- this.projection[8] = !this.benchmark && !this.world && this.canvas.clientWidth > 700 ? -0.25 : 0;
}
/** Every GPU render target this renderer holds: name, size, format, samples and bytes, largest first, with the total. */
diff --git a/tests/gltf-tolerance.test.js b/tests/gltf-tolerance.test.js
index faa4b840..080d66a7 100644
--- a/tests/gltf-tolerance.test.js
+++ b/tests/gltf-tolerance.test.js
@@ -71,3 +71,31 @@ test('morph targets without a base NORMAL load: normals are generated and the mo
assert.equal(asset.parts[0].geometry.morphTargets[0].normals, undefined);
assert.match(asset.warnings[0], /^Repaired primitive 0 of mesh "Tri": it has morph targets but no base NORMAL/);
});
+
+test('a primitive without NORMAL repairs vertices on zero-area or opposing faces with a warning', async () => {
+ const floats = new Float32Array([0, 0, 0, 1, 0, 0, 0, 1, 0, 5, 5, 5]);
+ const indices = new Uint16Array([0, 1, 2, 0, 2, 1, 3, 3, 3, 0, 1, 2]);
+ const bytes = new Uint8Array(floats.byteLength + indices.byteLength);
+ bytes.set(new Uint8Array(floats.buffer), 0);
+ bytes.set(new Uint8Array(indices.buffer), floats.byteLength);
+ const document = {
+ asset: { version: '2.0' },
+ scene: 0,
+ scenes: [{ nodes: [0] }],
+ nodes: [{ name: 'Tile', mesh: 0 }],
+ meshes: [{ name: 'Tile', primitives: [{ attributes: { POSITION: 0 }, indices: 1 }] }],
+ accessors: [
+ { bufferView: 0, byteOffset: 0, componentType: 5126, count: 4, type: 'VEC3', min: [0, 0, 0], max: [5, 5, 5] },
+ { bufferView: 1, byteOffset: 0, componentType: 5123, count: 12, type: 'SCALAR' },
+ ],
+ bufferViews: [
+ { buffer: 0, byteOffset: 0, byteLength: floats.byteLength },
+ { buffer: 0, byteOffset: floats.byteLength, byteLength: indices.byteLength },
+ ],
+ buffers: [{ byteLength: bytes.byteLength, uri: `data:application/octet-stream;base64,${Buffer.from(bytes).toString('base64')}` }],
+ };
+ const asset = await parseGltf(JSON.stringify(document));
+ assert.equal(asset.parts.length, 1);
+ assert.deepEqual(Array.from(asset.parts[0].geometry.normals), [0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 1, 0]);
+ assert.deepEqual(asset.warnings, ['Repaired primitive 0 of mesh "Tile": 1 vertex normal(s) had zero length and were rebuilt from the triangles.']);
+});
diff --git a/tests/renderer.test.js b/tests/renderer.test.js
index 498a5631..76284db8 100644
--- a/tests/renderer.test.js
+++ b/tests/renderer.test.js
@@ -563,3 +563,23 @@ test('blend batches draw their opaque texels with depth writes before the blende
assert.equal(draws.filter(draw => draw.opacity === 0.3).length, 1, 'a translucent material has no opaque texels to draw first');
assert.equal(baked.alphaCutoff, 0);
});
+
+test('resize keeps the projection centered at 699 px and 1440 px', () => {
+ const renderer = Object.create(Renderer67.prototype);
+ renderer.context = { getParameter: () => 8192 };
+ renderer.projection = new Float32Array(16);
+ renderer.pixelRatio = 1;
+ renderer.samples = 1;
+ renderer.memoryBudgetMiB = 64;
+ renderer.geometryBytes = 0;
+ renderer.textureBytes = 0;
+ renderer.hdr = false;
+ renderer.benchmark = true;
+ renderer.depth = false;
+ renderer.world = null;
+ for (const width of [699, 1440]) {
+ renderer.canvas = { clientWidth: width, clientHeight: 500, width: 0, height: 0 };
+ renderer.resize();
+ assert.equal(renderer.projection[8], 0);
+ }
+});