Skip to content

armgit / 67.js

Public Imported from GitHub
0

3D engine that AI agents drive

Fit trailer portrait framing to output aspect

Nguyen Xuan An1abf7b195207
diff --git a/docs/camera-path.md b/docs/camera-path.md
index 7f57fa43..f5e588cb 100644
--- a/docs/camera-path.md
+++ b/docs/camera-path.md
@@ -65,6 +65,27 @@ Invalid poses and cubic lens overshoot throw before the frame changes.
Float32 outputs also reject positions that collapse into an identical eye and target after rounding.
A parallel up vector fails explicitly. This API does not choose a replacement orientation at camera poles.
+## Framing a perspective camera
+
+`fitPerspectiveDistance(bounds, view, aspect, padding = 1.15)` returns an eye-to-target distance that contains all eight corners of a world-space axis-aligned box. It preserves the camera direction, up vector and vertical field of view. The target remains the caller's choice; use the bounds center when framing a subject.
+
+```js
+import { fitPerspectiveDistance } from '67js';
+
+const bounds = { minimum: [-0.4, 0, -0.2], maximum: [0.4, 2, 0.25] };
+const view = { eye: [0, 1, 4], target: [0, 1, 0], fov: 30, near: 0.1, far: 100 };
+const aspect = canvas.clientWidth / canvas.clientHeight;
+const distance = fitPerspectiveDistance(bounds, view, aspect);
+const direction = view.eye.map((component, axis) => component - view.target[axis]);
+const length = Math.hypot(...direction);
+view.eye = view.target.map((component, axis) => component + direction[axis] / length * distance);
+renderer.render(view);
+```
+
+Padding applies to horizontal and vertical projected extents. The helper uses `fov = 45`, `near = 0.1` and `far = 100` when omitted, matching ordinary renderer projection defaults. World scenes using a different far plane must supply it explicitly. Invalid bounds, degenerate orientation, impossible clipping and fitted eyes that collapse after Float32 rounding throw. Large world coordinates need a local origin; the helper cannot restore precision lost by GPU matrices.
+
+The film addon accepts `sampleFilm(time, { aspect })`, defaulting to the authored 16:9 ratio. Narrow portrait shots keep their lens and blend toward centered subject framing as the aspect approaches square. Other narrow shots widen vertical field of view to retain authored horizontal coverage. Wide layouts retain the original camera. This is shot-specific framing, not automatic detection of subjects, animated bounds or occlusion.
+
## Lens conventions
`fovFromFocalLength` computes vertical field of view from focal length and sensor height.
diff --git a/docs/capability-audit.md b/docs/capability-audit.md
index 9c1c5a1c..7b33d42a 100644
--- a/docs/capability-audit.md
+++ b/docs/capability-audit.md
@@ -112,7 +112,7 @@ SwiftShader also rendered the updated shader without a WebGL error.
The current trailer does not meet the requested visual quality.
The current source replaces the scientist's unlit silhouette with lit facial features, shared head attachments and shaped headwear.
The rendered close-up still looks like a stylized mannequin with insufficient facial likeness.
-Portrait exports currently crop part of the headwear; aspect-aware film framing remains unfinished.
+The current source frames portrait shots by output aspect and retains the face and headwear in inspected 540 × 960 renders. Wide cameras retain their authored framing. The subject bounds are authored for these shots; automatic animated-subject framing remains unfinished.
This source change has not been deployed or published to npm.
Rigid joint animation and GPU skinning provide motion tools, but do not solve character modeling or material quality by themselves.
diff --git a/scripts/smoke-package.mjs b/scripts/smoke-package.mjs
index e77c6c14..22428972 100644
--- a/scripts/smoke-package.mjs
+++ b/scripts/smoke-package.mjs
@@ -30,7 +30,7 @@ const sourceArchive = resolve(consumer, packedSource.filename);
const installed = spawnSync(process.execPath, [npmCli, 'install', `67js@file:${sourceArchive.replaceAll('\\', '/')}`, '@dimforge/[email protected]', '--ignore-scripts', '--no-audit', '--no-fund'], { cwd: consumer, windowsHide: true, encoding: 'utf8' });
assert.equal(installed.status, 0, installed.stderr);
const example = `import assert from 'node:assert/strict';
-import { VERSION, Renderer67, box, assemblyOffset, cameraView, createAnimationClip, sampleAnimationClip, EFFECT_PRESETS } from '67js';
+import { VERSION, Renderer67, box, assemblyOffset, cameraView, fitPerspectiveDistance, createAnimationClip, sampleAnimationClip, EFFECT_PRESETS } from '67js';
import { createModel } from '67js/addons/model';
import * as nature from '67js/addons/nature';
import * as film from '67js/addons/film';
@@ -47,6 +47,11 @@ assert.ok(parts.every(part => assemblyOffset(part, 1).some(value => value !== 0)
assert.ok(Object.keys(nature).length > 0);
assert.ok(Object.keys(film).length > 0);
assert.equal(cameraView('top').projection, 'orthographic');
+const fitBounds = { minimum: [-1, -1, -1], maximum: [1, 1, 1] };
+const fitView = { eye: [0, 0, 5], target: [0, 0, 0], fov: 45, far: 100 };
+const fitDistance = fitPerspectiveDistance(fitBounds, fitView, 0.5, 1);
+assert.ok(Math.abs(fitDistance - (1 + 2 / Math.tan(Math.PI / 8))) < 1e-10);
+assert.ok(film.sampleFilm(162, { aspect: 0.5 }).camera.eye.every(Number.isFinite));
assert.ok(EFFECT_PRESETS.cinematic.bloom.strength > 0);
const clip = createAnimationClip({ duration: 2, tracks: [{ target: 'cube', property: 'value', keyframes: [{ time: 0, value: 0 }, { time: 2, value: 2 }] }] });
assert.equal(sampleAnimationClip(clip, 1)[0].value, 1);
diff --git a/src/camera.js b/src/camera.js
index bbe50c70..c39c2944 100644
--- a/src/camera.js
+++ b/src/camera.js
@@ -46,3 +46,70 @@ export function fitOrthographicHeight(bounds, view, aspect, padding = 1.15) {
}
return Math.max(maximum[1] - minimum[1], (maximum[0] - minimum[0]) / aspect) * padding;
}
+
+// Return the eye-to-target distance needed to contain a box without changing the lens.
+export function fitPerspectiveDistance(bounds, view, aspect, padding = 1.15) {
+ if (!Number.isFinite(aspect) || aspect <= 0 || !Number.isFinite(padding) || padding < 1) {
+ throw new RangeError('Fit aspect must be positive and padding at least one');
+ }
+ const finiteVector = vector => vector?.length === 3 && Array.from(vector).every(value => typeof value === 'number' && Number.isFinite(value));
+ if (!finiteVector(bounds?.minimum) || !finiteVector(bounds?.maximum) || !bounds.maximum.every((value, axis) => value >= bounds.minimum[axis])) {
+ throw new RangeError('Fit bounds must be finite and ordered');
+ }
+ const up = view?.up ?? [0, 1, 0];
+ if (!finiteVector(view?.eye) || !finiteVector(view?.target) || !finiteVector(up)) {
+ throw new RangeError('Fit camera vectors must be finite');
+ }
+ if (view.projection && view.projection !== 'perspective') {
+ throw new RangeError('Perspective fit requires a perspective camera');
+ }
+ const fov = view.fov ?? 45;
+ const near = view.near ?? 0.1;
+ const far = view.far ?? 100;
+ if (!Number.isFinite(fov) || fov <= 0 || fov >= 180 || !Number.isFinite(near) || !Number.isFinite(far) || near <= 0 || far <= near) {
+ throw new RangeError('Fit lens must have 0 < fov < 180 and 0 < near < far');
+ }
+ const forward = vec3.subtract([], view.target, view.eye);
+ const forwardLength = Math.hypot(...forward);
+ if (!Number.isFinite(forwardLength) || forwardLength === 0) {
+ throw new RangeError('Fit eye and target must differ');
+ }
+ for (let axis = 0; axis < 3; axis++) forward[axis] /= forwardLength;
+ const upLength = Math.hypot(...up);
+ if (!Number.isFinite(upLength) || upLength === 0) {
+ throw new RangeError('Fit up must have a finite nonzero length');
+ }
+ const normalizedUp = Array.from(up, component => component / upLength);
+ const right = vec3.cross([], forward, normalizedUp);
+ const rightLength = Math.hypot(...right);
+ if (!Number.isFinite(rightLength) || rightLength === 0) {
+ throw new RangeError('Fit up must not be parallel to the view direction');
+ }
+ for (let axis = 0; axis < 3; axis++) right[axis] /= rightLength;
+ const vertical = vec3.cross([], right, forward);
+ const verticalTangent = Math.tan(fov * Math.PI / 360);
+ const horizontalTangent = verticalTangent * aspect;
+ if (!Number.isFinite(horizontalTangent) || horizontalTangent <= 0) {
+ throw new RangeError('Fit aspect and lens exceed the supported numeric range');
+ }
+ let distance = near;
+ let maximumDepth = -Infinity;
+ for (let corner = 0; corner < 8; corner++) {
+ const offset = [0, 1, 2].map(axis => (corner & (1 << axis) ? bounds.maximum[axis] : bounds.minimum[axis]) - view.target[axis]);
+ const horizontal = vec3.dot(offset, right);
+ const height = vec3.dot(offset, vertical);
+ const depth = vec3.dot(offset, forward);
+ distance = Math.max(distance, Math.abs(horizontal) * padding / horizontalTangent - depth, Math.abs(height) * padding / verticalTangent - depth, near - depth);
+ maximumDepth = Math.max(maximumDepth, depth);
+ }
+ if (!Number.isFinite(distance) || distance <= 0 || distance + maximumDepth > far) {
+ throw new RangeError('Fit bounds cannot fit within the camera clipping planes');
+ }
+ const fittedEye = view.target.map((component, axis) => Math.fround(component - forward[axis] * distance));
+ const roundedTarget = view.target.map(component => Math.fround(component));
+ if (!fittedEye.every(Number.isFinite) || !roundedTarget.every(Number.isFinite)
+ || fittedEye.every((component, axis) => component === roundedTarget[axis])) {
+ throw new RangeError('Fit camera collapses or overflows after Float32 rounding; use coordinates closer to the origin');
+ }
+ return distance;
+}
diff --git a/src/film-player.js b/src/film-player.js
index b9240daa..d2b352f4 100644
--- a/src/film-player.js
+++ b/src/film-player.js
@@ -52,7 +52,7 @@ function displayTime(seconds) {
}
function renderAt(time) {
- const sample = sampleFilm(time);
+ const sample = sampleFilm(time, { aspect: canvas.clientWidth / canvas.clientHeight });
const scene = scenes[sample.scene];
if (activeScene !== sample.scene) {
renderer?.dispose();
diff --git a/src/film.js b/src/film.js
index 21a55e6b..378ac682 100644
--- a/src/film.js
+++ b/src/film.js
@@ -1,6 +1,7 @@
import { mat4, quat, vec3 } from 'gl-matrix';
import { createCameraPath } from './camera-path.js';
import { createFilmActorRig } from './film-rig.js';
+import { fitPerspectiveDistance } from './camera.js';
import { box, cylinder, sphere, torus } from './geometry.js';
export const FILM_DURATION = 187;
@@ -854,12 +855,35 @@ function smoothstep(value) {
return bounded * bounded * (3 - 2 * bounded);
}
-export function sampleFilm(time) {
+export function sampleFilm(time, { aspect = 16 / 9 } = {}) {
if (!Number.isFinite(time)) throw new TypeError('Film time must be finite.');
+ if (!Number.isFinite(aspect) || aspect <= 0) throw new RangeError('Film aspect must be positive and finite.');
const boundedTime = Math.max(0, Math.min(FILM_DURATION, time));
const shotIndex = FILM_SHOTS.findIndex(candidate => boundedTime < candidate.end);
const selected = FILM_SHOTS[shotIndex < 0 ? FILM_SHOTS.length - 1 : shotIndex];
const camera = selected.cameraPath.sample(boundedTime - selected.start);
+ if (aspect < 16 / 9) {
+ if (selected.scene === 'portrait') {
+ const bounds = selected.start === 145
+ ? { minimum: [-0.38, 0, -0.2], maximum: [0.38, 2, 0.25] }
+ : { minimum: [-0.27, 1.22, -0.2], maximum: [0.27, 2, 0.25] };
+ const direction = vec3.subtract([], camera.eye, camera.target);
+ const authoredDistance = Math.hypot(...direction);
+ vec3.scale(direction, direction, 1 / authoredDistance);
+ const center = bounds.minimum.map((value, axis) => (value + bounds.maximum[axis]) / 2);
+ const fittingView = { ...camera, target: center, eye: center.map((value, axis) => value + direction[axis] * authoredDistance) };
+ const distance = Math.max(authoredDistance, fitPerspectiveDistance(bounds, fittingView, aspect, 1.1));
+ const framingAmount = Math.min(1, (16 / 9 - aspect) / (16 / 9 - 1));
+ const framedDistance = authoredDistance + (distance - authoredDistance) * framingAmount;
+ camera.target = camera.target.map((value, axis) => value + (center[axis] - value) * framingAmount);
+ camera.eye = camera.target.map((value, axis) => value + direction[axis] * framedDistance);
+ } else {
+ camera.fov = Math.atan(Math.tan(camera.fov * Math.PI / 360) * (16 / 9) / aspect) * 360 / Math.PI;
+ if (!Number.isFinite(camera.fov) || camera.fov >= 180) {
+ throw new RangeError('Film aspect exceeds the supported lens range.');
+ }
+ }
+ }
const ignitionTime = boundedTime - 181;
const flash = ignitionTime >= 0 && ignitionTime < 0.7 ? Math.exp(-ignitionTime * 7) : 0;
const visibility = smoothstep(boundedTime / 0.8) * (1 - smoothstep((boundedTime - 185.8) / 1.2));
diff --git a/src/index.js b/src/index.js
index 4e90a552..3423d3cf 100644
--- a/src/index.js
+++ b/src/index.js
@@ -10,7 +10,7 @@ export { createSkinPose, updateSkinPose } from './skinning.js';
export { RENDER_PRESETS, planRenderSize, estimateFrameBytes } from './budget.js';
export { assemblyOffset } from './assembly.js';
-export { cameraView, fitOrthographicHeight } from './camera.js';
+export { cameraView, fitOrthographicHeight, fitPerspectiveDistance } from './camera.js';
export { createCameraPath, fovFromFocalLength } from './camera-path.js';
export { EFFECT_PRESETS, resolveEffects } from './effects.js';
export { createAnimationClip, sampleAnimationClip, createAnimationPlayer } from './animation.js';
diff --git a/tests/camera.test.js b/tests/camera.test.js
index 93097702..23b1df9d 100644
--- a/tests/camera.test.js
+++ b/tests/camera.test.js
@@ -1,7 +1,8 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { mat4, vec3 } from 'gl-matrix';
-import { applyProjection, cameraView, fitOrthographicHeight } from '../src/camera.js';
+import { applyProjection, cameraView, fitOrthographicHeight, fitPerspectiveDistance } from '../src/camera.js';
+import { PerspectiveCamera, Vector3 } from 'three';
function project(point, frame, aspect = 1) {
const projection = applyProjection(mat4.create(), frame, aspect);
@@ -50,3 +51,54 @@ test('orthographic fit respects both horizontal and vertical extents', () => {
assert.throws(() => applyProjection(mat4.create(), { fov: 190 }, 1), /field/);
assert.throws(() => cameraView('diagonal'), /view/);
});
+
+test('perspective fit contains off-center boxes under tilted and rolled Three.js cameras', () => {
+ const bounds = { minimum: [-0.7, -0.2, -0.9], maximum: [1.3, 1.8, 0.5] };
+ for (const aspect of [9 / 16, 1, 16 / 9, 3]) {
+ for (const up of [[0, 1, 0], [0.4, 1, 0.3]]) {
+ const view = { eye: [3, 2, 5], target: [0.2, 0.3, 0], up, fov: 38, near: 0.1, far: 100 };
+ const distance = fitPerspectiveDistance(bounds, view, aspect, 1.15);
+ const camera = new PerspectiveCamera(view.fov, aspect, view.near, view.far);
+ camera.up.fromArray(up);
+ const direction = new Vector3().fromArray(view.eye).sub(new Vector3().fromArray(view.target)).normalize();
+ camera.position.fromArray(view.target).addScaledVector(direction, distance);
+ camera.lookAt(...view.target);
+ camera.updateMatrixWorld();
+ let tightest = 0;
+ for (let corner = 0; corner < 8; corner++) {
+ const coordinates = [0, 1, 2].map(axis => corner & (1 << axis) ? bounds.maximum[axis] : bounds.minimum[axis]);
+ const projected = new Vector3(...coordinates).project(camera);
+ tightest = Math.max(tightest, Math.abs(projected.x), Math.abs(projected.y));
+ assert.ok(Math.abs(projected.x) <= 1 / 1.15 + 1e-10);
+ assert.ok(Math.abs(projected.y) <= 1 / 1.15 + 1e-10);
+ assert.ok(projected.z >= -1 && projected.z <= 1);
+ }
+ assert.ok(Math.abs(tightest - 1 / 1.15) < 1e-10, 'fit retains the requested margin without unnecessary zoom-out');
+ }
+ }
+});
+
+test('perspective fit rejects invalid bounds, lenses and impossible clipping without mutating inputs', () => {
+ const bounds = { minimum: [-1, -1, -1], maximum: [1, 1, 1] };
+ const view = { eye: [0, 0, 5], target: [0, 0, 0], fov: 40, near: 0.1, far: 100 };
+ const snapshot = structuredClone({ bounds, view });
+ for (const aspect of [0, -1, NaN, Infinity]) assert.throws(() => fitPerspectiveDistance(bounds, view, aspect));
+ assert.throws(() => fitPerspectiveDistance(bounds, { ...view, far: 1 }, 0.5), /clipping/);
+ assert.throws(() => fitPerspectiveDistance(bounds, { ...view, target: view.eye }, 1), /differ/);
+ assert.throws(() => fitPerspectiveDistance(bounds, { ...view, up: [0, 0, 1] }, 1), /parallel/);
+ assert.throws(() => fitPerspectiveDistance(bounds, { ...view, fov: 180 }, 1), /lens/);
+ assert.throws(() => fitPerspectiveDistance(bounds, { ...view, projection: 'orthographic' }, 1), /perspective/);
+ assert.throws(() => fitPerspectiveDistance({ minimum: [0, 0, 0], maximum: [-1, 1, 1] }, view, 1), /bounds/);
+ assert.throws(() => fitPerspectiveDistance(bounds, view, 1e-320), /range|clipping/);
+ assert.deepEqual({ bounds, view }, snapshot);
+});
+
+test('perspective fit shares renderer clipping defaults and rejects unrepresentable camera positions', () => {
+ const bounds = { minimum: [-1, -1, -150], maximum: [1, 1, -140] };
+ const view = { eye: [0, 0, 1], target: [0, 0, 0], fov: 45 };
+ assert.throws(() => fitPerspectiveDistance(bounds, view, 1), /clipping/);
+ assert.equal(fitPerspectiveDistance(bounds, { ...view, far: 600 }, 1), 0.1);
+ const distantBounds = { minimum: [1e20, -1, -1], maximum: [1e20, 1, 1] };
+ const distantView = { eye: [0, 0, 0], target: [1e20, 0, 0], fov: 45, far: 600 };
+ assert.throws(() => fitPerspectiveDistance(distantBounds, distantView, 1), /Float32/);
+});
diff --git a/tests/film.test.js b/tests/film.test.js
index d83ccd00..3da71f01 100644
--- a/tests/film.test.js
+++ b/tests/film.test.js
@@ -4,6 +4,7 @@ import { createFilmScenes, FILM_DURATION, FILM_SHOTS, sampleFilm } from '../src/
import { resolveEffects } from '../src/effects.js';
import { planRenderSize } from '../src/budget.js';
import { mat4 } from 'gl-matrix';
+import { PerspectiveCamera, Vector3 } from 'three';
const distance = (first, second) => Math.hypot(...first.map((value, axis) => value - second[axis]));
@@ -203,3 +204,32 @@ test('facial features share the head joint and remain attached during arbitrary
});
}
});
+
+test('narrow portrait shots retain face and headwear through camera moves and backward seeks', () => {
+ for (const aspect of [9 / 16, 390 / 844, 1]) {
+ for (const time of [161, 162, 164.9, 150, 145, 153.9, 162]) {
+ const sample = sampleFilm(time, { aspect });
+ const expected = structuredClone(sample);
+ sampleFilm(70, { aspect });
+ assert.deepEqual(sampleFilm(time, { aspect }), expected);
+ assert.equal(sample.camera.fov, sampleFilm(time).camera.fov);
+ const camera = new PerspectiveCamera(sample.camera.fov, aspect, sample.camera.near, sample.camera.far);
+ camera.position.fromArray(sample.camera.eye);
+ camera.up.fromArray(sample.camera.up);
+ camera.lookAt(...sample.camera.target);
+ camera.updateMatrixWorld();
+ for (const point of [[-0.22, 1.92, 0], [0.22, 1.92, 0], [0, 1.61, 0.15]]) {
+ const projected = new Vector3(...point).project(camera);
+ assert.ok(Math.abs(projected.x) < 1 && Math.abs(projected.y) < 1, `${time}: ${point}`);
+ }
+ }
+ }
+ for (const time of [150, 162]) {
+ const original = sampleFilm(time);
+ assert.deepEqual(sampleFilm(time, { aspect: 16 / 9 }), original);
+ const nearlyWide = sampleFilm(time, { aspect: 16 / 9 - 1e-6 });
+ assert.ok(distance(original.camera.eye, nearlyWide.camera.eye) < 1e-5);
+ assert.ok(distance(original.camera.target, nearlyWide.camera.target) < 1e-5);
+ }
+ for (const aspect of [0, -1, NaN, Infinity, 1e-320]) assert.throws(() => sampleFilm(10, { aspect }));
+});