Skip to content

armgit / 67.js

Public Imported from GitHub
0

3D engine that AI agents drive

Add orthographic camera helpers and an animated flat vector viewer

Nguyen Xuan And72e2751475f
diff --git a/src/camera.js b/src/camera.js
new file mode 100644
index 00000000..bbe50c70
--- /dev/null
+++ b/src/camera.js
@@ -0,0 +1,48 @@
+import { mat4, vec3 } from 'gl-matrix';
+
+export function applyProjection(matrix, frame, aspect, { world = false } = {}) {
+ if (!Number.isFinite(aspect) || aspect <= 0) throw new RangeError('Camera aspect must be positive and finite');
+ if (frame.projection === undefined && frame.fov === undefined) return matrix;
+ const near = frame.near ?? 0.1;
+ const far = frame.far ?? (world ? 600 : 100);
+ if (!Number.isFinite(near) || !Number.isFinite(far) || near <= 0 || far <= near) throw new RangeError('Camera clipping planes must satisfy 0 < near < far');
+ if (frame.projection === 'orthographic') {
+ const height = frame.orthographicHeight ?? 4;
+ if (!Number.isFinite(height) || height <= 0) throw new RangeError('Orthographic height must be positive and finite');
+ const halfHeight = height / 2;
+ return mat4.ortho(matrix, -halfHeight * aspect, halfHeight * aspect, -halfHeight, halfHeight, near, far);
+ }
+ if (frame.projection && frame.projection !== 'perspective') throw new RangeError(`Unsupported camera projection: ${frame.projection}`);
+ const fov = frame.fov ?? 45;
+ if (!Number.isFinite(fov) || fov <= 0 || fov >= 180) throw new RangeError('Camera field of view must be between 0 and 180 degrees');
+ return mat4.perspective(matrix, fov * Math.PI / 180, aspect, near, far);
+}
+
+const viewDirections = { front: [0, 0, 1], right: [1, 0, 0], top: [0, 1, 0], perspective: [0.58, 0.34, 0.74] };
+
+export function cameraView(name = 'front', { target = [0, 1.5, 0], height = 3.8, distance = 8 } = {}) {
+ const direction = viewDirections[name];
+ if (!direction) throw new RangeError(`Unsupported camera view: ${name}`);
+ if (!Number.isFinite(height) || height <= 0) throw new RangeError('Orthographic height must be positive and finite');
+ if (target.length !== 3 || !target.every(Number.isFinite) || !Number.isFinite(distance) || distance <= 0) throw new RangeError('Camera target and positive distance must be finite');
+ const unitDirection = vec3.normalize(vec3.create(), direction);
+ const eye = Array.from(vec3.scaleAndAdd(vec3.create(), target, unitDirection, distance));
+ return { eye, target: [...target], up: name === 'top' ? [0, 0, -1] : [0, 1, 0], projection: name === 'perspective' ? 'perspective' : 'orthographic', orthographicHeight: height, fov: 45 };
+}
+
+export function fitOrthographicHeight(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');
+ if (bounds.minimum.length !== 3 || bounds.maximum.length !== 3 || !bounds.minimum.every(Number.isFinite) || !bounds.maximum.every((value, axis) => Number.isFinite(value) && value >= bounds.minimum[axis])) throw new RangeError('Fit bounds must be finite and ordered');
+ const basis = mat4.lookAt(mat4.create(), view.eye, view.target, view.up ?? [0, 1, 0]);
+ const minimum = [Infinity, Infinity];
+ const maximum = [-Infinity, -Infinity];
+ for (let corner = 0; corner < 8; corner++) {
+ const point = [0, 1, 2].map(axis => corner & (1 << axis) ? bounds.maximum[axis] : bounds.minimum[axis]);
+ const projected = vec3.transformMat4(vec3.create(), point, basis);
+ for (let axis = 0; axis < 2; axis++) {
+ minimum[axis] = Math.min(minimum[axis], projected[axis]);
+ maximum[axis] = Math.max(maximum[axis], projected[axis]);
+ }
+ }
+ return Math.max(maximum[1] - minimum[1], (maximum[0] - minimum[0]) / aspect) * padding;
+}
diff --git a/src/canvas2d.js b/src/canvas2d.js
new file mode 100644
index 00000000..1e2f1f0a
--- /dev/null
+++ b/src/canvas2d.js
@@ -0,0 +1,118 @@
+import { mat4, quat } from 'gl-matrix';
+
+function mesh(positions, indices) {
+ const normals = [];
+ for (let index = 0; index < positions.length / 3; index++) normals.push(0, 0, 1);
+ return { positions: new Float32Array(positions), normals: new Float32Array(normals), indices: new Uint32Array(indices) };
+}
+
+export function disk2D(segments = 96, innerRadius = 0) {
+ const positions = [];
+ const indices = [];
+ if (innerRadius === 0) {
+ positions.push(0, 0, 0);
+ for (let index = 0; index <= segments; index++) {
+ const angle = index / segments * Math.PI * 2;
+ positions.push(Math.cos(angle), Math.sin(angle), 0);
+ }
+ for (let index = 0; index < segments; index++) indices.push(0, index + 1, index + 2);
+ } else {
+ for (let index = 0; index <= segments; index++) {
+ const angle = index / segments * Math.PI * 2;
+ for (const radius of [innerRadius, 1]) positions.push(Math.cos(angle) * radius, Math.sin(angle) * radius, 0);
+ }
+ for (let index = 0; index < segments; index++) {
+ const first = index * 2;
+ indices.push(first, first + 1, first + 2, first + 1, first + 3, first + 2);
+ }
+ }
+ return mesh(positions, indices);
+}
+
+export function roundedRect2D(radius = 0.08, segments = 12) {
+ const positions = [0, 0, 0];
+ const indices = [];
+ for (let corner = 0; corner < 4; corner++) {
+ const angle = corner * Math.PI / 2;
+ const center = [Math.cos(angle + Math.PI / 4) > 0 ? 0.5 - radius : -0.5 + radius, Math.sin(angle + Math.PI / 4) > 0 ? 0.5 - radius : -0.5 + radius];
+ for (let index = 0; index <= segments; index++) {
+ const pointAngle = angle + index / segments * Math.PI / 2;
+ positions.push(center[0] + Math.cos(pointAngle) * radius, center[1] + Math.sin(pointAngle) * radius, 0);
+ }
+ }
+ const count = positions.length / 3 - 1;
+ for (let index = 0; index < count; index++) indices.push(0, index + 1, (index + 1) % count + 1);
+ return mesh(positions, indices);
+}
+
+export function createCanvas2D() {
+ const geometries = {
+ rectangle: mesh([-0.5, -0.5, 0, 0.5, -0.5, 0, 0.5, 0.5, 0, -0.5, 0.5, 0], [0, 1, 2, 0, 2, 3]),
+ rounded: roundedRect2D(),
+ disk: disk2D(),
+ ring: disk2D(144, 0.987),
+ };
+ const colors = {
+ paper: [0.83, 0.85, 0.82], ink: [0.022, 0.027, 0.03], purple: [0.31, 0.16, 0.57], acid: [0.69, 0.91, 0.08], pale: [0.52, 0.61, 0.59], white: [0.95, 0.96, 0.92],
+ };
+ const parts = [];
+ const animated = [];
+ function add(name, shape, position, size, color, roll = 0) {
+ const matrix = mat4.fromRotationTranslationScale(mat4.create(), quat.fromEuler(quat.create(), 0, 0, roll * 180 / Math.PI), position, [size[0], size[1], 1]);
+ const part = { name, geometry: geometries[shape], matrix, material: { tag: 'unlit', color: colors[color], metallic: 0, roughness: 1, emission: 0 } };
+ parts.push(part);
+ return part;
+ }
+ function line(name, start, end, depth, width, color) {
+ const delta = end.map((value, axis) => value - start[axis]);
+ return add(name, 'rectangle', [(start[0] + end[0]) / 2, (start[1] + end[1]) / 2, depth], [Math.hypot(...delta), width], color, Math.atan2(delta[1], delta[0]));
+ }
+ add('Poster paper', 'rounded', [0, 0, 0], [4, 5], 'paper');
+ add('Purple upper inset', 'rounded', [0, 0.65, 0.01], [3.6, 3.25], 'purple');
+ add('Orbital lime disk', 'disk', [0, 0.46, 0.02], [1.05, 1.05], 'acid');
+ add('Orbital center', 'disk', [0, 0.46, 0.025], [0.11, 0.11], 'ink');
+ for (let index = 0; index < 3; index++) add('Orbital ellipse', 'ring', [0, 0.46, 0.03 + index * 0.002], [1.55, 0.6 + index * 0.26], 'white', index * Math.PI / 3);
+ for (let index = 0; index < 48; index++) {
+ const angle = index / 48 * Math.PI * 2;
+ const radius = 1.26;
+ line('Radial registration mark', [Math.cos(angle) * radius, 0.46 + Math.sin(angle) * radius], [Math.cos(angle) * (radius + (index % 4 === 0 ? 0.09 : 0.035)), 0.46 + Math.sin(angle) * (radius + (index % 4 === 0 ? 0.09 : 0.035))], 0.04, 0.008, 'ink');
+ }
+ for (let index = 0; index < 4; index++) {
+ const part = add('Orbiting vector dot', 'disk', [0, 0, 0.05], [0.068, 0.068], index % 2 ? 'acid' : 'white');
+ animated.push({ part, index });
+ }
+ const digitSegments = [[-0.09, 0.12, 0.18, 0.035], [-0.09, 0, 0.18, 0.035], [-0.09, -0.12, 0.18, 0.035], [-0.19, 0.06, 0.035, 0.13], [-0.19, -0.06, 0.035, 0.13], [0.01, 0.06, 0.035, 0.13], [0.01, -0.06, 0.035, 0.13]];
+ for (const [horizontal, visible] of [[-1.25, [0, 1, 2, 3, 4, 6]], [-0.94, [0, 5, 6]]]) {
+ for (const segment of visible) {
+ const [offsetX, offsetY, width, height] = digitSegments[segment];
+ add('Vector 67 digit', 'rectangle', [horizontal + offsetX, 1.98 + offsetY, 0.06], [width, height], 'white');
+ }
+ }
+ for (let index = 0; index < 3; index++) add('Poster header dot', 'disk', [1.09 + index * 0.19, 1.98, 0.06], [0.038, 0.038], 'acid');
+ add('Waveform strip', 'rounded', [0, -1.58, 0.01], [3.6, 0.88], 'ink');
+ for (let index = 0; index < 47; index++) {
+ const start = -1.58 + index / 47 * 3.16;
+ const end = -1.58 + (index + 1) / 47 * 3.16;
+ line('Signal waveform', [start, -1.58 + Math.sin(index * 0.34) * 0.17], [end, -1.58 + Math.sin((index + 1) * 0.34) * 0.17], 0.02, 0.022, 'acid');
+ }
+ for (let index = 0; index < 29; index++) add('Vector footer code', 'rectangle', [-1.65 + index * 0.037, -2.22, 0.01], [index % 3 === 0 ? 0.022 : 0.01, index % 4 === 0 ? 0.16 : 0.11], 'ink');
+ line('Footer direction shaft', [0.97, -2.22], [1.55, -2.22], 0.02, 0.024, 'ink');
+ line('Footer arrow upper', [1.4, -2.08], [1.55, -2.22], 0.02, 0.024, 'ink');
+ line('Footer arrow lower', [1.4, -2.36], [1.55, -2.22], 0.02, 0.024, 'ink');
+ function animate(time) {
+ if (!Number.isFinite(time)) throw new TypeError('Canvas timeline time must be finite');
+ const phase = time / 8 * Math.PI * 2;
+ for (const { part, index } of animated) {
+ const angle = phase + index * Math.PI / 2;
+ const orbit = index % 3;
+ const roll = orbit * Math.PI / 3;
+ const horizontal = Math.cos(angle) * 1.55;
+ const vertical = Math.sin(angle) * (0.6 + orbit * 0.26);
+ part.matrix[12] = Math.cos(roll) * horizontal - Math.sin(roll) * vertical;
+ part.matrix[13] = 0.46 + Math.sin(roll) * horizontal + Math.cos(roll) * vertical;
+ }
+ return animated.map(item => item.part);
+ }
+ animate(0);
+ return { parts, duration: 8, animate, bounds: { minimum: [-2, -2.5, 0], maximum: [2, 2.5, 0.06] }, camera: { eye: [0, 0, 8], target: [0, 0, 0], up: [0, 1, 0], projection: 'orthographic', orthographicHeight: 5.8 } };
+}
diff --git a/src/view2d.css b/src/view2d.css
new file mode 100644
index 00000000..25b1c868
--- /dev/null
+++ b/src/view2d.css
@@ -0,0 +1,58 @@
+:root { font: 14px/1.5 Inter, ui-sans-serif, system-ui, sans-serif; color: #eef1ef; background: #1e2327; color-scheme: dark; }
+* { box-sizing: border-box; }
+body { margin: 0; }
+button, select { font: inherit; }
+button, select, label, nav, footer, .brand { user-select: none; }
+button { border: 0; border-radius: 8px; background: #ffffff0b; color: inherit; padding: 10px 14px; cursor: pointer; }
+button:hover { background: #ffffff18; }
+button[aria-pressed=true] { color: #c5f091; background: #c5f09112; }
+button:disabled { opacity: .45; cursor: default; }
+:focus-visible { outline: 2px solid #c5f091; outline-offset: 4px; }
+.workspace { height: 100svh; min-height: 560px; display: flex; flex-direction: column; padding: 24px 30px 16px; gap: 16px; }
+.toolbar { display: flex; flex-wrap: wrap; align-items: center; gap: 16px; }
+.brand { color: #f1f4f0; text-decoration: none; font-weight: 750; font-size: 28px; letter-spacing: -1.8px; }
+.brand span { color: #aab4b7; font-weight: 450; }
+h1 { font-size: 16px; font-weight: 500; margin: 0 12px 0 0; }
+.scene-picker { display: flex; align-items: center; gap: 10px; color: #b6c2c5; }
+select { color: #eef1ef; border: 0; background: #ffffff0b; border-radius: 8px; padding: 9px 12px; }
+nav { display: flex; gap: 4px; }
+[hidden] { display: none !important; }
+.toolbar-actions { display: flex; gap: 8px; margin-left: auto; }
+.primary { color: #213016; background: #c5f091; font-weight: 600; }
+.primary:hover { background: #d9f9b3; }
+.primary span { padding-left: 14px; }
+.stage { position: relative; flex: 1; min-height: 250px; overflow: hidden; border-radius: 18px; background: #252b30; }
+#viewport { display: block; width: 100%; height: 100%; touch-action: none; cursor: grab; outline-offset: -4px; }
+#viewport:active { cursor: grabbing; }
+.scene-caption { position: absolute; bottom: 18px; left: 22px; display: flex; flex-direction: column; gap: 3px; pointer-events: none; color: #eef1ef; }
+.scene-caption strong { font-weight: 500; font-size: 15px; }
+.scene-caption span { color: #b2bfc4; font-size: 11px; }
+.timeline { display: flex; align-items: center; gap: 14px; min-height: 44px; }
+.timeline label { color: #bec9cc; font-size: 12px; }
+input[type=range] { flex: 1; min-width: 80px; accent-color: #c5f091; cursor: pointer; }
+output { font-variant-numeric: tabular-nums; color: #bec9cc; min-width: 98px; font-size: 12px; }
+.metrics { color: #99a8af; font-size: 11px; }
+.hint { display: flex; gap: 20px; margin: 0; color: #98a6ad; font-size: 11px; }
+.hint a { margin-left: auto; color: #bec9cc; text-decoration: none; }
+.notice { position: absolute; bottom: 80px; left: 50%; transform: translateX(-50%); background: #1e2327; padding: 12px 18px; border-radius: 8px; max-width: 90%; }
+.export-view .workspace { padding: 0; gap: 0; min-height: 0; }
+.export-view .toolbar, .export-view .timeline, .export-view .hint, .export-view .scene-caption { display: none; }
+.export-view .stage { border-radius: 0; }
+@media (max-width: 750px) {
+ .workspace { padding: 14px 14px 12px; gap: 12px; min-height: 650px; }
+ .toolbar { gap: 10px; }
+ h1 { font-size: 14px; margin: 0; }
+ .scene-picker { margin-left: auto; font-size: 12px; }
+ select { padding: 8px; max-width: 130px; }
+ .toolbar-actions { margin-left: 0; }
+ nav { order: 2; flex: 1; }
+ nav button { padding: 9px 11px; font-size: 12px; }
+ .toolbar-actions button { padding: 9px 12px; font-size: 12px; }
+ .stage { min-height: 310px; }
+ .timeline { flex-wrap: wrap; gap: 9px; }
+ .timeline label { display: none; }
+ .metrics { width: 100%; text-align: right; }
+ .scene-caption { bottom: 12px; left: 16px; }
+ .hint { font-size: 10px; }
+}
+@media (prefers-reduced-motion: reduce) { * { scroll-behavior: auto; } }
diff --git a/src/view2d.js b/src/view2d.js
new file mode 100644
index 00000000..fddfdde2
--- /dev/null
+++ b/src/view2d.js
@@ -0,0 +1,205 @@
+import './view2d.css';
+import { vec3 } from 'gl-matrix';
+import { Renderer67 } from './renderer.js';
+import { createModel } from './model.js';
+import { createCanvas2D } from './canvas2d.js';
+import { cameraView, fitOrthographicHeight } from './camera.js';
+
+const canvas = document.querySelector('#viewport');
+const parameters = new URLSearchParams(location.search);
+const exporting = parameters.get('export') === '1';
+const reducedMotion = matchMedia('(prefers-reduced-motion: reduce)');
+const poster = createCanvas2D();
+const model = createModel();
+const modelBounds = { minimum: [-1.241, 0.0515, -0.761], maximum: [1.241, 2.876, 0.934] };
+const initialView = ['front', 'top', 'right', 'perspective'].includes(parameters.get('view')) ? parameters.get('view') : 'front';
+const state = { scene: parameters.get('scene') === 'model' ? 'model' : 'poster', view: initialView, time: 0, playing: false, zoom: 1, pan: [0, 0], exporting };
+let renderer;
+let requestedFrame = 0;
+let lastFrameTime = 0;
+let dragging;
+
+if (exporting) {
+ document.body.classList.add('export-view');
+ const width = Number(parameters.get('width'));
+ const height = Number(parameters.get('height'));
+ if (width > 0 && height > 0) {
+ document.querySelector('.workspace').style.width = `${width}px`;
+ document.querySelector('.workspace').style.height = `${height}px`;
+ }
+}
+
+function notify(message, failure = false) {
+ const notice = document.querySelector('#notice');
+ notice.textContent = `${failure ? '⚠' : '✓'} ${message}`;
+ notice.hidden = false;
+}
+
+function camera() {
+ const aspect = Math.max(1, canvas.clientWidth) / Math.max(1, canvas.clientHeight);
+ const target = state.scene === 'poster' ? [0, 0, 0] : [0, 1.46, 0];
+ const view = cameraView(state.scene === 'poster' ? 'front' : state.view, { target, distance: 7.8 });
+ const bounds = state.scene === 'poster' ? poster.bounds : modelBounds;
+ const fitted = fitOrthographicHeight(bounds, view, aspect, state.scene === 'poster' ? 1.14 : 1.2);
+ view.orthographicHeight = fitted * state.zoom;
+ const forward = vec3.normalize(vec3.create(), vec3.subtract(vec3.create(), view.target, view.eye));
+ const right = vec3.normalize(vec3.create(), vec3.cross(vec3.create(), forward, view.up));
+ const shift = vec3.scale(vec3.create(), right, state.pan[0]);
+ vec3.scaleAndAdd(shift, shift, view.up, state.pan[1]);
+ view.target = view.target.map((value, axis) => value + shift[axis]);
+ view.eye = view.eye.map((value, axis) => value + shift[axis]);
+ if (view.projection === 'perspective') {
+ const distance = Math.max(5, fitted * 1.55) * state.zoom;
+ const direction = vec3.normalize(vec3.create(), vec3.subtract(vec3.create(), view.eye, view.target));
+ view.eye = Array.from(vec3.scaleAndAdd(vec3.create(), view.target, direction, distance));
+ }
+ return { ...view, armorColor: [0.73, 0.43, 0.065], armorSurface: [0.62, 0.43], exposure: 1, time: state.time, assemblyAmount: 0 };
+}
+
+function renderAt(time) {
+ if (!renderer || !Number.isFinite(time)) return;
+ state.time = Math.max(0, Math.min(poster.duration, time));
+ if (state.scene === 'poster') {
+ const changed = poster.animate(state.time);
+ renderer.updateParts(changed, { shadows: false });
+ }
+ renderer.render(camera());
+ document.querySelector('#time').value = String(state.time);
+ document.querySelector('#time-value').textContent = `${state.time.toFixed(2)} / ${poster.duration.toFixed(2)} s`;
+}
+
+function tick(time) {
+ requestedFrame = 0;
+ if (document.hidden) return;
+ if (state.playing) {
+ state.time = (state.time + Math.min((time - lastFrameTime) / 1000, 0.05)) % poster.duration;
+ }
+ lastFrameTime = time;
+ renderAt(state.time);
+ if (state.playing) invalidate();
+}
+
+function invalidate() {
+ if (!requestedFrame && renderer && !document.hidden) requestedFrame = requestAnimationFrame(tick);
+}
+
+function setPlaying(playing) {
+ state.playing = playing;
+ lastFrameTime = performance.now();
+ const button = document.querySelector('#play');
+ button.textContent = playing ? 'Ⅱ Pause' : '▶ Play';
+ button.setAttribute('aria-label', playing ? 'Pause timeline' : 'Play timeline');
+ invalidate();
+}
+
+function initialize() {
+ setPlaying(false);
+ renderer?.dispose();
+ const parts = state.scene === 'poster' ? poster.parts : model;
+ renderer = new Renderer67(canvas, parts, { ground: false, samples: 4, pixelRatio: exporting ? 1 : 1.25, memoryBudgetMiB: 192 });
+ document.querySelector('#scene').value = state.scene;
+ document.querySelector('#view-controls').hidden = state.scene === 'poster';
+ document.querySelectorAll('[data-view]').forEach(control => control.setAttribute('aria-pressed', String(control.dataset.view === state.view)));
+ document.querySelector('#scene-title').textContent = state.scene === 'poster' ? 'Orbital field' : 'WALL·E study';
+ document.querySelector('#view-title').textContent = state.scene === 'poster' ? 'Flat vector geometry · orthographic' : `${state.view[0].toUpperCase()}${state.view.slice(1)} · ${state.view === 'perspective' ? 'perspective' : 'orthographic'}`;
+ document.querySelector('#metrics').textContent = `${parts.length} parts · ${renderer.batches.length} draws`;
+ document.querySelector('#time').disabled = state.scene === 'model';
+ document.querySelector('#play').disabled = state.scene === 'model';
+ canvas.setAttribute('aria-label', `${state.scene === 'poster' ? 'Vector poster' : 'WALL-E camera view'}. Drag to pan, scroll to zoom. Arrow keys pan, plus and minus zoom.`);
+ invalidate();
+}
+
+document.querySelector('#scene').addEventListener('change', event => {
+ state.scene = event.target.value;
+ state.pan = [0, 0];
+ state.zoom = 1;
+ initialize();
+});
+document.querySelectorAll('[data-view]').forEach(button => button.addEventListener('click', () => {
+ state.view = button.dataset.view;
+ state.pan = [0, 0];
+ state.zoom = 1;
+ document.querySelectorAll('[data-view]').forEach(control => control.setAttribute('aria-pressed', String(control === button)));
+ document.querySelector('#view-title').textContent = `${button.textContent} · ${state.view === 'perspective' ? 'perspective' : 'orthographic'}`;
+ invalidate();
+}));
+document.querySelector('#time').addEventListener('input', event => {
+ setPlaying(false);
+ renderAt(Number(event.target.value));
+});
+document.querySelector('#play').addEventListener('click', () => setPlaying(!state.playing));
+document.querySelector('#fit').addEventListener('click', () => {
+ state.zoom = 1;
+ state.pan = [0, 0];
+ invalidate();
+});
+
+canvas.addEventListener('pointerdown', event => {
+ if (event.button !== 0) return;
+ dragging = { id: event.pointerId, x: event.clientX, y: event.clientY };
+ canvas.setPointerCapture(event.pointerId);
+});
+canvas.addEventListener('pointermove', event => {
+ if (!dragging || dragging.id !== event.pointerId) return;
+ const scale = camera().orthographicHeight / canvas.clientHeight;
+ state.pan[0] -= (event.clientX - dragging.x) * scale;
+ state.pan[1] += (event.clientY - dragging.y) * scale;
+ dragging.x = event.clientX;
+ dragging.y = event.clientY;
+ invalidate();
+});
+for (const eventName of ['pointerup', 'pointercancel', 'lostpointercapture']) canvas.addEventListener(eventName, () => { dragging = null; });
+canvas.addEventListener('wheel', event => {
+ event.preventDefault();
+ state.zoom = Math.max(0.25, Math.min(4, state.zoom * Math.exp(event.deltaY * 0.001)));
+ invalidate();
+}, { passive: false });
+canvas.addEventListener('keydown', event => {
+ const movement = { ArrowLeft: [-0.15, 0], ArrowRight: [0.15, 0], ArrowUp: [0, 0.15], ArrowDown: [0, -0.15] }[event.key];
+ if (movement) {
+ event.preventDefault();
+ state.pan = state.pan.map((value, axis) => value + movement[axis] * state.zoom);
+ invalidate();
+ }
+ if (event.key === '+' || event.key === '=' || event.key === '-') {
+ event.preventDefault();
+ state.zoom = Math.max(0.25, Math.min(4, state.zoom * (event.key === '-' ? 1.1 : 0.9)));
+ invalidate();
+ }
+ if (event.key.toLowerCase() === 'f') document.querySelector('#fit').click();
+});
+
+document.querySelector('#download').addEventListener('click', () => {
+ renderAt(state.time);
+ canvas.toBlob(blob => {
+ if (!blob) return notify('PNG could not be created', true);
+ const url = URL.createObjectURL(blob);
+ const link = document.createElement('a');
+ link.href = url;
+ link.download = `67js-${state.scene}-${state.view}.png`;
+ link.click();
+ setTimeout(() => URL.revokeObjectURL(url), 1000);
+ notify('PNG saved');
+ }, 'image/png');
+});
+
+document.addEventListener('visibilitychange', () => {
+ if (document.hidden) {
+ if (requestedFrame) cancelAnimationFrame(requestedFrame);
+ requestedFrame = 0;
+ setPlaying(false);
+ } else invalidate();
+});
+reducedMotion.addEventListener('change', () => { if (reducedMotion.matches) setPlaying(false); });
+window.addEventListener('pagehide', () => {
+ if (requestedFrame) cancelAnimationFrame(requestedFrame);
+ renderer?.dispose();
+});
+new ResizeObserver(() => {
+ renderer?.resize();
+ invalidate();
+}).observe(canvas);
+
+window.__scene = { get renderer() { return renderer; }, renderAt, duration: poster.duration };
+window.__views = { state, poster, model, camera, renderAt, get renderer() { return renderer; } };
+try { initialize(); } catch (error) { notify(error.message, true); }
diff --git a/tests/camera.test.js b/tests/camera.test.js
new file mode 100644
index 00000000..93097702
--- /dev/null
+++ b/tests/camera.test.js
@@ -0,0 +1,52 @@
+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';
+
+function project(point, frame, aspect = 1) {
+ const projection = applyProjection(mat4.create(), frame, aspect);
+ const view = mat4.lookAt(mat4.create(), frame.eye, frame.target, frame.up);
+ return vec3.transformMat4(vec3.create(), point, mat4.multiply(mat4.create(), projection, view));
+}
+
+test('orthographic XY size is invariant with depth and perspective size is not', () => {
+ const frame = cameraView('front', { target: [0, 0, 0], height: 4 });
+ const close = project([1, 1, 2], frame);
+ const distant = project([1, 1, -2], frame);
+ assert.equal(close[0], distant[0]);
+ assert.equal(close[1], distant[1]);
+ assert.notEqual(close[2], distant[2]);
+ frame.projection = 'perspective';
+ assert.ok(project([1, 0, 2], frame)[0] > project([1, 0, -2], frame)[0]);
+});
+
+test('axis views keep the expected screen direction, including a usable top up vector', () => {
+ const front = cameraView('front', { target: [0, 0, 0] });
+ const right = cameraView('right', { target: [0, 0, 0] });
+ const top = cameraView('top', { target: [0, 0, 0] });
+ assert.ok(project([1, 0, 0], front)[0] > 0);
+ assert.ok(project([0, 1, 0], front)[1] > 0);
+ assert.ok(project([0, 0, -1], right)[0] > 0);
+ assert.ok(project([1, 0, 0], top)[0] > 0);
+ assert.ok(project([0, 0, -1], top)[1] > 0);
+ assert.ok(Array.from(project([1, 0, 1], top)).every(Number.isFinite));
+});
+
+test('projection preserves existing shifts for callers without explicit camera projection', () => {
+ const projection = mat4.perspective(mat4.create(), Math.PI / 4, 1.5, 0.1, 100);
+ projection[8] = -0.25;
+ const original = Array.from(projection);
+ assert.equal(applyProjection(projection, {}, 1.5), projection);
+ assert.deepEqual(Array.from(projection), original);
+});
+
+test('orthographic fit respects both horizontal and vertical extents', () => {
+ const bounds = { minimum: [-2, -1, -0.5], maximum: [2, 1, 0.5] };
+ const front = cameraView('front', { target: [0, 0, 0] });
+ assert.equal(fitOrthographicHeight(bounds, front, 2, 1), 2);
+ assert.equal(fitOrthographicHeight(bounds, front, 0.5, 1), 8);
+ assert.equal(fitOrthographicHeight(bounds, cameraView('top', { target: [0, 0, 0] }), 2, 1), 2);
+ assert.throws(() => applyProjection(mat4.create(), { projection: 'orthographic', orthographicHeight: 0 }, 1), /height/);
+ assert.throws(() => applyProjection(mat4.create(), { fov: 190 }, 1), /field/);
+ assert.throws(() => cameraView('diagonal'), /view/);
+});
diff --git a/tests/canvas2d.test.js b/tests/canvas2d.test.js
new file mode 100644
index 00000000..9c89ee91
--- /dev/null
+++ b/tests/canvas2d.test.js
@@ -0,0 +1,51 @@
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import { createCanvas2D, disk2D, roundedRect2D } from '../src/canvas2d.js';
+
+test('flat vector primitives have positive XY winding and no fictitious thickness', () => {
+ for (const geometry of [disk2D(), disk2D(96, 0.98), roundedRect2D()]) {
+ for (let vertex = 0; vertex < geometry.positions.length; vertex += 3) {
+ assert.equal(geometry.positions[vertex + 2], 0);
+ assert.deepEqual(Array.from(geometry.normals.slice(vertex, vertex + 3)), [0, 0, 1]);
+ }
+ for (let triangle = 0; triangle < geometry.indices.length; triangle += 3) {
+ const [first, second, third] = Array.from(geometry.indices.slice(triangle, triangle + 3), value => value * 3);
+ const positions = geometry.positions;
+ const area = (positions[second] - positions[first]) * (positions[third + 1] - positions[first + 1]) - (positions[second + 1] - positions[first + 1]) * (positions[third] - positions[first]);
+ assert.ok(area > 0, 'counterclockwise nondegenerate triangles');
+ }
+ }
+});
+
+test('2D poster is layered vector geometry with shared identities and deterministic reusable animation', () => {
+ const scene = createCanvas2D();
+ const geometries = new Set(scene.parts.map(part => part.geometry));
+ assert.equal(geometries.size, 4);
+ assert.ok(scene.parts.length > 100);
+ assert.ok(scene.parts.every(part => part.material.tag === 'unlit'));
+ const originalMatrices = scene.parts.map(part => part.matrix);
+ scene.animate(2);
+ const sample = scene.parts.map(part => Array.from(part.matrix));
+ scene.animate(5);
+ scene.animate(2);
+ assert.deepEqual(scene.parts.map(part => Array.from(part.matrix)), sample);
+ scene.parts.forEach((part, index) => assert.equal(part.matrix, originalMatrices[index]));
+ scene.animate(0);
+ const initial = scene.parts.map(part => Array.from(part.matrix));
+ scene.animate(scene.duration);
+ scene.parts.forEach((part, index) => part.matrix.forEach((value, axis) => assert.ok(Math.abs(value - initial[index][axis]) < 1e-6)));
+ let triangles = 0;
+ for (const part of scene.parts) {
+ triangles += part.geometry.indices.length / 3;
+ for (let vertex = 0; vertex < part.geometry.positions.length; vertex += 3) {
+ for (let axis = 0; axis < 3; axis++) {
+ const positions = part.geometry.positions;
+ const matrix = part.matrix;
+ const value = matrix[axis] * positions[vertex] + matrix[axis + 4] * positions[vertex + 1] + matrix[axis + 8] * positions[vertex + 2] + matrix[axis + 12];
+ assert.ok(value >= scene.bounds.minimum[axis] - 1e-6 && value <= scene.bounds.maximum[axis] + 1e-6);
+ }
+ }
+ }
+ console.log(JSON.stringify({ parts: scene.parts.length, geometries: geometries.size, triangles, bounds: scene.bounds }));
+ assert.ok(triangles < 5000);
+});
diff --git a/view2d.html b/view2d.html
new file mode 100644
index 00000000..6d495c4e
--- /dev/null
+++ b/view2d.html
@@ -0,0 +1,39 @@
+<!doctype html>
+<html lang="en">
+ <head>
+ <meta charset="UTF-8">
+ <meta name="viewport" content="width=device-width, initial-scale=1">
+ <meta name="theme-color" content="#1e2327">
+ <title>2D & orthographic views · 67.js</title>
+ </head>
+ <body>
+ <main class="workspace">
+ <header class="toolbar">
+ <a class="brand" href="/">67<span>.js</span></a>
+ <h1>2D & views</h1>
+ <label class="scene-picker">Scene <select id="scene"><option value="poster">Vector poster</option><option value="model">WALL·E</option></select></label>
+ <nav id="view-controls" aria-label="Camera view" hidden>
+ <button data-view="front" aria-pressed="true">Front</button>
+ <button data-view="top" aria-pressed="false">Top</button>
+ <button data-view="right" aria-pressed="false">Right</button>
+ <button data-view="perspective" aria-pressed="false">Perspective</button>
+ </nav>
+ <div class="toolbar-actions"><button id="fit">Fit view</button><button id="download" class="primary">Save PNG <span aria-hidden="true">↗</span></button></div>
+ </header>
+ <section class="stage" aria-label="Interactive scene">
+ <canvas id="viewport" tabindex="0" aria-label="Vector poster. Drag to pan, scroll to zoom. Arrow keys pan, plus and minus zoom."></canvas>
+ <div class="scene-caption"><strong id="scene-title">Orbital field</strong><span id="view-title">Flat vector geometry · orthographic</span></div>
+ <p class="notice" id="notice" role="status" hidden></p>
+ </section>
+ <footer class="timeline">
+ <button id="play" aria-label="Play timeline">▶ Play</button>
+ <label for="time" id="timeline-label">Timeline</label>
+ <input id="time" type="range" min="0" max="8" step="0.01" value="0">
+ <output id="time-value" for="time">0.00 / 8.00 s</output>
+ <span class="metrics" id="metrics"></span>
+ </footer>
+ <p class="hint">Drag to pan · Scroll to zoom · F to fit <a href="/object.html">Open 3D studio ↗</a></p>
+ </main>
+ <script type="module" src="/src/view2d.js"></script>
+ </body>
+</html>