3D engine that AI agents drive
Add deterministic camera paths and curved film moves
Nguyen Xuan An411fb84f8c05
diff --git a/README.md b/README.mdindex 9271c1eb..d88c68f4 100644--- a/README.md+++ b/README.md@@ -155,6 +155,8 @@ renderer.render({ eye: [4, 3, 7], target: [0, 1.5, 0], assemblyAmount: 0.5 });```The core exports animation helpers, camera views and effect presets. `renderer.updateParts(parts)` uploads changes without replacing geometry buffers.+The current source adds [camera paths](docs/camera-path.md) with cubic moves, target tracking, roll and focal-length conversion.+These camera helpers are not included in the published `0.3.3` package yet.The [optional asset addon](docs/gltf.md) loads glTF/GLB meshes, base-color textures, opaque vertex colors and rigid node animation.It uses Three.js as a decoder. The core renderer and standalone module remain separate from this dependency.diff --git a/docs/camera-path.md b/docs/camera-path.mdnew file mode 100644index 00000000..7f57fa43--- /dev/null+++ b/docs/camera-path.md@@ -0,0 +1,85 @@+# Camera paths++This API exists in the current source checkout. The published `0.3.3` package does not include it yet.++`createCameraPath` samples camera position, target, vertical field of view and roll at an absolute time.+The trailer uses this API for every shot. Its atom and gadget shots use curved camera moves.++```js+import { createCameraPath, fovFromFocalLength } from '67js';++const path = createCameraPath({+ duration: 6,+ eye: {+ interpolation: 'CUBICSPLINE',+ keyframes: [+ { time: 0, value: [0, 2, 5], inTangent: [0, 0, 0], outTangent: [0, 0, 0] },+ { time: 3, value: [3, 2, 4], inTangent: [1, 0, -1], outTangent: [1, 0, -1] },+ { time: 6, value: [5, 2, 0], inTangent: [0, 0, 0], outTangent: [0, 0, 0] },+ ],+ },+ target: [0, 1, 0],+ fov: fovFromFocalLength(50, { sensorHeight: 24 }),+ near: 0.1,+ far: 100,+});++renderer.render(path.sample(3));+```++## Channels and time++`eye` and `target` accept a three-component vector or a keyframe channel.+`fov` and `roll` accept a number or a keyframe channel.+Channels support `LINEAR`, `STEP`, `SMOOTH` and `CUBICSPLINE`, using the existing animation sampler.++Cubic tangents use units per second. `fov` uses degrees, and `roll` uses radians around the viewing direction.+`up` is a constant vector. `near` and `far` are constant positive clipping distances.++The duration must be positive. Samples clamp to the duration unless `loop` is true.+Looping wraps negative times too. Matching end poses and tangents are the author's responsibility.++The path copies input vectors and keyframes. The returned `clip` is immutable. `JSON.stringify` can serialize it.++## Tracking and retained frames++The optional `targetMatrix` transforms the sampled target from local coordinates into world coordinates.+The eye remains in world coordinates. The caller supplies the current matrix explicitly, so seeking has no hidden playback state.++```js+const frame = {+ eye: new Float64Array(3),+ target: new Float64Array(3),+ up: new Float64Array(3),+};++path.sample(time, frame, { targetMatrix: graph.getNode('Actor').worldMatrix });+renderer.render(frame);+```++The output object and its vectors retain their identities. Samples still perform validation and allocate small temporary bookkeeping objects.+Without an output argument, each sample returns an independent frame.+Output vectors accept plain arrays, `Float32Array` or `Float64Array`. They must be writable and must not overlap.++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.++## Lens conventions++`fovFromFocalLength` computes vertical field of view from focal length and sensor height.+Both arguments use the same unit, normally millimeters. The default sensor height is 24 mm.+The helper matches Three.js focal-length projection when its effective sensor height is the same.+It does not add depth of field, focus pulls or lens distortion.++## Design++| Alternative | Tradeoff |+| --- | --- |+| Mutable controller advanced by delta time | Convenient playback, but hidden target state makes arbitrary seeks harder. |+| Immutable channels sampled at absolute time | Reuses clip interpolation and gives identical results for the same inputs. |++The implementation uses immutable channels. Tracking matrices are separate sample inputs, rather than callbacks stored in the path.+This API provides camera authoring primitives. It does not provide a visual timeline editor or automatic collision avoidance.++Primary reference: [Three.js PerspectiveCamera](https://threejs.org/docs/pages/PerspectiveCamera.html).diff --git a/package.json b/package.jsonindex 848784ca..38b60849 100644--- a/package.json+++ b/package.json@@ -26,7 +26,8 @@"docs/animation-mixer.md","docs/material-maps.md","docs/modeling.md",- "docs/scene-graph.md"+ "docs/scene-graph.md",+ "docs/camera-path.md"],"main": "./build/67.module.js","module": "./build/67.module.js",diff --git a/src/camera-path.js b/src/camera-path.jsnew file mode 100644index 00000000..4af5edab--- /dev/null+++ b/src/camera-path.js@@ -0,0 +1,172 @@+import { compileAnimationSampler, createAnimationClip } from './animation.js';++function cameraTrack(name, property, channel) {+ if (channel && typeof channel === 'object' && !Array.isArray(channel) && !ArrayBuffer.isView(channel)) {+ return { ...channel, target: name, property };+ }+ return { target: name, property, keyframes: [{ time: 0, value: channel }] };+}++function validateVector(vector, name) {+ if ((!Array.isArray(vector) && !ArrayBuffer.isView(vector)) || vector.length !== 3) {+ throw new TypeError(`${name} must contain three finite components.`);+ }+ for (const component of vector) {+ if (!Number.isFinite(component)) throw new RangeError(`${name} must contain three finite components.`);+ }+}++function validatePose(eye, target, up) {+ validateVector(eye, 'Camera eye');+ validateVector(target, 'Camera target');+ validateVector(up, 'Camera up');+ const horizontal = target[0] - eye[0];+ const vertical = target[1] - eye[1];+ const depth = target[2] - eye[2];+ const distance = Math.hypot(horizontal, vertical, depth);+ const upLength = Math.hypot(...up);+ if (!Number.isFinite(distance) || distance <= 1e-8 || !Number.isFinite(upLength) || upLength <= 1e-8) {+ throw new RangeError('Camera eye and target must be distinct, with a nonzero up vector.');+ }+ const alignment = Math.abs((horizontal / distance * (up[0] / upLength)) + (vertical / distance * (up[1] / upLength)) + (depth / distance * (up[2] / upLength)));+ if (!Number.isFinite(alignment) || alignment >= 1 - 1e-10) {+ throw new RangeError('Camera up must not be parallel to the viewing direction.');+ }+}++function validateLens(fov, near, far) {+ if (!Number.isFinite(fov) || fov <= 0 || fov >= 180) {+ throw new RangeError('Camera field of view must be between 0 and 180 degrees.');+ }+ if (!Number.isFinite(near) || !Number.isFinite(far) || near <= 0 || far <= near) {+ throw new RangeError('Camera clipping planes must satisfy 0 < near < far.');+ }+}++function validateWritableField(object, property) {+ const ownDescriptor = Object.getOwnPropertyDescriptor(object, property);+ let descriptor = ownDescriptor;+ let prototype = Object.getPrototypeOf(object);+ while (!descriptor && prototype !== null) {+ descriptor = Object.getOwnPropertyDescriptor(prototype, property);+ prototype = Object.getPrototypeOf(prototype);+ }+ if ((descriptor && (!('value' in descriptor) || !descriptor.writable)) || (!ownDescriptor && !Object.isExtensible(object))) {+ throw new TypeError('Camera output fields must be writable data properties.');+ }+}++function transformTarget(target, matrix) {+ if ((!Array.isArray(matrix) && !ArrayBuffer.isView(matrix)) || matrix.length !== 16 || !Array.from(matrix).every(Number.isFinite)) {+ throw new TypeError('Tracking requires a finite affine target matrix.');+ }+ if (matrix[3] !== 0 || matrix[7] !== 0 || matrix[11] !== 0 || matrix[15] !== 1) {+ throw new RangeError('Tracking requires an affine target matrix.');+ }+ const horizontal = target[0];+ const vertical = target[1];+ const depth = target[2];+ for (let axis = 0; axis < 3; axis++) {+ target[axis] = matrix[axis] * horizontal + matrix[axis + 4] * vertical + matrix[axis + 8] * depth + matrix[axis + 12];+ }+}++/** Vertical field of view in degrees; focal length and sensor height use the same unit. */+export function fovFromFocalLength(focalLength, { sensorHeight = 24 } = {}) {+ if (!Number.isFinite(focalLength) || focalLength <= 0 || !Number.isFinite(sensorHeight) || sensorHeight <= 0) {+ throw new RangeError('Focal length and sensor height must be positive and finite.');+ }+ const fov = 2 * Math.atan(sensorHeight / focalLength / 2) * 180 / Math.PI;+ validateLens(fov, 0.1, 100);+ return fov;+}++/** Absolute-time camera channels reuse the same interpolation as animation clips. */+export function createCameraPath({ duration, loop = false, eye, target = [0, 0, 0], fov = 45, roll = 0, up = [0, 1, 0], near = 0.1, far = 100 } = {}) {+ validateVector(up, 'Camera up');+ validateLens(45, near, far);+ if (Math.hypot(...up) <= 1e-8) throw new RangeError('Camera up must be nonzero.');+ const baseUp = Object.freeze(Array.from(up));+ const upLength = Math.hypot(...baseUp);+ const normalizedUp = baseUp.map(component => component / upLength);+ const clip = createAnimationClip({ duration, loop, tracks: [+ cameraTrack('eye', 'translation', eye),+ cameraTrack('target', 'translation', target),+ cameraTrack('fov', 'value', fov),+ cameraTrack('roll', 'value', roll),+ ] });+ for (const keyframe of clip.tracks[2].keyframes) validateLens(keyframe.value, near, far);+ const sampler = compileAnimationSampler(clip);+ const stagedEye = new Float64Array(3);+ const stagedTarget = new Float64Array(3);+ const stagedUp = new Float64Array(3);+ const direction = new Float64Array(3);++ function sample(time, output = { eye: [0, 0, 0], target: [0, 0, 0], up: [0, 0, 0] }, { targetMatrix } = {}) {+ const destinations = [output.eye, output.target, output.up];+ for (const destination of destinations) {+ if (!(Array.isArray(destination) || destination instanceof Float32Array || destination instanceof Float64Array) || destination.length !== 3) {+ throw new TypeError('Camera output needs writable three-component eye, target and up arrays.');+ }+ if (Object.isFrozen(destination)) throw new TypeError('Camera output arrays must be writable.');+ if (Array.isArray(destination)) {+ for (let axis = 0; axis < 3; axis++) {+ validateWritableField(destination, axis);+ }+ }+ }+ if (new Set(destinations).size !== 3 || Object.isFrozen(output)) {+ throw new TypeError('Camera output must be writable and its vectors must be distinct.');+ }+ for (let first = 0; first < destinations.length; first++) {+ for (let second = first + 1; second < destinations.length; second++) {+ const left = destinations[first];+ const right = destinations[second];+ if (ArrayBuffer.isView(left) && ArrayBuffer.isView(right) && left.buffer === right.buffer &&+ left.byteOffset < right.byteOffset + right.byteLength && right.byteOffset < left.byteOffset + left.byteLength) {+ throw new TypeError('Camera output vectors must not overlap in memory.');+ }+ }+ }+ for (const property of ['fov', 'near', 'far', 'projection']) {+ validateWritableField(output, property);+ }+ const tracks = sampler.sample(time);+ stagedEye.set(tracks[0].output);+ stagedTarget.set(tracks[1].output);+ if (targetMatrix !== undefined) transformTarget(stagedTarget, targetMatrix);+ validatePose(stagedEye, stagedTarget, baseUp);+ const fieldOfView = tracks[2].output[0];+ validateLens(fieldOfView, near, far);+ const angle = tracks[3].output[0];+ const directionLength = Math.hypot(stagedTarget[0] - stagedEye[0], stagedTarget[1] - stagedEye[1], stagedTarget[2] - stagedEye[2]);+ for (let axis = 0; axis < 3; axis++) direction[axis] = (stagedTarget[axis] - stagedEye[axis]) / directionLength;+ const cosine = Math.cos(angle);+ const sine = Math.sin(angle);+ const dot = direction[0] * normalizedUp[0] + direction[1] * normalizedUp[1] + direction[2] * normalizedUp[2];+ for (let axis = 0; axis < 3; axis++) {+ const next = (axis + 1) % 3;+ const last = (axis + 2) % 3;+ const cross = direction[next] * normalizedUp[last] - direction[last] * normalizedUp[next];+ stagedUp[axis] = normalizedUp[axis] * cosine + cross * sine + direction[axis] * dot * (1 - cosine);+ }+ const stagedVectors = [stagedEye, stagedTarget, stagedUp];+ for (let index = 0; index < destinations.length; index++) {+ if (destinations[index] instanceof Float32Array) {+ for (let axis = 0; axis < 3; axis++) stagedVectors[index][axis] = Math.fround(stagedVectors[index][axis]);+ }+ }+ validatePose(stagedEye, stagedTarget, stagedUp);+ for (let index = 0; index < destinations.length; index++) {+ for (let axis = 0; axis < 3; axis++) destinations[index][axis] = stagedVectors[index][axis];+ }+ output.fov = fieldOfView;+ output.near = near;+ output.far = far;+ output.projection = 'perspective';+ return output;+ }++ sample(0);+ return Object.freeze({ duration: clip.duration, loop: clip.loop, clip, sample });+}diff --git a/src/film.js b/src/film.jsindex 5bbe3bca..804a152c 100644--- a/src/film.js+++ b/src/film.js@@ -1,4 +1,5 @@import { mat4, quat, vec3 } from 'gl-matrix';+import { createCameraPath } from './camera-path.js';import { box, cylinder, sphere, torus } from './geometry.js';export const FILM_DURATION = 187;@@ -706,7 +707,33 @@ export function createFilmScenes() {// Camera endpoints belong to shots; reused sets never carry playback state.function shot(start, end, scene, eye, nextEye, target, nextTarget = target, fov = [40, 38], monochrome = 0, exposure = 0.95) {- return { start, end, scene, eye: [eye, nextEye], target: [target, nextTarget], fov, monochrome, exposure };+ const duration = end - start;+ const channel = (first, last) => ({ interpolation: 'SMOOTH', keyframes: [+ { time: 0, value: first },+ { time: duration, value: last },+ ] });+ let eyeChannel = channel(eye, nextEye);+ if (['atom', 'gadget'].includes(scene)) {+ const horizontalTravel = nextEye[0] - eye[0];+ const depthTravel = nextEye[2] - eye[2];+ const midpoint = eye.map((value, axis) => (value + nextEye[axis]) / 2);+ midpoint[0] -= depthTravel * 0.14;+ midpoint[2] += horizontalTravel * 0.14;+ const tangent = eye.map((value, axis) => (nextEye[axis] - value) * 1.5 / duration);+ eyeChannel = { interpolation: 'CUBICSPLINE', keyframes: [+ { time: 0, value: eye, inTangent: [0, 0, 0], outTangent: [0, 0, 0] },+ { time: duration / 2, value: midpoint, inTangent: tangent, outTangent: tangent },+ { time: duration, value: nextEye, inTangent: [0, 0, 0], outTangent: [0, 0, 0] },+ ] };+ }+ const cameraPath = createCameraPath({+ duration,+ eye: eyeChannel,+ target: channel(target, nextTarget),+ fov: channel(fov[0], fov[1]),+ far: 600,+ });+ return { start, end, scene, eye: [eye, nextEye], target: [target, nextTarget], fov, monochrome, exposure, cameraPath };}export const FILM_SHOTS = [@@ -750,21 +777,12 @@ function smoothstep(value) {return bounded * bounded * (3 - 2 * bounded);}-function interpolate(first, second, fraction) {- return first + (second - first) * fraction;-}-export function sampleFilm(time) {if (!Number.isFinite(time)) throw new TypeError('Film time must be 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 eased = smoothstep((boundedTime - selected.start) / (selected.end - selected.start));- const camera = {- eye: selected.eye[0].map((value, axis) => interpolate(value, selected.eye[1][axis], eased)),- target: selected.target[0].map((value, axis) => interpolate(value, selected.target[1][axis], eased)),- fov: interpolate(...selected.fov, eased),- };+ const camera = selected.cameraPath.sample(boundedTime - selected.start);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.jsindex cad5d473..0deb5d8e 100644--- a/src/index.js+++ b/src/index.js@@ -10,5 +10,6 @@ export { RENDER_PRESETS, planRenderSize, estimateFrameBytes } from './budget.js'export { assemblyOffset } from './assembly.js';export { cameraView, fitOrthographicHeight } 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-path.test.js b/tests/camera-path.test.jsnew file mode 100644index 00000000..3008f682--- /dev/null+++ b/tests/camera-path.test.js@@ -0,0 +1,101 @@+import test from 'node:test';+import assert from 'node:assert/strict';+import { PerspectiveCamera, Matrix4, Vector3 } from 'three';+import { createCameraPath, fovFromFocalLength } from '../src/camera-path.js';++function close(actual, expected, tolerance = 1e-10) {+ assert.equal(actual.length, expected.length);+ actual.forEach((value, index) => assert.ok(Math.abs(value - expected[index]) < tolerance, `${value} differs from ${expected[index]}`));+}++test('lens conversion agrees with a Three camera with a 24mm sensor height', () => {+ const reference = new PerspectiveCamera(45, 35 / 24);+ for (const focalLength of [18, 35, 50, 85]) {+ reference.setFocalLength(focalLength);+ assert.ok(Math.abs(fovFromFocalLength(focalLength) - reference.fov) < 1e-12);+ }+ assert.throws(() => fovFromFocalLength(0), /positive/);+});++test('camera follows a Hermite arc and is independent of seek order and input mutation', () => {+ const keyframes = [+ { time: 0, value: [0, 1, 4], inTangent: [0, 0, 0], outTangent: [2, 0, 0] },+ { time: 2, value: [2, 1, 4], inTangent: [0, 0, 0], outTangent: [0, 0, 0] },+ ];+ const path = createCameraPath({ duration: 2, eye: { interpolation: 'CUBICSPLINE', keyframes } });+ const midpoint = path.sample(1);+ close(midpoint.eye, [1.5, 1, 4]);+ keyframes[0].value[0] = 100;+ path.sample(2);+ assert.deepEqual(path.sample(1), midpoint);+ assert.notEqual(path.sample(1).eye, midpoint.eye);+ close(path.sample(-10).eye, [0, 1, 4]);+ close(path.sample(20).eye, [2, 1, 4]);+});++test('tracking transforms a local target offset and roll changes the up vector', () => {+ const matrix = new Matrix4().makeRotationY(Math.PI / 2).setPosition(2, 0, 0);+ const path = createCameraPath({ duration: 1, eye: [2, 0, 5], target: [1, 0, 0], roll: Math.PI / 2 });+ const frame = path.sample(0, undefined, { targetMatrix: matrix.elements });+ close(frame.target, new Vector3(1, 0, 0).applyMatrix4(matrix).toArray());+ close(frame.up, [1, 0, 0]);+});++test('retained outputs preserve identity and rejected samples leave the frame untouched', () => {+ const path = createCameraPath({ duration: 1, eye: [0, 0, 4] });+ const output = { eye: new Float32Array(3), target: new Float32Array(3), up: new Float32Array(3) };+ assert.equal(path.sample(0.5, output), output);+ const before = structuredClone(output);+ const eye = output.eye;+ assert.throws(() => path.sample(NaN, output), /finite/);+ assert.deepEqual(output, before);+ assert.equal(output.eye, eye);+ const collapse = new Matrix4().makeTranslation(0, 0, 4).elements;+ assert.throws(() => path.sample(0, output, { targetMatrix: collapse }), /distinct/);+ assert.deepEqual(output, before);+});++test('Float32 precision collapse is rejected before publishing outputs', () => {+ const path = createCameraPath({ duration: 1, eye: [1e10, 0, 0], target: [1e10 + 1, 0, 0] });+ const output = { eye: new Float32Array(3), target: new Float32Array(3), up: new Float32Array(3) };+ assert.throws(() => path.sample(0, output), /distinct/);+ close(output.eye, [0, 0, 0]);+});++test('overlapping views and readonly output components reject before any writes', () => {+ const path = createCameraPath({ duration: 1, eye: [0, 0, 4] });+ const buffer = new ArrayBuffer(48);+ const output = { eye: new Float32Array(buffer, 0, 3), target: new Float32Array(buffer, 8, 3), up: [0, 0, 0] };+ assert.throws(() => path.sample(0, output), /overlap/);+ const readonly = { eye: [9, 9, 9], target: [8, 8, 8], up: [7, 7, 7] };+ Object.defineProperty(readonly.target, '1', { writable: false });+ assert.throws(() => path.sample(0, readonly), /writable/);+ assert.deepEqual(readonly.eye, [9, 9, 9]);+ const sealed = Object.seal({ eye: [9, 9, 9], target: [8, 8, 8], up: [7, 7, 7] });+ assert.throws(() => path.sample(0, sealed), /writable/);+ assert.deepEqual(sealed.eye, [9, 9, 9]);+ const prototype = {};+ Object.defineProperty(prototype, 'fov', { value: 45, writable: false });+ const inherited = Object.assign(Object.create(prototype), { eye: [9, 9, 9], target: [8, 8, 8], up: [7, 7, 7] });+ assert.throws(() => path.sample(0, inherited), /writable/);+ assert.deepEqual(inherited.eye, [9, 9, 9]);+});++test('looping and cubic lens overshoot obey camera domain constraints', () => {+ const loop = createCameraPath({ duration: 2, loop: true, eye: {+ keyframes: [{ time: 0, value: [0, 0, 4] }, { time: 2, value: [2, 0, 4] }],+ } });+ assert.deepEqual(loop.sample(-0.5), loop.sample(1.5));+ const path = createCameraPath({ duration: 2, eye: [0, 0, 4], fov: {+ interpolation: 'CUBICSPLINE', keyframes: [+ { time: 0, value: 45, inTangent: 0, outTangent: 600 },+ { time: 2, value: 45, inTangent: -600, outTangent: 0 },+ ],+ } });+ const output = path.sample(0);+ const before = structuredClone(output);+ assert.throws(() => path.sample(1, output), /field of view/);+ assert.deepEqual(output, before);+ assert.throws(() => createCameraPath({ duration: 1, eye: [0, 4, 0] }), /parallel/);+ assert.throws(() => createCameraPath({ duration: 1, eye: [0, 0, 4], far: 0.05 }), /clipping/);+});