feat(registry): add path-traced-3d example with raster preview and path-traced export (#7219)

* feat(registry): add path-traced-3d example with raster preview and path-traced export

An opt-in Three.js starter: previews with raster rendering and exports with
three-gpu-pathtracer, from one scene file. three 0.180.0, three-gpu-pathtracer
0.0.24 and three-mesh-bvh 0.9.5 ship as one local, pinned ES module with their
licences and a rebuild recipe, so renders make no network requests and 2D
projects never load the tracer.

Setup is one buildReady promise that awaits library readiness promises only
and ends with a throwaway frame and a one-pixel readback. Frames are drawn in
the hf-seek listener through waitUntil, each time from zero with a fixed
sample count. Math.random is seeded while the scene and tracer are built,
because object ids order light sampling and the tracer's noise textures come
from it.

Adds a skill reference and a docs guide for the setup and seek contract, the
frozen clock, why scheduler.yield() waits hang, and sample/bounce cost.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* fix(registry): list path-traced-3d in CLI docs and tighten its notes

Add the example's section to the CLI examples doc, which docs.test.ts
requires for every registry example. Throw if the tracer reports compiling
but exposes no compile promise, instead of spinning renderSample(). Say that
three's object uuids set the tracer's sort order, that later-created objects
need the seed too, and that Date and performance.now read the current seek
time during a render rather than staying at 0.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
James Russo
2026-11-05 06:40:37 +00:00
committed by GitHub
co-authored by Claude Opus 5.5
parent 898d0fb00b
commit d452a6fad4
26 changed files with 9617 additions and 6 deletions
+1
View File
@@ -15,6 +15,7 @@
"registry/blocks/**/lib/*.iife.js",
"registry/blocks/{glass-shard-title,code-slice-hero,cuboid-carousel,frost-sequence-camera-orbit,orbit-card}/**/*.{js,mjs}",
"registry/blocks/frost-sequence-camera-orbit/source/**",
"registry/examples/path-traced-3d/assets/vendor/*.min.js",
"chrome/",
"packages/cli/src/media-use/lib/svg-sanitize.mjs"
],
+1
View File
@@ -35,6 +35,7 @@ registry/blocks/cuboid-carousel/assets/addons/**/*.js
registry/blocks/orbit-card/assets/three.core.min.js
registry/blocks/orbit-card/assets/three.module.min.js
registry/blocks/orbit-card/assets/gsap-3.14.2.min.js
registry/examples/path-traced-3d/assets/vendor/three-path-tracer.min.js
# generated Lottie data: pretty-printing multiplies its size
registry/blocks/lottie-character-walk/assets/mascot.json
# repo-native skill examples with intentional pseudo-markup placeholders
+1 -1
View File
@@ -10,7 +10,7 @@ description: "Connect a seekable animation timeline to a custom HyperFrames host
A frame adapter answers one question: what state should an animation have at frame N?
Most composition authors do not implement this interface. HyperFrames already seeks registered GSAP, CSS, Anime.js, Lottie, Three.js, Web Animations, and TypeGPU animation through its browser runtime. Use the [GSAP guide](/guides/gsap-animation) for the normal authoring path.
Most composition authors do not implement this interface. HyperFrames already seeks registered GSAP, CSS, Anime.js, Lottie, Three.js, Web Animations, and TypeGPU animation through its browser runtime. Use the [GSAP guide](/guides/gsap-animation) for the normal authoring path. For a Three.js scene with a raster preview and a path-traced export, start from the [path-traced 3D example](/guides/path-tracing).
Use `FrameAdapter` when you are building a custom host around a seekable animation object.
+84
View File
@@ -0,0 +1,84 @@
---
title: "Path-Traced 3D"
description: "Preview a Three.js scene with fast raster frames, then export it path traced, with every frame identical however it is seeked."
---
Use the `path-traced-3d` example when a 3D shot needs real light: soft shadows, light bouncing between objects and reflections of the scene itself. It previews with ordinary Three.js raster rendering and exports with a path tracer, from the same scene file.
```bash Terminal
npx hyperframes init my-3d --example path-traced-3d
cd my-3d
npx hyperframes preview
```
The tracer is opt-in. A project gets it only by starting from this example, so 2D projects never load it.
## What is in the project
| File | Holds |
| --- | --- |
| `index.html` | The 1920×1080, 6-second root and its three variables |
| `assets/scene.js` | The scene and `poseAt(t)`, the only code that moves anything |
| `assets/render.js` | Setup, the seek handler and the tracer settings |
| `assets/vendor/three-path-tracer.min.js` | three 0.180.0, three-gpu-pathtracer 0.0.24 and three-mesh-bvh 0.9.5 as one local ES module, with their licences and a note on how to rebuild it |
Everything loads from the project folder, so a render never fetches a library from the network.
## Preview in raster, export path traced
| Variable | Default | Meaning |
| --- | --- | --- |
| `renderer` | `raster` | `raster` draws a frame in milliseconds. `path` traces it. |
| `samples` | `64` | Path samples per pixel, traced for every frame. |
| `bounces` | `4` | How many times a ray may bounce. |
Work in raster, then export once with the tracer:
```bash Terminal
npx hyperframes render --variables '{"renderer":"path","samples":64}' -o final.mp4
```
Path tracing costs far more than raster. Measured on an Apple M4 Max with a hardware GPU, an 8-second 720p clip took 10.8 s rasterized and 810.5 s path traced at 32 samples per pixel and 6 bounces. Noise falls with the square root of the samples, so halving it costs four times the samples, and every extra bounce makes each path longer.
<Note>
Without a hardware GPU, Chrome draws WebGL in software and the tracer is much slower: on SwiftShader its first shader run alone took about a minute at 320×180, longer than the default 45-second readiness wait. Check path mode at a small size with 1 or 2 samples, and raise the wait with `--timeout 170000` for `check` and `snapshot` or `--player-ready-timeout 180000` for `render`.
</Note>
## How it stays deterministic
HyperFrames seeks frames one by one, in any order and across several workers, so `render.js` follows these rules. Keep them when you change it.
- **Setup is one `window.__hf.buildReady` promise.** It builds the scene, compiles the shaders, sets up the tracer and draws one throwaway frame, because the first frame a renderer draws differs from later ones. It then reads one pixel back, so the GPU has really finished that first, slowest run before setup resolves.
- **Frames are drawn only in the `hf-seek` listener**, registered with `event.detail.waitUntil(promise)`. Nothing runs a render loop.
- **Each new time starts from zero.** The handler poses the scene for that time, rebuilds the tracer's copy of it and traces exactly `samples` passes. A seek back to the time already on screen does no work.
- **The tracer never waits on time.** `renderDelay` and `fadeDuration` are 0, because the tracer times them with a clock that does not move during a render.
- **Randomness is seeded.** Three's object uuids, which set the order the tracer sorts lights, meshes and textures in, and the tracer's noise textures come from `Math.random`, so the scene and the tracer are built under a fixed seed. Without it, every render worker draws different grain. Anything you add later, such as a model loaded during setup, must also be created under the seed.
### The frozen clock
During a render, `Date.now()` and `performance.now()` return the current seek time and do not move between seeks (they read 0 until the first seek), and `requestAnimationFrame` callbacks wait for a seek. The first seek waits for setup. Setup that waits for an animation frame or for the clock to advance never finishes. Composition code uses no timers of its own either. Await the library's readiness promise instead:
```js assets/render.js
await renderer.compileAsync(scene, camera);
```
three-gpu-pathtracer 0.0.24 shows its shader compilation only as the `isCompiling` flag. The promise behind that flag is three's `compileAsync`, so `render.js` awaits it in one helper, `tracerCompiled()`, whenever a `renderSample()` call leaves `isCompiling` set. It decides only when drawing may start, never what is drawn.
Do not wait with `scheduler.yield()`. Its continuations run ahead of timers, so a loop that yields until a compile finishes starves the timer `compileAsync` polls with, and the page never becomes ready. Do not swap `compileAsync` for the synchronous `compile` to hide that; fix the wait.
## Check a change
Seek to a time, an earlier time, then the first time again, and compare the two stills:
```bash Terminal
npx hyperframes snapshot --at 4,0,4 --no-end
```
The two stills at 4 s must be byte-identical. Then render a short clip and look at its frames. In the HyperFrames repository, `registry/examples/path-traced-3d/source/verify-render.mjs` runs these checks in both modes at 320×180 and checks the exported pixels.
## Related
- [Frame adapters](/concepts/frame-adapters) for how the runtime seeks Three.js
- [Variables](/concepts/variables) for `--variables` and batch renders
- [Determinism](/concepts/determinism) for the general rules
- [Performance](/guides/performance) for render speed
+1 -1
View File
@@ -54,7 +54,7 @@
"player:perf": "bun run --filter @hyperframes/player perf",
"format:check": "oxfmt --check .",
"knip": "knip",
"test:scripts": "node --import tsx --test scripts/animejs-v4-guidance.test.mjs scripts/check-tracked-artifacts.test.mjs scripts/check-registry-set-delta.test.mjs scripts/check-no-main-deletions.test.mjs scripts/check-pr-captures.test.mjs scripts/check-comment-citations.test.mjs scripts/comments-workflow.test.mjs scripts/comment-ratchet.test.mjs scripts/check-docs-snippet-motion.test.mjs scripts/registry-target-paths.test.mjs scripts/check-workspace-contracts.test.mjs scripts/check-media-use-copy-parity.test.mjs scripts/check-svg-sanitize-parity.test.mjs scripts/check-media-use-svg-sanitize-generated.test.mjs scripts/check-package-cycles.test.mjs scripts/check-cli-process-ownership.test.mjs scripts/check-cli-lazy-deps.test.mjs scripts/file-url-paths.test.mjs scripts/check-studio-copy-dashes.test.mjs scripts/check-large-files.test.mjs scripts/package-subpaths.test.mjs scripts/validate-release-channel.test.mjs scripts/clawhub-sync.test.mjs scripts/clawhub-unlist-retired.test.mjs scripts/publish-workflow.test.mjs scripts/pr-edit-concurrency.test.mjs scripts/merge-queue-workflows.test.mjs scripts/ci-cache-workflows.test.mjs scripts/install-workspace-dependencies.test.mjs scripts/check-edit-accuracy-filter.test.mjs scripts/edit-accuracy-retry.test.mjs scripts/draft-changelog.test.ts scripts/set-version.test.ts scripts/release-prepare.test.ts scripts/cli-options.test.ts scripts/changelog-weekly.test.ts scripts/claude-plugin-compression.test.ts scripts/catalog-payload-assets.test.ts scripts/host-registry-assets.test.ts scripts/catalog-preview-temp.test.ts scripts/backfill-block-previews.test.ts scripts/catalog-hosted-files.test.ts scripts/player-cdn-pin.test.ts scripts/studio-runtime-smoke.test.mjs scripts/verify-packed-manifests.test.mjs scripts/rewrite-relative-import-extensions.test.mjs scripts/lint-skills.test.mjs scripts/check-core-skills.test.mjs scripts/creator-editing-recipes.test.mjs packages/gcp-cloud-run/check-dockerfile-workspaces.test.mjs packages/core/scripts/writeGeneratedFile.test.ts scripts/catalog-publication.test.mjs scripts/ci/resolve-workflow-pr.test.mjs scripts/lefthook-order.test.mjs scripts/inline-gsap.test.mjs scripts/ci/flake-gate.test.mjs scripts/ci/base-file.test.mjs scripts/ci/release-only-diff.test.mjs scripts/check-catalog-source-pr.test.mjs scripts/generate-registry-items.test.ts scripts/catalog-drift.test.ts scripts/catalog-fetch-mirror.test.ts scripts/catalog-script-inlining.test.ts scripts/catalog-detail.test.ts scripts/generate-catalog-pages.test.ts scripts/verify-catalog-payloads.test.ts scripts/registry-theme-fallbacks.test.ts scripts/registry-skill-files.test.ts scripts/creator-editing-capabilities.test.mjs scripts/generate-catalog-previews.test.ts scripts/registry-primitive-payloads.test.ts registry/components/pan-stations/pan-stations.test.mjs registry/components/filmed-screen/filmed-screen.test.mjs registry/components/echo-smear/echo-smear.test.mjs && vitest run scripts/catalog/ scripts/contrastRatchet.test.ts scripts/generate-catalog-payloads.test.ts",
"test:scripts": "node --import tsx --test scripts/animejs-v4-guidance.test.mjs scripts/check-tracked-artifacts.test.mjs scripts/check-registry-set-delta.test.mjs scripts/check-no-main-deletions.test.mjs scripts/check-pr-captures.test.mjs scripts/check-comment-citations.test.mjs scripts/comments-workflow.test.mjs scripts/comment-ratchet.test.mjs scripts/check-docs-snippet-motion.test.mjs scripts/registry-target-paths.test.mjs scripts/check-workspace-contracts.test.mjs scripts/check-media-use-copy-parity.test.mjs scripts/check-svg-sanitize-parity.test.mjs scripts/check-media-use-svg-sanitize-generated.test.mjs scripts/check-package-cycles.test.mjs scripts/check-cli-process-ownership.test.mjs scripts/check-cli-lazy-deps.test.mjs scripts/file-url-paths.test.mjs scripts/check-studio-copy-dashes.test.mjs scripts/check-large-files.test.mjs scripts/package-subpaths.test.mjs scripts/validate-release-channel.test.mjs scripts/clawhub-sync.test.mjs scripts/clawhub-unlist-retired.test.mjs scripts/publish-workflow.test.mjs scripts/pr-edit-concurrency.test.mjs scripts/merge-queue-workflows.test.mjs scripts/ci-cache-workflows.test.mjs scripts/install-workspace-dependencies.test.mjs scripts/check-edit-accuracy-filter.test.mjs scripts/edit-accuracy-retry.test.mjs scripts/draft-changelog.test.ts scripts/set-version.test.ts scripts/release-prepare.test.ts scripts/cli-options.test.ts scripts/changelog-weekly.test.ts scripts/claude-plugin-compression.test.ts scripts/catalog-payload-assets.test.ts scripts/host-registry-assets.test.ts scripts/catalog-preview-temp.test.ts scripts/backfill-block-previews.test.ts scripts/catalog-hosted-files.test.ts scripts/player-cdn-pin.test.ts scripts/studio-runtime-smoke.test.mjs scripts/verify-packed-manifests.test.mjs scripts/rewrite-relative-import-extensions.test.mjs scripts/lint-skills.test.mjs scripts/check-core-skills.test.mjs scripts/creator-editing-recipes.test.mjs packages/gcp-cloud-run/check-dockerfile-workspaces.test.mjs packages/core/scripts/writeGeneratedFile.test.ts scripts/catalog-publication.test.mjs scripts/ci/resolve-workflow-pr.test.mjs scripts/lefthook-order.test.mjs scripts/inline-gsap.test.mjs scripts/ci/flake-gate.test.mjs scripts/ci/base-file.test.mjs scripts/ci/release-only-diff.test.mjs scripts/check-catalog-source-pr.test.mjs scripts/generate-registry-items.test.ts scripts/catalog-drift.test.ts scripts/catalog-fetch-mirror.test.ts scripts/catalog-script-inlining.test.ts scripts/catalog-detail.test.ts scripts/generate-catalog-pages.test.ts scripts/verify-catalog-payloads.test.ts scripts/registry-theme-fallbacks.test.ts scripts/registry-skill-files.test.ts scripts/creator-editing-capabilities.test.mjs scripts/generate-catalog-previews.test.ts scripts/registry-primitive-payloads.test.ts registry/components/pan-stations/pan-stations.test.mjs registry/components/filmed-screen/filmed-screen.test.mjs registry/components/echo-smear/echo-smear.test.mjs registry/examples/path-traced-3d/source/path-traced-3d.test.mjs && vitest run scripts/catalog/ scripts/contrastRatchet.test.ts scripts/generate-catalog-payloads.test.ts",
"typecheck:scripts": "tsc --noEmit -p scripts/tsconfig.json",
"test:skills": "HYPERFRAMES_MEDIA_HOME_REQUIRED=1 node --import ./packages/cli/scripts/test-home.mjs --test 'skills/**/*.test.mjs' 'packages/cli/src/media-use/**/*.test.mjs'",
"generate:previews": "tsx scripts/generate-template-previews.ts",
+4
View File
@@ -18,6 +18,10 @@ Bold kinetic typography promo.
Animated data chart in print editorial style.
## path-traced-3d
Three.js scene with a fast raster preview and an opt-in path-traced export.
## play-mode
Playful elastic animations.
@@ -0,0 +1,142 @@
// Draws the scene for HyperFrames, rasterized for quick previews or path traced for export.
//
// - Setup is one `window.__hf.buildReady` promise; the first seek waits for it.
// - Each `hf-seek` registers its frame with `event.detail.waitUntil`, so a frame is captured
// only once every sample for it is done.
// - Every new time starts a fresh accumulation with the same noise, so a time gives the same
// pixels whatever was drawn before it. Seeking again to the time on screen does no work.
import * as THREE from "./vendor/three-path-tracer.min.js";
import { createScene } from "./scene.js";
const READY_KEY = "path-traced-3d";
const root = document.querySelector("[data-composition-id]");
const canvas = document.getElementById("pt-canvas");
const width = Number(root.dataset.width);
const height = Number(root.dataset.height);
const variables = window.__hyperframes?.getVariables?.() ?? {};
const mode = variables.renderer === "path" ? "path" : "raster";
const samples = Math.max(1, Math.round(Number(variables.samples) || 64));
const bounces = Math.max(1, Math.round(Number(variables.bounces) || 4));
// While HyperFrames renders, the clock stands still and requestAnimationFrame callbacks wait
// until the first seek, and that seek waits for setup. So nothing here waits on a frame, the
// clock or a timer of its own, and nothing starts a render loop: setup and seeks only await
// the libraries' own promises, and every frame is drawn from the seek time alone.
// three-gpu-pathtracer 0.0.24 reports shader compilation only as the `isCompiling` flag. The
// promise behind that flag is three's `renderer.compileAsync`, so await it directly rather than
// polling the flag. It only decides when drawing may start, never what is drawn.
function tracerCompiled() {
const compiling = tracer._pathTracer._compilePromise;
// Waiting on nothing here would spin renderSample() forever; fail loudly if a tracer upgrade
// moves the promise.
if (!compiling)
throw new Error("path-traced-3d: tracer is compiling but exposes no compile promise");
return compiling;
}
// Math.random decides two things the tracer bakes in: three's object uuids, which set the order
// lights, meshes and textures are sorted in, and the tracer's noise textures, built when it is
// constructed. With a fixed seed around both, every page (every render worker, every reload)
// draws the same grain. Only synchronous construction is covered: anything created later, such
// as a model loaded during setup, must be built under the seed too.
function withSeededRandom(seed, build) {
const nativeRandom = Math.random;
let state = seed >>> 0;
Math.random = () => {
state = (state + 0x6d2b79f5) >>> 0;
let t = state;
t = Math.imul(t ^ (t >>> 15), t | 1);
t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
};
try {
return build();
} finally {
Math.random = nativeRandom;
}
}
const renderer = new THREE.WebGLRenderer({ canvas, antialias: true, preserveDrawingBuffer: true });
renderer.setPixelRatio(1);
renderer.setSize(width, height, false);
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
const { scene, camera, poseAt } = withSeededRandom(1, () =>
createScene(THREE, { aspect: width / height }),
);
let tracer = null;
let shownTime = null;
const pixel = new Uint8Array(4);
// gl.finish() can return before a software GPU has run the queued work; reading one pixel back
// cannot, so the frame (and the first, slowest shader run) is really done when this returns.
function waitForGpu() {
const gl = renderer.getContext();
renderer.setRenderTarget(null);
gl.readPixels(0, 0, 1, 1, gl.RGBA, gl.UNSIGNED_BYTE, pixel);
}
// Sampling is driven by an explicit count, never by time: the tracer's own delay and fade
// settings read a clock that does not move during a render.
async function trace(target) {
// Objects moved, so rebuild the tracer's copy of the scene; this also restarts accumulation.
tracer.setScene(scene, camera);
while (tracer.samples < target) {
tracer.renderSample();
// The first call after a shader change starts a compile and draws nothing; wait for it.
if (tracer.isCompiling) await tracerCompiled();
}
}
// The first image a renderer draws differs from later ones (shader warm-up, first uploads), so
// setup draws one throwaway frame and leaves nothing marked as shown.
async function setup() {
poseAt(0);
if (mode === "raster") {
await renderer.compileAsync(scene, camera);
renderer.render(scene, camera);
waitForGpu();
return;
}
tracer = withSeededRandom(2, () => new THREE.WebGLPathTracer(renderer));
// No delay, fade or low-resolution stand-in: those depend on elapsed time.
tracer.renderDelay = 0;
tracer.fadeDuration = 0;
tracer.minSamples = 1;
tracer.dynamicLowRes = false;
tracer.rasterizeScene = false;
tracer.stableNoise = true;
tracer.bounces = bounces;
tracer.filterGlossyFactor = 0.5;
await trace(samples);
waitForGpu();
}
async function draw(time) {
if (time === shownTime) return;
shownTime = null;
poseAt(time);
if (mode === "path") await trace(samples);
else renderer.render(scene, camera);
waitForGpu();
shownTime = time;
}
const ready = setup();
window.__hf = window.__hf || {};
window.__hf.buildReady = window.__hf.buildReady || {};
window.__hf.buildReady[READY_KEY] = ready;
let queue = ready;
window.addEventListener("hf-seek", (event) => {
const { time } = event.detail;
queue = queue
.catch(() => {})
.then(() => ready)
.then(() => draw(time));
event.detail.waitUntil(queue);
});
@@ -0,0 +1,119 @@
// The scene: a few PBR objects on a plinth under a soft spotlight. Edit freely.
// `poseAt(t)` is the only thing that moves anything, and it reads nothing but `t`,
// so any frame can be drawn on its own and in any order.
export const DURATION = 6;
export function createScene(THREE, { aspect }) {
const scene = new THREE.Scene();
scene.background = new THREE.Color("#0e1115");
scene.environment = studioEnvironment(THREE);
scene.environmentIntensity = 0.55;
const camera = new THREE.PerspectiveCamera(30, aspect, 0.1, 200);
const floorMat = new THREE.MeshStandardMaterial({ color: "#121418", roughness: 0.9 });
const plinthMat = new THREE.MeshStandardMaterial({ color: "#3a3d42", roughness: 0.6 });
const gold = new THREE.MeshStandardMaterial({ color: "#d9a94e", metalness: 1, roughness: 0.3 });
const chrome = new THREE.MeshStandardMaterial({
color: "#c9ced4",
metalness: 1,
roughness: 0.12,
});
const ceramic = new THREE.MeshPhysicalMaterial({
color: "#ece6db",
roughness: 0.4,
clearcoat: 1,
clearcoatRoughness: 0.1,
});
const lacquer = new THREE.MeshStandardMaterial({ color: "#b23a2e", roughness: 0.45 });
function add(geometry, material, x = 0, y = 0, z = 0) {
const mesh = new THREE.Mesh(geometry, material);
mesh.position.set(x, y, z);
mesh.castShadow = true;
mesh.receiveShadow = true;
scene.add(mesh);
return mesh;
}
const floor = add(new THREE.PlaneGeometry(120, 120), floorMat);
floor.rotation.x = -Math.PI / 2;
add(new THREE.CylinderGeometry(2.1, 2.2, 0.5, 96), plinthMat, 0, 0.25, 0);
const knot = add(new THREE.TorusKnotGeometry(0.5, 0.17, 220, 32), gold);
const orbiters = [
{ mesh: add(new THREE.SphereGeometry(0.38, 64, 32), ceramic), phase: 0, radius: 1.45, y: 0.88 },
{
mesh: add(new THREE.BoxGeometry(0.52, 0.52, 0.52), lacquer),
phase: 2.1,
radius: 1.5,
y: 0.76,
},
{ mesh: add(new THREE.SphereGeometry(0.26, 64, 32), chrome), phase: 4.2, radius: 1.4, y: 0.76 },
];
// PhysicalSpotLight is a three SpotLight with a radius, so the tracer draws soft shadows
// from it and the raster renderer still treats it as an ordinary spotlight.
const key = new THREE.PhysicalSpotLight("#ffe3bd", 140);
key.position.set(-4, 6.5, 3.5);
key.angle = 0.55;
key.penumbra = 0.45;
key.radius = 0.5;
key.castShadow = true;
key.shadow.mapSize.set(1024, 1024);
key.shadow.bias = -0.0002;
key.target.position.set(0, 0.8, 0);
scene.add(key, key.target);
const rim = new THREE.DirectionalLight("#bcd2ff", 1.1);
rim.position.set(4, 4, -5);
scene.add(rim);
function poseAt(t) {
const p = Math.min(Math.max(t / DURATION, 0), 1);
const eased = p * p * (3 - 2 * p);
knot.position.set(0, 1.5 + 0.08 * Math.sin(t * 1.3), 0);
knot.rotation.set(0.35, t * 0.9, 0.15 * Math.sin(t * 0.7));
for (const { mesh, phase, radius, y } of orbiters) {
const angle = phase + t * 0.55;
mesh.position.set(Math.cos(angle) * radius, y, Math.sin(angle) * radius);
mesh.rotation.set(t * 0.4, angle, 0);
}
const orbit = -0.55 + 1.0 * eased;
const distance = 7.4 - 1.6 * eased;
camera.position.set(Math.sin(orbit) * distance, 2.7 - 0.6 * eased, Math.cos(orbit) * distance);
camera.lookAt(0, 1.05, 0);
camera.updateMatrixWorld();
scene.updateMatrixWorld(true);
}
return { scene, camera, poseAt };
}
// A dark studio with two soft light strips, as a float equirect texture both renderers can use.
function studioEnvironment(THREE) {
const width = 256;
const height = 128;
const pixels = new Float32Array(width * height * 4);
for (let y = 0; y < height; y++) {
for (let x = 0; x < width; x++) {
const u = x / width;
const v = y / height;
const warm = Math.exp(-(((u - 0.2) / 0.06) ** 4) - ((v - 0.32) / 0.12) ** 4) * 4;
const cool = Math.exp(-(((u - 0.7) / 0.04) ** 4) - ((v - 0.38) / 0.16) ** 4) * 2.2;
const base = 0.05 + 0.08 * Math.max(0, Math.cos(v * Math.PI));
const i = (y * width + x) * 4;
pixels[i] = base + warm + cool * 0.7;
pixels[i + 1] = base + warm * 0.86 + cool * 0.85;
pixels[i + 2] = base + warm * 0.66 + cool;
pixels[i + 3] = 1;
}
}
const texture = new THREE.DataTexture(pixels, width, height, THREE.RGBAFormat, THREE.FloatType);
texture.mapping = THREE.EquirectangularReflectionMapping;
texture.needsUpdate = true;
return texture;
}
@@ -0,0 +1,20 @@
# Vendored 3D libraries
`three-path-tracer.min.js` is one local ES module, so the project renders without any network
access. It re-exports all of three plus these classes from three-gpu-pathtracer:
`WebGLPathTracer`, `PhysicalSpotLight`, `ShapedAreaLight`, `PhysicalCamera`, `DenoiseMaterial`
and `GradientEquirectTexture`.
| Package | Version | Licence |
| -------------------- | ------- | --------------------------------------- |
| three | 0.180.0 | MIT, `three.LICENSE.txt` |
| three-gpu-pathtracer | 0.0.24 | MIT, `three-gpu-pathtracer.LICENSE.txt` |
| three-mesh-bvh | 0.9.5 | MIT, `three-mesh-bvh.LICENSE.txt` |
Built with esbuild 0.25.12 (`--bundle --format=esm --minify --target=es2020`). SHA-256 of the
bundle: `a247cb7f88eff8b1d423a2892e5ca27c7d03d83939fe0ca6fa9a11c7f9f21fc9`.
To rebuild it, or to change the versions, use the `source/` folder of this example in the
HyperFrames repository
(https://github.com/heygen-com/hyperframes/tree/main/registry/examples/path-traced-3d/source):
`npm ci && npm run build`. The same pinned versions produce the same file.
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2021 Garrett Johnson
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2018 Garrett Johnson
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
File diff suppressed because one or more lines are too long
@@ -0,0 +1,21 @@
The MIT License
Copyright © 2010-2025 three.js authors
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
+57
View File
@@ -0,0 +1,57 @@
<!doctype html>
<html
lang="en"
data-composition-variables='[{"id":"renderer","type":"enum","label":"Renderer","description":"raster draws each frame in milliseconds for previews. path traces light bounces for the final export and is much slower.","default":"raster","options":[{"value":"raster","label":"Raster (fast preview)"},{"value":"path","label":"Path tracing (export)"}]},{"id":"samples","type":"number","label":"Path samples per pixel","description":"Samples traced for every frame in path mode. More samples mean less noise and proportionally longer renders.","default":64,"min":1,"max":1024,"step":1},{"id":"bounces","type":"number","label":"Path light bounces","description":"How many times a ray may bounce in path mode. Reflections between objects need at least 2.","default":4,"min":1,"max":12,"step":1}]'
>
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=1920, height=1080" />
<title>Path-traced 3D - HyperFrames</title>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
html,
body {
width: 1920px;
height: 1080px;
overflow: hidden;
background: #0e1115;
}
#root {
position: relative;
width: 100%;
height: 100%;
}
#pt-canvas {
position: absolute;
inset: 0;
width: 100%;
height: 100%;
display: block;
}
</style>
</head>
<body>
<div
id="root"
data-composition-id="main"
data-start="0"
data-duration="6"
data-width="1920"
data-height="1080"
data-no-timeline
>
<canvas
id="pt-canvas"
class="clip"
data-start="0"
data-duration="6"
data-track-index="1"
></canvas>
</div>
<script type="module" src="assets/render.js"></script>
</body>
</html>
@@ -0,0 +1,55 @@
{
"$schema": "https://hyperframes.heygen.com/schema/registry-item.json",
"name": "path-traced-3d",
"type": "hyperframes:example",
"title": "Path-Traced 3D",
"description": "Three.js scene with a fast raster preview and an opt-in path-traced export",
"tags": ["3d", "three-js", "path-tracing", "webgl"],
"dimensions": {
"width": 1920,
"height": 1080
},
"duration": 6,
"files": [
{
"path": "assets/render.js",
"target": "assets/render.js",
"type": "hyperframes:asset"
},
{
"path": "assets/scene.js",
"target": "assets/scene.js",
"type": "hyperframes:asset"
},
{
"path": "assets/vendor/README.md",
"target": "assets/vendor/README.md",
"type": "hyperframes:asset"
},
{
"path": "assets/vendor/three-gpu-pathtracer.LICENSE.txt",
"target": "assets/vendor/three-gpu-pathtracer.LICENSE.txt",
"type": "hyperframes:asset"
},
{
"path": "assets/vendor/three-mesh-bvh.LICENSE.txt",
"target": "assets/vendor/three-mesh-bvh.LICENSE.txt",
"type": "hyperframes:asset"
},
{
"path": "assets/vendor/three-path-tracer.min.js",
"target": "assets/vendor/three-path-tracer.min.js",
"type": "hyperframes:asset"
},
{
"path": "assets/vendor/three.LICENSE.txt",
"target": "assets/vendor/three.LICENSE.txt",
"type": "hyperframes:asset"
},
{
"path": "index.html",
"target": "index.html",
"type": "hyperframes:composition"
}
]
}
@@ -0,0 +1,42 @@
# Source for the path-traced-3d example
These files stay in the repository; `hyperframes init --example path-traced-3d` installs only the
files listed in `../registry-item.json`.
## Rebuild the vendored bundle
`build.mjs` bundles `vendor-entry.js` with the versions pinned in `package.json` and
`package-lock.json` into `../assets/vendor/three-path-tracer.min.js`, and copies the three
licence files beside it.
```sh
npm ci
npm run build
```
Update the versions and the SHA-256 in `../assets/vendor/README.md` when they change.
## Check what reaches the pixels
`verify-render.mjs` copies the example to a temporary folder at 320x180, then uses the
HyperFrames CLI and ffmpeg to check, in raster and in path mode (2 samples per pixel):
- `hyperframes check` passes in path mode, so setup (including the first, slowest tracing run)
resolves its `buildReady` promise;
- stills taken at 4 s, 0 s, then 4 s again in one page are byte-identical at 4 s, differ from
0 s, and are not blank;
- a new page draws the same 4 s still (no grain that changes per page load);
- path mode draws different pixels from raster mode;
- every frame of an exported MP4 (raster: 1 s at 30 fps; path: 0.8 s at 10 fps on two workers)
is not blank, the clip moves, and no step between neighbouring frames is more than 3x the
typical step.
```sh
node verify-render.mjs
# or, from a HyperFrames checkout, with the CLI built from source:
HYPERFRAMES_CLI=packages/cli/bin/hyperframes.mjs node registry/examples/path-traced-3d/source/verify-render.mjs
```
Every command gets a 170 s readiness wait, because on a software GPU the tracer's first shader
run takes about a minute. It prints a JSON report with the wall time of every step. Set `KEEP_VERIFY_OUTPUT=1` to keep the
renders. `path-traced-3d.test.mjs` is the fast check that runs with the repository's script tests.
@@ -0,0 +1,23 @@
// Rebuilds ../assets/vendor/three-path-tracer.min.js and its licence files from the versions
// pinned in package.json and package-lock.json. Run `npm ci && npm run build` in this folder.
import { build } from "esbuild";
import { copyFile } from "node:fs/promises";
const out = new URL("../assets/vendor/", import.meta.url);
await build({
entryPoints: [new URL("vendor-entry.js", import.meta.url).pathname],
bundle: true,
format: "esm",
minify: true,
target: "es2020",
outfile: new URL("three-path-tracer.min.js", out).pathname,
});
for (const pkg of ["three", "three-gpu-pathtracer", "three-mesh-bvh"]) {
await copyFile(
new URL(`node_modules/${pkg}/LICENSE`, import.meta.url),
new URL(`${pkg}.LICENSE.txt`, out),
);
}
console.log("built assets/vendor/three-path-tracer.min.js");
+537
View File
@@ -0,0 +1,537 @@
{
"name": "path-traced-3d-vendor",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "path-traced-3d-vendor",
"devDependencies": {
"esbuild": "0.25.12",
"three": "0.180.0",
"three-gpu-pathtracer": "0.0.24",
"three-mesh-bvh": "0.9.5"
}
},
"node_modules/@esbuild/aix-ppc64": {
"version": "0.25.12",
"resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.25.12.tgz",
"integrity": "sha512-Hhmwd6CInZ3dwpuGTF8fJG6yoWmsToE+vYgD4nytZVxcu1ulHpUQRAB1UJ8+N1Am3Mz4+xOByoQoSZf4D+CpkA==",
"cpu": [
"ppc64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"aix"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/android-arm": {
"version": "0.25.12",
"resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.25.12.tgz",
"integrity": "sha512-VJ+sKvNA/GE7Ccacc9Cha7bpS8nyzVv0jdVgwNDaR4gDMC/2TTRc33Ip8qrNYUcpkOHUT5OZ0bUcNNVZQ9RLlg==",
"cpu": [
"arm"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"android"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/android-arm64": {
"version": "0.25.12",
"resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.25.12.tgz",
"integrity": "sha512-6AAmLG7zwD1Z159jCKPvAxZd4y/VTO0VkprYy+3N2FtJ8+BQWFXU+OxARIwA46c5tdD9SsKGZ/1ocqBS/gAKHg==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"android"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/android-x64": {
"version": "0.25.12",
"resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.25.12.tgz",
"integrity": "sha512-5jbb+2hhDHx5phYR2By8GTWEzn6I9UqR11Kwf22iKbNpYrsmRB18aX/9ivc5cabcUiAT/wM+YIZ6SG9QO6a8kg==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"android"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/darwin-arm64": {
"version": "0.25.12",
"resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.25.12.tgz",
"integrity": "sha512-N3zl+lxHCifgIlcMUP5016ESkeQjLj/959RxxNYIthIg+CQHInujFuXeWbWMgnTo4cp5XVHqFPmpyu9J65C1Yg==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"darwin"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/darwin-x64": {
"version": "0.25.12",
"resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.25.12.tgz",
"integrity": "sha512-HQ9ka4Kx21qHXwtlTUVbKJOAnmG1ipXhdWTmNXiPzPfWKpXqASVcWdnf2bnL73wgjNrFXAa3yYvBSd9pzfEIpA==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"darwin"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/freebsd-arm64": {
"version": "0.25.12",
"resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.25.12.tgz",
"integrity": "sha512-gA0Bx759+7Jve03K1S0vkOu5Lg/85dou3EseOGUes8flVOGxbhDDh/iZaoek11Y8mtyKPGF3vP8XhnkDEAmzeg==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"freebsd"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/freebsd-x64": {
"version": "0.25.12",
"resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.25.12.tgz",
"integrity": "sha512-TGbO26Yw2xsHzxtbVFGEXBFH0FRAP7gtcPE7P5yP7wGy7cXK2oO7RyOhL5NLiqTlBh47XhmIUXuGciXEqYFfBQ==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"freebsd"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-arm": {
"version": "0.25.12",
"resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.25.12.tgz",
"integrity": "sha512-lPDGyC1JPDou8kGcywY0YILzWlhhnRjdof3UlcoqYmS9El818LLfJJc3PXXgZHrHCAKs/Z2SeZtDJr5MrkxtOw==",
"cpu": [
"arm"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-arm64": {
"version": "0.25.12",
"resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.25.12.tgz",
"integrity": "sha512-8bwX7a8FghIgrupcxb4aUmYDLp8pX06rGh5HqDT7bB+8Rdells6mHvrFHHW2JAOPZUbnjUpKTLg6ECyzvas2AQ==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-ia32": {
"version": "0.25.12",
"resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.25.12.tgz",
"integrity": "sha512-0y9KrdVnbMM2/vG8KfU0byhUN+EFCny9+8g202gYqSSVMonbsCfLjUO+rCci7pM0WBEtz+oK/PIwHkzxkyharA==",
"cpu": [
"ia32"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-loong64": {
"version": "0.25.12",
"resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.25.12.tgz",
"integrity": "sha512-h///Lr5a9rib/v1GGqXVGzjL4TMvVTv+s1DPoxQdz7l/AYv6LDSxdIwzxkrPW438oUXiDtwM10o9PmwS/6Z0Ng==",
"cpu": [
"loong64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-mips64el": {
"version": "0.25.12",
"resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.25.12.tgz",
"integrity": "sha512-iyRrM1Pzy9GFMDLsXn1iHUm18nhKnNMWscjmp4+hpafcZjrr2WbT//d20xaGljXDBYHqRcl8HnxbX6uaA/eGVw==",
"cpu": [
"mips64el"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-ppc64": {
"version": "0.25.12",
"resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.25.12.tgz",
"integrity": "sha512-9meM/lRXxMi5PSUqEXRCtVjEZBGwB7P/D4yT8UG/mwIdze2aV4Vo6U5gD3+RsoHXKkHCfSxZKzmDssVlRj1QQA==",
"cpu": [
"ppc64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-riscv64": {
"version": "0.25.12",
"resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.25.12.tgz",
"integrity": "sha512-Zr7KR4hgKUpWAwb1f3o5ygT04MzqVrGEGXGLnj15YQDJErYu/BGg+wmFlIDOdJp0PmB0lLvxFIOXZgFRrdjR0w==",
"cpu": [
"riscv64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-s390x": {
"version": "0.25.12",
"resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.25.12.tgz",
"integrity": "sha512-MsKncOcgTNvdtiISc/jZs/Zf8d0cl/t3gYWX8J9ubBnVOwlk65UIEEvgBORTiljloIWnBzLs4qhzPkJcitIzIg==",
"cpu": [
"s390x"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-x64": {
"version": "0.25.12",
"resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.25.12.tgz",
"integrity": "sha512-uqZMTLr/zR/ed4jIGnwSLkaHmPjOjJvnm6TVVitAa08SLS9Z0VM8wIRx7gWbJB5/J54YuIMInDquWyYvQLZkgw==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/netbsd-arm64": {
"version": "0.25.12",
"resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.25.12.tgz",
"integrity": "sha512-xXwcTq4GhRM7J9A8Gv5boanHhRa/Q9KLVmcyXHCTaM4wKfIpWkdXiMog/KsnxzJ0A1+nD+zoecuzqPmCRyBGjg==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"netbsd"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/netbsd-x64": {
"version": "0.25.12",
"resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.25.12.tgz",
"integrity": "sha512-Ld5pTlzPy3YwGec4OuHh1aCVCRvOXdH8DgRjfDy/oumVovmuSzWfnSJg+VtakB9Cm0gxNO9BzWkj6mtO1FMXkQ==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"netbsd"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/openbsd-arm64": {
"version": "0.25.12",
"resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.25.12.tgz",
"integrity": "sha512-fF96T6KsBo/pkQI950FARU9apGNTSlZGsv1jZBAlcLL1MLjLNIWPBkj5NlSz8aAzYKg+eNqknrUJ24QBybeR5A==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"openbsd"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/openbsd-x64": {
"version": "0.25.12",
"resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.25.12.tgz",
"integrity": "sha512-MZyXUkZHjQxUvzK7rN8DJ3SRmrVrke8ZyRusHlP+kuwqTcfWLyqMOE3sScPPyeIXN/mDJIfGXvcMqCgYKekoQw==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"openbsd"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/openharmony-arm64": {
"version": "0.25.12",
"resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.25.12.tgz",
"integrity": "sha512-rm0YWsqUSRrjncSXGA7Zv78Nbnw4XL6/dzr20cyrQf7ZmRcsovpcRBdhD43Nuk3y7XIoW2OxMVvwuRvk9XdASg==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"openharmony"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/sunos-x64": {
"version": "0.25.12",
"resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.25.12.tgz",
"integrity": "sha512-3wGSCDyuTHQUzt0nV7bocDy72r2lI33QL3gkDNGkod22EsYl04sMf0qLb8luNKTOmgF/eDEDP5BFNwoBKH441w==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"sunos"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/win32-arm64": {
"version": "0.25.12",
"resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.25.12.tgz",
"integrity": "sha512-rMmLrur64A7+DKlnSuwqUdRKyd3UE7oPJZmnljqEptesKM8wx9J8gx5u0+9Pq0fQQW8vqeKebwNXdfOyP+8Bsg==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"win32"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/win32-ia32": {
"version": "0.25.12",
"resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.25.12.tgz",
"integrity": "sha512-HkqnmmBoCbCwxUKKNPBixiWDGCpQGVsrQfJoVGYLPT41XWF8lHuE5N6WhVia2n4o5QK5M4tYr21827fNhi4byQ==",
"cpu": [
"ia32"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"win32"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/win32-x64": {
"version": "0.25.12",
"resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.25.12.tgz",
"integrity": "sha512-alJC0uCZpTFrSL0CCDjcgleBXPnCrEAhTBILpeAp7M/OFgoqtAetfBzX0xM00MUsVVPpVjlPuMbREqnZCXaTnA==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"win32"
],
"engines": {
"node": ">=18"
}
},
"node_modules/esbuild": {
"version": "0.25.12",
"resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.25.12.tgz",
"integrity": "sha512-bbPBYYrtZbkt6Os6FiTLCTFxvq4tt3JKall1vRwshA3fdVztsLAatFaZobhkBC8/BrPetoa0oksYoKXoG4ryJg==",
"dev": true,
"hasInstallScript": true,
"license": "MIT",
"bin": {
"esbuild": "bin/esbuild"
},
"engines": {
"node": ">=18"
},
"optionalDependencies": {
"@esbuild/aix-ppc64": "0.25.12",
"@esbuild/android-arm": "0.25.12",
"@esbuild/android-arm64": "0.25.12",
"@esbuild/android-x64": "0.25.12",
"@esbuild/darwin-arm64": "0.25.12",
"@esbuild/darwin-x64": "0.25.12",
"@esbuild/freebsd-arm64": "0.25.12",
"@esbuild/freebsd-x64": "0.25.12",
"@esbuild/linux-arm": "0.25.12",
"@esbuild/linux-arm64": "0.25.12",
"@esbuild/linux-ia32": "0.25.12",
"@esbuild/linux-loong64": "0.25.12",
"@esbuild/linux-mips64el": "0.25.12",
"@esbuild/linux-ppc64": "0.25.12",
"@esbuild/linux-riscv64": "0.25.12",
"@esbuild/linux-s390x": "0.25.12",
"@esbuild/linux-x64": "0.25.12",
"@esbuild/netbsd-arm64": "0.25.12",
"@esbuild/netbsd-x64": "0.25.12",
"@esbuild/openbsd-arm64": "0.25.12",
"@esbuild/openbsd-x64": "0.25.12",
"@esbuild/openharmony-arm64": "0.25.12",
"@esbuild/sunos-x64": "0.25.12",
"@esbuild/win32-arm64": "0.25.12",
"@esbuild/win32-ia32": "0.25.12",
"@esbuild/win32-x64": "0.25.12"
}
},
"node_modules/three": {
"version": "0.180.0",
"resolved": "https://registry.npmjs.org/three/-/three-0.180.0.tgz",
"integrity": "sha512-o+qycAMZrh+TsE01GqWUxUIKR1AL0S8pq7zDkYOQw8GqfX8b8VoCKYUoHbhiX5j+7hr8XsuHDVU6+gkQJQKg9w==",
"dev": true,
"license": "MIT"
},
"node_modules/three-gpu-pathtracer": {
"version": "0.0.24",
"resolved": "https://registry.npmjs.org/three-gpu-pathtracer/-/three-gpu-pathtracer-0.0.24.tgz",
"integrity": "sha512-fHQ7g7ywvSwRAQywhsfech2/kspQKinfFNOcNDTJS2Q34CzcF1kpESlOVvJH8kX/bGlCnxMI+Qo16kWGAy7zCA==",
"dev": true,
"license": "MIT",
"peerDependencies": {
"three": ">=0.180.0",
"three-mesh-bvh": ">=0.7.4",
"xatlas-web": "^0.1.0"
}
},
"node_modules/three-mesh-bvh": {
"version": "0.9.5",
"resolved": "https://registry.npmjs.org/three-mesh-bvh/-/three-mesh-bvh-0.9.5.tgz",
"integrity": "sha512-MYpwzUWDxPAKGhSBFin9E/7K4AAHyIm4IfMZQ/3+Z/jq/swa2dAhXx0yUNDd9mjlhLuzXkMBTGDZioL2GSlIfQ==",
"dev": true,
"license": "MIT",
"peerDependencies": {
"three": ">= 0.159.0"
}
},
"node_modules/xatlas-web": {
"version": "0.1.0",
"resolved": "https://registry.npmjs.org/xatlas-web/-/xatlas-web-0.1.0.tgz",
"integrity": "sha512-PprVfuXbaIskxLTLBUQRaWfgSy9xUQqAMIRooOw0P6NYqwgh6T0voeer6+Z5M7AFt5SGXUybuww/uDGs1yw8vQ==",
"dev": true,
"license": "MIT",
"peer": true
}
}
}
@@ -0,0 +1,14 @@
{
"name": "path-traced-3d-vendor",
"private": true,
"type": "module",
"scripts": {
"build": "node build.mjs"
},
"devDependencies": {
"esbuild": "0.25.12",
"three": "0.180.0",
"three-gpu-pathtracer": "0.0.24",
"three-mesh-bvh": "0.9.5"
}
}
@@ -0,0 +1,81 @@
import assert from "node:assert/strict";
import { createHash } from "node:crypto";
import { readdirSync, readFileSync } from "node:fs";
import { join, relative } from "node:path";
import test from "node:test";
import { fileURLToPath } from "node:url";
const example = fileURLToPath(new URL("..", import.meta.url));
const read = (path) => readFileSync(join(example, path), "utf8");
test("the manifest installs exactly the page and its assets", () => {
const item = JSON.parse(read("registry-item.json"));
const onDisk = readdirSync(join(example, "assets"), { recursive: true, withFileTypes: true })
.filter((entry) => entry.isFile())
.map((entry) => relative(example, join(entry.parentPath, entry.name)))
.concat("index.html")
.sort();
assert.deepEqual(item.files.map((file) => file.path).sort(), onDisk);
for (const file of item.files) assert.equal(file.target, file.path);
});
test("the page loads nothing from the network and defaults to the raster preview", () => {
const html = read("index.html");
assert.doesNotMatch(html, /<script[^>]+src="https?:/);
const variables = JSON.parse(html.match(/data-composition-variables='([^']+)'/)[1]);
assert.equal(variables.find((v) => v.id === "renderer").default, "raster");
for (const file of ["assets/render.js", "assets/scene.js"]) {
for (const match of read(file).matchAll(/from\s+"([^"]+)"/g)) {
assert.match(match[1], /^\.\//, `${file} imports ${match[1]}`);
}
}
});
test("the vendored bundle matches the hash its note records", () => {
const bundle = readFileSync(join(example, "assets/vendor/three-path-tracer.min.js"));
const hash = createHash("sha256").update(bundle).digest("hex");
assert.ok(read("assets/vendor/README.md").includes(hash));
const pins = JSON.parse(read("source/package.json")).devDependencies;
assert.equal(pins.three, "0.180.0");
assert.equal(pins["three-gpu-pathtracer"], "0.0.24");
assert.equal(pins["three-mesh-bvh"], "0.9.5");
});
test("rendering never waits on frames or the clock", () => {
const source = read("assets/render.js").replace(/^\s*\/\/.*$/gm, "");
for (const banned of [
"requestAnimationFrame",
"setAnimationLoop",
"performance.now",
"Date.now",
"scheduler.yield",
"compileAsync =",
"setTimeout",
"setInterval",
]) {
assert.ok(!source.includes(banned), `render.js uses ${banned}`);
}
assert.match(source, /tracer\.renderDelay = 0;/);
assert.match(source, /tracer\.stableNoise = true;/);
assert.match(source, /window\.__hf\.buildReady\[READY_KEY\] = ready;/);
assert.match(source, /event\.detail\.waitUntil\(queue\);/);
});
test("a pose depends only on its time, whatever was posed before", async () => {
const THREE = await import(new URL("../assets/vendor/three-path-tracer.min.js", import.meta.url));
const { createScene } = await import(new URL("../assets/scene.js", import.meta.url));
const { scene, camera, poseAt } = createScene(THREE, { aspect: 16 / 9 });
const snapshot = () => [
...camera.matrixWorld.elements,
...scene.children.flatMap((object) => object.matrixWorld.elements),
];
poseAt(4);
const atFour = snapshot();
poseAt(0);
const atZero = snapshot();
poseAt(2.5);
poseAt(4);
assert.deepEqual(snapshot(), atFour);
assert.notDeepEqual(atZero, atFour);
});
@@ -0,0 +1,10 @@
// Everything the starter imports, as one local ES module: all of three plus the tracer classes.
export * from "three";
export {
DenoiseMaterial,
GradientEquirectTexture,
PhysicalCamera,
PhysicalSpotLight,
ShapedAreaLight,
WebGLPathTracer,
} from "three-gpu-pathtracer";
@@ -0,0 +1,211 @@
#!/usr/bin/env node
// Renders the starter at 320x180 in both modes and checks the pixels that come out:
// - out-of-order seeks (4 s, 0 s, 4 s) give byte-identical PNGs for the same time;
// - a second page load draws the same 4 s still as the first (no per-load noise);
// - exported MP4 frames are neither blank nor frozen, and no step between frames jumps
// (path mode renders with two workers, so their chunks must join seamlessly).
// Needs ffmpeg on PATH. See README.md.
//
// node verify-render.mjs # uses `npx hyperframes`
// HYPERFRAMES_CLI=path/to/hyperframes.mjs node verify-render.mjs
import { spawnSync } from "node:child_process";
import { createHash } from "node:crypto";
import { cpSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { fileURLToPath } from "node:url";
const EXAMPLE = fileURLToPath(new URL("..", import.meta.url));
const WIDTH = 320;
const HEIGHT = 180;
const PATH_SAMPLES = 2;
// Setup includes the tracer's first shader run, which takes about a minute on a software GPU.
const READY_MS = "170000";
const env = { ...process.env, HYPERFRAMES_NO_TELEMETRY: "1", DO_NOT_TRACK: "1" };
const cli = process.env.HYPERFRAMES_CLI
? [process.execPath, process.env.HYPERFRAMES_CLI]
: ["npx", "--yes", "hyperframes"];
const scratch = mkdtempSync(join(tmpdir(), "path-traced-3d-verify-"));
const report = { size: `${WIDTH}x${HEIGHT}`, pathSamples: PATH_SAMPLES, steps: [] };
function fail(message) {
throw new Error(message);
}
function replaceOnce(text, from, to) {
if (!text.includes(from)) fail(`index.html no longer contains ${from}`);
return text.replace(from, to);
}
// A copy of the starter at a small size, with the renderer chosen through the variable defaults
// (snapshot has no --variables flag, so the defaults are what both commands read).
function makeProject(name, { renderer, duration }) {
const dir = join(scratch, name);
cpSync(join(EXAMPLE, "index.html"), join(dir, "index.html"));
cpSync(join(EXAMPLE, "assets"), join(dir, "assets"), { recursive: true });
let html = readFileSync(join(dir, "index.html"), "utf8");
html = html.replaceAll("1920", String(WIDTH)).replaceAll("1080", String(HEIGHT));
html = html.replaceAll('data-duration="6"', `data-duration="${duration}"`);
html = replaceOnce(html, '"default":"raster"', `"default":"${renderer}"`);
html = replaceOnce(html, '"default":64', `"default":${PATH_SAMPLES}`);
writeFileSync(join(dir, "index.html"), html);
return dir;
}
function run(label, args) {
const started = performance.now();
const result = spawnSync(cli[0], [...cli.slice(1), ...args], { env, encoding: "utf8" });
const seconds = Number(((performance.now() - started) / 1000).toFixed(1));
report.steps.push({ step: label, wallSeconds: seconds, exit: result.status });
if (result.status !== 0) {
fail(`${label} exited ${result.status}\n${result.stdout}\n${result.stderr}`);
}
return result.stdout;
}
function decode(file) {
const result = spawnSync(
"ffmpeg",
["-v", "error", "-i", file, "-f", "rawvideo", "-pix_fmt", "rgb24", "-"],
{ maxBuffer: 1 << 30 },
);
if (result.status !== 0) fail(`ffmpeg could not decode ${file}: ${result.stderr}`);
const frameBytes = WIDTH * HEIGHT * 3;
const frames = [];
for (let at = 0; at + frameBytes <= result.stdout.length; at += frameBytes) {
frames.push(result.stdout.subarray(at, at + frameBytes));
}
return frames;
}
function spread(pixels) {
let sum = 0;
let squares = 0;
for (const value of pixels) {
sum += value;
squares += value * value;
}
const mean = sum / pixels.length;
return Math.sqrt(squares / pixels.length - mean * mean);
}
function meanDifference(a, b) {
let total = 0;
for (let i = 0; i < a.length; i++) total += Math.abs(a[i] - b[i]);
return total / a.length;
}
const sha = (buffer) => createHash("sha256").update(buffer).digest("hex").slice(0, 16);
function checkSeekOrder(renderer) {
const dir = makeProject(`${renderer}-seek`, { renderer, duration: 6 });
const out = join(dir, "shots");
run(`${renderer} snapshot 4s, 0s, 4s`, [
"snapshot",
dir,
"--at",
"4,0,4",
"--no-end",
"--timeout",
READY_MS,
"-o",
out,
]);
const files = readdirSync(out)
.filter((file) => /^frame-\d+-at-.*\.png$/.test(file))
.sort();
if (files.length !== 3) fail(`${renderer}: expected 3 stills, found ${files.join(", ")}`);
const hashes = files.map((file) => sha(readFileSync(join(out, file))));
const frames = files.map((file) => decode(join(out, file))[0]);
report[`${renderer}SeekHashes`] = Object.fromEntries(files.map((file, i) => [file, hashes[i]]));
if (hashes[0] !== hashes[2]) fail(`${renderer}: 4 s differs after seeking back from 0 s`);
if (hashes[0] === hashes[1]) fail(`${renderer}: 0 s and 4 s are identical, nothing moved`);
for (const [i, frame] of frames.entries()) {
if (spread(frame) < 4) fail(`${renderer}: ${files[i]} is blank`);
}
return { atZero: frames[1], atFourHash: hashes[0] };
}
function checkReload(renderer, firstHash) {
const dir = makeProject(`${renderer}-reload`, { renderer, duration: 6 });
const out = join(dir, "shots");
run(`${renderer} snapshot 4s in a new page`, [
"snapshot",
dir,
"--at",
"4",
"--no-end",
"--timeout",
READY_MS,
"-o",
out,
]);
const file = readdirSync(out).find((name) => /^frame-\d+-at-.*\.png$/.test(name));
const hash = sha(readFileSync(join(out, file)));
report[`${renderer}ReloadHash`] = hash;
if (hash !== firstHash)
fail(`${renderer}: a new page drew 4 s differently (${hash} vs ${firstHash})`);
}
function checkExport(renderer, { duration, fps, workers }) {
const dir = makeProject(`${renderer}-export`, { renderer, duration });
const output = join(dir, "out.mp4");
run(`${renderer} render ${duration} s at ${fps} fps`, [
"render",
dir,
"--fps",
String(fps),
"--workers",
String(workers),
"--player-ready-timeout",
READY_MS,
"-o",
output,
]);
const frames = decode(output);
const expected = Math.round(duration * fps);
const spreads = frames.map((frame) => Number(spread(frame).toFixed(1)));
const firstToLast = Number(meanDifference(frames[0], frames.at(-1)).toFixed(2));
// A jump shows up as one step between neighbouring frames far larger than the typical one:
// a cold first frame, or grain that changes where one worker's chunk meets the next.
const steps = frames.slice(1).map((frame, i) => meanDifference(frames[i], frame));
const median = [...steps].sort((a, b) => a - b)[steps.length >> 1];
const stepRatios = steps.map((step) => Number((step / median).toFixed(2)));
report[`${renderer}Export`] = {
workers,
frames: frames.length,
spreads,
firstToLast,
stepRatios,
};
if (frames.length !== expected)
fail(`${renderer}: ${frames.length} frames, expected ${expected}`);
if (spreads.some((value) => value < 4)) fail(`${renderer}: an exported frame is blank`);
if (firstToLast < 0.5) fail(`${renderer}: first and last exported frames look the same`);
if (stepRatios.some((ratio) => ratio > 3)) fail(`${renderer}: a frame-to-frame step jumps`);
}
try {
run("check", [
"check",
makeProject("check", { renderer: "path", duration: 6 }),
"--timeout",
READY_MS,
]);
const raster = checkSeekOrder("raster");
const path = checkSeekOrder("path");
checkReload("path", path.atFourHash);
report.rasterVsPathAtZero = Number(meanDifference(raster.atZero, path.atZero).toFixed(2));
if (report.rasterVsPathAtZero < 0.5) fail("path mode drew the same pixels as raster mode");
checkExport("raster", { duration: 1, fps: 30, workers: 1 });
checkExport("path", { duration: 0.8, fps: 10, workers: 2 });
console.log(JSON.stringify(report, null, 2));
console.log("PASS");
} catch (error) {
console.error(JSON.stringify(report, null, 2));
console.error(`FAIL: ${error.message}`);
process.exitCode = 1;
} finally {
if (!process.env.KEEP_VERIFY_OUTPUT) rmSync(scratch, { recursive: true, force: true });
else console.log(`kept ${scratch}`);
}
+2 -2
View File
@@ -6,8 +6,8 @@
"files": 2
},
"hyperframes": {
"hash": "c8d63424db2726d3",
"files": 77
"hash": "7794480f96489b7d",
"files": 78
},
"hyperframes-cli": {
"hash": "571fffd79a7d42f9",
@@ -0,0 +1,36 @@
# Path-traced 3D
Path tracing gives real soft shadows, light bouncing between objects and reflections of the scene, at many times the cost of raster (75 times the export time in the measurement below). Start from the `path-traced-3d` example (`npx hyperframes init <dir> --example path-traced-3d`): a Three.js scene with a fast raster preview and an opt-in path-traced export, with three, three-gpu-pathtracer (WebGL) and three-mesh-bvh vendored as one pinned local file, so a 2D project never loads the tracer. Edit `assets/scene.js`; `assets/render.js` holds the contract below.
## Raster or path
| Variable | Use | Cost |
| ------------------------------ | ------------------------------------------------------------------------------------- | -------------------------------------------------------------- |
| `renderer: "raster"` (default) | Previews, drafts, timing, the Studio preview | Milliseconds a frame |
| `renderer: "path"` | The final export, when bounced light, soft shadows or inter-reflections are the point | Every frame traces `samples` passes of up to `bounces` bounces |
Preview in raster, then export once: `npx hyperframes render --variables '{"renderer":"path","samples":64}'`. Measured on an Apple M4 Max with a hardware GPU for an 8 s 720p clip: raster 10.8 s, path traced 810.5 s at 32 samples per pixel and 6 bounces. Noise falls with the square root of the samples, so halving it costs four times the samples, and every extra bounce makes each path longer; the example defaults to 64 samples and 4 bounces.
Without a hardware GPU, Chrome draws WebGL in software: on SwiftShader the tracer's first shader run alone took about a minute at 320×180, longer than the default 45 s readiness wait. Test path mode there at a few hundred pixels wide and 1 to 2 samples, and raise the wait: `--timeout 170000` for `check` and `snapshot`, `--player-ready-timeout 180000` for `render`. A setup that times out can be reported as "Composition has zero duration".
## The contract
- Setup is one `window.__hf.buildReady["<key>"]` promise: build the scene, `await renderer.compileAsync(scene, camera)`, construct the tracer, then draw one throwaway frame and read one pixel back. The first frame a renderer draws differs from later ones, and the readback makes the GPU finish that first, slowest run inside setup; `gl.finish()` can return before a software GPU has run the work.
- Draw only inside the `hf-seek` listener and register the work synchronously: `e.detail.waitUntil(promise)`. Queue each seek behind the previous one. Never start a loop (`renderer.setAnimationLoop`, a `requestAnimationFrame` loop).
- Every visible thing is a function of `e.detail.time`. Each new time calls `tracer.setScene` (objects moved) and accumulates exactly `samples` passes from zero; a repeat seek to the time already on the canvas does no work. Drive sampling by that count, never by elapsed time or the tracer's own "done" state.
- Set `tracer.renderDelay = 0`, `fadeDuration = 0`, `minSamples = 1`, `dynamicLowRes = false`, `rasterizeScene = false` and `stableNoise = true`. The tracer times its delay and fade with `THREE.Clock`, which reads a clock that does not move during a render.
- Seed `Math.random` while you build the scene and construct the tracer, then restore it. Anything created later (a model loaded during setup) must be built under the seed too. Three's object uuids come from it and set the order the tracer sorts lights, meshes and textures in, and the tracer builds its noise textures from it, so without a seed every page load (every render worker) draws different grain, which jumps where one worker's frames meet the next. Local renders leave `Math.random` native; only distributed renders seed it.
- Keep the set of lights and material features fixed over time. A change that alters the tracer's shader starts a compile inside a seek.
## The frozen clock
During a render `Date.now()` and `performance.now()` return the current seek time and do not move between seeks (0 until the first seek), and `requestAnimationFrame` callbacks wait until a seek, and the first seek waits for every `buildReady` promise. So setup that awaits an animation frame or waits for the clock to advance never finishes. Composition code uses no timers of its own; await the libraries' readiness promises instead:
- Raster: `await renderer.compileAsync(scene, camera)`.
- three-gpu-pathtracer 0.0.24 shows compilation only as the `isCompiling` flag. The promise behind it is three's `compileAsync`, so the example awaits that, `tracer._pathTracer._compilePromise`, in one small helper after any `renderSample` that leaves `isCompiling` set. It only decides when drawing may start, never what is drawn.
Never wait with `scheduler.yield()`: its continuations run ahead of timers, so a loop that yields until a compile finishes starves the `setTimeout` poll inside `compileAsync`, and the page hangs, with or without HyperFrames. Do not replace `renderer.compileAsync` with the synchronous `compile` to get around a hang; fix the wait.
## Check it
Snapshot a time, an earlier time, then the first again in one run: `npx hyperframes snapshot --at 4,0,4 --no-end`. The two stills at 4 s must be byte-identical. Then render a short clip and look at the frames themselves, not just the exit code. The example's `source/verify-render.mjs` in the HyperFrames repository does both in raster and path mode, renders path mode on two workers and checks that a new page load draws the same still.
+1 -1
View File
@@ -23,7 +23,7 @@ HyperFrames seeks each frame on its own, so motion must be a function of time, n
| anime.js v4 | Existing anime code | `autoplay: false`, push to `window.__hfAnime`, `anime.createSeededRandom` |
| Three.js, WebGPU, p5, canvas | 3D and generative | Draw from `e.detail.time` in an `hf-seek` listener; set `data-duration` on the root |
Charts and map overlays: drive them from a GSAP tween's `onUpdate`, not the library's own transitions. A real place is shown on baked imagery, not drawn (`film.md` "Maps and real places"). Heavy setup (big meshes, shader compiles) registers a `window.__hf.buildReady["<key>"]` promise.
Charts and map overlays: drive them from a GSAP tween's `onUpdate`, not the library's own transitions. A real place is shown on baked imagery, not drawn (`film.md` "Maps and real places"). Heavy setup (big meshes, shader compiles) registers a `window.__hf.buildReady["<key>"]` promise. Setup awaits library promises such as `renderer.compileAsync(...)`, never `requestAnimationFrame`, the clock, its own timers or `scheduler.yield()` (`path-tracing.md`).
## dotLottie browser setup
+1 -1
View File
@@ -1,6 +1,6 @@
# 3D, simulations and generative pieces
Use 3D when the film earns it: an object or a set as the payoff, a product, a simulation that explains. Loading Three.js, WebGPU, p5 or canvas and the seek protocol are in `../runtimes.md`.
Use 3D when the film earns it: an object or a set as the payoff, a product, a simulation that explains. Loading Three.js, WebGPU, p5 or canvas and the seek protocol are in `../runtimes.md`; path-traced light (soft shadows, bounced light, reflections between objects) with a fast raster preview is in `../path-tracing.md`.
## Deterministic by construction