From 7b500af3704d6b277fe6e765b9d089cc90bd0c81 Mon Sep 17 00:00:00 2001 From: lxf82dev Date: Tue, 10 Nov 2026 17:06:56 +0800 Subject: [PATCH 01/49] Add hybrid scenes: composite code-rendered elements inside footage A hybrid shot mixes footage (filmed or generated) with code-rendered elements that must agree with it: a product hidden by a passing hand, a headline behind a presenter, a price pinned to a moving sign, a product lit by the room it stands in. EditableFrames runs no model. Mattes, depth maps, tracks and camera paths are inputs from other tools; this change pins them, checks them and draws with them. - Derived assets: plate data records the hash of the footage it was computed from. A replaced take, a duplicate role or a frame-count mismatch is refused. asset-add gains --role/--of and depth flags, and JSON data assets are accepted. - editableframes/plate: corner pins, track and camera sampling, frame-rate conform, depth encodings, plate measurements, seeded grain, id colours and shutter sampling. Pure and renderer-independent. - editableframes/three-plate: depth occlusion, matte hold-out, lighting from the plate, camera replay, shadow catcher and control passes. - Renderer contract: optional mediaInfo and derived services, declared passes with clock.pass, render --pass. - Export: render --motion-blur averages sub-frame samples premultiplied. - init --hybrid: a starter whose synthetic plate, matte, depth and track come from one set of formulas, so tests state where pixels must land. - Fix transparent DOM-root exports capturing the preview page's header through the scene. Runtime files changed, so existing projects need their normal rebind. Co-Authored-By: Claude Fable 5.2 --- .github/workflows/ci.yml | 1 + CHANGELOG.md | 14 ++ README.md | 1 + bin/editableframe.mjs | 9 +- docs/architecture.md | 6 +- docs/hybrid-scenes.md | 201 +++++++++++++++++++ docs/media/README.md | 2 + docs/media/hybrid-passes.png | Bin 0 -> 9219 bytes docs/media/hybrid-starter.png | Bin 0 -> 28699 bytes docs/renderer-contract.md | 16 ++ docs/roadmap.md | 2 +- package.json | 5 +- packages/core/renderer.mjs | 3 + packages/plate/camera.mjs | 47 +++++ packages/plate/canvas.mjs | 47 +++++ packages/plate/color.mjs | 106 ++++++++++ packages/plate/conform.mjs | 33 +++ packages/plate/depth.mjs | 62 ++++++ packages/plate/homography.mjs | 66 ++++++ packages/plate/index.mjs | 13 ++ packages/plate/manifest.mjs | 37 ++++ packages/plate/motion-blur.mjs | 16 ++ packages/plate/passes.mjs | 24 +++ packages/plate/track.mjs | 48 +++++ packages/runtime/editor.mjs | 17 +- packages/runtime/renderer-compositor.mjs | 7 +- packages/runtime/renderer-host.mjs | 2 +- packages/three/plate.mjs | 181 +++++++++++++++++ scripts/demo-hybrid.mjs | 29 +++ scripts/media.mjs | 16 +- scripts/project.mjs | 18 +- scripts/render.mjs | 31 ++- skills/editableframes/SKILL.md | 4 + skills/editableframes/references/hybrid.md | 193 ++++++++++++++++++ skills/editableframes/references/renderer.md | 16 ++ templates/hybrid/clip.mjs | 98 +++++++++ tests/cli.test.mjs | 2 +- tests/hybrid-integration.mjs | 100 +++++++++ tests/plate.test.mjs | 176 ++++++++++++++++ 39 files changed, 1612 insertions(+), 37 deletions(-) create mode 100644 docs/hybrid-scenes.md create mode 100644 docs/media/hybrid-passes.png create mode 100644 docs/media/hybrid-starter.png create mode 100644 packages/plate/camera.mjs create mode 100644 packages/plate/canvas.mjs create mode 100644 packages/plate/color.mjs create mode 100644 packages/plate/conform.mjs create mode 100644 packages/plate/depth.mjs create mode 100644 packages/plate/homography.mjs create mode 100644 packages/plate/index.mjs create mode 100644 packages/plate/manifest.mjs create mode 100644 packages/plate/motion-blur.mjs create mode 100644 packages/plate/passes.mjs create mode 100644 packages/plate/track.mjs create mode 100644 packages/three/plate.mjs create mode 100644 scripts/demo-hybrid.mjs create mode 100644 skills/editableframes/references/hybrid.md create mode 100644 templates/hybrid/clip.mjs create mode 100644 tests/hybrid-integration.mjs create mode 100644 tests/plate.test.mjs diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 518e222..bd0a260 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -21,6 +21,7 @@ jobs: - run: npx playwright install --with-deps chromium - run: npm run test:beta - run: npm run test:renderer + - run: npm run test:hybrid - run: npm run test:browser website: name: Website validation diff --git a/CHANGELOG.md b/CHANGELOG.md index 3750737..843fc3c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,19 @@ # Changelog +## Unreleased + +Hybrid scenes: code-rendered elements composited with filmed or generated footage. See [hybrid scenes](docs/hybrid-scenes.md). + +- Add derived assets: a matte, depth map, normals, track, camera path or environment is pinned to the hash of the footage it was computed from. A replaced take, a second asset for one role, or a derived video with a different frame count is refused. `asset-add` gains `--role`, `--of` and depth-encoding flags; JSON `data` assets are accepted. +- Add `editableframes/plate`: corner-pin homographies, track and camera-path sampling, frame-rate conform and cadence, depth encodings, plate measurements (levels, light direction, noise), seeded grain, object-id colours and shutter sampling. +- Add `editableframes/three-plate`: depth occlusion by the footage, matte hold-out, lighting from the footage, camera-path replay, a shadow catcher and clay/depth/normal/id/matte passes. +- Add optional `mediaInfo` and `derived` renderer services, declared control passes (`passes`, `clock.pass`) and `render --pass`. +- Add shutter motion blur at export: `render --motion-blur ANGLE [--samples N]`. +- Add `init --hybrid`, a starter with a synthetic plate, and `npm run test:hybrid`. +- Fix transparent DOM-root exports capturing the preview page's own header through the scene. Any transparent renderer export smaller than the header area was affected. + +Runtime files changed, so existing projects need their normal `rebind`. + ## 0.1.0-beta.1 — 2026-10-07 First beta for trusted local-code projects. No remote publication is implied. diff --git a/README.md b/README.md index e295ea8..e9b31cb 100644 --- a/README.md +++ b/README.md @@ -76,6 +76,7 @@ These are original code-built studies and previews, not copies of other creators - **Give each clip the right controls.** Expose a camera for a 3D scene, colors for a title, or media timing for an embedded speaker. Panels support conditional fields, presets and numeric macros. - **Let people and agents refine the same work.** Stable anchors, validated changes, saved history and undo/redo make targeted edits practical. - **Bring video into the scene.** Import an MP4 as an editable media port, with timing, playback speed and audio controls. Export an opaque video or a transparent overlay. +- **Put code inside footage.** Let a filmed or generated shot hide, light and carry code-rendered elements: a product behind a passing hand, a headline behind a presenter, a price pinned to a moving sign. Mattes, depth and tracks are pinned inputs from any tool; no model runs here. See [hybrid scenes](docs/hybrid-scenes.md). - **Choose your model and host.** No Stitchable account, Remotion dependency or model API key is required by the framework. The shared skill and CLI are available for Claude Code, Codex and other tool-capable agents, including Grok; host-specific setup is documented separately. ## Try it diff --git a/bin/editableframe.mjs b/bin/editableframe.mjs index 2c8bf2a..edad244 100755 --- a/bin/editableframe.mjs +++ b/bin/editableframe.mjs @@ -3,18 +3,19 @@ import fs from 'node:fs/promises';import path from 'node:path'; import {root,buildApps} from '../scripts/build.mjs';import {serve} from '../scripts/server.mjs';import {init,readProject,mutate,preview,rebind,importAsset} from '../scripts/project.mjs'; const [cmd,...args]=process.argv.slice(2),out=v=>console.log(JSON.stringify(v,null,2)); try{ - if(cmd==='init')out(await init(args[0]||'my-clip',{template:args.includes('--media')?'media':args.includes('--renderer')?'renderer':'canvas'})); + const flag=name=>{const i=args.indexOf(name);return i<0?undefined:args[i+1]}; + if(cmd==='init')out(await init(args[0]||'my-clip',{template:args.includes('--media')?'media':args.includes('--renderer')?'renderer':args.includes('--hybrid')?'hybrid':'canvas'})); else if(cmd==='inspect'){const d=await readProject(args[0]),cap=d.studio.capabilities(d.studio.doc.clips[0].id);out({...cap,baseRevision:d.revision,history:{length:d.studio.history.length,cursor:d.studio.cursor}})} else if(cmd==='apply'){const p=JSON.parse(await fs.readFile(args[1],'utf8'));out(await mutate(args[0],d=>{if(p.baseRevision!==d.revision)throw Error('Stale revision: inspect again');d.studio.execute(p.command,d.studio.revision,'model')}))} - else if(cmd==='asset-add')out(await importAsset(args[0],args[1],args[2])); + else if(cmd==='asset-add'){const depth=flag('--depth');out(await importAsset(args[0],args[1],args[2],{role:flag('--role'),of:flag('--of'),encoding:depth?{kind:depth,near:Number(flag('--near')),far:Number(flag('--far')),packing:flag('--packing')??'gray8'}:undefined}));} else if(cmd==='rebind')out(await rebind(args[0],{reset:args.includes('--reset')})); else if(cmd==='undo'||cmd==='redo')out(await mutate(args[0],d=>d.studio[cmd]())); else if(cmd==='preview'){const h=await preview(args[0],{port:Number(args[1]||8791)});console.log(h.url);for(const signal of ['SIGINT','SIGTERM'])process.once(signal,async()=>{h.server.closeAllConnections?.();await h.close();process.exit(0)})} else if(cmd==='studio'){await buildApps();const h=await serve(root,{port:Number(args[0]||8790)});console.log(h.url)} - else if(cmd==='render'){const {render}=await import('../scripts/render.mjs');const option=name=>{const i=args.indexOf(name);return i<0?undefined:args[i+1]};const controller=new AbortController();process.once('SIGINT',()=>controller.abort());out(await render(args[0],args[1],{frames:option('--frames')?Number(option('--frames')):args[2]&&!args[2].startsWith('--')?Number(args[2]):undefined,fps:option('--fps'),format:option('--format'),background:option('--background'),signal:controller.signal,onProgress:p=>{if(p.phase!=='frames'||p.frame%24===0)console.error(JSON.stringify(p))}}))} + else if(cmd==='render'){const {render}=await import('../scripts/render.mjs');const option=name=>{const i=args.indexOf(name);return i<0?undefined:args[i+1]};const controller=new AbortController();process.once('SIGINT',()=>controller.abort());out(await render(args[0],args[1],{frames:option('--frames')?Number(option('--frames')):args[2]&&!args[2].startsWith('--')?Number(args[2]):undefined,fps:option('--fps'),format:option('--format'),background:option('--background'),pass:option('--pass'),motionBlur:option('--motion-blur')?{angle:Number(option('--motion-blur')),samples:option('--samples')?Number(option('--samples')):8}:undefined,signal:controller.signal,onProgress:p=>{if(p.phase!=='frames'||p.frame%24===0)console.error(JSON.stringify(p))}}))} else if(cmd==='assets'){const {run}=await import('../scripts/assets.mjs');await run(args)} else if(cmd==='install-skill'){const {install}=await import('../scripts/install-skill.mjs');out(await install(args[0],args[1]))} else if(cmd==='doctor'){const {run,ffmpeg,ffprobe}=await import('../scripts/process.mjs');const {chromium}=await import('playwright');const checks={};for(const [name,command]of [['ffmpeg',ffmpeg()],['ffprobe',ffprobe()]]){try{checks[name]=(await run(command,['-version'])).toString().split('\n')[0]}catch(e){checks[name]='MISSING: '+e.message}}try{await fs.access(chromium.executablePath());checks.browser='installed'}catch{checks.browser='MISSING: run npx playwright install chromium'}out({node:process.version,version:'0.1.0-beta.1',platform:process.platform,checks,ready:Object.values(checks).every(x=>!x.startsWith('MISSING')),trust:'Local trusted source; not an untrusted-code sandbox',distribution:'source-checkout',npmPublished:false})} - else if(!cmd||cmd==='help'||cmd==='--help')console.log(`EditableFrames 0.1.0-beta.1\n\n init DIR [--media|--renderer] Create an editable clip (media demo needs FFmpeg)\n rebind DIR [--reset] Accept edited source; archive prior project\n inspect DIR JSON controls + current file revision\n apply DIR proposal.json Revision-checked atomic edit\n undo DIR | redo DIR Saved edit history\n preview DIR [PORT] Preview trusted code on loopback\n render DIR OUTPUT [--frames N] [--fps 30000/1001] [--format png]\n .mp4 = opaque; .mov = alpha ProRes4444\n asset-add DIR ID FILE Pin local media; rebind then swap a port\n studio [PORT] Open all bundled studies and device library\n assets list|verify|pack|install-pack [FILE]\n install-skill codex|claude|grok|generic TARGET\n doctor Show environment requirements\n\nCustom clip modules are executable JavaScript. Use trusted projects.\nNo model, account, cloud service, or Stitchable installation required.`); + else if(!cmd||cmd==='help'||cmd==='--help')console.log(`EditableFrames 0.1.0-beta.1\n\n init DIR [--media|--renderer|--hybrid] Create an editable clip (media and hybrid demos need FFmpeg)\n rebind DIR [--reset] Accept edited source; archive prior project\n inspect DIR JSON controls + current file revision\n apply DIR proposal.json Revision-checked atomic edit\n undo DIR | redo DIR Saved edit history\n preview DIR [PORT] Preview trusted code on loopback\n render DIR OUTPUT [--frames N] [--fps 30000/1001] [--format png]\n [--pass clay|depth|normal|id|matte] [--motion-blur ANGLE [--samples N]]\n .mp4 = opaque; .mov = alpha ProRes4444\n asset-add DIR ID FILE Pin local media; rebind then swap a port\n [--role matte|depth|normals|track|camera|environment --of PLATE_ID]\n [--depth inverse|linear --near N --far F] Data derived from a plate\n studio [PORT] Open all bundled studies and device library\n assets list|verify|pack|install-pack [FILE]\n install-skill codex|claude|grok|generic TARGET\n doctor Show environment requirements\n\nCustom clip modules are executable JavaScript. Use trusted projects.\nNo model, account, cloud service, or Stitchable installation required.`); else throw Error('Unknown command. Run editableframes help'); }catch(e){console.error(e.message);process.exitCode=1} diff --git a/docs/architecture.md b/docs/architecture.md index c21c28f..8b4a3aa 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -38,13 +38,13 @@ not imply depth, layer, simulation, device or audio-automation services. See the `AdapterRegistry` supports versioned adapters with `create(context)` returning `render(frame)`. An adapter can declare required host services. `createEffectHost` supplies only real implementations; missing services produce an explicit error. The initial demos include direct rendering paths as well as this optional registry. They do not yet all route through a single scheduler. -The beta media host supplies `frameAt` and editable `portFrame`. General `layerAt`, `audioAt`, `maskAt`, `depthAt`, and `simulationAt` services remain extension work. Frame identity must include source revision, time, quality, color and effect order. Temporal effects must define whether they sample original source or upstream composition. Do not fake frame history by repeatedly drawing the same current frame. +The beta media host supplies `frameAt` and editable `portFrame`. Mattes, depth maps, tracks and camera paths reach a renderer as ordinary pinned assets linked to the footage they were computed from (`mediaInfo`, `derived`; see [hybrid scenes](hybrid-scenes.md)). General `layerAt`, `audioAt` and `simulationAt` services, and depth ordering between separate clips, remain extension work. Frame identity must include source revision, time, quality, color and effect order. Temporal effects must define whether they sample original source or upstream composition. Do not fake frame history by repeatedly drawing the same current frame. ## Implemented and proposed -Implemented: authoring core, disk-backed panel editor, revision-checked agent proposals, procedural Canvas/Three/WebGL2 studies, floating-point effects, device lighting, shared clip compositor, PTS-indexed local media frames, static audio-port mixing, rational frame exports and RGBA/ProRes transparency. See beta.md for the exact supported contract. +Implemented: authoring core, disk-backed panel editor, revision-checked agent proposals, procedural Canvas/Three/WebGL2 studies, floating-point effects, device lighting, shared clip compositor, PTS-indexed local media frames, static audio-port mixing, rational frame exports and RGBA/ProRes transparency. See beta.md for the exact supported contract. Since beta 1: derived plate assets, depth occlusion, matte cut-outs, corner pins, lighting from a plate, declared control passes and shutter motion blur at export (hybrid-scenes.md). -Proposed: streaming/hardware media decode, depth/ID sources, audio automation, untrusted-code sandboxing, distributed scheduling, EffectCraft/WASM bridge, broader DOM/media conformance, device-profile unification and explicit schema migration maps. +Proposed: streaming/hardware media decode, depth ordering between clips, audio automation, untrusted-code sandboxing, distributed scheduling, EffectCraft/WASM bridge, broader DOM/media conformance, device-profile unification and explicit schema migration maps. New custom code remains supported even when it exposes no editable controls. Unknown capabilities must not be discarded or converted to a smaller primitive vocabulary. In this beta, unknown template adapters prevent loading rather than mutating the saved document. diff --git a/docs/hybrid-scenes.md b/docs/hybrid-scenes.md new file mode 100644 index 0000000..1d652b6 --- /dev/null +++ b/docs/hybrid-scenes.md @@ -0,0 +1,201 @@ +# Hybrid scenes: code inside footage + +A hybrid scene combines two kinds of picture in one shot: + +- **Footage** (a "plate"): filmed, or made by a video model. It supplies what only has to look real: people, places, weather, light. +- **Code**: it supplies what has to be exactly right: the product's shape and label, a price, an interface, a chart, a logo, a caption. + +Stacking one on top of the other is easy and already worked. This document covers the harder case, where the two must agree with each other: a hand passes in front of a code-rendered product, a headline sits behind a presenter, a price stays stuck to a moving sign, the product is lit by the room it stands in. + +![Two frames of the hybrid starter: a code-rendered can inside a synthetic plate. On the right, the plate's foreground bar passes in front of the can and the headline, while the price stays pinned to the moving board.](media/hybrid-starter.png) + +*The hybrid starter, frames 7 and 34. The plate is a synthetic diagnostic pattern, not footage. The can, its label, the price screen and the headline are code.* + +## Goal + +Make a code-rendered element belong to the footage it is placed in, while keeping what EditableFrames is for: the code part stays an editable document. Changing the label, the price or the language re-renders the same frames with only that change. Nothing is regenerated and the footage is not touched. + +EditableFrames does not run any model. Mattes, depth maps, tracks and camera paths are **inputs**. You make them with whatever tool you trust and license, and EditableFrames pins them, checks them and draws with them. This keeps the framework model-neutral and keeps export deterministic: the same inputs give the same frames. + +## Video creation journeys + +Each journey says what the author does, what EditableFrames does, and how far it is proven. + +| # | Journey | The author supplies | EditableFrames does | Proven by | +|---|---|---|---|---| +| 1 | **A product in a generated place.** A hard-surface product sits in a scene made by a video model and takes on its light. | The plate. | Wraps the plate into an environment, estimates which side the light is on, and lights the product with both. Lighting from the plate is an editable, undoable control. | Integration test: the lit side follows the bright area, the colour follows the plate, toggling it changes only the product. | +| 2 | **Something in the footage passes in front of the product.** A hand, a person, a pillar. | The plate and a depth map of it. | Writes the plate's depth into the depth buffer, so every mesh is hidden exactly where the footage is nearer. | Integration test: the product is covered by the plate foreground and visible beside it. | +| 3 | **A headline behind the presenter.** Text or graphics sit between the subject and the background. | The plate and a matte of the subject. | Redraws the matted subject over the DOM layers. | Integration test: no headline pixel survives in front of the subject, and the text continues on both sides. | +| 4 | **Screen or label replacement.** An exact interface, price or label sits on a surface that moves in the footage. | The plate and a planar track of the surface. | Pins a DOM element to the tracked quad on every frame, including between frames. | Integration test: the element covers the tracked surface edge to edge as it moves. | +| 5 | **Code first, footage second.** The code scene sets the camera and blocking; a video model paints a world around it; the exact product goes back on top. | A scene that declares control passes. | Exports the scene as clay, depth, normal, object-id and matte passes from the same camera and timing. | Integration test for the passes. Sending them to a video model and compositing the result is outside this repository and unproven here. | +| 6 | **Many versions from one take.** The same shot in twenty prices, five languages, three label colours. | One plate and its data, then control edits. | Re-renders each version from the same pinned inputs. If the plate is replaced, its old matte, depth and track are refused instead of being composited slightly wrong. | Integration test for the refusals; edits use the existing revision-checked history. | +| 7 | **Fast motion.** Code elements that move quickly should smear like the footage does. | A shutter angle. | Renders several sub-frame samples per output frame and averages them. | Integration test: smear width and edge colour. | +| 8 | **A moving camera.** The product stays put in a shot whose camera travels. | A camera path solved elsewhere. | Replays the path on a Three.js camera, with rotation interpolated correctly. | Unit tests only. Not yet tried on a real solve; solves of generated footage are approximate. | + +## Try it + +```sh +node bin/editableframes.mjs init ./my-hybrid --hybrid +node bin/editableframes.mjs preview ./my-hybrid +node bin/editableframes.mjs render ./my-hybrid ./hybrid.mp4 +node bin/editableframes.mjs render ./my-hybrid ./hybrid-blur.mp4 --motion-blur 180 +node bin/editableframes.mjs render ./my-hybrid ./clay --format png --pass clay +``` + +The starter generates its own plate, matte, depth map and track with FFmpeg from one set of formulas, so tests can state where every pixel must land. Replace them with your own: + +```sh +node bin/editableframes.mjs asset-add ./my-hybrid shot ./shot.mp4 +node bin/editableframes.mjs asset-add ./my-hybrid shot-matte ./shot-matte.mp4 --role matte --of shot +node bin/editableframes.mjs asset-add ./my-hybrid shot-depth ./shot-depth.mp4 --role depth --of shot --depth inverse --near 1 --far 20 +node bin/editableframes.mjs asset-add ./my-hybrid shot-track ./shot-track.json --role track --of shot +node bin/editableframes.mjs rebind ./my-hybrid +``` + +## Layers + +Back to front, this order is right for most shots: + +1. **Plate.** +2. **Far DOM**: screens pinned to surfaces in the background; text that passes behind the subject. +3. **Cut-out**: the plate's subject again (plate × matte), which restores it over layer 2. +4. **3D canvas**, depth-tested against the plate's depth. Depth decides per pixel whether the subject or the object is in front, so the canvas can sit above the cut-out. +5. **Near DOM**: captions, calls to action, logos. + +A scene can draw all five itself, as the starter does. That keeps one clock and one set of inputs. Depth ordering between separate clips is not available: clips stack with a transform and opacity only. + +## Plate data + +Data computed from a plate is declared in `assets.json` as a **derived** asset. It records the hash of the plate it was computed from: + +```json +"shot-matte": {"src": "assets/…mp4", "type": "video", "sha256": "…", + "derived": {"of": "shot", "role": "matte", "sourceSha256": ""}} +``` + +`asset-add --role … --of …` writes this for you. + +| Role | Type | Meaning | +|---|---|---| +| `matte` | video or image | White keeps the subject, black drops it. Luminance is coverage. | +| `depth` | video or image | Distance from the camera. White is near. Needs an `encoding` (below). | +| `normals` | video or image | Camera-space normals, `(n + 1) / 2` in RGB. Accepted and pinned; no helper consumes it yet. | +| `track` | data (JSON) | A planar or point track. See `packages/plate/track.mjs`. | +| `camera` | data (JSON) | A camera path. See `packages/plate/camera.mjs`. | +| `environment` | image | An equirectangular picture of the plate's surroundings. Accepted and pinned; the starter does not use one. | + +Rules, each refused with a message that says what to do: + +- The plate's hash must equal `sourceSha256`. A regenerated take invalidates its derived data. +- A plate has at most one asset per role. +- A derived asset cannot derive from another derived asset. +- A derived video must have exactly as many frames as its plate. +- A depth asset must carry an encoding. Tracks and camera paths are validated when loaded. + +**Depth encoding** is `{kind, near, far, packing}`. `kind` is `inverse` (what monocular depth models emit; precision is spent close to the camera) or `linear`. `near` and `far` are the distances white and black stand for, in scene units. `packing` is `gray8`, or `rg16` for 16 bits across red and green. Relative depth has no true scale, so `near` and `far` are values you tune until occlusion lands. They are not measurements. + +**Track** files are `{version: 1, kind: "planar" | "point", width, height, frameRate: {num, den}, frames: [{frame, quad | point, confidence?}]}`. Coordinates are plate pixels from the top-left. Quads are ordered top-left, top-right, bottom-right, bottom-left. Frames may be sparse; samples between them are interpolated, and samples outside them hold the nearest frame and say so. + +**Camera path** files are `{version: 1, frameRate, frames: [{frame, position, quaternion, fovY}]}`: camera-to-world, +Y up, looking down −Z, `fovY` in degrees. + +## Renderer contract additions + +Two optional services join `asset` and `mediaFrame`. Check that they exist before using them. + +- `context.mediaInfo(id)` returns `{type, width, height, duration, frames, frameRate, derived}` for a declared asset. +- `context.derived(id, role)` returns the id of the asset derived from `id` with that role, or `undefined`. + +`mediaFrame(id, seconds)` serves matte and depth frames like any other video. `asset(id)` returns a URL for a data asset; fetch it and parse the JSON. + +A scene may declare **control passes**: + +```js +defineRenderer({ …, passes: ['clay', 'depth', 'normal', 'id', 'matte'], … }) +``` + +![The starter's can drawn four ways: clay, depth, normals and object ids.](media/hybrid-passes.png) + +*Clay, depth, normal and object-id passes of the starter, exported with `render --pass`.* + +The host then supplies `clock.pass` (`'beauty'` unless a pass was requested). A host never asks for a pass the scene did not declare, and the CLI refuses one. Pass names are open, like renderer names. `beauty` is implied and cannot be declared. + +## Helpers + +`editableframes/plate` is pure and renderer-independent: + +| Area | Functions | +|---|---| +| Corner pin | `solveHomography`, `applyHomography`, `invertHomography`, `cornerPinTransform`, `cssMatrix3d`, `quadArea` | +| Tracks | `validateTrack`, `sampleTrack`, `scalePoints` | +| Camera | `validateCameraPath`, `sampleCameraPath`, `slerp` | +| Frame rate | `plateFrameIndex`, `conformSeconds`, `cadence` | +| Depth | `validateDepthEncoding`, `decodeDepth`, `encodeDepth`, `packDepth`, `unpackDepth`, `depthGlsl`, `unprojectDepth`, `fitGroundPlane` | +| Measuring a plate | `plateStats`, `matchLevels`, `applyLevels`, `estimateKeyLight`, `estimateNoise`, `grainAt`, `expandHighlights` | +| Passes | `idColor`, `idFromColor`, `validatePasses` | +| Canvas | `drawCutout`, `drawGrain`, `createFrameLoader` | +| Shutter | `shutterSamples`, `validateShutter` | + +`editableframes/three-plate` is an optional Three.js adapter: + +| Function | Purpose | +|---|---| +| `createDepthOccluder(encoding)` | Lets the plate's own geometry hide the scene. Needs WebGL2, a perspective camera and the standard depth buffer. | +| `createMatteHoldout()` | Punches the matted subject out of the canvas. The cheap alternative when there is no depth; it is all-or-nothing per pixel. | +| `createPlateEnvironment(renderer)` | Lights the scene with the plate. | +| `applyKeyLight(light, estimate)` | Aims a directional light from `estimateKeyLight`. | +| `applyCameraSample(camera, sample)` | Replays a camera path. | +| `createShadowCatcher(plane)` | An invisible plane that shows only shadows, laid on a plane from `fitGroundPlane`. | +| `renderPass(renderer, scene, camera, pass, options)` | Draws the scene as clay, depth, normal, id or matte. | +| `dataTexture(image)` | A texture for plate data with no colour management. | + +None of this narrows what a renderer may draw. A scene that uses other libraries can read the same assets and implement its own passes. + +## What is estimated, and how far to trust it + +Three helpers guess from a single view. Expose their results as controls. + +- **`estimateKeyLight`** reads which side the light is on from the brightest 5% of the frame. A picture cannot say how far in front of or behind the subject the light is, so that part is a stated assumption: a small source is placed level with the subject, a broad one in front of it. +- **`createPlateEnvironment`** has only what the camera saw. It puts the plate in front and a mirrored copy behind the camera, and pushes clipped highlights above 1 so they can act as light sources. The result is plausible. It is not a measurement of the real surroundings, and the highlight boost is not recovered data. Use a real `environment` asset when you have one. +- **Depth `near` and `far`** are yours to tune, as above. + +## Frame rate + +Video models emit a fixed rate: commonly 24 fps, sometimes 16 or 30. Two things follow. + +- Anything locked to the footage should move on the footage's frame grid. `conformSeconds(seconds, plate.frameRate)` gives the time of the plate frame on screen; sample tracks, mattes and depth at that time. Otherwise a pinned element slides against the picture between plate frames. +- A plate inside a timeline of another rate repeats frames unevenly. `cadence({num: 24, den: 1}, {num: 30, den: 1})` reports the pattern `2,1,1,1`, which is visible as judder on any move. Render the project at the plate's rate, or interpolate the plate before importing it. + +## Export + +- `render DIR OUT --pass NAME` renders a declared pass. The receipt records it. +- `render DIR OUT --motion-blur ANGLE [--samples N]` opens a shutter of `ANGLE` degrees (0–360, default samples 8, range 2–64) centred on each frame. Samples are averaged as premultiplied colour, so a half-covered pixel keeps its hue. The mean is taken on encoded values, not linear light. Preview shows no motion blur. +- An export re-encodes its inputs. Content credentials or other provenance metadata carried by a generated plate are not copied to the output. If a law or a platform requires you to disclose AI-generated content, that remains your responsibility. + +## Compared with a full compositing checklist + +Professional compositing uses more steps than this. Stated plainly: + +| Step | Status | +|---|---| +| Occlusion by plate geometry | Done, from a depth map. | +| Subject in front of graphics | Done, from a matte. | +| Planar tracking and corner pin | Drawing done. The track comes from another tool. | +| Reflections of the plate in the object | Approximated by `createPlateEnvironment`. | +| Light direction | Estimated; editable. | +| Black and white point match | Measured by `plateStats` / `matchLevels`. Applying it is left to the scene. | +| Grain match | Measured by `estimateNoise`; `drawGrain` adds seeded grain. Not applied by the starter. | +| Motion blur | Done at export, for code layers. | +| Shadow of the object on the plate | `fitGroundPlane` and `createShadowCatcher` exist. Not exercised by the starter or the integration test. | +| Camera match | Replay only. No solver. | +| Depth of field, lens distortion, chromatic aberration, light wrap, atmospheric haze | Not provided. | +| Reflection or shadow of the object in the plate's own surfaces | Not provided. It needs the plate's normals and roughness. | +| Linear-light compositing | Not provided. Layers are composited by the browser on encoded values. | + +## Limits + +- The plate, matte and depth are decoded to PNG frames before preview and export, within the existing 8 GiB budget. Three videos per shot use it three times as fast. +- A renderer scene has no audio port. Sound from footage inside a scene is not mixed; keep speech on a media-port clip. +- `createDepthOccluder` assumes the plate and the scene share one camera. A depth map from a monocular model is consistent with itself, not with your scene units. +- Antialiased edges mix values, so `id` and `depth` passes are exact only away from silhouettes. `renderPass` does not handle skinned or instanced meshes. +- Results differ slightly across GPUs and browsers, as elsewhere in this framework. +- The tests use a synthetic plate. They prove that pixels land where the inputs say. They do not prove that a particular matting, depth or tracking tool gives good inputs on real footage. diff --git a/docs/media/README.md b/docs/media/README.md index fbb3a30..b47c0d0 100644 --- a/docs/media/README.md +++ b/docs/media/README.md @@ -7,3 +7,5 @@ Actions are actual UI interactions: raise Tower height from 1 to 1.4, set Trees The recording uses the standalone film study, whose edits can be saved by downloading a project snapshot. Disk-backed project previews additionally persist edits immediately. This GIF does not demonstrate a hosted account, a remote agent session or an export. Gallery thumbnails elsewhere in the README are existing renders from `apps/films/previews`, `apps/effects/previews` and `assets/devices/previews`. No private posts or third-party screenshots are included. Device credits are in `assets/devices/ATTRIBUTIONS.txt`. + +`hybrid-starter.png` and `hybrid-passes.png` are frames of the `init --hybrid` starter rendered by the CLI: frames 7 and 34 of the picture, and the clay, depth, normal and object-id passes of frame 1 over a dark backdrop. The plate in them is a synthetic diagnostic pattern generated by FFmpeg, not footage. diff --git a/docs/media/hybrid-passes.png b/docs/media/hybrid-passes.png new file mode 100644 index 0000000000000000000000000000000000000000..167b043c66856fce9043dd7d65ec2c36c04b1047 GIT binary patch literal 9219 zcmeHtc`%#p*MBIb6z!u#8$|a-(bkgMX{o2RRTWi)QcJ9@wGs)cXn9mOJF(SXTM=7= z7S-B`C5f%n9-$S9HOVh+p6|^2&b%|f`Th6)@w;b|`&`$3&biKYmMb}*xnJBiF%S|s zCIA2cgl_(=cLxCAWs`tv{{8IluIO+@_U*u^@ClQl#QUB%3ua-vk7PlTYN?Kfa`2!MTo^WU8 zR?!<^5%w!+?p#4AmOu_3H0b8C_f3uvpx}qHG`4 zzi(y5k?UgEM8?GA8s7>9jV7j`;{0JL*13&lHpMQpYeZ*d!CoRUiir3o-)@InA`OobEy^GkJi|Y zS%0jxfoT5`Qh{H+_0hLE_?1gLli*31pl3+-jWO4F0gyW*+EYXC&neOR-kq5e|MaFb z5^}P~lI)n;kW+Bg#E8*V6bcATzM~j>#{q5mJozKlsjuC`%P+lpX#yU?oqd`5`HcR&UeE^%a|h^< z`_Ry(IL)*n;?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?L0O&Laq=&yQersFzamR^q3MC94{Q`C0 z7y96&;+M+q1_s|f_&Hqg~1At9U2KQ_|;)Ua>iwnf9@ zFRfX>_th51StdS_$6O5wBz84Hy1^<55g0>ietnAngByrD{uq+|(@x{H+swl&cmZD( z{0U?{146B*`1e568nl}t2g@E_oW2~H0E+)g0l0MeIq-W_T-9#2vG}xhr~{N=;{z}T z;khy0wHrYH^Rj}c7XChG(fR8SC@4lC)-9H*rlDt5Q96aRXBD=^U;f+7u7s(Yg}Lm5 zP;Q4)OYLpzbKDB_H~4Kp7da3n4rJMxSR)s8sSAO-S|jeTFaxV?3mB`Jbqb8rB7AjMqmFI3bNJ0 literal 0 HcmV?d00001 diff --git a/docs/renderer-contract.md b/docs/renderer-contract.md index c463e9a..13c0966 100644 --- a/docs/renderer-contract.md +++ b/docs/renderer-contract.md @@ -129,6 +129,22 @@ path does not mix arbitrary DOM audio automatically. Legacy media-port audio kee its existing mixing path. `captureSurface` is absent in this host. Feature-check optional services; do not invent layer, depth, simulation or screen services. +`context.mediaInfo(id)` returns `{type, width, height, duration, frames, frameRate, +derived}` for a declared asset. `context.derived(id, role)` returns the ID of the +asset computed from `id` with that role (`matte`, `depth`, `normals`, `track`, +`camera`, `environment`), or undefined. Both exist only when the project declares +media. A `data` asset is JSON: fetch `asset(id)` and parse it. See +[hybrid scenes](hybrid-scenes.md) for compositing code with footage. + +## Optional control passes + +A scene may declare `passes: ['clay', 'depth', …]`: other ways it can draw +itself, for conditioning a video model or compositing elsewhere. Names are open +lowercase identifiers; `beauty` is implied and cannot be declared. The host +supplies `clock.pass`, which is `'beauty'` unless a pass was requested, and never +requests a pass the scene did not declare. `render DIR OUT --pass NAME` exports +one. Draw nothing but the pass: hide footage and DOM layers. + When exposing controls for separate components, use distinct stable semantic anchors and matching properties. Connect controlled DOM nodes to those IDs, or implement Canvas/WebGL picking against the current rendered geometry and props. diff --git a/docs/roadmap.md b/docs/roadmap.md index 6184942..4b6dd4b 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -6,7 +6,7 @@ The implemented beta contract and verification commands are in [beta.md](beta.md 2. Streaming demux/decode with bounded on-disk caches, hardware backends, performance benchmarks and native webview parity. 3. Audio automation, exact browser audio scheduling, mastering/loudness and additional export containers/deliverables. 4. Explicit source/schema migration maps, restoring historic dependency graphs, incremental timeline state and large-project benchmarks. -5. DOM capture and additional output adapters, general depth/layer/mask/simulation services, measured EffectCraft/WASM bridges. +5. DOM capture and additional output adapters, depth ordering between clips and general layer/simulation services, measured EffectCraft/WASM bridges. For [hybrid scenes](hybrid-scenes.md): depth of field and lens matching, light wrap, linear-light compositing, shadows and reflections cast onto footage, and a real-footage acceptance set. 6. Unify device looks and more film/effect studies as generic project adapters; finish per-model screen calibration. 7. Promote research labs for maps, fashion, avatars and other genres using the same media/adapter/credit contracts. 8. Validate live agent-host installation and evaluate MCP packaging; publish an actual repository/release and asset-pack URLs when requested. diff --git a/package.json b/package.json index 3f258d4..c122474 100644 --- a/package.json +++ b/package.json @@ -27,6 +27,8 @@ "./manipulation": "./packages/core/manipulation.mjs", "./three-manipulation": "./packages/three/manipulation.mjs", "./key-timing": "./packages/core/key-timing.mjs", + "./plate": "./packages/plate/index.mjs", + "./three-plate": "./packages/three/plate.mjs", "./rotation": "./packages/core/rotation.mjs", "./spatial-session": "./packages/core/spatial-session.mjs", "./three-editor": "./packages/three/spatial-editor.mjs" @@ -46,7 +48,8 @@ "test:renderer": "node tests/renderer-integration.mjs", "build:scene": "node examples/scene-editor/build.mjs", "dev:scene": "node examples/scene-editor/serve.mjs", - "test:scene": "node tests/scene-editor-browser.mjs" + "test:scene": "node tests/scene-editor-browser.mjs", + "test:hybrid": "node tests/hybrid-integration.mjs" }, "dependencies": { "esbuild": "0.25.10", diff --git a/packages/core/renderer.mjs b/packages/core/renderer.mjs index 37eccc8..7d0787b 100644 --- a/packages/core/renderer.mjs +++ b/packages/core/renderer.mjs @@ -20,6 +20,9 @@ export function defineRenderer(scene) { if(!Number.isFinite(scene.fps)||scene.fps<=0)throw Error('Invalid renderer fps'); if(scene.frameRate&&(!Number.isSafeInteger(scene.frameRate.num)||scene.frameRate.num<1||!Number.isSafeInteger(scene.frameRate.den)||scene.frameRate.den<1||Math.abs(scene.frameRate.num/scene.frameRate.den-scene.fps)>1e-7))throw Error('Renderer frameRate disagrees with fps'); if(scene.animationPolicy!==undefined&&!['clock','authored'].includes(scene.animationPolicy))throw Error('Invalid animation policy'); + // Optional control passes (clay, depth, id...) the scene can draw besides its picture. + // A host passes clock.pass and never asks for one that is not declared here. + if(scene.passes!==undefined&&(!Array.isArray(scene.passes)||scene.passes.length>16||new Set(scene.passes).size!==scene.passes.length||scene.passes.some(p=>typeof p!=='string'||!/^[a-z][a-z0-9-]{0,31}$/.test(p)||p==='beauty')))throw Error('Invalid renderer passes'); return Object.freeze({...scene,protocol:RENDERER_PROTOCOL}); } /** Optional picking result; not a grammar for scene objects. Coordinates are diff --git a/packages/plate/camera.mjs b/packages/plate/camera.mjs new file mode 100644 index 0000000..41c8118 --- /dev/null +++ b/packages/plate/camera.mjs @@ -0,0 +1,47 @@ +/** A solved or authored camera path for a plate. + * + * {version:1, width, height, frameRate:{num,den}, + * frames:[{frame, position:[x,y,z], quaternion:[x,y,z,w], fovY}]} + * + * Convention: camera-to-world, right-handed, +Y up, looking down -Z (the + * Three.js camera convention). fovY is the vertical field of view in degrees. + * A solve of generated footage is approximate; EditableFrames only replays it. */ +const finite = v => typeof v === 'number' && Number.isFinite(v); +export function validateCameraPath(path) { + if (!path || path.version !== 1) throw Error('Camera path needs version 1'); + const r = path.frameRate; + if (!r || !Number.isSafeInteger(r.num) || !Number.isSafeInteger(r.den) || r.num < 1 || r.den < 1) throw Error('Camera path needs frameRate {num,den}'); + if (!Array.isArray(path.frames) || !path.frames.length || path.frames.length > 100_000) throw Error('Camera path needs 1..100000 frames'); + let previous = -1; + for (const f of path.frames) { + if (!Number.isSafeInteger(f.frame) || f.frame <= previous) throw Error('Camera frames must be strictly increasing integers'); + previous = f.frame; + if (!Array.isArray(f.position) || f.position.length !== 3 || !f.position.every(finite)) throw Error(`Camera frame ${f.frame} needs position [x,y,z]`); + if (!Array.isArray(f.quaternion) || f.quaternion.length !== 4 || !f.quaternion.every(finite) || Math.abs(Math.hypot(...f.quaternion) - 1) > 1e-3) throw Error(`Camera frame ${f.frame} needs a unit quaternion [x,y,z,w]`); + if (!(f.fovY > 0 && f.fovY < 180)) throw Error(`Camera frame ${f.frame} needs fovY in degrees`); + } + return path; +} +export function slerp(a, b, t) { + let dot = a[0] * b[0] + a[1] * b[1] + a[2] * b[2] + a[3] * b[3]; + const sign = dot < 0 ? -1 : 1; dot = Math.min(1, Math.abs(dot)); + let wa = 1 - t, wb = t; + if (dot < 0.9995) { const theta = Math.acos(dot), s = Math.sin(theta); wa = Math.sin((1 - t) * theta) / s; wb = Math.sin(t * theta) / s; } + const out = a.map((v, i) => v * wa + sign * b[i] * wb), length = Math.hypot(...out); + return out.map(v => v / length); +} +/** Sample at plate seconds; ends are held. */ +export function sampleCameraPath(path, seconds) { + if (!finite(seconds)) throw Error('Camera sample needs finite seconds'); + const frames = path.frames, position = seconds * path.frameRate.num / path.frameRate.den; + let lo = 0, hi = frames.length - 1; + if (position <= frames[0].frame) hi = 0; + else if (position >= frames[hi].frame) lo = hi; + else { while (hi - lo > 1) { const mid = (lo + hi) >> 1; if (frames[mid].frame <= position) lo = mid; else hi = mid; } } + const a = frames[lo], b = frames[hi], t = a === b ? 0 : (position - a.frame) / (b.frame - a.frame); + return { + position: a.position.map((v, i) => v + (b.position[i] - v) * t), + quaternion: slerp(a.quaternion, b.quaternion, t), + fovY: a.fovY + (b.fovY - a.fovY) * t, + }; +} diff --git a/packages/plate/canvas.mjs b/packages/plate/canvas.mjs new file mode 100644 index 0000000..3969d90 --- /dev/null +++ b/packages/plate/canvas.mjs @@ -0,0 +1,47 @@ +/** 2D-canvas helpers for layering DOM and Canvas content with a plate. */ +/** Draw `plate` keeping only what `matte` marks white, onto `context`'s canvas. + * Layer the result above anything that should pass BEHIND the plate's subject + * (a headline behind a presenter). `scratch` is a second canvas this function + * may resize and overwrite; pass the same one every frame. */ +export function drawCutout(context, plate, matte, scratch) { + const {width, height} = context.canvas; + if (scratch.width !== width) scratch.width = width; + if (scratch.height !== height) scratch.height = height; + const s = scratch.getContext('2d', {willReadFrequently: true}); + s.globalCompositeOperation = 'copy'; s.drawImage(matte, 0, 0, width, height); + const alpha = s.getImageData(0, 0, width, height), a = alpha.data; + // Luminance becomes coverage. The matte's own colour is discarded. + for (let i = 0; i < a.length; i += 4) { a[i + 3] = (a[i] * 54 + a[i + 1] * 183 + a[i + 2] * 19) >> 8; a[i] = a[i + 1] = a[i + 2] = 0; } + s.putImageData(alpha, 0, 0); + s.globalCompositeOperation = 'source-in'; s.drawImage(plate, 0, 0, width, height); + s.globalCompositeOperation = 'source-over'; + context.clearRect(0, 0, width, height); context.drawImage(scratch, 0, 0); +} +/** Deterministic film grain over `context`'s canvas, sized by `sigma` (0..1, + * for example from `estimateNoise`). */ +export function drawGrain(context, grainAt, {sigma, frame, seed = 1}) { + const {width, height} = context.canvas, image = context.createImageData(width, height), d = image.data, amplitude = Math.min(1, sigma * 3) * 255; + for (let y = 0, i = 0; y < height; y++) for (let x = 0; x < width; x++, i += 4) { + const g = grainAt(x, y, frame, seed); + d[i] = d[i + 1] = d[i + 2] = g > 0 ? 255 : 0; d[i + 3] = Math.abs(g) * amplitude; + } + context.putImageData(image, 0, 0); +} +/** Decode plate frames by URL, keeping the most recent few. Await the image + * inside `render` so the host captures only finished frames. */ +export function createFrameLoader({max = 12, document: doc = globalThis.document} = {}) { + const cache = new Map(); + return { + load(url) { + if (!url) return Promise.resolve(null); + let hit = cache.get(url); + if (hit) { cache.delete(url); cache.set(url, hit); return hit; } + hit = (async () => { const image = doc.createElement('img'); image.src = url; await image.decode(); return image; })(); + hit.catch(() => cache.delete(url)); + cache.set(url, hit); + while (cache.size > max) cache.delete(cache.keys().next().value); + return hit; + }, + dispose() { cache.clear(); }, + }; +} diff --git a/packages/plate/color.mjs b/packages/plate/color.mjs new file mode 100644 index 0000000..ef61fe0 --- /dev/null +++ b/packages/plate/color.mjs @@ -0,0 +1,106 @@ +/** Measuring a plate so code-rendered pixels can be matched to it. + * Every function takes 8-bit RGBA (`Uint8ClampedArray`, as ImageData gives) and + * is deterministic. They are estimates from one view of the scene: expose the + * results as editable controls instead of trusting them blindly. */ +export const srgbToLinear = v => v <= 0.04045 ? v / 12.92 : ((v + 0.055) / 1.055) ** 2.4; +export const linearToSrgb = v => v <= 0.0031308 ? v * 12.92 : 1.055 * v ** (1 / 2.4) - 0.055; +const LUT = Float64Array.from({length: 256}, (_, i) => srgbToLinear(i / 255)); +const luminance = (r, g, b) => 0.2126 * r + 0.7152 * g + 0.0722 * b; +function check(rgba, width, height) { + if (!Number.isSafeInteger(width) || !Number.isSafeInteger(height) || width < 1 || height < 1 || rgba?.length !== width * height * 4) throw Error('Expected RGBA pixels matching width x height'); +} +function percentile(histogram, total, fraction) { + let seen = 0; const target = total * fraction; + for (let i = 0; i < 256; i++) { seen += histogram[i]; if (seen >= target) return i; } + return 255; +} +/** Black point, white point and mean per channel, in linear light. The points + * are the 1st and 99th percentiles, so a few stray pixels do not set them. */ +export function plateStats(rgba, width, height) { + check(rgba, width, height); + const h = [new Uint32Array(256), new Uint32Array(256), new Uint32Array(256)], sum = [0, 0, 0], total = width * height; + for (let i = 0; i < rgba.length; i += 4) for (let c = 0; c < 3; c++) { h[c][rgba[i + c]]++; sum[c] += LUT[rgba[i + c]]; } + return { + black: h.map(x => LUT[percentile(x, total, 0.01)]), + white: h.map(x => LUT[percentile(x, total, 0.99)]), + mean: sum.map(v => v / total), + }; +} +/** Levels that sit a full-range (0..1 linear) render inside the plate's own + * range, so its blacks are no blacker and its whites no whiter than the plate's. */ +export function matchLevels(stats) { + return {offset: [...stats.black], gain: stats.white.map((w, c) => Math.max(0, w - stats.black[c]))}; +} +export const applyLevels = (rgb, levels) => rgb.map((v, c) => levels.offset[c] + v * levels.gain[c]); + +/** Where the light seems to come from, judged from the brightest 5% of the + * frame. Returns a unit vector in camera space pointing FROM the subject TOWARD + * the light (Three.js convention: +X right, +Y up, +Z toward the camera), its + * colour, how concentrated it is (0 = flat overcast, 1 = one small source) and + * the colour of everything else as ambient fill. + * + * A picture says which SIDE the light is on, not how far in front of or behind + * the subject it sits, and nothing about what is behind the camera. So the + * side-to-side and up-down parts come from where the bright area is in frame, + * and the front-to-back part is a stated assumption: a small source is placed + * level with the subject (side light), a broad one in front of it (frontal). + * Treat the result as a starting value for an editable control. */ +export function estimateKeyLight(rgba, width, height) { + check(rgba, width, height); + const histogram = new Uint32Array(256), total = width * height, lum = new Float32Array(total); + for (let i = 0, p = 0; i < rgba.length; i += 4, p++) { + lum[p] = luminance(LUT[rgba[i]], LUT[rgba[i + 1]], LUT[rgba[i + 2]]); + histogram[Math.min(255, Math.round(linearToSrgb(lum[p]) * 255))]++; + } + // The histogram bin is a rounded value; the margin keeps a flat frame from + // reading as a faint light source through that rounding. + const threshold = srgbToLinear(percentile(histogram, total, 0.95) / 255) + 2e-3; + let weight = 0, cx = 0, cy = 0, spread = 0; const key = [0, 0, 0], ambient = [0, 0, 0]; let ambientCount = 0; + for (let y = 0, p = 0; y < height; y++) for (let x = 0; x < width; x++, p++) { + const i = p * 4, w = lum[p] - threshold; + if (w > 0) { weight += w; cx += w * (x + 0.5); cy += w * (y + 0.5); for (let c = 0; c < 3; c++) key[c] += w * LUT[rgba[i + c]]; } + else { ambientCount++; for (let c = 0; c < 3; c++) ambient[c] += LUT[rgba[i + c]]; } + } + const fill = ambient.map(v => ambientCount ? v / ambientCount : 0); + if (!(weight > 1e-9)) return {toward: [0, 0.7071, 0.7071], color: [1, 1, 1], concentration: 0, ambient: fill}; + cx /= weight; cy /= weight; + for (let y = 0, p = 0; y < height; y++) for (let x = 0; x < width; x++, p++) { const w = lum[p] - threshold; if (w > 0) spread += w * (((x + 0.5 - cx) / width) ** 2 + ((y + 0.5 - cy) / height) ** 2); } + // A uniform frame has spread 1/6 across both axes; a point source has 0. + const concentration = Math.min(1, Math.max(0, 1 - Math.sqrt(spread / weight) / Math.sqrt(1 / 6))); + const toward = [cx / width * 2 - 1, 1 - cy / height * 2, 0.25 + 0.75 * (1 - concentration)]; + const length = Math.hypot(...toward), peak = Math.max(...key, 1e-9); + return {toward: toward.map(v => v / length), color: key.map(v => v / peak), concentration, ambient: fill}; +} +/** Noise standard deviation in 0..1 code values (Immerkaer's fast estimator, + * on luma). Use it to size the grain added over code-rendered layers. */ +export function estimateNoise(rgba, width, height) { + check(rgba, width, height); + if (width < 3 || height < 3) return 0; + const y = new Float32Array(width * height); + for (let i = 0, p = 0; i < rgba.length; i += 4, p++) y[p] = (0.2126 * rgba[i] + 0.7152 * rgba[i + 1] + 0.0722 * rgba[i + 2]) / 255; + let sum = 0; + for (let r = 1; r < height - 1; r++) for (let c = 1; c < width - 1; c++) { + const p = r * width + c; + sum += Math.abs(y[p - width - 1] - 2 * y[p - width] + y[p - width + 1] - 2 * y[p - 1] + 4 * y[p] - 2 * y[p + 1] + y[p + width - 1] - 2 * y[p + width] + y[p + width + 1]); + } + return Math.sqrt(Math.PI / 2) * sum / (6 * (width - 2) * (height - 2)); +} +/** Seeded grain in -1..1 for one pixel of one frame: no Math.random, so a + * repeated or backward seek draws the same grain. */ +export function grainAt(x, y, frame, seed = 1) { + let h = Math.imul(x | 0, 374761393) ^ Math.imul(y | 0, 668265263) ^ Math.imul(frame | 0, 2147483647) ^ Math.imul(seed | 0, 1274126177); + h = Math.imul(h ^ (h >>> 13), 1274126177); h ^= h >>> 16; + return (h >>> 0) / 2147483647.5 - 1; +} +/** Lift an 8-bit frame into linear float RGBA and push its clipped highlights + * above 1, so a display-referred plate can stand in for a light source. The + * boost is a guess at what the tone curve threw away; it is not recovered data. */ +export function expandHighlights(rgba, {knee = 0.8, boost = 6} = {}) { + const out = new Float32Array(rgba.length); + for (let i = 0; i < rgba.length; i += 4) { + const r = LUT[rgba[i]], g = LUT[rgba[i + 1]], b = LUT[rgba[i + 2]], l = luminance(r, g, b); + const over = l > knee ? (l - knee) / (1 - knee) : 0, k = 1 + boost * over * over; + out[i] = r * k; out[i + 1] = g * k; out[i + 2] = b * k; out[i + 3] = 1; + } + return out; +} diff --git a/packages/plate/conform.mjs b/packages/plate/conform.mjs new file mode 100644 index 0000000..dc0eac7 --- /dev/null +++ b/packages/plate/conform.mjs @@ -0,0 +1,33 @@ +/** Keeping code and plate on the same instants. + * Video generators emit a fixed rate (commonly 24 fps; some 16 or 30). A code + * layer that is locked to something in the plate must move on the plate's frame + * grid, or it slides against the picture between plate frames. */ +const rate = r => { if (!r || !Number.isSafeInteger(r.num) || !Number.isSafeInteger(r.den) || r.num < 1 || r.den < 1) throw Error('Frame rate needs positive integers {num,den}'); return r; }; +const gcd = (a, b) => b ? gcd(b, a % b) : a; +/** Index of the plate frame on screen at `seconds`. */ +export function plateFrameIndex(seconds, frameRate) { + rate(frameRate); + if (!(seconds >= 0)) throw Error('Plate time must be non-negative seconds'); + return Math.floor(seconds * frameRate.num / frameRate.den + 1e-9); +} +/** `seconds` snapped back to the start of the plate frame that is showing. */ +export function conformSeconds(seconds, frameRate) { + return plateFrameIndex(seconds, frameRate) * frameRate.den / frameRate.num; +} +/** How a plate plays inside a timeline of another rate: how many timeline + * frames each plate frame is held for, over one repeating cycle. An uneven + * pattern (24 in 30 -> 1,1,1,2) is visible judder on any camera or subject move. */ +export function cadence(plateRate, timelineRate) { + rate(plateRate); rate(timelineRate); + // timeline frames per plate frame = (t.num/t.den) / (p.num/p.den) + const num = timelineRate.num * plateRate.den, den = timelineRate.den * plateRate.num, g = gcd(num, den); + const cycleTimeline = num / g, cyclePlate = den / g; + if (cyclePlate > 10_000) return {pattern: null, even: false, dropsFrames: num < den, advice: 'Rates share no short cycle; render the timeline at the plate rate or interpolate the plate.'}; + const pattern = new Array(cyclePlate).fill(0); + for (let i = 0; i < cycleTimeline; i++) pattern[Math.floor((i * cyclePlate + 1e-9) / cycleTimeline)]++; + const even = pattern.every(v => v === pattern[0]), dropsFrames = pattern.some(v => v === 0); + const advice = even && !dropsFrames ? 'Even cadence; no conform needed.' + : dropsFrames ? 'The timeline is slower than the plate and drops plate frames; render at the plate rate.' + : `Uneven cadence ${pattern.join(',')}; render the timeline at ${plateRate.num}/${plateRate.den} fps or interpolate the plate first.`; + return {pattern, even, dropsFrames, advice}; +} diff --git a/packages/plate/depth.mjs b/packages/plate/depth.mjs new file mode 100644 index 0000000..3535597 --- /dev/null +++ b/packages/plate/depth.mjs @@ -0,0 +1,62 @@ +/** Depth plates. A depth asset is an ordinary image or video whose pixels + * encode distance from the camera; the manifest says how. + * + * encoding = {kind:'inverse'|'linear', near, far, packing:'gray8'|'rg16'} + * + * White is NEAR in both kinds. `inverse` (disparity-like, what monocular depth + * models emit) spends its precision close to the camera; `linear` spreads it + * evenly. `near` and `far` are the distances that white and black stand for, in + * scene units along the view axis. Relative depth has no true scale: near/far + * are a choice the author tunes until occlusion lands, not a measurement. */ +export function validateDepthEncoding(encoding) { + if (!encoding || !['inverse', 'linear'].includes(encoding.kind)) throw Error('Depth encoding needs kind inverse or linear'); + if (!(encoding.near > 0) || !(encoding.far > encoding.near) || !Number.isFinite(encoding.far)) throw Error('Depth encoding needs 0 < near < far'); + if (!['gray8', 'rg16'].includes(encoding.packing ?? 'gray8')) throw Error('Depth packing must be gray8 or rg16'); + return {kind: encoding.kind, near: encoding.near, far: encoding.far, packing: encoding.packing ?? 'gray8'}; +} +/** Channel bytes to a 0..1 code value. rg16 keeps 16 bits in red (high) and green (low). */ +export const unpackDepth = (r, g, packing = 'gray8') => packing === 'rg16' ? (r * 256 + g) / 65535 : r / 255; +export function packDepth(value, packing = 'gray8') { + const v = Math.min(1, Math.max(0, value)); + if (packing !== 'rg16') { const byte = Math.round(v * 255); return [byte, byte, byte]; } + const code = Math.round(v * 65535); return [code >> 8, code & 255, 0]; +} +/** Code value (white = near) to view-axis distance. */ +export function decodeDepth(value, encoding) { + const {kind, near, far} = encoding, v = Math.min(1, Math.max(0, value)); + return kind === 'inverse' ? 1 / (1 / far + v * (1 / near - 1 / far)) : far - v * (far - near); +} +export function encodeDepth(distance, encoding) { + const {kind, near, far} = encoding, d = Math.min(far, Math.max(near, distance)); + return kind === 'inverse' ? (1 / d - 1 / far) / (1 / near - 1 / far) : (far - d) / (far - near); +} +/** GLSL for the same decode: `float plateDistance(vec4 texel)`. */ +export function depthGlsl(encoding) { + const {kind, near, far, packing} = validateDepthEncoding(encoding), f = v => Number(v).toPrecision(9).replace(/^(-?\d+)$/, '$1.0'); + const code = packing === 'rg16' ? '(texel.r * 65280.0 + texel.g * 255.0) / 65535.0' : 'texel.r'; + const distance = kind === 'inverse' ? `1.0 / (${f(1 / far)} + v * ${f(1 / near - 1 / far)})` : `${f(far)} - v * ${f(far - near)}`; + return `float plateDistance(vec4 texel){float v=clamp(${code},0.0,1.0);return ${distance};}`; +} +/** Pixel + distance to a camera-space point (Three.js convention: -Z forward). */ +export function unprojectDepth(u, v, distance, fovY, aspect) { + const tan = Math.tan(fovY * Math.PI / 360); + return [(u * 2 - 1) * tan * aspect * distance, (1 - v * 2) * tan * distance, -distance]; +} +/** Least-squares plane y = a*x + b*z + c through camera-space points: enough + * to lay a shadow catcher on a floor or table read from a depth plate. */ +export function fitGroundPlane(points) { + if (!Array.isArray(points) || points.length < 3) throw Error('A plane needs at least three points'); + let sxx = 0, sxz = 0, szz = 0, sx = 0, sz = 0, sxy = 0, szy = 0, sy = 0; const n = points.length; + for (const [x, y, z] of points) { sxx += x * x; sxz += x * z; szz += z * z; sx += x; sz += z; sxy += x * y; szy += z * y; sy += y; } + const m = [[sxx, sxz, sx, sxy], [sxz, szz, sz, szy], [sx, sz, n, sy]]; + for (let col = 0; col < 3; col++) { + let pivot = col; + for (let r = col + 1; r < 3; r++) if (Math.abs(m[r][col]) > Math.abs(m[pivot][col])) pivot = r; + if (Math.abs(m[pivot][col]) < 1e-12) throw Error('Points do not span a ground plane'); + [m[col], m[pivot]] = [m[pivot], m[col]]; + for (let r = 0; r < 3; r++) if (r !== col) { const k = m[r][col] / m[col][col]; for (let c = col; c < 4; c++) m[r][c] -= k * m[col][c]; } + } + const a = m[0][3] / m[0][0], b = m[1][3] / m[1][1], c = m[2][3] / m[2][2], length = Math.hypot(a, 1, b); + let rms = 0; for (const [x, y, z] of points) rms += (a * x + b * z + c - y) ** 2; + return {normal: [-a / length, 1 / length, -b / length], point: [0, c, 0], rms: Math.sqrt(rms / n)}; +} diff --git a/packages/plate/homography.mjs b/packages/plate/homography.mjs new file mode 100644 index 0000000..4ed6fde --- /dev/null +++ b/packages/plate/homography.mjs @@ -0,0 +1,66 @@ +/** Planar projective maps for corner pins and screen/label replacement. + * A homography is a row-major 3x3 array [a,b,c, d,e,f, g,h,1]. Quads are four + * [x,y] corners in the order top-left, top-right, bottom-right, bottom-left. */ +const finite = v => typeof v === 'number' && Number.isFinite(v); +export function validateQuad(quad, what = 'Quad') { + if (!Array.isArray(quad) || quad.length !== 4 || quad.some(p => !Array.isArray(p) || p.length !== 2 || !p.every(finite))) throw Error(`${what} needs four finite [x,y] corners`); + return quad; +} +export const rectQuad = (width, height) => [[0, 0], [width, 0], [width, height], [0, height]]; + +/** The homography carrying each `from` corner onto the matching `to` corner. */ +export function solveHomography(from, to) { + validateQuad(from, 'Source quad'); validateQuad(to, 'Target quad'); + const rows = []; + for (let i = 0; i < 4; i++) { + const [x, y] = from[i], [u, v] = to[i]; + rows.push([x, y, 1, 0, 0, 0, -u * x, -u * y, u]); + rows.push([0, 0, 0, x, y, 1, -v * x, -v * y, v]); + } + // Gaussian elimination with partial pivoting on the 8x8 system. + for (let col = 0; col < 8; col++) { + let pivot = col; + for (let r = col + 1; r < 8; r++) if (Math.abs(rows[r][col]) > Math.abs(rows[pivot][col])) pivot = r; + if (Math.abs(rows[pivot][col]) < 1e-12) throw Error('Degenerate quad: three corners are collinear or two coincide'); + [rows[col], rows[pivot]] = [rows[pivot], rows[col]]; + for (let r = 0; r < 8; r++) { + if (r === col) continue; + const factor = rows[r][col] / rows[col][col]; + if (factor) for (let c = col; c < 9; c++) rows[r][c] -= factor * rows[col][c]; + } + } + return [...rows.map((row, i) => row[8] / row[i]), 1]; +} +export function applyHomography(h, [x, y]) { + const w = h[6] * x + h[7] * y + h[8]; + return [(h[0] * x + h[1] * y + h[2]) / w, (h[3] * x + h[4] * y + h[5]) / w]; +} +export function multiplyHomography(a, b) { + const out = new Array(9); + for (let r = 0; r < 3; r++) for (let c = 0; c < 3; c++) out[r * 3 + c] = a[r * 3] * b[c] + a[r * 3 + 1] * b[3 + c] + a[r * 3 + 2] * b[6 + c]; + return out.map(v => v / out[8]); +} +export function invertHomography(h) { + const [a, b, c, d, e, f, g, i, j] = h; + const det = a * (e * j - f * i) - b * (d * j - f * g) + c * (d * i - e * g); + if (Math.abs(det) < 1e-15) throw Error('Homography is not invertible'); + const inv = [e * j - f * i, c * i - b * j, b * f - c * e, f * g - d * j, a * j - c * g, c * d - a * f, d * i - e * g, b * g - a * i, a * e - b * d]; + return inv.map(v => v / inv[8]); +} +/** CSS matrix3d for an element whose transform-origin is its top-left corner. */ +export function cssMatrix3d(h) { + const n = v => { const r = Math.abs(v) < 1e-12 ? 0 : v; return Number(r.toFixed(10)); }; + return `matrix3d(${[h[0], h[3], 0, h[6], h[1], h[4], 0, h[7], 0, 0, 1, 0, h[2], h[5], 0, h[8]].map(n).join(',')})`; +} +/** Transform that lays a `width`x`height` element onto `quad` (same units as + * the element's offset parent). Set `transform-origin: 0 0` on the element. */ +export function cornerPinTransform(width, height, quad) { + if (!(width > 0) || !(height > 0)) throw Error('Corner pin needs a positive element size'); + return cssMatrix3d(solveHomography(rectQuad(width, height), quad)); +} +/** Signed area; negative means the quad is mirrored (seen from behind). */ +export function quadArea(quad) { + let area = 0; + for (let i = 0; i < 4; i++) { const [x1, y1] = quad[i], [x2, y2] = quad[(i + 1) % 4]; area += x1 * y2 - x2 * y1; } + return area / 2; +} diff --git a/packages/plate/index.mjs b/packages/plate/index.mjs new file mode 100644 index 0000000..00749e5 --- /dev/null +++ b/packages/plate/index.mjs @@ -0,0 +1,13 @@ +/** Hybrid scenes: code-rendered elements composited with footage ("plates"), + * generated or filmed. Pure, renderer-independent helpers; nothing here runs a + * model. See docs/hybrid-scenes.md. */ +export * from './homography.mjs'; +export * from './track.mjs'; +export * from './camera.mjs'; +export * from './conform.mjs'; +export * from './motion-blur.mjs'; +export * from './depth.mjs'; +export * from './color.mjs'; +export * from './passes.mjs'; +export * from './manifest.mjs'; +export * from './canvas.mjs'; diff --git a/packages/plate/manifest.mjs b/packages/plate/manifest.mjs new file mode 100644 index 0000000..add80e7 --- /dev/null +++ b/packages/plate/manifest.mjs @@ -0,0 +1,37 @@ +/** Derived assets: data computed FROM another asset, pinned to the exact bytes + * it was computed from. + * + * "presenter-matte": {src, type:"video", sha256, + * derived:{of:"presenter", role:"matte", sourceSha256:""}} + * + * A matte, depth map, track or camera solve describes one particular take. + * Regenerate the take and they describe something that no longer exists, so a + * mismatch is refused instead of being composited a few pixels off. */ +import {validateDepthEncoding} from './depth.mjs'; +export const DERIVED_ROLES = Object.freeze({ + matte: ['video', 'image'], // white = keep (subject), black = drop + depth: ['video', 'image'], // see depth.mjs; needs `encoding` + normals: ['video', 'image'], // camera-space normals, (n+1)/2 in RGB + track: ['data'], // track.mjs + camera: ['data'], // camera.mjs + environment: ['image'], // an equirectangular picture of the plate's surroundings +}); +export function validateDerived(assets) { + const index = {}; + for (const [id, asset] of Object.entries(assets)) { + const d = asset.derived; + if (d === undefined) continue; + if (!d || typeof d.of !== 'string' || !Object.hasOwn(assets, d.of) || d.of === id) throw Error(`Derived asset ${id} must name another declared asset in derived.of`); + if (assets[d.of].derived) throw Error(`Derived asset ${id} cannot derive from ${d.of}, which is itself derived`); + if (!Object.hasOwn(DERIVED_ROLES, d.role)) throw Error(`Derived asset ${id} has unknown role ${d.role}`); + if (!DERIVED_ROLES[d.role].includes(asset.type)) throw Error(`A ${d.role} must be ${DERIVED_ROLES[d.role].join(' or ')}, not ${asset.type}: ${id}`); + if (!/^[a-f0-9]{64}$/.test(d.sourceSha256 ?? '')) throw Error(`Derived asset ${id} needs derived.sourceSha256`); + if (d.sourceSha256 !== assets[d.of].sha256) throw Error(`${id} was made from different bytes than the current ${d.of}; regenerate the ${d.role} for this take`); + if (d.role === 'depth') validateDepthEncoding(d.encoding); + else if (d.encoding !== undefined) throw Error(`Only depth assets carry an encoding: ${id}`); + index[d.of] ??= {}; + if (index[d.of][d.role]) throw Error(`${d.of} has two ${d.role} assets (${index[d.of][d.role]}, ${id}); keep one`); + index[d.of][d.role] = id; + } + return index; +} diff --git a/packages/plate/motion-blur.mjs b/packages/plate/motion-blur.mjs new file mode 100644 index 0000000..2d125c8 --- /dev/null +++ b/packages/plate/motion-blur.mjs @@ -0,0 +1,16 @@ +/** Sub-frame sample times for an offline shutter. Frames are explicit, so a + * host can afford N renders per output frame and average them. */ +export function validateShutter({samples = 8, angle = 180, phase = 'centered'} = {}) { + if (!Number.isSafeInteger(samples) || samples < 2 || samples > 64) throw Error('Motion blur samples must be an integer 2..64'); + if (!(angle > 0 && angle <= 360)) throw Error('Shutter angle must be in (0, 360] degrees'); + if (!['centered', 'forward'].includes(phase)) throw Error('Shutter phase must be centered or forward'); + return {samples, angle, phase}; +} +/** Fractional frames to render for output `frame`. `centered` straddles the + * frame instant; `forward` opens at it. Times before frame 0 are clamped. */ +export function shutterSamples(frame, options) { + const {samples, angle, phase} = validateShutter(options); + if (!(frame >= 0)) throw Error('Shutter needs a non-negative frame'); + const open = angle / 360, start = phase === 'centered' ? frame - open / 2 : frame; + return Array.from({length: samples}, (_, k) => Math.max(0, start + (k + 0.5) / samples * open)); +} diff --git a/packages/plate/passes.mjs b/packages/plate/passes.mjs new file mode 100644 index 0000000..e501b31 --- /dev/null +++ b/packages/plate/passes.mjs @@ -0,0 +1,24 @@ +/** Control passes: the same scene drawn as structure instead of as a picture, + * to condition a video model or to composite elsewhere. A scene declares the + * passes it implements; a host never invents one it was not given. */ +export const PASS = /^[a-z][a-z0-9-]{0,31}$/; +export const COMMON_PASSES = Object.freeze(['beauty', 'clay', 'depth', 'normal', 'id', 'matte']); +export function validatePasses(passes) { + if (passes === undefined) return []; + if (!Array.isArray(passes) || passes.length > 16 || new Set(passes).size !== passes.length || passes.some(p => typeof p !== 'string' || !PASS.test(p))) throw Error('passes must be up to 16 unique lowercase names'); + return passes.filter(p => p !== 'beauty'); +} +// An odd multiplier is a bijection on 24-bit integers, so neighbouring ids get +// far-apart colours and every colour still decodes to exactly one id. +const SPREAD = 0x9E3779, MASK = 0xFFFFFF; +let inverse = 1; for (let i = 0; i < 5; i++) inverse = Math.imul(inverse, 2 - Math.imul(SPREAD, inverse)) & MASK; +/** Byte colour for object `index` (0-based). Colour [0,0,0] means "no object". */ +export function idColor(index) { + if (!Number.isSafeInteger(index) || index < 0 || index >= MASK) throw Error('Object index out of range'); + const code = Math.imul(index + 1, SPREAD) & MASK; + return [code >> 16, (code >> 8) & 255, code & 255]; +} +/** Object index for a byte colour, or -1 for the empty colour. */ +export function idFromColor([r, g, b]) { + return (Math.imul((r << 16) | (g << 8) | b, inverse) & MASK) - 1; +} diff --git a/packages/plate/track.mjs b/packages/plate/track.mjs new file mode 100644 index 0000000..ec4816f --- /dev/null +++ b/packages/plate/track.mjs @@ -0,0 +1,48 @@ +/** Tracking data a host or any external tool produced for a plate. + * + * {version:1, kind:'planar'|'point', width, height, frameRate:{num,den}, + * frames:[{frame, quad:[[x,y]*4] | point:[x,y], confidence?}]} + * + * Coordinates are plate pixels, origin top-left. Frames are plate frame + * numbers; they may be sparse. EditableFrames never runs a tracker itself. */ +import {validateQuad} from './homography.mjs'; +const finite = v => typeof v === 'number' && Number.isFinite(v); +export function validateTrack(track) { + if (!track || track.version !== 1 || !['planar', 'point'].includes(track.kind)) throw Error('Track needs version 1 and kind planar or point'); + if (!Number.isSafeInteger(track.width) || !Number.isSafeInteger(track.height) || track.width < 1 || track.height < 1) throw Error('Track needs the plate width and height'); + const r = track.frameRate; + if (!r || !Number.isSafeInteger(r.num) || !Number.isSafeInteger(r.den) || r.num < 1 || r.den < 1) throw Error('Track needs the plate frameRate {num,den}'); + if (!Array.isArray(track.frames) || !track.frames.length || track.frames.length > 100_000) throw Error('Track needs 1..100000 frames'); + let previous = -1; + for (const f of track.frames) { + if (!Number.isSafeInteger(f.frame) || f.frame <= previous) throw Error('Track frames must be strictly increasing integers'); + previous = f.frame; + if (track.kind === 'planar') validateQuad(f.quad, `Track frame ${f.frame}`); + else if (!Array.isArray(f.point) || f.point.length !== 2 || !f.point.every(finite)) throw Error(`Track frame ${f.frame} needs a finite [x,y] point`); + if (f.confidence !== undefined && !(f.confidence >= 0 && f.confidence <= 1)) throw Error('Track confidence must be 0..1'); + } + return track; +} +const mix = (a, b, t) => a + (b - a) * t; +/** Sample at plate seconds. Between tracked frames the shape is interpolated + * (sub-frame samples are what motion blur needs); outside the tracked range the + * nearest tracked frame is held and `held` says so. */ +export function sampleTrack(track, seconds) { + if (!finite(seconds)) throw Error('Track sample needs finite seconds'); + const frames = track.frames, position = seconds * track.frameRate.num / track.frameRate.den; + let lo = 0, hi = frames.length - 1; + if (position <= frames[0].frame) hi = 0; + else if (position >= frames[hi].frame) lo = hi; + else { while (hi - lo > 1) { const mid = (lo + hi) >> 1; if (frames[mid].frame <= position) lo = mid; else hi = mid; } } + const a = frames[lo], b = frames[hi], t = a === b ? 0 : (position - a.frame) / (b.frame - a.frame); + // Exactly on a tracked frame, that frame's own confidence stands; between two, the worse one. + const confidence = t === 0 ? a.confidence ?? 1 : Math.min(a.confidence ?? 1, b.confidence ?? 1); + const held = position < frames[0].frame || position > frames.at(-1).frame; + if (track.kind === 'point') return {point: [mix(a.point[0], b.point[0], t), mix(a.point[1], b.point[1], t)], confidence, held}; + return {quad: a.quad.map((p, i) => [mix(p[0], b.quad[i][0], t), mix(p[1], b.quad[i][1], t)]), confidence, held}; +} +/** Plate pixels to another raster of the same aspect (for example the scene). */ +export function scalePoints(points, track, width, height) { + const sx = width / track.width, sy = height / track.height; + return points.map(([x, y]) => [x * sx, y * sy]); +} diff --git a/packages/runtime/editor.mjs b/packages/runtime/editor.mjs index ae89fe9..897f2cf 100644 --- a/packages/runtime/editor.mjs +++ b/packages/runtime/editor.mjs @@ -3,13 +3,20 @@ import {createRendererCompositor} from './renderer-compositor.mjs';import {ptsIn import {Studio,clone,HZ} from '../core/index.mjs';import {createMediaHost} from '../media/browser.mjs';import {createAudioPlayback} from '../media/playback.mjs';import {createCompositor} from './compositor.mjs'; export async function mount({templates,createRenderer,scene,binding,initial,mediaCatalog={},assetIds=[],persistence=null,capture=false}){ const $=s=>document.querySelector(s);let canvas=$('#screen'); - if(scene){const stage=document.createElement('div');stage.id='screen';canvas.replaceWith(stage);canvas=stage;if(capture){stage.style.background='transparent';stage.style.borderRadius='0';document.documentElement.style.background='transparent';document.body.style.background='transparent';}} + if(scene){const stage=document.createElement('div');stage.id='screen';canvas.replaceWith(stage);canvas=stage;if(capture){stage.style.background='transparent';stage.style.borderRadius='0';document.documentElement.style.background='transparent';document.body.style.background='transparent'; + // The stage is transparent where the scene draws nothing, so the editor's own chrome would be captured through it. + document.body.style.visibility='hidden';stage.style.visibility='visible';}} let studio; if(initial)studio=Studio.restore(initial,templates,binding);else{studio=new Studio(templates,{binding});studio.doc.clips=Object.keys(templates).map(id=>studio.make(id));studio.check(studio.doc);studio.base=clone(studio.doc)} - let selected=studio.doc.clips[0]?.id,time=0,playing=false,last=0,timeline=false,revision=persistence?.revision,operations=Promise.resolve(),disposed=false; + let selected=studio.doc.clips[0]?.id,time=0,playing=false,last=0,timeline=false,pass='beauty',revision=persistence?.revision,operations=Promise.resolve(),disposed=false; const host=createMediaHost(mediaCatalog),services={}; if(assetIds.length)services.asset=id=>{if(!assetIds.includes(id))throw Error('Undeclared asset: '+id);return '/__ef/source/'+encodeURIComponent(id);}; - if(Object.keys(mediaCatalog).length)services.mediaFrame=(id,time)=>{const a=mediaCatalog[id];if(!a||a.type==='audio')throw Error('Missing visual asset: '+id);const index=ptsIndex(a.pts,time);return index<0?undefined:a.url+String(index+1).padStart(6,'0')+'.png';}; + if(Object.keys(mediaCatalog).length){ + // Facts about a declared asset, and the data derived from it (matte, depth, track, camera). + services.mediaInfo=id=>{const a=mediaCatalog[id];if(!a)throw Error('Undeclared asset: '+id);return {type:a.type,width:a.width,height:a.height,duration:a.duration,frames:a.pts?.length??0,frameRate:a.frameRate?{...a.frameRate}:undefined,derived:a.derived?structuredClone(a.derived):undefined};}; + services.derived=(id,role)=>{if(!mediaCatalog[id])throw Error('Undeclared asset: '+id);return Object.keys(mediaCatalog).find(key=>mediaCatalog[key].derived?.of===id&&mediaCatalog[key].derived.role===role);}; + } + if(Object.keys(mediaCatalog).length)services.mediaFrame=(id,time)=>{const a=mediaCatalog[id];if(!a||a.type==='audio'||a.type==='data')throw Error('Missing visual asset: '+id);const index=ptsIndex(a.pts,time);return index<0?undefined:a.url+String(index+1).padStart(6,'0')+'.png';}; const renderer=scene?createRendererCompositor(canvas,{scene,templates,services,capture}):createCompositor(canvas,{templates,createRenderer,host}),audio=createAudioPlayback(mediaCatalog);let selection=null,selectionVersion=0; if(scene)canvas.addEventListener('pointerdown',async event=>{ const ticket=++selectionVersion; @@ -26,7 +33,7 @@ export async function mount({templates,createRenderer,scene,binding,initial,medi const keySelection=event=>{if(scene&&selection&&(event.key==='Escape'||event.altKey&&event.key==='ArrowUp')){event.preventDefault();selectParent();}}; if(scene)document.addEventListener('keydown',keySelection); const fail=e=>{$('#status').textContent=e.message;playing=false;audio.stop();$('#play').textContent='Play'}; - function draw(){selectionVersion++;const hadSelection=selection!==null;selection=null;if(hadSelection)refresh();const at=time,mode=timeline,id=selected;return renderer.render(studio,at,{selected:id,timeline:mode,playing})} + function draw(){selectionVersion++;const hadSelection=selection!==null;selection=null;if(hadSelection)refresh();const at=time,mode=timeline,id=selected;return renderer.render(studio,at,{selected:id,timeline:mode,playing,...(scene?{pass}:{})})} function context(){return {...studio.capabilities(selected),baseRevision:persistence?revision:studio.revision,...(scene?{selection,objects:objectRows(),capture:{kind:'dom',selector:'#screen'}}:{})}} function refresh(){ if(!studio.doc.clips.some(c=>c.id===selected))selected=studio.doc.clips[0]?.id; @@ -66,5 +73,5 @@ export async function mount({templates,createRenderer,scene,binding,initial,medi $('#open').onchange=async e=>{try{studio=Studio.restore(await e.target.files[0].text(),templates,binding);refresh();await draw()}catch(e){fail(e)}}; $('#apply').onclick=()=>{try{const p=JSON.parse($('#proposal').value);edit(p.command,p.baseRevision,'model').catch(fail)}catch(e){fail(e)}}; async function loop(now){if(disposed)return;if(playing){try{time=(time+Math.max(0,Math.min(.1,(now-last)/1000)))%duration();$('#seek').value=time;await draw();let s=studio,t=time;if(!timeline){s=Object.create(studio);s.doc={...studio.doc,clips:[{...clip(),start:0}]}}if(playing)await audio.update(s,t,true);else audio.stop()}catch(e){fail(e)}}last=now;requestAnimationFrame(loop)}requestAnimationFrame(loop); - refresh();await draw();window.editableframes=window.editableframe={ready:true,get studio(){return studio},get selected(){return selected},templates,binding,context,selectObject,selectParent,select(id){selected=studio.doc.clips.find(c=>c.template===id||c.id===id)?.id??selected;time=0;playing=false;audio.stop();refresh();return draw()},async seek(t,options={}){playing=false;audio.stop();time=t;timeline=options.timeline??timeline;await draw()},edit,undo:()=>change('undo'),redo:()=>change('redo'),serialize:()=>studio.serialize(),captureTarget:scene?{kind:'dom',selector:'#screen'}:{kind:'canvas',selector:'#screen'},png:()=>{if(scene)throw Error('This renderer uses DOM-root capture; screenshot captureTarget after seek');return canvas.toDataURL('image/png')} ,stats:()=>({...host.stats(),audio:audio.stats()}),async dispose(){disposed=true;document.removeEventListener('keydown',keySelection);await audio.dispose();await renderer.dispose()}}; + refresh();await draw();window.editableframes=window.editableframe={ready:true,get studio(){return studio},get selected(){return selected},templates,binding,context,selectObject,selectParent,select(id){selected=studio.doc.clips.find(c=>c.template===id||c.id===id)?.id??selected;time=0;playing=false;audio.stop();refresh();return draw()},async seek(t,options={}){playing=false;audio.stop();time=t;timeline=options.timeline??timeline;if(options.pass!==undefined){if(!scene&&options.pass!=='beauty')throw Error('Only renderer scenes draw control passes');pass=options.pass;}await draw()},edit,undo:()=>change('undo'),redo:()=>change('redo'),serialize:()=>studio.serialize(),captureTarget:scene?{kind:'dom',selector:'#screen'}:{kind:'canvas',selector:'#screen'},png:()=>{if(scene)throw Error('This renderer uses DOM-root capture; screenshot captureTarget after seek');return canvas.toDataURL('image/png')} ,stats:()=>({...host.stats(),audio:audio.stats()}),async dispose(){disposed=true;document.removeEventListener('keydown',keySelection);await audio.dispose();await renderer.dispose()}}; } diff --git a/packages/runtime/renderer-compositor.mjs b/packages/runtime/renderer-compositor.mjs index b271465..03bce24 100644 --- a/packages/runtime/renderer-compositor.mjs +++ b/packages/runtime/renderer-compositor.mjs @@ -8,8 +8,9 @@ export function createRendererCompositor(stage,{scene,templates,services={},capt const residents=new Map();let chain=Promise.resolve(),disposed=false,lastRequest,renderVersion=0,pickVersion=0,activeJob,pendingJob,disposal; stage.style.position=capture?'fixed':'relative';stage.style.overflow='hidden'; if(capture){stage.style.left='0';stage.style.top='0';stage.style.zIndex='2147483647';} - async function draw(studio,time,{selected,timeline=false,playing=false}={}) { + async function draw(studio,time,{selected,timeline=false,playing=false,pass='beauty'}={}) { if(disposed)throw Error('Compositor disposed'); + if(pass!=='beauty'&&!(scene.passes??[]).includes(pass))throw Error(`This scene does not declare a ${pass} pass`); if(!Number.isFinite(time)||time<0)throw Error('Invalid source time'); const clips=timeline?studio.doc.clips.filter(c=>time>=c.start/HZ&&time<(c.start+c.duration)/HZ):[studio.clip(selected)]; const active=new Set(clips.map(c=>c.id)); @@ -31,12 +32,12 @@ export function createRendererCompositor(stage,{scene,templates,services={},capt const tr=clip.transform;resident.layer.style.opacity=String(tr.opacity);resident.layer.style.transform=`translate(${tr.x/width*100}%,${tr.y/height*100}%) scale(${tr.scale})`; resident.root.style.transform=`scale(${stage.clientWidth/scene.width},${stage.clientHeight/scene.height})`; const evaluated=evaluateClip(studio,clip,timeline?time:clip.start/HZ+time); - const clock={frame:evaluated.sourceTime*scene.fps,fps:scene.fps,frameRate:rendererFrameRate(scene),width:scene.width,height:scene.height,durationInFrames:scene.durationInFrames,capture,playing}; + const clock={frame:evaluated.sourceTime*scene.fps,fps:scene.fps,frameRate:rendererFrameRate(scene),width:scene.width,height:scene.height,durationInFrames:scene.durationInFrames,capture,playing,pass}; resident.clock=clock; try {await resident.instance.render(clock,sampledRendererProps(scene,templates[clip.template],clip,evaluated.nodes));} catch(error){residents.delete(clip.id);resident.layer.remove();await resident.instance.dispose().catch(()=>{});throw error;} resident.overlays.style.transform=`scale(${stage.clientWidth/1920},${stage.clientHeight/1080})`;resident.overlays.replaceChildren(); - for(const node of evaluated.nodes.filter(n=>n.overlay)){ + for(const node of pass==='beauty'?evaluated.nodes.filter(n=>n.overlay):[]){ const p=node.props;if(!p.visible||evaluated.sourceTimep.end)continue; const label=document.createElement('div');label.textContent=p.text; Object.assign(label.style,{position:'absolute',left:`${p.x-14}px`,top:`${p.y-10}px`,padding:'10px 14px',font:`600 ${p.size}px sans-serif`,color:p.color,opacity:p.opacity,whiteSpace:'pre',background:p.style==='plain'?'transparent':p.background,borderRadius:p.style==='pill'?`${p.size}px`:'10px'}); diff --git a/packages/runtime/renderer-host.mjs b/packages/runtime/renderer-host.mjs index a2a142b..f0b9ae0 100644 --- a/packages/runtime/renderer-host.mjs +++ b/packages/runtime/renderer-host.mjs @@ -11,7 +11,7 @@ export async function mountRenderer(scene,{root,props={},services={},timeoutMs=3 if (!root?.ownerDocument?.createElement || !root.append || !Number.isFinite(timeoutMs) || timeoutMs<=0) throw Error('Renderer host needs a DOM root and positive deadline'); const current=mergeProps(scene.defaultProps??{},props),readiness=new Readiness(),controller=new AbortController(); const supplied={}; - for (const key of ['asset','mediaFrame','captureSurface']) if (services[key]!==undefined) {if(typeof services[key]!=='function')throw Error(`Invalid ${key} service`);supplied[key]=services[key];} + for (const key of ['asset','mediaFrame','captureSurface','mediaInfo','derived']) if (services[key]!==undefined) {if(typeof services[key]!=='function')throw Error(`Invalid ${key} service`);supplied[key]=services[key];} // Each mount owns a replaceable surface. A late async frame can only write // into its detached surface, never a retry's DOM. This is not a code sandbox. const surface=root.ownerDocument.createElement('div'); diff --git a/packages/three/plate.mjs b/packages/three/plate.mjs new file mode 100644 index 0000000..6dc4ed7 --- /dev/null +++ b/packages/three/plate.mjs @@ -0,0 +1,181 @@ +/** Optional Three.js adapter for hybrid scenes: a code-rendered 3D object that + * has to sit INSIDE footage (a "plate") instead of on top of it. + * + * Not a restriction on renderers. Nothing here runs a model; mattes, depth, + * tracks and camera paths are inputs the host or the author supplies. + * See docs/hybrid-scenes.md. */ +import * as T from 'three'; +import {depthGlsl, validateDepthEncoding} from '../plate/depth.mjs'; +import {expandHighlights} from '../plate/color.mjs'; +import {idColor} from '../plate/passes.mjs'; +export const revision = 'editableframes.three-plate/1'; +const QUAD_VERTEX = 'varying vec2 vUv;void main(){vUv=position.xy*0.5+0.5;gl_Position=vec4(position.xy,0.0,1.0);}'; +function fullscreen(material, renderOrder) { + const mesh = new T.Mesh(new T.PlaneGeometry(2, 2), material); + mesh.frustumCulled = false; mesh.renderOrder = renderOrder; mesh.userData.plateHelper = true; + return mesh; +} +/** A texture for plate data (matte, depth, normals): no colour management, no + * mipmaps. `image` is anything WebGL can upload. */ +export function dataTexture(image, {filter = T.LinearFilter} = {}) { + const texture = new T.Texture(image); + texture.colorSpace = T.NoColorSpace; texture.minFilter = texture.magFilter = filter; texture.generateMipmaps = false; texture.needsUpdate = true; + return texture; +} +/** Let the plate's own geometry hide the scene. Draws nothing visible; it + * writes the plate's depth into the depth buffer first, so every mesh is then + * depth-tested against the footage: a hand in front of the product covers it, + * a wall behind it does not. + * + * Needs WebGL2 and a perspective camera with the standard depth buffer (not + * logarithmic or reversed). Add the returned `mesh` to the scene; call + * `update(texture, camera)` whenever the plate frame or the camera changes. */ +export function createDepthOccluder(encoding) { + const material = new T.ShaderMaterial({ + colorWrite: false, depthWrite: true, depthTest: true, depthFunc: T.AlwaysDepth, + uniforms: {map: {value: null}, near: {value: 0.1}, far: {value: 100}}, + vertexShader: QUAD_VERTEX, + fragmentShader: `uniform sampler2D map;uniform float near;uniform float far;varying vec2 vUv;${depthGlsl(encoding)} +void main(){float d=clamp(plateDistance(texture2D(map,vUv)),near,far);float ndc=(far+near)/(far-near)-(2.0*far*near)/((far-near)*d);gl_FragDepth=ndc*0.5+0.5;gl_FragColor=vec4(0.0);}`, + }); + const mesh = fullscreen(material, -1e9); + return { + mesh, + update(texture, camera) { + if (!camera?.isPerspectiveCamera) throw Error('Depth occlusion needs a perspective camera'); + material.uniforms.map.value = texture; material.uniforms.near.value = camera.near; material.uniforms.far.value = camera.far; + }, + dispose() { mesh.geometry.dispose(); material.dispose(); }, + }; +} +/** Punch the plate's subject out of everything drawn so far. Where the matte + * is white the canvas becomes transparent, so the footage underneath shows + * through: the cheap way to put a 3D object BEHIND a matted subject when no + * depth is available. Coverage is all-or-nothing per pixel; it cannot place + * the object in front of one part of the subject and behind another. */ +export function createMatteHoldout() { + const material = new T.ShaderMaterial({ + transparent: true, depthTest: false, depthWrite: false, blending: T.CustomBlending, blendEquation: T.AddEquation, + blendSrc: T.ZeroFactor, blendDst: T.OneMinusSrcAlphaFactor, blendSrcAlpha: T.ZeroFactor, blendDstAlpha: T.OneMinusSrcAlphaFactor, + uniforms: {map: {value: null}}, + vertexShader: QUAD_VERTEX, + fragmentShader: 'uniform sampler2D map;varying vec2 vUv;void main(){vec3 m=texture2D(map,vUv).rgb;gl_FragColor=vec4(0.0,0.0,0.0,dot(m,vec3(0.2126,0.7152,0.0722)));}', + }); + const mesh = fullscreen(material, 1e9); + return {mesh, update(texture) { material.uniforms.map.value = texture; }, dispose() { mesh.geometry.dispose(); material.dispose(); }}; +} +/** Light the scene with the plate itself. The frame is wrapped into a + * panorama (in front of the camera as shot, mirrored behind it), its clipped + * highlights are pushed above 1, and the result is prefiltered for physically + * based reflections. A metal object then reflects the footage it stands in. + * + * This is the standard stand-in when no real environment capture exists. It is + * plausible, not measured: what is behind the camera is invented by mirroring. + * Prefer a real `environment` asset for the plate when one exists. + * + * `update(source)` accepts anything a 2D canvas can draw and returns the + * environment texture; assign it to `scene.environment`. */ +export function createPlateEnvironment(renderer, {width = 256, knee = 0.8, boost = 6, document: doc = globalThis.document} = {}) { + const height = width / 2, canvas = doc.createElement('canvas'); canvas.width = width; canvas.height = height; + const context = canvas.getContext('2d', {willReadFrequently: true}), generator = new T.PMREMGenerator(renderer); + generator.compileEquirectangularShader(); + let target; + return { + update(source) { + const half = width / 2; + // Three's equirect lookup puts -Z (into the picture) at u = 0.25. + context.setTransform(1, 0, 0, 1, 0, 0); context.drawImage(source, 0, 0, half, height); + context.setTransform(-1, 0, 0, 1, width + half, 0); context.drawImage(source, 0, 0, half, height); + context.setTransform(1, 0, 0, 1, 0, 0); + const linear = expandHighlights(context.getImageData(0, 0, width, height).data, {knee, boost}), pixels = new Uint16Array(linear.length); + for (let i = 0; i < linear.length; i++) pixels[i] = T.DataUtils.toHalfFloat(Math.min(65000, linear[i])); + const texture = new T.DataTexture(pixels, width, height, T.RGBAFormat, T.HalfFloatType); + texture.flipY = true; texture.minFilter = texture.magFilter = T.LinearFilter; texture.generateMipmaps = false; + texture.colorSpace = T.LinearSRGBColorSpace; texture.mapping = T.EquirectangularReflectionMapping; texture.needsUpdate = true; + const next = generator.fromEquirectangular(texture); texture.dispose(); target?.dispose(); target = next; + return target.texture; + }, + dispose() { target?.dispose(); generator.dispose(); }, + }; +} +/** Aim a directional light using `estimateKeyLight`'s result. `target` is the + * point the light should fall on; `strength` scales the final intensity. */ +export function applyKeyLight(light, estimate, {target = new T.Vector3(), distance = 6, strength = 2} = {}) { + light.position.set(...estimate.toward).multiplyScalar(distance).add(target); + light.target.position.copy(target); light.target.updateMatrixWorld(); + light.color.setRGB(...estimate.color, T.LinearSRGBColorSpace); + // A flat, overcast plate has no key to speak of; a single hot source has a strong one. + light.intensity = strength * (0.25 + 0.75 * estimate.concentration); + return light; +} +/** Replay a sampled camera path (`sampleCameraPath`) on a perspective camera. */ +export function applyCameraSample(camera, sample) { + camera.position.set(...sample.position); camera.quaternion.set(...sample.quaternion); + if (camera.fov !== sample.fovY) { camera.fov = sample.fovY; camera.updateProjectionMatrix(); } + camera.updateMatrixWorld(); +} +/** An invisible plane that only shows the shadows cast onto it, laid on a + * floor or table found in the plate (`fitGroundPlane`), in camera space. */ +export function createShadowCatcher(plane, {size = 40, opacity = 0.35} = {}) { + const mesh = new T.Mesh(new T.PlaneGeometry(size, size), new T.ShadowMaterial({opacity})); + mesh.quaternion.setFromUnitVectors(new T.Vector3(0, 0, 1), new T.Vector3(...plane.normal).normalize()); + mesh.position.set(...plane.point); mesh.receiveShadow = true; mesh.userData.plateHelper = true; + return mesh; +} +const RAW_VERTEX = 'varying vec3 vView;void main(){vec4 mv=modelViewMatrix*vec4(position,1.0);vView=mv.xyz;gl_Position=projectionMatrix*mv;}'; +// ShaderMaterial bypasses tone mapping and output colour conversion, so these +// passes write the exact bytes a decoder expects. +const rawColor = rgb => new T.ShaderMaterial({uniforms: {color: {value: new T.Vector3(...rgb)}}, vertexShader: RAW_VERTEX, fragmentShader: 'uniform vec3 color;void main(){gl_FragColor=vec4(color,1.0);}'}); +/** Draw the scene as one control pass instead of as a picture. + * + * clay matte grey under the scene's own lights: shape, camera and shading + * depth distance as grey, white = near, in `encoding` (default inverse) + * normal camera-space normals + * id one flat colour per object in `ids` (decode with `idFromColor`) + * matte white silhouette on a transparent background + * + * Objects are named by `userData.passId` on a mesh or the nearest ancestor, else + * the mesh's own `name`. Helper meshes this module creates, and anything with + * `userData.passExclude`, are left out. Edges are antialiased, so id and depth + * values are exact only away from silhouettes. Scene state is restored. */ +export function renderPass(renderer, scene, camera, pass, {ids = [], encoding} = {}) { + if (pass === 'beauty') { renderer.render(scene, camera); return; } + if (!['clay', 'depth', 'normal', 'id', 'matte'].includes(pass)) throw Error('Unknown pass: ' + pass); + const depth = validateDepthEncoding(encoding ?? {kind: 'inverse', near: camera.near, far: camera.far}); + const saved = {background: scene.background, override: scene.overrideMaterial, clear: renderer.getClearColor(new T.Color()), alpha: renderer.getClearAlpha(), tone: renderer.toneMapping}, swapped = [], hidden = [], made = []; + const passId = object => { for (let o = object; o; o = o.parent) if (typeof o.userData?.passId === 'string') return o.userData.passId; return object.name; }; + const use = (mesh, material) => { swapped.push([mesh, mesh.material]); mesh.material = material; }; + try { + scene.background = null; renderer.setClearColor(0x000000, 0); + const shared = pass === 'clay' ? new T.MeshStandardMaterial({color: 0xb8b8b8, roughness: 0.85, metalness: 0}) + : pass === 'normal' ? new T.MeshNormalMaterial() + : pass === 'matte' ? rawColor([1, 1, 1]) + : pass === 'depth' ? new T.ShaderMaterial({vertexShader: RAW_VERTEX, fragmentShader: `varying vec3 vView;${depthEncodeGlsl(depth)}void main(){gl_FragColor=vec4(vec3(plateCode(-vView.z)),1.0);}`}) + : null; + if (shared) made.push(shared); + if (pass !== 'clay') renderer.toneMapping = T.NoToneMapping; + const byId = new Map(); + scene.traverse(object => { + if (!object.isMesh && !object.isLine && !object.isPoints && !object.isSprite) return; + if (object.userData.plateHelper || object.userData.passExclude || !object.isMesh) { if (object.visible) { hidden.push(object); object.visible = false; } return; } + if (shared) { use(object, shared); return; } + const index = ids.indexOf(passId(object)); + if (index < 0) { hidden.push(object); object.visible = false; return; } + if (!byId.has(index)) { const material = rawColor(idColor(index).map(v => v / 255)); byId.set(index, material); made.push(material); } + use(object, byId.get(index)); + }); + renderer.render(scene, camera); + } finally { + for (const [mesh, material] of swapped) mesh.material = material; + for (const object of hidden) object.visible = true; + for (const material of made) material.dispose(); + scene.background = saved.background; scene.overrideMaterial = saved.override; renderer.setClearColor(saved.clear, saved.alpha); renderer.toneMapping = saved.tone; + } +} +function depthEncodeGlsl(encoding) { + // Mirrors encodeDepth() in ../plate/depth.mjs, so a depth pass and a depth plate share one convention. + const {kind, near, far} = encoding, f = v => Number(v).toPrecision(9).replace(/^(-?\d+)$/, '$1.0'); + return kind === 'inverse' + ? `float plateCode(float d){d=clamp(d,${f(near)},${f(far)});return (1.0/d-${f(1 / far)})/${f(1 / near - 1 / far)};}` + : `float plateCode(float d){d=clamp(d,${f(near)},${f(far)});return (${f(far)}-d)/${f(far - near)};}`; +} diff --git a/scripts/demo-hybrid.mjs b/scripts/demo-hybrid.mjs new file mode 100644 index 0000000..36feb57 --- /dev/null +++ b/scripts/demo-hybrid.mjs @@ -0,0 +1,29 @@ +import fs from 'node:fs/promises';import path from 'node:path';import {run,ffmpeg} from './process.mjs';import {fileHash} from './media.mjs'; +// A diagnostic plate with a known answer, not footage: a warm wall with a bright +// window (the light), a slate board drifting right (a surface to pin a screen +// to) and a dark bar sweeping across in front of everything (the occluder). +// Its matte, depth and track are generated from the same formulas, so tests can +// state where every pixel must land. Real plates get these from other tools. +export const HYBRID_DEMO={width:640,height:360,fps:24,seconds:3,board:{y:50,width:160,height:90,x:frame=>Math.floor(430+frame/2)},bar:{width:70,x:frame=>Math.floor(60+150*frame/24)},depth:{kind:'inverse',near:1.2,far:12,packing:'gray8'},codes:{wall:38,board:51,bar:230},colors:{wall:'0x9a5a32',window:'0xfff2d0',board:'0x3a3f4a',bar:'0x12324a'}}; +export async function createHybridDemo(dir){ + const d=HYBRID_DEMO,size=`${d.width}x${d.height}`,common=`r=${d.fps}:d=${d.seconds}`,gray=v=>'0x'+v.toString(16).padStart(2,'0').repeat(3); + await fs.mkdir(path.join(dir,'assets'),{recursive:true}); + const source=(color,s)=>`color=c=${color}:s=${s}:${common},format=gbrp`; + // overlay truncates x to whole pixels in a planar RGB format, matching Math.floor above. + const boardX=`x='430+t*${d.fps}/2'`,barX=`x='60+150*t'`; + const graphs={ + 'plate.mp4':`${source(d.colors.wall,size)}[w];${source(d.colors.window,'120x90')}[n];${source(d.colors.board,`${d.board.width}x${d.board.height}`)}[b];${source(d.colors.bar,`${d.bar.width}x${d.height}`)}[r];[w][n]overlay=x=40:y=30:format=gbrp[a];[a][b]overlay=${boardX}:y=${d.board.y}:format=gbrp[c];[c][r]overlay=${barX}:y=0:format=gbrp[v]`, + 'plate-matte.mp4':`${source('black',size)}[w];${source('white',`${d.bar.width}x${d.height}`)}[r];[w][r]overlay=${barX}:y=0:format=gbrp[v]`, + 'plate-depth.mp4':`${source(gray(d.codes.wall),size)}[w];${source(gray(d.codes.board),`${d.board.width}x${d.board.height}`)}[b];${source(gray(d.codes.bar),`${d.bar.width}x${d.height}`)}[r];[w][b]overlay=${boardX}:y=${d.board.y}:format=gbrp[c];[c][r]overlay=${barX}:y=0:format=gbrp[v]`, + }; + for(const [name,graph]of Object.entries(graphs))await run(ffmpeg(),['-v','error','-n','-filter_complex',graph,'-map','[v]','-frames:v',String(d.fps*d.seconds),'-c:v','libx264','-qp','0','-pix_fmt','yuv444p',path.join(dir,'assets',name)]); + const frames=Array.from({length:d.fps*d.seconds},(_,frame)=>{const x=d.board.x(frame),{y,width,height}=d.board;return {frame,quad:[[x,y],[x+width,y],[x+width,y+height],[x,y+height]],confidence:1}}); + await fs.writeFile(path.join(dir,'assets','board-track.json'),JSON.stringify({version:1,kind:'planar',width:d.width,height:d.height,frameRate:{num:d.fps,den:1},frames})); + const sha=name=>fileHash(path.join(dir,'assets',name)),plate=await sha('plate.mp4'),derived=(role,extra={})=>({derived:{of:'plate',role,sourceSha256:plate,...extra}}); + await fs.writeFile(path.join(dir,'assets.json'),JSON.stringify({version:1,assets:{ + plate:{src:'assets/plate.mp4',type:'video',sha256:plate}, + 'plate-matte':{src:'assets/plate-matte.mp4',type:'video',sha256:await sha('plate-matte.mp4'),...derived('matte')}, + 'plate-depth':{src:'assets/plate-depth.mp4',type:'video',sha256:await sha('plate-depth.mp4'),...derived('depth',{encoding:d.depth})}, + 'board-track':{src:'assets/board-track.json',type:'data',sha256:await sha('board-track.json'),...derived('track')}, + }},null,2)); +} diff --git a/scripts/media.mjs b/scripts/media.mjs index 21e7764..31fbf67 100644 --- a/scripts/media.mjs +++ b/scripts/media.mjs @@ -1,20 +1,25 @@ import fs from 'node:fs/promises';import path from 'node:path';import os from 'node:os';import {createHash} from 'node:crypto';import {createReadStream} from 'node:fs'; -import {run,ffmpeg,ffprobe} from './process.mjs'; +import {run,ffmpeg,ffprobe} from './process.mjs';import {validateDerived} from '../packages/plate/manifest.mjs';import {validateTrack} from '../packages/plate/track.mjs';import {validateCameraPath} from '../packages/plate/camera.mjs'; export async function fileHash(file){const h=createHash('sha256');for await(const chunk of createReadStream(file))h.update(chunk);return h.digest('hex')} export async function readAssets(dir){ let manifest;try{manifest=JSON.parse(await fs.readFile(path.join(dir,'assets.json'),'utf8'))}catch(e){if(e.code==='ENOENT')return {};throw e} if(manifest.version!==1 || !manifest.assets || Array.isArray(manifest.assets))throw Error('Invalid assets manifest'); const assets={};for(const [id,a]of Object.entries(manifest.assets)){ - if(['__proto__','constructor','prototype'].includes(id)||!/^[a-zA-Z0-9_-]{1,80}$/.test(id)||!['video','audio','image'].includes(a.type)||typeof a.src!=='string'||path.isAbsolute(a.src)||a.src.split(/[\\/]/).some(p=>p==='..'||p.startsWith('.'))||!/^[a-f0-9]{64}$/.test(a.sha256))throw Error('Invalid asset declaration: '+id); + if(['__proto__','constructor','prototype'].includes(id)||!/^[a-zA-Z0-9_-]{1,80}$/.test(id)||!['video','audio','image','data'].includes(a.type)||typeof a.src!=='string'||path.isAbsolute(a.src)||a.src.split(/[\\/]/).some(p=>p==='..'||p.startsWith('.'))||!/^[a-f0-9]{64}$/.test(a.sha256))throw Error('Invalid asset declaration: '+id); const file=await fs.realpath(path.join(dir,a.src));if(!file.startsWith(dir+path.sep))throw Error('Asset escapes project: '+id); if(await fileHash(file)!==a.sha256)throw Error('Asset content changed: '+id+'; import it as a new immutable asset'); + // `data` is small JSON a renderer reads (a track, a camera path); it is never decoded as media. + if(a.type==='data'){if((await fs.stat(file)).size>8*1024**2)throw Error('Data asset exceeds 8 MiB: '+id);let json;try{json=JSON.parse(await fs.readFile(file,'utf8'))}catch{throw Error('Data asset is not JSON: '+id)}if(a.derived?.role==='track')validateTrack(json);if(a.derived?.role==='camera')validateCameraPath(json);} assets[id]={...a,file}; - }return assets; + } + // Mattes, depth, tracks and camera paths are pinned to the exact bytes they were computed from. + validateDerived(assets);return assets; } export async function prepareMedia(assets,{signal,maxDecodedBytes=8*1024**3,maxFrames=18000}={}){ const dir=await fs.mkdtemp(path.join(os.tmpdir(),'ef-media-')),catalog={},frozenAssets={};let budget=0; try{await fs.mkdir(path.join(dir,'sources'));for(const [id,original]of Object.entries(assets)){ const file=path.join(dir,'sources',id+path.extname(original.file));await fs.copyFile(original.file,file);if(await fileHash(file)!==original.sha256)throw Error('Asset changed while preparing: '+id);const a={...original,file};frozenAssets[id]=a; + if(a.type==='data'){catalog[id]={type:'data',sha256:a.sha256,derived:a.derived,audio:false,pts:[],url:'/__ef/source/'+id};continue} const info=JSON.parse((await run(ffprobe(),['-v','error','-show_streams','-show_format','-of','json',a.file],{signal})).toString()); const v=info.streams.find(s=>s.codec_type==='video'),astream=info.streams.find(s=>s.codec_type==='audio'),audio=!!astream; let pts=[],duration=Number(info.format.duration??v?.duration??0); @@ -34,8 +39,11 @@ export async function prepareMedia(assets,{signal,maxDecodedBytes=8*1024**3,maxF } if(a.type==='audio'&&!audio)throw Error('Asset has no audio: '+id); if(audio){budget+=duration*48000*4;if(!Number.isFinite(duration)||duration<=0||budget>maxDecodedBytes)throw Error('Audio decode budget exceeded');a.previewAudio=path.join(dir,'sources',id+'-audio.wav');await run(ffmpeg(),['-v','error','-n','-i',a.file,'-map','0:a:0','-vn','-af',`apad=whole_dur=${duration},atrim=duration=${duration}`,'-ar','48000','-ac','2','-c:a','pcm_s16le',a.previewAudio],{signal,timeout:300000});} - catalog[id]={type:a.type,sha256:a.sha256,duration,pts,audio,width:v?.width,height:v?.height,audioOffset:Number(astream?.start_time??0)-Number(v?.start_time??0),sourceUrl:audio?'/__ef/audio/'+id:null,url:'/__ef/media/'+id+'/'}; + const [rn,rd]=String(v?.avg_frame_rate??'').split('/').map(Number),frameRate=a.type==='video'&&Number.isSafeInteger(rn)&&Number.isSafeInteger(rd)&&rn>0&&rd>0?{num:rn,den:rd}:undefined; + catalog[id]={type:a.type,sha256:a.sha256,derived:a.derived,frameRate,duration,pts,audio,width:v?.width,height:v?.height,audioOffset:Number(astream?.start_time??0)-Number(v?.start_time??0),sourceUrl:audio?'/__ef/audio/'+id:null,url:'/__ef/media/'+id+'/'}; } + // A per-frame matte or depth map only lines up when it has exactly the plate's frames. + for(const [id,entry]of Object.entries(catalog)){const d=entry.derived;if(!d||entry.type!=='video')continue;const parent=catalog[d.of];if(parent.type==='video'&&parent.pts.length!==entry.pts.length)throw Error(`${id} has ${entry.pts.length} frames but ${d.of} has ${parent.pts.length}; a ${d.role} must match its plate frame for frame`)} return {dir,catalog,assets:frozenAssets,close:()=>fs.rm(dir,{recursive:true,force:true})}; }catch(e){await fs.rm(dir,{recursive:true,force:true});throw e} } diff --git a/scripts/project.mjs b/scripts/project.mjs index 7a32ac4..dc46a26 100644 --- a/scripts/project.mjs +++ b/scripts/project.mjs @@ -1,6 +1,6 @@ import fs from 'node:fs/promises';import path from 'node:path';import {pathToFileURL} from 'node:url';import {createHash,randomUUID} from 'node:crypto';import {build} from 'esbuild'; import {root} from './build.mjs';import {Studio,clone} from '../packages/core/index.mjs';import {serve,sendFile} from './server.mjs';import {readAssets,prepareMedia,fileHash} from './media.mjs'; -import {normalizeClipModule} from '../packages/core/definition.mjs'; +import {normalizeClipModule} from '../packages/core/definition.mjs';import {validateDerived} from '../packages/plate/manifest.mjs';import {validateTrack} from '../packages/plate/track.mjs';import {validateCameraPath} from '../packages/plate/camera.mjs'; const publicExports=JSON.parse(await fs.readFile(path.join(root,'package.json'),'utf8')).exports; function publicPackagePlugin(){return {name:'editableframes-public-exports',setup(b){b.onResolve({filter:/^editableframes(?:\/.*)?$/},args=>{const key=args.path==='editableframes'?'.':'./'+args.path.slice('editableframes/'.length),file=publicExports[key];return file?{path:path.join(root,file)}:{errors:[{text:'Unknown EditableFrames export: '+args.path}]};});}};} export const hash=s=>createHash('sha256').update(s).digest('hex'); @@ -16,9 +16,10 @@ export async function definition(dir){ } export async function init(dir,{template='canvas'}={}){ await fs.mkdir(dir,{recursive:true});if((await fs.readdir(dir)).length)throw Error('init needs an empty directory'); - if(!['canvas','media','renderer'].includes(template))throw Error('Unknown starter'); + if(!['canvas','media','renderer','hybrid'].includes(template))throw Error('Unknown starter'); await fs.copyFile(path.join(root,'templates',template,'clip.mjs'),path.join(dir,'clip.mjs')); if(template==='media'){const {createDemoMedia}=await import('./demo-media.mjs');await createDemoMedia(dir);} + if(template==='hybrid'){const {createHybridDemo}=await import('./demo-hybrid.mjs');await createHybridDemo(dir);} const d=await definition(dir),s=new Studio(d.templates,{binding:d.binding});s.doc.clips=[s.make(d.template.id)];s.doc.width=d.template.width??1280;s.doc.height=d.template.height??720;s.doc.fps=d.frameRate;s.check(s.doc);s.base=clone(s.doc); await snapshotSource(d);await fs.writeFile(path.join(dir,'project.json'),s.serialize());return {directory:path.resolve(dir),template:d.template.id}; } @@ -81,15 +82,20 @@ export async function rebind(dir,{reset=false}={}){ }finally{await fd.close();await fs.rm(lock,{force:true})} } -export async function importAsset(dir,id,source,{type}={}){ +export async function importAsset(dir,id,source,{type,role,of,encoding}={}){ if(['__proto__','constructor','prototype'].includes(id)||!/^[a-zA-Z0-9_-]{1,80}$/.test(id))throw Error('Invalid asset ID'); dir=await fs.realpath(dir);const lock=path.join(dir,'.editableframe-edit.lock'),fd=await fs.open(lock,'wx'); try{ const d=await readProject(dir);if(Object.hasOwn(d.assets,id))throw Error('Asset IDs are immutable; use a new ID and swap the port'); - const ext=path.extname(source).toLowerCase();type??=(['.png','.jpg','.jpeg','.webp'].includes(ext)?'image':['.wav','.mp3','.flac','.m4a'].includes(ext)?'audio':'video'); - if(!['image','audio','video'].includes(type)||!/^\.[a-z0-9]{1,8}$/.test(ext))throw Error('Invalid asset type/extension'); + const ext=path.extname(source).toLowerCase();type??=(['.png','.jpg','.jpeg','.webp'].includes(ext)?'image':['.wav','.mp3','.flac','.m4a'].includes(ext)?'audio':ext==='.json'?'data':'video'); + if(!['image','audio','video','data'].includes(type)||!/^\.[a-z0-9]{1,8}$/.test(ext))throw Error('Invalid asset type/extension'); + // A derived asset records the hash of the take it describes, so a regenerated take cannot reuse it. + if((role===undefined)!==(of===undefined))throw Error('Use --role and --of together'); + let derived;if(role){if(!Object.hasOwn(d.assets,of))throw Error('Unknown --of asset: '+of);derived={of,role,sourceSha256:d.assets[of].sha256,...(encoding?{encoding}:{})};} const sha256=await fileHash(source),src='assets/'+sha256+ext;await fs.mkdir(path.join(dir,'assets'),{recursive:true});await fs.copyFile(source,path.join(dir,src)); - const manifest={version:1,assets:{...d.assetIdentity,[id]:{src,type,sha256}}}; + const manifest={version:1,assets:{...d.assetIdentity,[id]:{src,type,sha256,...(derived?{derived}:{})}}}; + // Validate the whole manifest before publishing it; a refused import leaves assets.json unchanged. + validateDerived(manifest.assets);if(type==='data'&&role){const json=JSON.parse(await fs.readFile(source,'utf8'));if(role==='track')validateTrack(json);if(role==='camera')validateCameraPath(json);} const file=path.join(dir,'assets.json'),tmp=file+'.'+randomUUID()+'.tmp';await fs.writeFile(tmp,JSON.stringify(manifest,null,2));await fs.rename(tmp,file); // Rebinding is separate and explicit; the old project/source snapshot is retained. return {id,sha256,next:'Run rebind to accept the added asset; set a media port to its ID.'}; diff --git a/scripts/render.mjs b/scripts/render.mjs index 1ca6db0..32faf03 100644 --- a/scripts/render.mjs +++ b/scripts/render.mjs @@ -1,15 +1,18 @@ import fs from 'node:fs/promises';import path from 'node:path';import {randomUUID} from 'node:crypto';import {chromium} from 'playwright'; -import {preview,readProject} from './project.mjs';import {mixAudio} from './audio.mjs';import {run,ffmpeg,ffprobe} from './process.mjs';import {HZ} from '../packages/core/index.mjs'; +import {preview,readProject} from './project.mjs';import {mixAudio} from './audio.mjs';import {run,ffmpeg,ffprobe} from './process.mjs';import {HZ} from '../packages/core/index.mjs';import {shutterSamples,validateShutter} from '../packages/plate/motion-blur.mjs'; export function frameRate(value={num:24,den:1}){ if(typeof value==='string'){const [num,den=1]=value.split('/').map(Number);value={num,den}} if(typeof value==='number')value={num:value,den:1}; if(!Number.isSafeInteger(value.num)||!Number.isSafeInteger(value.den)||value.num<1||value.den<1||value.num/value.den>120||value.num/value.den<1||value.num>1000000||value.den>1000000)throw Error('Invalid rational frame rate');return value; } async function absent(file){try{await fs.lstat(file);throw Error('Output already exists: '+file)}catch(e){if(e.code!=='ENOENT')throw e}} -export async function render(dir,output,{fps,frames,format,background='#101922',signal,onProgress=()=>{}}={}){ +export async function render(dir,output,{fps,frames,format,background='#101922',pass='beauty',motionBlur,signal,onProgress=()=>{}}={}){ if(!output)throw Error('Output path is required');signal?.throwIfAborted(); const d=await readProject(dir),rate=frameRate(fps??d.studio.doc.fps),duration=Math.max(0,...d.studio.doc.clips.map(c=>(c.start+c.duration)/HZ)); const count=frames??Math.ceil(duration*rate.num/rate.den);if(!Number.isSafeInteger(count)||count<1||count>36000)throw Error('Invalid export frame budget'); + // A control pass exists only where the scene's own code draws it. + if(pass!=='beauty'&&(d.kind!=='renderer'||!(d.scene.passes??[]).includes(pass)))throw Error(`This scene does not declare a ${pass} pass`+(d.kind==='renderer'&&d.scene.passes?.length?`; it declares: ${d.scene.passes.join(', ')}`:'')); + const shutter=motionBlur?validateShutter(motionBlur):null;if(shutter&&count*shutter.samples>144000)throw Error('Motion blur sample budget exceeded; lower --samples or the frame count'); format??=path.extname(output)==='.mov'?'mov':path.extname(output)==='.mp4'?'mp4':null; if(!['mp4','mov','png'].includes(format))throw Error('Use .mp4, .mov (alpha), or --format png'); if(!/^#[0-9a-f]{6}$/i.test(background))throw Error('Background must be a six-digit color'); @@ -21,15 +24,27 @@ export async function render(dir,output,{fps,frames,format,background='#101922', onProgress({phase:'media',progress:0});host=await preview(dir,{port:0,editable:false,signal,snapshot:d}); browser=await chromium.launch({headless:true,args:['--enable-webgl',process.platform==='darwin'?'--use-angle=metal':'--use-angle=swiftshader']}); const page=await browser.newPage();page.on('pageerror',e=>errors.push(e.message));await page.goto(host.url);await page.waitForFunction(()=>window.editableframe?.ready,{},{timeout:30000}); - const frameDir=path.join(temp,'frames');await fs.mkdir(frameDir); + const frameDir=path.join(temp,'frames'),sampleDir=path.join(temp,'samples');await fs.mkdir(frameDir);if(shutter)await fs.mkdir(sampleDir); for(let frame=0;framewindow.editableframe.seek(t,{timeline:true}),frame*rate.den/rate.num);bytes=await page.locator('#screen').screenshot({omitBackground:true,timeout:30000});} - else{const png=await page.evaluate(async t=>{await window.editableframe.seek(t,{timeline:true});return window.editableframe.png()},frame*rate.den/rate.num);bytes=Buffer.from(png.split(',')[1],'base64');} - await fs.writeFile(path.join(frameDir,String(frame+1).padStart(6,'0')+'.png'),bytes); + // One capture per output frame, or one per shutter sample when motion blur is on. + const times=shutter?shutterSamples(frame,shutter):[frame]; + for(let sample=0;samplewindow.editableframe.seek(t,{timeline:true,pass}),[seconds,pass]);bytes=await page.locator('#screen').screenshot({omitBackground:true,timeout:30000});} + else{const png=await page.evaluate(async t=>{await window.editableframe.seek(t,{timeline:true});return window.editableframe.png()},seconds);bytes=Buffer.from(png.split(',')[1],'base64');} + await fs.writeFile(shutter?path.join(sampleDir,String(frame*shutter.samples+sample+1).padStart(8,'0')+'.png'):path.join(frameDir,String(frame+1).padStart(6,'0')+'.png'),bytes); + } onProgress({phase:'frames',frame:frame+1,total:count,progress:(frame+1)/count}); } + if(shutter){ + // Average each frame's samples as premultiplied colour, so a half-covered pixel keeps its hue instead of darkening. + // The mean is taken on encoded (display) values, not linear light. + onProgress({phase:'shutter',progress:0}); + await run(ffmpeg(),['-v','error','-n','-framerate','1','-i',path.join(sampleDir,'%08d.png'),'-vf',`format=gbrap,premultiply=inplace=1,tmix=frames=${shutter.samples},select='not(mod(n+1\\,${shutter.samples}))',unpremultiply=inplace=1,format=rgba`,'-fps_mode','passthrough','-frames:v',String(count),path.join(frameDir,'%06d.png')],{signal,timeout:600000}); + if((await fs.readdir(frameDir)).length!==count)throw Error('Motion blur produced the wrong number of frames'); + await fs.rm(sampleDir,{recursive:true,force:true}); + } const actualDuration=count*rate.den/rate.num,audioPath=path.join(temp,'audio.wav');const audio=await mixAudio({...d,assets:host.media.assets},host.media.catalog,audioPath,actualDuration,{signal}); let result; if(format==='png'){ @@ -46,7 +61,7 @@ export async function render(dir,output,{fps,frames,format,background='#101922', if(!info.streams.some(s=>s.codec_type==='video')||audio.tracks&&!info.streams.some(s=>s.codec_type==='audio'))throw Error('Encoded media failed stream validation'); } signal?.throwIfAborted(); - const receipt={version:1,engine:'editableframe',binding:d.binding,projectRevision:d.revision,fps:rate,frames:count,duration:actualDuration,format,alpha:format!=='mp4',runtime:d.runtimeIdentity,browser:browser.version(),ffmpeg:(await run(ffmpeg(),['-version'])).toString().split('\n')[0],platform:process.platform,background:format==='mp4'?background:null,audio:audio.tracks>0,audioTracks:audio.tracks,assets:Object.fromEntries(Object.entries(d.assets).map(([id,a])=>[id,a.sha256]))}; + const receipt={version:1,engine:'editableframe',binding:d.binding,projectRevision:d.revision,fps:rate,frames:count,duration:actualDuration,format,alpha:format!=='mp4',pass,motionBlur:shutter,runtime:d.runtimeIdentity,browser:browser.version(),ffmpeg:(await run(ffmpeg(),['-version'])).toString().split('\n')[0],platform:process.platform,background:format==='mp4'?background:null,audio:audio.tracks>0,audioTracks:audio.tracks,assets:Object.fromEntries(Object.entries(d.assets).map(([id,a])=>[id,a.sha256]))}; // Reserve the receipt path, and publish a complete file without overwriting another writer. const receiptFile=output+'.json',fd=await fs.open(receiptFile,'wx');let published=false; try{await fd.writeFile(JSON.stringify(receipt,null,2));await fd.sync();if(format==='png'){await absent(output);await fs.rename(result,output)}else await fs.link(result,output);published=true}finally{await fd.close();if(!published)await fs.rm(receiptFile,{force:true})} diff --git a/skills/editableframes/SKILL.md b/skills/editableframes/SKILL.md index d9edd07..eb0f0b2 100644 --- a/skills/editableframes/SKILL.md +++ b/skills/editableframes/SKILL.md @@ -23,6 +23,10 @@ Use `preview ` and inspect more than one meaningful frame. For an M The bundled `studio` has effect and creative studies plus the device library. Study their code when useful, while keeping new renderers free to use other libraries. EffectCraft's 306-entry map is research; only 24 scoped visual prototypes are demonstrated. Device assets keep their individual licenses and credits. +## Code inside footage + +When a shot mixes code with filmed or generated video, let footage supply what only has to look real (people, places, light) and code supply what must be exactly right (the product, labels, prices, interfaces, captions). Read [references/hybrid.md](references/hybrid.md) before authoring. `init --hybrid` creates a working example. A matte, depth map, track or camera path is an input made by another tool: import it with `asset-add --role --of `, never invent one, and say so when a shot needs one that is missing. Replacing the footage invalidates data derived from it. Sample anything locked to the footage at `conformSeconds(seconds, plate.frameRate)`, and render the project at the footage's frame rate. `render --pass ` exports a declared control pass; `render --motion-blur 180` adds a shutter. Light and depth scale are estimates: expose them as controls and check real frames. + ## Spatial objects For separately editable spatial objects expose one animatable vec3 with role position and explicit coordinateSpace/unit, plus one positive number with role scale. Use editableframes/manipulation (or editableframes/three-manipulation) and consume the same props in rendering. Publish working per-object manipulationCapabilities and measurement; roles alone cannot make a renderer draggable. Nonspatial lighting parameters need no invented transforms. Keep the 200-control budget; arbitrary renderer code and future libraries remain supported. Read docs/object-manipulation.md for source tick identity, first-key holding and gesture write policy. Preserve existing split-number tracks; migrate them explicitly rather than relabeling their type. diff --git a/skills/editableframes/references/hybrid.md b/skills/editableframes/references/hybrid.md new file mode 100644 index 0000000..d1d642a --- /dev/null +++ b/skills/editableframes/references/hybrid.md @@ -0,0 +1,193 @@ +# Hybrid scenes: code inside footage + +A hybrid scene combines two kinds of picture in one shot: + +- **Footage** (a "plate"): filmed, or made by a video model. It supplies what only has to look real: people, places, weather, light. +- **Code**: it supplies what has to be exactly right: the product's shape and label, a price, an interface, a chart, a logo, a caption. + +Stacking one on top of the other is easy and already worked. This document covers the harder case, where the two must agree with each other: a hand passes in front of a code-rendered product, a headline sits behind a presenter, a price stays stuck to a moving sign, the product is lit by the room it stands in. + +## Goal + +Make a code-rendered element belong to the footage it is placed in, while keeping what EditableFrames is for: the code part stays an editable document. Changing the label, the price or the language re-renders the same frames with only that change. Nothing is regenerated and the footage is not touched. + +EditableFrames does not run any model. Mattes, depth maps, tracks and camera paths are **inputs**. You make them with whatever tool you trust and license, and EditableFrames pins them, checks them and draws with them. This keeps the framework model-neutral and keeps export deterministic: the same inputs give the same frames. + +## Video creation journeys + +Each journey says what the author does, what EditableFrames does, and how far it is proven. + +| # | Journey | The author supplies | EditableFrames does | Proven by | +|---|---|---|---|---| +| 1 | **A product in a generated place.** A hard-surface product sits in a scene made by a video model and takes on its light. | The plate. | Wraps the plate into an environment, estimates which side the light is on, and lights the product with both. Lighting from the plate is an editable, undoable control. | Integration test: the lit side follows the bright area, the colour follows the plate, toggling it changes only the product. | +| 2 | **Something in the footage passes in front of the product.** A hand, a person, a pillar. | The plate and a depth map of it. | Writes the plate's depth into the depth buffer, so every mesh is hidden exactly where the footage is nearer. | Integration test: the product is covered by the plate foreground and visible beside it. | +| 3 | **A headline behind the presenter.** Text or graphics sit between the subject and the background. | The plate and a matte of the subject. | Redraws the matted subject over the DOM layers. | Integration test: no headline pixel survives in front of the subject, and the text continues on both sides. | +| 4 | **Screen or label replacement.** An exact interface, price or label sits on a surface that moves in the footage. | The plate and a planar track of the surface. | Pins a DOM element to the tracked quad on every frame, including between frames. | Integration test: the element covers the tracked surface edge to edge as it moves. | +| 5 | **Code first, footage second.** The code scene sets the camera and blocking; a video model paints a world around it; the exact product goes back on top. | A scene that declares control passes. | Exports the scene as clay, depth, normal, object-id and matte passes from the same camera and timing. | Integration test for the passes. Sending them to a video model and compositing the result is outside this repository and unproven here. | +| 6 | **Many versions from one take.** The same shot in twenty prices, five languages, three label colours. | One plate and its data, then control edits. | Re-renders each version from the same pinned inputs. If the plate is replaced, its old matte, depth and track are refused instead of being composited slightly wrong. | Integration test for the refusals; edits use the existing revision-checked history. | +| 7 | **Fast motion.** Code elements that move quickly should smear like the footage does. | A shutter angle. | Renders several sub-frame samples per output frame and averages them. | Integration test: smear width and edge colour. | +| 8 | **A moving camera.** The product stays put in a shot whose camera travels. | A camera path solved elsewhere. | Replays the path on a Three.js camera, with rotation interpolated correctly. | Unit tests only. Not yet tried on a real solve; solves of generated footage are approximate. | + +## Try it + +```sh +node bin/editableframes.mjs init ./my-hybrid --hybrid +node bin/editableframes.mjs preview ./my-hybrid +node bin/editableframes.mjs render ./my-hybrid ./hybrid.mp4 +node bin/editableframes.mjs render ./my-hybrid ./hybrid-blur.mp4 --motion-blur 180 +node bin/editableframes.mjs render ./my-hybrid ./clay --format png --pass clay +``` + +The starter generates its own plate, matte, depth map and track with FFmpeg from one set of formulas, so tests can state where every pixel must land. Replace them with your own: + +```sh +node bin/editableframes.mjs asset-add ./my-hybrid shot ./shot.mp4 +node bin/editableframes.mjs asset-add ./my-hybrid shot-matte ./shot-matte.mp4 --role matte --of shot +node bin/editableframes.mjs asset-add ./my-hybrid shot-depth ./shot-depth.mp4 --role depth --of shot --depth inverse --near 1 --far 20 +node bin/editableframes.mjs asset-add ./my-hybrid shot-track ./shot-track.json --role track --of shot +node bin/editableframes.mjs rebind ./my-hybrid +``` + +## Layers + +Back to front, this order is right for most shots: + +1. **Plate.** +2. **Far DOM**: screens pinned to surfaces in the background; text that passes behind the subject. +3. **Cut-out**: the plate's subject again (plate × matte), which restores it over layer 2. +4. **3D canvas**, depth-tested against the plate's depth. Depth decides per pixel whether the subject or the object is in front, so the canvas can sit above the cut-out. +5. **Near DOM**: captions, calls to action, logos. + +A scene can draw all five itself, as the starter does. That keeps one clock and one set of inputs. Depth ordering between separate clips is not available: clips stack with a transform and opacity only. + +## Plate data + +Data computed from a plate is declared in `assets.json` as a **derived** asset. It records the hash of the plate it was computed from: + +```json +"shot-matte": {"src": "assets/…mp4", "type": "video", "sha256": "…", + "derived": {"of": "shot", "role": "matte", "sourceSha256": ""}} +``` + +`asset-add --role … --of …` writes this for you. + +| Role | Type | Meaning | +|---|---|---| +| `matte` | video or image | White keeps the subject, black drops it. Luminance is coverage. | +| `depth` | video or image | Distance from the camera. White is near. Needs an `encoding` (below). | +| `normals` | video or image | Camera-space normals, `(n + 1) / 2` in RGB. Accepted and pinned; no helper consumes it yet. | +| `track` | data (JSON) | A planar or point track. See `packages/plate/track.mjs`. | +| `camera` | data (JSON) | A camera path. See `packages/plate/camera.mjs`. | +| `environment` | image | An equirectangular picture of the plate's surroundings. Accepted and pinned; the starter does not use one. | + +Rules, each refused with a message that says what to do: + +- The plate's hash must equal `sourceSha256`. A regenerated take invalidates its derived data. +- A plate has at most one asset per role. +- A derived asset cannot derive from another derived asset. +- A derived video must have exactly as many frames as its plate. +- A depth asset must carry an encoding. Tracks and camera paths are validated when loaded. + +**Depth encoding** is `{kind, near, far, packing}`. `kind` is `inverse` (what monocular depth models emit; precision is spent close to the camera) or `linear`. `near` and `far` are the distances white and black stand for, in scene units. `packing` is `gray8`, or `rg16` for 16 bits across red and green. Relative depth has no true scale, so `near` and `far` are values you tune until occlusion lands. They are not measurements. + +**Track** files are `{version: 1, kind: "planar" | "point", width, height, frameRate: {num, den}, frames: [{frame, quad | point, confidence?}]}`. Coordinates are plate pixels from the top-left. Quads are ordered top-left, top-right, bottom-right, bottom-left. Frames may be sparse; samples between them are interpolated, and samples outside them hold the nearest frame and say so. + +**Camera path** files are `{version: 1, frameRate, frames: [{frame, position, quaternion, fovY}]}`: camera-to-world, +Y up, looking down −Z, `fovY` in degrees. + +## Renderer contract additions + +Two optional services join `asset` and `mediaFrame`. Check that they exist before using them. + +- `context.mediaInfo(id)` returns `{type, width, height, duration, frames, frameRate, derived}` for a declared asset. +- `context.derived(id, role)` returns the id of the asset derived from `id` with that role, or `undefined`. + +`mediaFrame(id, seconds)` serves matte and depth frames like any other video. `asset(id)` returns a URL for a data asset; fetch it and parse the JSON. + +A scene may declare **control passes**: + +```js +defineRenderer({ …, passes: ['clay', 'depth', 'normal', 'id', 'matte'], … }) +``` + +The host then supplies `clock.pass` (`'beauty'` unless a pass was requested). A host never asks for a pass the scene did not declare, and the CLI refuses one. Pass names are open, like renderer names. `beauty` is implied and cannot be declared. + +## Helpers + +`editableframes/plate` is pure and renderer-independent: + +| Area | Functions | +|---|---| +| Corner pin | `solveHomography`, `applyHomography`, `invertHomography`, `cornerPinTransform`, `cssMatrix3d`, `quadArea` | +| Tracks | `validateTrack`, `sampleTrack`, `scalePoints` | +| Camera | `validateCameraPath`, `sampleCameraPath`, `slerp` | +| Frame rate | `plateFrameIndex`, `conformSeconds`, `cadence` | +| Depth | `validateDepthEncoding`, `decodeDepth`, `encodeDepth`, `packDepth`, `unpackDepth`, `depthGlsl`, `unprojectDepth`, `fitGroundPlane` | +| Measuring a plate | `plateStats`, `matchLevels`, `applyLevels`, `estimateKeyLight`, `estimateNoise`, `grainAt`, `expandHighlights` | +| Passes | `idColor`, `idFromColor`, `validatePasses` | +| Canvas | `drawCutout`, `drawGrain`, `createFrameLoader` | +| Shutter | `shutterSamples`, `validateShutter` | + +`editableframes/three-plate` is an optional Three.js adapter: + +| Function | Purpose | +|---|---| +| `createDepthOccluder(encoding)` | Lets the plate's own geometry hide the scene. Needs WebGL2, a perspective camera and the standard depth buffer. | +| `createMatteHoldout()` | Punches the matted subject out of the canvas. The cheap alternative when there is no depth; it is all-or-nothing per pixel. | +| `createPlateEnvironment(renderer)` | Lights the scene with the plate. | +| `applyKeyLight(light, estimate)` | Aims a directional light from `estimateKeyLight`. | +| `applyCameraSample(camera, sample)` | Replays a camera path. | +| `createShadowCatcher(plane)` | An invisible plane that shows only shadows, laid on a plane from `fitGroundPlane`. | +| `renderPass(renderer, scene, camera, pass, options)` | Draws the scene as clay, depth, normal, id or matte. | +| `dataTexture(image)` | A texture for plate data with no colour management. | + +None of this narrows what a renderer may draw. A scene that uses other libraries can read the same assets and implement its own passes. + +## What is estimated, and how far to trust it + +Three helpers guess from a single view. Expose their results as controls. + +- **`estimateKeyLight`** reads which side the light is on from the brightest 5% of the frame. A picture cannot say how far in front of or behind the subject the light is, so that part is a stated assumption: a small source is placed level with the subject, a broad one in front of it. +- **`createPlateEnvironment`** has only what the camera saw. It puts the plate in front and a mirrored copy behind the camera, and pushes clipped highlights above 1 so they can act as light sources. The result is plausible. It is not a measurement of the real surroundings, and the highlight boost is not recovered data. Use a real `environment` asset when you have one. +- **Depth `near` and `far`** are yours to tune, as above. + +## Frame rate + +Video models emit a fixed rate: commonly 24 fps, sometimes 16 or 30. Two things follow. + +- Anything locked to the footage should move on the footage's frame grid. `conformSeconds(seconds, plate.frameRate)` gives the time of the plate frame on screen; sample tracks, mattes and depth at that time. Otherwise a pinned element slides against the picture between plate frames. +- A plate inside a timeline of another rate repeats frames unevenly. `cadence({num: 24, den: 1}, {num: 30, den: 1})` reports the pattern `2,1,1,1`, which is visible as judder on any move. Render the project at the plate's rate, or interpolate the plate before importing it. + +## Export + +- `render DIR OUT --pass NAME` renders a declared pass. The receipt records it. +- `render DIR OUT --motion-blur ANGLE [--samples N]` opens a shutter of `ANGLE` degrees (0–360, default samples 8, range 2–64) centred on each frame. Samples are averaged as premultiplied colour, so a half-covered pixel keeps its hue. The mean is taken on encoded values, not linear light. Preview shows no motion blur. +- An export re-encodes its inputs. Content credentials or other provenance metadata carried by a generated plate are not copied to the output. If a law or a platform requires you to disclose AI-generated content, that remains your responsibility. + +## Compared with a full compositing checklist + +Professional compositing uses more steps than this. Stated plainly: + +| Step | Status | +|---|---| +| Occlusion by plate geometry | Done, from a depth map. | +| Subject in front of graphics | Done, from a matte. | +| Planar tracking and corner pin | Drawing done. The track comes from another tool. | +| Reflections of the plate in the object | Approximated by `createPlateEnvironment`. | +| Light direction | Estimated; editable. | +| Black and white point match | Measured by `plateStats` / `matchLevels`. Applying it is left to the scene. | +| Grain match | Measured by `estimateNoise`; `drawGrain` adds seeded grain. Not applied by the starter. | +| Motion blur | Done at export, for code layers. | +| Shadow of the object on the plate | `fitGroundPlane` and `createShadowCatcher` exist. Not exercised by the starter or the integration test. | +| Camera match | Replay only. No solver. | +| Depth of field, lens distortion, chromatic aberration, light wrap, atmospheric haze | Not provided. | +| Reflection or shadow of the object in the plate's own surfaces | Not provided. It needs the plate's normals and roughness. | +| Linear-light compositing | Not provided. Layers are composited by the browser on encoded values. | + +## Limits + +- The plate, matte and depth are decoded to PNG frames before preview and export, within the existing 8 GiB budget. Three videos per shot use it three times as fast. +- A renderer scene has no audio port. Sound from footage inside a scene is not mixed; keep speech on a media-port clip. +- `createDepthOccluder` assumes the plate and the scene share one camera. A depth map from a monocular model is consistent with itself, not with your scene units. +- Antialiased edges mix values, so `id` and `depth` passes are exact only away from silhouettes. `renderPass` does not handle skinned or instanced meshes. +- Results differ slightly across GPUs and browsers, as elsewhere in this framework. +- The tests use a synthetic plate. They prove that pixels land where the inputs say. They do not prove that a particular matting, depth or tracking tool gives good inputs on real footage. diff --git a/skills/editableframes/references/renderer.md b/skills/editableframes/references/renderer.md index c463e9a..13c0966 100644 --- a/skills/editableframes/references/renderer.md +++ b/skills/editableframes/references/renderer.md @@ -129,6 +129,22 @@ path does not mix arbitrary DOM audio automatically. Legacy media-port audio kee its existing mixing path. `captureSurface` is absent in this host. Feature-check optional services; do not invent layer, depth, simulation or screen services. +`context.mediaInfo(id)` returns `{type, width, height, duration, frames, frameRate, +derived}` for a declared asset. `context.derived(id, role)` returns the ID of the +asset computed from `id` with that role (`matte`, `depth`, `normals`, `track`, +`camera`, `environment`), or undefined. Both exist only when the project declares +media. A `data` asset is JSON: fetch `asset(id)` and parse it. See +[hybrid scenes](hybrid-scenes.md) for compositing code with footage. + +## Optional control passes + +A scene may declare `passes: ['clay', 'depth', …]`: other ways it can draw +itself, for conditioning a video model or compositing elsewhere. Names are open +lowercase identifiers; `beauty` is implied and cannot be declared. The host +supplies `clock.pass`, which is `'beauty'` unless a pass was requested, and never +requests a pass the scene did not declare. `render DIR OUT --pass NAME` exports +one. Draw nothing but the pass: hide footage and DOM layers. + When exposing controls for separate components, use distinct stable semantic anchors and matching properties. Connect controlled DOM nodes to those IDs, or implement Canvas/WebGL picking against the current rendered geometry and props. diff --git a/templates/hybrid/clip.mjs b/templates/hybrid/clip.mjs new file mode 100644 index 0000000..c14b8ba --- /dev/null +++ b/templates/hybrid/clip.mjs @@ -0,0 +1,98 @@ +// Hybrid starter: a code-rendered product inside footage. +// +// Footage ("plate") supplies what should merely look real. Code supplies what +// must be exactly right: the product, its label, the screen and the headline. +// The plate here is a synthetic diagnostic pattern; swap in your own with +// `asset-add`, together with the matte, depth and track made from it. +// +// Layers, back to front: +// plate the footage +// screen DOM, corner-pinned to a tracked surface in the plate +// headline DOM, passes BEHIND the plate's subject +// cut-out the plate's subject again (plate x matte), restoring it over the DOM layers +// product WebGL, depth-tested against the plate's own depth +import * as THREE from 'three'; +import {RoomEnvironment} from 'three/examples/jsm/environments/RoomEnvironment.js'; +import {defineRenderer} from 'editableframes/renderer'; +import {sampleTrack,scalePoints,cornerPinTransform,conformSeconds,drawCutout,createFrameLoader,estimateKeyLight} from 'editableframes/plate'; +import {createDepthOccluder,createPlateEnvironment,applyKeyLight,dataTexture,renderPass} from 'editableframes/three-plate'; + +const WIDTH=640,HEIGHT=360,IDS=['can.body','can.lid']; +export default defineRenderer({ + id:'hybrid-product',title:'Product in footage',renderer:'three+dom',width:WIDTH,height:HEIGHT,fps:24,durationInFrames:72, + passes:['clay','depth','normal','id','matte'], + defaultProps:{label:'ORBIT',detail:'330 ml · 0 kcal',color:'#d8263c',headline:'Cold. Always.',price:'$2.49',distance:3,offset:0,plateLight:true}, + controls:{version:1,objects:[{id:'scene',label:'Scene'},{id:'can',label:'Can',parentId:'scene'},{id:'headline',label:'Headline',parentId:'scene'},{id:'screen',label:'Screen',parentId:'scene'},{id:'light',label:'Lighting',parentId:'scene'}],fields:[ + {key:'label',anchor:'can',property:'label',path:'/label',type:'string',label:'Label'}, + {key:'detail',anchor:'can',property:'detail',path:'/detail',type:'string',label:'Small print'}, + {key:'color',anchor:'can',property:'color',path:'/color',type:'color',label:'Can colour'}, + {key:'distance',anchor:'can',property:'distance',path:'/distance',type:'number',min:1.5,max:8,label:'Distance from camera',animatable:true}, + {key:'offset',anchor:'can',property:'offset',path:'/offset',type:'number',min:-2,max:2,label:'Left / right',animatable:true}, + {key:'headline',anchor:'headline',property:'text',path:'/headline',type:'string',label:'Headline'}, + {key:'price',anchor:'screen',property:'text',path:'/price',type:'string',label:'Screen text'}, + {key:'plateLight',anchor:'light',property:'fromPlate',path:'/plateLight',type:'bool',label:'Light from the footage'}, + ]}, + async create({root,props,asset,mediaFrame,mediaInfo,derived}){ + if(!asset||!mediaFrame||!mediaInfo||!derived)throw Error('This scene needs a host that serves plate media (asset, mediaFrame, mediaInfo, derived)'); + const plate=mediaInfo('plate'),matteId=derived('plate','matte'),depthId=derived('plate','depth'),trackId=derived('plate','track'); + if(!matteId||!depthId||!trackId)throw Error('The plate needs a matte, a depth map and a track; add them with asset-add --role … --of plate'); + const encoding=mediaInfo(depthId).derived.encoding,track=await (await fetch(asset(trackId))).json(); + const doc=root.ownerDocument,layer=(tag,css)=>{const node=doc.createElement(tag);node.style.cssText='position:absolute;left:0;top:0;'+css;stage.append(node);return node;}; + const stage=doc.createElement('div');stage.style.cssText=`position:relative;width:${WIDTH}px;height:${HEIGHT}px;overflow:hidden`;root.append(stage); + const sized=canvas=>{canvas.width=WIDTH;canvas.height=HEIGHT;return canvas;}; + const plateCanvas=sized(layer('canvas','')),plateContext=plateCanvas.getContext('2d',{willReadFrequently:true}); + const screen=layer('div','width:160px;height:90px;transform-origin:0 0;display:flex;flex-direction:column;align-items:center;justify-content:center;background:#0b1220;color:#fff;font:700 34px/1 system-ui,sans-serif'); + screen.dataset.efAnchor='screen';const priceText=doc.createElement('div'),priceNote=doc.createElement('div');priceNote.textContent='per can';priceNote.style.cssText='font:500 11px/1.6 system-ui,sans-serif;opacity:.75';screen.append(priceText,priceNote); + const headline=layer('div',`width:${WIDTH}px;top:296px;text-align:center;color:#fff;font:800 40px/1 system-ui,sans-serif;letter-spacing:-.01em`);headline.dataset.efAnchor='headline'; + const cutCanvas=sized(layer('canvas','')),cutContext=cutCanvas.getContext('2d'),scratch=doc.createElement('canvas'); + const glCanvas=layer('canvas',`width:${WIDTH}px;height:${HEIGHT}px`); + + const renderer=new THREE.WebGLRenderer({canvas:glCanvas,alpha:true,antialias:true,preserveDrawingBuffer:true}); + renderer.setPixelRatio(1);renderer.setSize(WIDTH,HEIGHT,false);renderer.setClearColor(0x000000,0);renderer.outputColorSpace=THREE.SRGBColorSpace;renderer.toneMapping=THREE.NeutralToneMapping; + const scene=new THREE.Scene(),camera=new THREE.PerspectiveCamera(35,WIDTH/HEIGHT,0.1,50); + const key=new THREE.DirectionalLight(0xffffff,2);scene.add(key,key.target); + const can=new THREE.Group();can.userData.passId='can.body';scene.add(can); + const labelCanvas=doc.createElement('canvas');labelCanvas.width=1024;labelCanvas.height=512; + const labelMap=new THREE.CanvasTexture(labelCanvas);labelMap.colorSpace=THREE.SRGBColorSpace;labelMap.anisotropy=8; + const body=new THREE.Mesh(new THREE.CylinderGeometry(.33,.33,1,96,1,true),new THREE.MeshStandardMaterial({map:labelMap,metalness:.25,roughness:.36})); + const lidMaterial=new THREE.MeshStandardMaterial({color:0xd9dde2,metalness:1,roughness:.22}); + const lids=[.52,-.52].map(y=>{const lid=new THREE.Mesh(new THREE.CylinderGeometry(.3,.33,.04,96),lidMaterial);lid.position.y=y;lid.rotation.x=y<0?Math.PI:0;lid.userData.passId='can.lid';return lid;}); + can.add(body,...lids); + const occluder=createDepthOccluder(encoding),depthMap=dataTexture(doc.createElement('canvas'));scene.add(occluder.mesh); + const plateEnvironment=createPlateEnvironment(renderer),pmrem=new THREE.PMREMGenerator(renderer),room=new RoomEnvironment(),neutral=pmrem.fromScene(room,.04);room.dispose();pmrem.dispose(); + const frames=createFrameLoader(),probe=doc.createElement('canvas');probe.width=64;probe.height=36;const probeContext=probe.getContext('2d',{willReadFrequently:true}); + let labelKey,litFrom; + + function paintLabel(){ + const next=[props.label,props.detail,props.color].join('\n');if(next===labelKey)return;labelKey=next; + const c=labelCanvas.getContext('2d');c.fillStyle=props.color;c.fillRect(0,0,1024,512);c.fillStyle='rgba(255,255,255,.14)';c.fillRect(0,96,1024,8);c.fillRect(0,408,1024,8); + // The label is text laid out by the browser, so it is the same crisp string in every frame and every variant. + c.fillStyle='#fff';c.textAlign='center';c.textBaseline='middle'; + for(const x of [256,768]){c.font='900 150px system-ui,sans-serif';c.fillText(String(props.label),x,236);c.font='600 34px system-ui,sans-serif';c.fillText(String(props.detail),x,356);} + labelMap.needsUpdate=true; + } + return { + async render(clock){ + const pass=clock.pass??'beauty',seconds=clock.frame/clock.fps; + // Anything locked to the footage moves on the footage's own frame grid. + const plateTime=conformSeconds(Math.min(seconds,plate.duration-1e-6),plate.frameRate); + const [plateImage,matteImage,depthImage]=await Promise.all([plateTime,plateTime,plateTime].map((t,i)=>frames.load(mediaFrame(['plate',matteId,depthId][i],t)))); + paintLabel(); + can.position.set(props.offset,-.12,-props.distance);can.rotation.y=seconds*.9+.6; + if(pass!=='beauty'){stage.style.background='transparent';for(const node of [plateCanvas,screen,headline,cutCanvas])node.style.visibility='hidden';renderPass(renderer,scene,camera,pass,{ids:IDS,encoding});return;} + for(const node of [plateCanvas,screen,headline,cutCanvas])node.style.visibility='visible'; + plateContext.drawImage(plateImage,0,0,WIDTH,HEIGHT); + const pin=sampleTrack(track,plateTime);screen.style.transform=cornerPinTransform(160,90,scalePoints(pin.quad,track,WIDTH,HEIGHT));priceText.textContent=String(props.price); + headline.textContent=String(props.headline); + drawCutout(cutContext,plateImage,matteImage,scratch); + depthMap.image=depthImage;depthMap.needsUpdate=true;occluder.update(depthMap,camera); + if(props.plateLight){ + if(litFrom!==plateImage){litFrom=plateImage;scene.environment=plateEnvironment.update(plateImage);scene.environmentIntensity=1.5;probeContext.drawImage(plateImage,0,0,64,36);applyKeyLight(key,estimateKeyLight(probeContext.getImageData(0,0,64,36).data,64,36),{target:can.position});} + }else{litFrom=null;scene.environment=neutral.texture;scene.environmentIntensity=1;key.position.set(2,4,3);key.target.position.copy(can.position);key.target.updateMatrixWorld();key.color.set(0xffffff);key.intensity=1.2;} + renderer.render(scene,camera); + }, + pick({x,y}){const p=new THREE.Vector3().copy(can.position).project(camera);return Math.hypot(x-(p.x+1)/2*WIDTH,y-(1-p.y)/2*HEIGHT)<70?{anchor:'can',property:'label'}:null;}, + dispose(){frames.dispose();occluder.dispose();depthMap.dispose();plateEnvironment.dispose();neutral.dispose();labelMap.dispose();body.geometry.dispose();body.material.dispose();for(const lid of lids)lid.geometry.dispose();lidMaterial.dispose();renderer.dispose();renderer.forceContextLoss?.();stage.remove();}, + }; + } +}); diff --git a/tests/cli.test.mjs b/tests/cli.test.mjs index 33156b2..b841842 100644 --- a/tests/cli.test.mjs +++ b/tests/cli.test.mjs @@ -12,7 +12,7 @@ test('portable CLI starter and exact public documentation compile outside the ch const tmp=await fs.mkdtemp(path.join(os.tmpdir(),'ef-portable-cli-')),dir=path.join(tmp,'scene'); try{ cli('init',dir,'--renderer');const c=cli('inspect',dir);assert.equal(c.anchors[0].id,'orb');assert.equal(c.anchors[0].values.color,'#38bdf8'); - const guide=await fs.readFile(path.join(root,'docs/renderer-contract.md'),'utf8');assert.equal(await fs.readFile(path.join(root,'skills/editableframes/references/renderer.md'),'utf8'),guide); + const guide=await fs.readFile(path.join(root,'docs/renderer-contract.md'),'utf8');assert.equal(await fs.readFile(path.join(root,'skills/editableframes/references/renderer.md'),'utf8'),guide);/* The skill copy drops the pictures, whose relative links would not resolve from the skill folder. */assert.equal(await fs.readFile(path.join(root,'skills/editableframes/references/hybrid.md'),'utf8'),(await fs.readFile(path.join(root,'docs/hybrid-scenes.md'),'utf8')).replace(/\n!\[[^\n]*\]\(media\/[^\n]*\)\n\n\*[^\n]*\*\n/g,'')); const code=guide.match(/```js\n([\s\S]*?)```/)[1];await fs.writeFile(path.join(dir,'clip.mjs'),code);cli('rebind',dir,'--reset');assert.deepEqual(cli('inspect',dir).anchors,[]); const {readProject}=await import('../scripts/project.mjs');const d=await readProject(dir);assert.equal(d.kind,'renderer');assert.deepEqual(d.studio.doc.fps,{num:30,den:1});assert.equal(d.studio.doc.width,640); }finally{await fs.rm(tmp,{recursive:true,force:true})} diff --git a/tests/hybrid-integration.mjs b/tests/hybrid-integration.mjs new file mode 100644 index 0000000..e2ec0f9 --- /dev/null +++ b/tests/hybrid-integration.mjs @@ -0,0 +1,100 @@ +// Real pixels through the real CLI: a code-rendered product inside footage. +// The plate is synthetic so every assertion below has a known answer. +import assert from 'node:assert/strict'; +import fs from 'node:fs/promises';import os from 'node:os';import path from 'node:path'; +import {init,readProject,mutate,rebind,importAsset} from '../scripts/project.mjs'; +import {render} from '../scripts/render.mjs';import {run,ffmpeg} from '../scripts/process.mjs'; +import {HYBRID_DEMO as demo} from '../scripts/demo-hybrid.mjs'; +import {idFromColor,encodeDepth} from '../packages/plate/index.mjs'; + +const tmp=await fs.mkdtemp(path.join(os.tmpdir(),'ef-hybrid-')),dir=path.join(tmp,'film'),checks=[]; +const W=demo.width,H=demo.height,hex=value=>[1,3,5].map(i=>parseInt(value.replace('0x','#').slice(i,i+2),16)); +const WALL=hex(demo.colors.wall),BAR=hex(demo.colors.bar),BOARD=hex(demo.colors.board),SCREEN=[11,18,32]; +async function pixels(file){const data=await run(ffmpeg(),['-v','error','-i',file,'-pix_fmt','rgba','-f','rawvideo','-'],{maxOutput:64*1024**2});assert.equal(data.length,W*H*4);return {at:(x,y)=>[...data.subarray((y*W+x)*4,(y*W+x)*4+4)],data};} +const close=(actual,expected,tolerance=8)=>expected.every((v,i)=>Math.abs(actual[i]-v)<=tolerance); +const frameFile=(folder,frame)=>path.join(folder,String(frame+1).padStart(6,'0')+'.png'); +const mean=(image,x0,y0,x1,y1)=>{const sum=[0,0,0];let n=0;for(let y=y0;yv/n)}; +try{ + await init(dir,{template:'hybrid'}); + const project=await readProject(dir);assert.deepEqual(project.scene.passes,['clay','depth','normal','id','matte']);assert.deepEqual(project.studio.doc.fps,{num:24,den:1}); + + // --- Beauty: occlusion, layering and tracking -------------------------------- + const beauty=path.join(tmp,'beauty');await render(dir,beauty,{format:'png',frames:40}); + const early=6,late=35,barAt=frame=>demo.bar.x(frame),boardAt=frame=>demo.board.x(frame); + const a=await pixels(frameFile(beauty,early)),b=await pixels(frameFile(beauty,late)); + // Frame 6: the bar is far left; the product is in the clear. + assert.ok(barAt(early)+demo.bar.width<250); + const can=a.at(300,170);assert.ok(!close(can,WALL,30)&&!close(can,BAR,30),'the product is drawn over the wall');assert.ok(can[0]>can[2]*2,'and it is the red can'); + // Frame 35: the bar stands in front of the product's centre, and ONLY the plate's depth says so. + assert.ok(barAt(late)<320&&barAt(late)+demo.bar.width>320); + assert.ok(close(b.at(320,170),BAR),'the plate foreground hides the product where it is nearer'); + const beside=b.at(barAt(late)+demo.bar.width+12,170);assert.ok(!close(beside,WALL,30)&&!close(beside,BAR,30),'the product is still visible beside the foreground'); + checks.push('A 3D object is hidden by plate foreground and shown over plate background, from the depth map alone'); + + // The headline is DOM text; the cut-out layer puts the plate subject back over it. + const white=(image,x0,x1)=>{let n=0;for(let y=296;y<340;y++)for(let x=x0;x235&&p[1]>235&&p[2]>235)n++}return n}; + assert.ok(white(a,200,440)>400,'the headline is drawn'); + assert.equal(white(b,barAt(late)+2,barAt(late)+demo.bar.width-2),0,'no headline pixel survives in front of the bar'); + assert.ok(white(b,200,barAt(late))>50&&white(b,barAt(late)+demo.bar.width,440)>50,'and it continues on both sides'); + checks.push('DOM text passes behind the matted plate subject'); + + // The screen is a DOM element pinned to the tracked board, which moves 14px between these frames. + assert.equal(boardAt(late)-boardAt(early),14); + for(const [image,frame]of [[a,early],[b,late]]){const x=boardAt(frame); + assert.ok(close(image.at(x+4,demo.board.y+4),SCREEN),'screen covers the board corner');assert.ok(close(image.at(x+demo.board.width-4,demo.board.y+demo.board.height-4),SCREEN),'and its far corner'); + assert.ok(close(image.at(x-4,demo.board.y+4),WALL),'and stops at the board edge');assert.ok(!close(image.at(x+4,demo.board.y+4),BOARD,6));} + checks.push('A DOM screen stays corner-pinned to a tracked surface as it moves'); + + // --- Lighting from the plate -------------------------------------------------- + // The plate's only bright area is a window on the left, so the can's left side is the lit one. + const lit=mean(a,262,150,300,260),shade=mean(a,345,150,380,260);assert.ok(lit[0]>shade[0]*1.4,'the side facing the bright window is brighter'); + await mutate(dir,d=>d.studio.execute({type:'set',clip:d.studio.doc.clips[0].id,anchor:'light',property:'fromPlate',value:false},d.studio.revision,'model')); + const neutralDir=path.join(tmp,'neutral');await render(dir,neutralDir,{format:'png',frames:early+1});const n=await pixels(frameFile(neutralDir,early)); + const warm=rgb=>rgb[0]/(rgb[2]+1),plateLit=mean(a,262,150,380,260),studioLit=mean(n,262,150,380,260); + assert.ok(Math.abs(plateLit[0]-studioLit[0])+Math.abs(plateLit[1]-studioLit[1])+Math.abs(plateLit[2]-studioLit[2])>12,'turning plate lighting off changes the product'); + assert.ok(warm(plateLit)>warm(studioLit),'under the warm plate the product reads warmer than under neutral studio light'); + assert.ok(close(n.at(20,340),a.at(20,340),2),'the footage itself is untouched by the lighting control'); + await mutate(dir,d=>d.studio.undo()); + checks.push('The product is lit by the footage: direction follows the bright area, colour follows the plate, and it is an undoable control'); + + // --- Control passes ------------------------------------------------------------ + const pass=async name=>{const out=path.join(tmp,name);const receipt=await render(dir,out,{format:'png',frames:1,pass:name});assert.equal(receipt.pass,name);return pixels(frameFile(out,0));}; + const id=await pass('id');assert.equal(id.at(5,5)[3],0,'no plate, no DOM: the pass is transparent outside the object'); + assert.equal(idFromColor(id.at(320,200)),0,'the body decodes to the first declared id'); + let lid=false;for(let y=80;y<140&&!lid;y++)lid=id.at(320,y)[3]===255&&idFromColor(id.at(320,y))===1;assert.ok(lid,'the lid decodes to the second'); + const depth=await pass('depth'),front=3-.33,expected=Math.round(encodeDepth(front,demo.depth)*255); + assert.ok(Math.abs(depth.at(320,200)[0]-expected)<=3,`depth pass encodes the nearest surface (${depth.at(320,200)[0]} vs ${expected})`);assert.ok(depth.at(320,200)[0]>depth.at(262,200)[0],'and falls off toward the silhouette'); + const matte=await pass('matte');assert.deepEqual(matte.at(320,200),[255,255,255,255]);assert.equal(matte.at(5,5)[3],0); + // Nothing but the object: the capture page's own chrome must not show through a transparent frame. + let stray=0;for(let y=0;y410||y<70))stray++;assert.equal(stray,0,'a transparent pass contains only the scene'); + const normal=await pass('normal');assert.ok(normal.at(320,200)[2]>200&&Math.abs(normal.at(320,200)[0]-128)<25,'the surface facing the camera has a camera-facing normal'); + const clay=await pass('clay'),grey=clay.at(300,200);assert.equal(grey[3],255);assert.ok(Math.max(...grey.slice(0,3))-Math.min(...grey.slice(0,3))<70&&!close(grey,can,25),'clay replaces the label with neutral shading'); + await assert.rejects(render(dir,path.join(tmp,'albedo'),{format:'png',frames:1,pass:'albedo'}),/does not declare a albedo pass; it declares: clay/); + checks.push('clay, depth, normal, id and matte passes export from the same scene; an undeclared pass is refused'); + + // --- Derived data is pinned to its take --------------------------------------- + const short=path.join(tmp,'short.mp4');await run(ffmpeg(),['-v','error','-f','lavfi','-i',`color=c=gray:s=${W}x${H}:r=24:d=1`,'-c:v','libx264','-qp','0','-pix_fmt','yuv444p',short]); + await importAsset(dir,'plate-normals',short,{role:'normals',of:'plate'});await rebind(dir); + await assert.rejects(render(dir,path.join(tmp,'mismatch'),{format:'png',frames:1}),/plate-normals has 24 frames but plate has 72/); + await assert.rejects(importAsset(dir,'second-matte',short,{role:'matte',of:'plate'}),/two matte/); + const manifest=JSON.parse(await fs.readFile(path.join(dir,'assets.json'),'utf8'));manifest.assets['plate-matte'].derived.sourceSha256='0'.repeat(64);await fs.writeFile(path.join(dir,'assets.json'),JSON.stringify(manifest)); + await assert.rejects(readProject(dir),/regenerate the matte/); + checks.push('A matte from another take, a second matte, and a derived video with the wrong frame count are refused'); + + // --- Motion blur ------------------------------------------------------------------ + const blurDir=path.join(tmp,'blur-clip');await init(blurDir,{template:'renderer'}); + await fs.writeFile(path.join(blurDir,'clip.mjs'),`import {defineRenderer} from 'editableframes/renderer';export default defineRenderer({id:'mover',renderer:'dom',width:160,height:90,fps:24,durationInFrames:24,async create({root}){const box=document.createElement('div');box.style.cssText='position:absolute;top:30px;width:30px;height:30px;background:#00ff00';root.append(box);return {render(clock){box.style.left=(clock.frame*20)+'px';},dispose(){box.remove();}};}});`); + await rebind(blurDir,{reset:true}); + const sharpDir=path.join(tmp,'sharp'),softDir=path.join(tmp,'soft');await render(blurDir,sharpDir,{format:'png',frames:4}); + const receipt=await render(blurDir,softDir,{format:'png',frames:4,motionBlur:{angle:180,samples:8}});assert.deepEqual(receipt.motionBlur,{samples:8,angle:180,phase:'centered'});assert.equal((await fs.readdir(softDir)).length,4); + const row=async file=>{const data=await run(ffmpeg(),['-v','error','-i',file,'-pix_fmt','rgba','-f','rawvideo','-']);return Array.from({length:160},(_,x)=>[...data.subarray((45*160+x)*4,(45*160+x)*4+4)]);}; + const sharp=await row(frameFile(sharpDir,2)),soft=await row(frameFile(softDir,2)); + assert.ok(sharp.every(p=>p[3]===0||p[3]===255),'without a shutter every pixel is fully on or off'); + const partial=soft.filter(p=>p[3]>8&&p[3]<247);assert.ok(partial.length>=8,'the shutter leaves partly covered pixels along the direction of travel'); + // The shutter is open over 1.75..2.25 frames at 20px per frame. Eight samples sit at the middle of + // eight equal slices, so the first and last are 8.75px apart: 4px of smear on each side of the square. + assert.equal(soft.filter(p=>p[3]>0).length-sharp.filter(p=>p[3]>0).length,8); + assert.ok(partial.every(p=>p[1]>=245&&p[0]<=10&&p[2]<=10),'a half-covered pixel keeps the pure colour: samples are averaged premultiplied'); + checks.push('Shutter motion blur averages sub-frame samples with correct edge colour'); + console.log(JSON.stringify({checks},null,2)); +}finally{await fs.rm(tmp,{recursive:true,force:true});} diff --git a/tests/plate.test.mjs b/tests/plate.test.mjs new file mode 100644 index 0000000..e6cb2f4 --- /dev/null +++ b/tests/plate.test.mjs @@ -0,0 +1,176 @@ +import {test} from 'node:test'; +import assert from 'node:assert/strict'; +import * as plate from '../packages/plate/index.mjs'; +import {defineRenderer} from '../packages/core/renderer.mjs'; +import {mountRenderer} from '../packages/runtime/renderer-host.mjs'; + +const near = (a, b, tolerance = 1e-6) => assert.ok(Math.abs(a - b) <= tolerance, `${a} is not within ${tolerance} of ${b}`); +const image = (width, height, paint) => { const data = new Uint8ClampedArray(width * height * 4); for (let y = 0; y < height; y++) for (let x = 0; x < width; x++) { const [r, g, b] = paint(x, y); data.set([r, g, b, 255], (y * width + x) * 4); } return data; }; + +test('a corner pin carries every corner onto its target and inverts', () => { + const quad = [[10, 12], [130, 24], [118, 96], [4, 70]], h = plate.solveHomography(plate.rectQuad(160, 90), quad); + plate.rectQuad(160, 90).forEach((corner, i) => plate.applyHomography(h, corner).forEach((v, axis) => near(v, quad[i][axis], 1e-9))); + plate.applyHomography(plate.invertHomography(h), quad[2]).forEach((v, axis) => near(v, [160, 90][axis], 1e-8)); + const identity = plate.multiplyHomography(h, plate.invertHomography(h)); + [1, 0, 0, 0, 1, 0, 0, 0, 1].forEach((v, i) => near(identity[i], v, 1e-9)); + // A pure translation is the simplest case to read off the CSS matrix. + assert.equal(plate.cornerPinTransform(10, 10, [[5, 7], [15, 7], [15, 17], [5, 17]]), 'matrix3d(1,0,0,0,0,1,0,0,0,0,1,0,5,7,0,1)'); + assert.throws(() => plate.solveHomography(plate.rectQuad(10, 10), [[0, 0], [5, 5], [10, 10], [20, 20]]), /Degenerate/); + assert.throws(() => plate.cornerPinTransform(0, 10, quad), /positive/); + assert.ok(plate.quadArea(quad) > 0); assert.ok(plate.quadArea([...quad].reverse()) < 0); +}); + +test('tracks interpolate between frames, hold outside them and refuse bad data', () => { + const track = {version: 1, kind: 'planar', width: 640, height: 360, frameRate: {num: 24, den: 1}, frames: [ + {frame: 2, quad: [[0, 0], [10, 0], [10, 10], [0, 10]], confidence: 1}, + {frame: 6, quad: [[40, 0], [50, 0], [50, 10], [40, 10]], confidence: .5}, + ]}; + plate.validateTrack(track); + const mid = plate.sampleTrack(track, 4 / 24); + assert.deepEqual(mid.quad[0], [20, 0]); assert.equal(mid.confidence, .5); assert.equal(mid.held, false); + // The last good frame before a weaker one is still fully trusted. + assert.equal(plate.sampleTrack(track, 2 / 24).confidence, 1); assert.equal(plate.sampleTrack(track, 6 / 24).confidence, .5); + // Sub-frame times are what a motion-blur sample asks for. + near(plate.sampleTrack(track, 2.5 / 24).quad[0][0], 5); + assert.deepEqual(plate.sampleTrack(track, 0).quad[0], [0, 0]); assert.equal(plate.sampleTrack(track, 0).held, true); + assert.deepEqual(plate.sampleTrack(track, 9).quad[0], [40, 0]); assert.equal(plate.sampleTrack(track, 9).held, true); + assert.deepEqual(plate.scalePoints([[320, 180]], track, 1280, 720), [[640, 360]]); + const point = {...track, kind: 'point', frames: [{frame: 0, point: [0, 0]}, {frame: 10, point: [10, 20]}]}; + assert.deepEqual(plate.sampleTrack(plate.validateTrack(point), 5 / 24).point, [5, 10]); + assert.throws(() => plate.validateTrack({...track, frames: [track.frames[1], track.frames[0]]}), /increasing/); + assert.throws(() => plate.validateTrack({...track, frames: [{frame: 0, quad: [[0, 0]]}]}), /four finite/); + assert.throws(() => plate.validateTrack({...track, frameRate: {num: 24, den: 0}}), /frameRate/); +}); + +test('camera paths slerp rotation and hold their ends', () => { + const half = Math.SQRT1_2, path = plate.validateCameraPath({version: 1, frameRate: {num: 24, den: 1}, frames: [ + {frame: 0, position: [0, 0, 0], quaternion: [0, 0, 0, 1], fovY: 30}, + {frame: 24, position: [2, 0, -4], quaternion: [0, half, 0, half], fovY: 50}, + ]}); + const mid = plate.sampleCameraPath(path, .5); + assert.deepEqual(mid.position, [1, 0, -2]); near(mid.fovY, 40); + // Halfway to a 90-degree yaw is a 45-degree yaw, still a unit quaternion. + near(mid.quaternion[1], Math.sin(Math.PI / 8)); near(mid.quaternion[3], Math.cos(Math.PI / 8)); near(Math.hypot(...mid.quaternion), 1); + assert.deepEqual(plate.sampleCameraPath(path, 99).position, [2, 0, -4]); + // q and -q are the same rotation; the short way round is taken. + near(plate.slerp([0, 0, 0, 1], [0, 0, 0, -1], .5)[3], 1); + assert.throws(() => plate.validateCameraPath({...path, frames: [{...path.frames[0], quaternion: [0, 0, 0, 2]}]}), /unit quaternion/); +}); + +test('conform snaps code to the plate frame grid and names uneven cadence', () => { + const film = {num: 24, den: 1}; + assert.equal(plate.plateFrameIndex(.5, film), 12); assert.equal(plate.plateFrameIndex(1 / 24, film), 1); + near(plate.conformSeconds(.51, film), .5); near(plate.conformSeconds(1, {num: 30000, den: 1001}), 29 * 1001 / 30000); + assert.deepEqual(plate.cadence(film, {num: 30, den: 1}).pattern, [2, 1, 1, 1]); assert.equal(plate.cadence(film, {num: 30, den: 1}).even, false); + assert.deepEqual(plate.cadence(film, {num: 60, den: 1}).pattern, [3, 2]); + assert.equal(plate.cadence(film, film).even, true); assert.equal(plate.cadence({num: 30, den: 1}, {num: 60, den: 1}).even, true); + assert.equal(plate.cadence({num: 30, den: 1}, film).dropsFrames, true); + assert.throws(() => plate.plateFrameIndex(-1, film)); +}); + +test('shutter samples stay inside the open interval', () => { + assert.deepEqual(plate.shutterSamples(10, {samples: 4, angle: 180}), [9.8125, 9.9375, 10.0625, 10.1875]); + assert.deepEqual(plate.shutterSamples(0, {samples: 2, angle: 360, phase: 'forward'}), [.25, .75]); + assert.ok(plate.shutterSamples(0, {samples: 8, angle: 360}).every(t => t >= 0)); + for (const bad of [{samples: 1}, {samples: 65}, {angle: 0}, {angle: 361}, {phase: 'late'}]) assert.throws(() => plate.validateShutter(bad)); +}); + +test('depth encodings round-trip, white is near, and the shader carries the same constants', () => { + for (const kind of ['inverse', 'linear']) { + const encoding = plate.validateDepthEncoding({kind, near: 1.2, far: 12}); + near(plate.decodeDepth(1, encoding), 1.2); near(plate.decodeDepth(0, encoding), 12); + for (const distance of [1.2, 2, 3.3, 7, 12]) near(plate.decodeDepth(plate.encodeDepth(distance, encoding), encoding), distance, 1e-9); + assert.ok(plate.encodeDepth(2, encoding) > plate.encodeDepth(5, encoding)); + } + const [high, low] = plate.packDepth(.123456, 'rg16'); near(plate.unpackDepth(high, low, 'rg16'), .123456, 1 / 65535); + assert.deepEqual(plate.packDepth(1), [255, 255, 255]); + assert.match(plate.depthGlsl({kind: 'linear', near: 1, far: 9, packing: 'rg16'}), /texel\.r \* 65280\.0.*9\.00000000 - v \* 8\.00000000/); + assert.throws(() => plate.validateDepthEncoding({kind: 'inverse', near: 0, far: 5})); assert.throws(() => plate.validateDepthEncoding({kind: 'metric', near: 1, far: 5})); + assert.deepEqual(plate.unprojectDepth(.5, .5, 3, 35, 16 / 9), [0, 0, -3]); + // A floor one unit below the camera, sampled at four depths. + const floor = plate.fitGroundPlane([[0, -1, -2], [1, -1, -3], [-1, -1, -5], [2, -1, -4]]); + near(floor.normal[1], 1); near(floor.point[1], -1); near(floor.rms, 0); + assert.throws(() => plate.fitGroundPlane([[0, 0, 0], [1, 1, 0], [2, 2, 0]]), /ground plane/); +}); + +test('plate measurements: levels, light direction, noise and grain', () => { + const stats = plate.plateStats(image(40, 20, x => x < 20 ? [30, 30, 30] : [220, 200, 180]), 40, 20); + near(stats.black[0], plate.srgbToLinear(30 / 255)); near(stats.white[2], plate.srgbToLinear(180 / 255)); + const levels = plate.matchLevels(stats); + // A full-range render lands exactly on the plate's own black and white. + plate.applyLevels([0, 0, 0], levels).forEach((v, c) => near(v, stats.black[c])); + plate.applyLevels([1, 1, 1], levels).forEach((v, c) => near(v, stats.white[c])); + + const window = (x0, y0) => image(64, 36, (x, y) => x >= x0 && x < x0 + 8 && y >= y0 && y < y0 + 6 ? [255, 240, 200] : [90, 60, 40]); + const left = plate.estimateKeyLight(window(4, 3), 64, 36), right = plate.estimateKeyLight(window(52, 26), 64, 36); + assert.ok(left.toward[0] < -.4 && left.toward[1] > .3, 'a bright patch upper-left lights from upper-left'); + assert.ok(right.toward[0] > .4 && right.toward[1] < -.2, 'a bright patch lower-right lights from lower-right'); + near(Math.hypot(...left.toward), 1); assert.ok(left.concentration > .7); assert.ok(left.color[0] >= left.color[2]); + assert.ok(left.ambient[0] > left.ambient[2], 'the fill keeps the wall colour'); + assert.equal(plate.estimateKeyLight(image(64, 36, () => [128, 128, 128]), 64, 36).concentration, 0); + + assert.equal(plate.estimateNoise(image(64, 64, () => [128, 128, 128]), 64, 64), 0); + // Known Gaussian noise (seeded Box-Muller), sigma 8/255. + let seed = 7; const random = () => (seed = Math.imul(seed, 1664525) + 1013904223 >>> 0) / 4294967296; + const noisy = image(128, 128, () => { const g = Math.sqrt(-2 * Math.log(random() + 1e-12)) * Math.cos(2 * Math.PI * random()), v = Math.round(128 + 8 * g); return [v, v, v]; }); + near(plate.estimateNoise(noisy, 128, 128), 8 / 255, 4 / 255 / 4); + + assert.equal(plate.grainAt(3, 9, 12, 5), plate.grainAt(3, 9, 12, 5)); assert.notEqual(plate.grainAt(3, 9, 12, 5), plate.grainAt(3, 9, 13, 5)); + let sum = 0; for (let i = 0; i < 4000; i++) { const g = plate.grainAt(i % 80, i >> 4, 1); assert.ok(g >= -1 && g <= 1); sum += g; } + assert.ok(Math.abs(sum / 4000) < .08, 'grain is centred on zero'); + + const expanded = plate.expandHighlights(new Uint8ClampedArray([255, 255, 255, 255, 100, 100, 100, 255])); + assert.ok(expanded[0] > 6, 'a clipped white is pushed well above 1'); near(expanded[4], plate.srgbToLinear(100 / 255), 1e-6); + assert.throws(() => plate.plateStats(new Uint8ClampedArray(8), 4, 4)); +}); + +test('object ids survive a round trip through colour', () => { + const seen = new Set(); + for (const index of [0, 1, 2, 3, 255, 256, 65535, 1_000_000, 16_777_213]) { const color = plate.idColor(index); assert.equal(plate.idFromColor(color), index); seen.add(color.join()); } + assert.equal(seen.size, 9); assert.equal(plate.idFromColor([0, 0, 0]), -1); + // Neighbouring ids are far apart, so two adjacent objects stay distinguishable by eye. + const [a, b] = [plate.idColor(0), plate.idColor(1)]; assert.ok(Math.abs(a[0] - b[0]) + Math.abs(a[1] - b[1]) + Math.abs(a[2] - b[2]) > 100); + assert.throws(() => plate.idColor(-1)); + assert.deepEqual(plate.validatePasses(['beauty', 'clay', 'id']), ['clay', 'id']); + assert.throws(() => plate.validatePasses(['clay', 'clay'])); assert.throws(() => plate.validatePasses(['Depth'])); +}); + +test('a scene declares its passes; invalid declarations are refused', () => { + const base = {id: 'x', renderer: 'any', width: 16, height: 16, fps: 24, durationInFrames: 1, create: async () => ({render() {}, dispose() {}})}; + assert.deepEqual(defineRenderer({...base, passes: ['clay', 'depth']}).passes, ['clay', 'depth']); + assert.equal(defineRenderer(base).passes, undefined); + for (const passes of [['beauty'], ['clay', 'clay'], ['Bad Name'], 'clay']) assert.throws(() => defineRenderer({...base, passes}), /passes/); +}); + +test('derived assets are pinned to the take they were made from', () => { + const sha = c => c.repeat(64), ok = () => ({ + plate: {type: 'video', sha256: sha('a')}, + matte: {type: 'video', sha256: sha('b'), derived: {of: 'plate', role: 'matte', sourceSha256: sha('a')}}, + depth: {type: 'video', sha256: sha('c'), derived: {of: 'plate', role: 'depth', sourceSha256: sha('a'), encoding: {kind: 'inverse', near: 1, far: 10}}}, + track: {type: 'data', sha256: sha('d'), derived: {of: 'plate', role: 'track', sourceSha256: sha('a')}}, + }); + assert.deepEqual(plate.validateDerived(ok()), {plate: {matte: 'matte', depth: 'depth', track: 'track'}}); + const broken = edit => { const assets = ok(); edit(assets); return () => plate.validateDerived(assets); }; + // The plate was regenerated: its matte now describes a different picture. + assert.throws(broken(a => { a.plate.sha256 = sha('e'); }), /regenerate the matte/); + assert.throws(broken(a => { a.matte.derived.of = 'missing'; }), /another declared asset/); + assert.throws(broken(a => { a.matte.derived.of = 'matte'; }), /another declared asset/); + assert.throws(broken(a => { a.track.type = 'video'; }), /A track must be data/); + assert.throws(broken(a => { delete a.depth.derived.encoding; }), /encoding/); + assert.throws(broken(a => { a.matte.derived.encoding = {kind: 'inverse', near: 1, far: 2}; }), /Only depth/); + assert.throws(broken(a => { a.matte.derived.role = 'roto'; }), /unknown role/); + assert.throws(broken(a => { a.second = structuredClone(a.matte); }), /two matte/); + assert.throws(broken(a => { a.chain = {type: 'video', sha256: sha('f'), derived: {of: 'matte', role: 'matte', sourceSha256: sha('b')}}; }), /itself derived/); +}); + +test('the host hands plate services to a scene and nothing it was not given', async () => { + const element = () => ({style: {}, append() {}, remove() {}}); + const root = {ownerDocument: {createElement: element, fonts: {ready: Promise.resolve()}}, append() {}}; + let context; + const scene = defineRenderer({id: 'x', renderer: 'any', width: 16, height: 16, fps: 24, durationInFrames: 1, create: async c => { context = c; return {render() {}, dispose() {}}; }}); + const instance = await mountRenderer(scene, {root, services: {mediaInfo: id => ({id}), derived: (id, role) => `${id}-${role}`}}); + assert.deepEqual(context.mediaInfo('plate'), {id: 'plate'}); assert.equal(context.derived('plate', 'matte'), 'plate-matte'); + assert.equal(context.mediaFrame, undefined); assert.equal(context.asset, undefined); + await instance.dispose(); + await assert.rejects(mountRenderer(scene, {root, services: {derived: 'nope'}}), /Invalid derived service/); +}); From 627d0f8eb63b32f30e8537e3bf0d187644ebe0a6 Mon Sep 17 00:00:00 2001 From: lxf82dev Date: Tue, 10 Nov 2026 23:42:41 +0800 Subject: [PATCH 02/49] Hybrid scenes: fix the plate environment and the import sequence; report a trial on generated footage Two defects found by running the hybrid helpers on plates from video models: - createPlateEnvironment drew the mirrored half of its panorama off the canvas (translate width + half on a canvas `width` wide), so everything behind the camera was black and a mirror-like product lit from the footage rendered black. The panorama is now painted by an exported paintPlatePanorama, with a unit test for where both halves land and a real-pixel check that the side turned away from the light still reflects footage. - A second asset-add before rebind failed with "Incompatible project", so the sequence shown in docs/hybrid-scenes.md did not run. importAsset now reads the clip definition and asset manifest, not the bound project. A real-pixel check runs the documented sequence. The lit/shaded threshold in the integration test was set against the half-empty environment (ratio 2.65); with both halves filled it is 1.32. The clay check is split: the label must be gone under the plate's light, and under neutral light clay must be neutral grey. Docs: how to conform mattes and depth maps made by other tools (align by frame number, hold a dropped tail, never stretch; depth must be grey), the limits of the key-light estimate and of a four-corner pin on a surface that bends, and what a trial on twelve generated plates found. Co-Authored-By: Claude Fable 5.2 --- CHANGELOG.md | 1 + docs/hybrid-scenes.md | 35 +++++++++++++++++++-- docs/media/README.md | 2 ++ docs/media/hybrid-generated-plates.jpg | Bin 0 -> 56299 bytes packages/three/plate.mjs | 18 ++++++++--- scripts/project.mjs | 4 ++- skills/editableframes/references/hybrid.md | 31 ++++++++++++++++-- tests/hybrid-integration.mjs | 21 +++++++++++-- tests/plate.test.mjs | 8 +++++ 9 files changed, 105 insertions(+), 15 deletions(-) create mode 100644 docs/media/hybrid-generated-plates.jpg diff --git a/CHANGELOG.md b/CHANGELOG.md index 843fc3c..cb9f9e5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,7 @@ Hybrid scenes: code-rendered elements composited with filmed or generated footag - Add optional `mediaInfo` and `derived` renderer services, declared control passes (`passes`, `clock.pass`) and `render --pass`. - Add shutter motion blur at export: `render --motion-blur ANGLE [--samples N]`. - Add `init --hybrid`, a starter with a synthetic plate, and `npm run test:hybrid`. +- Document a trial of the hybrid helpers on generated footage, and how to conform mattes and depth maps made by other tools. - Fix transparent DOM-root exports capturing the preview page's own header through the scene. Any transparent renderer export smaller than the header area was affected. Runtime files changed, so existing projects need their normal `rebind`. diff --git a/docs/hybrid-scenes.md b/docs/hybrid-scenes.md index 1d652b6..d1b04b6 100644 --- a/docs/hybrid-scenes.md +++ b/docs/hybrid-scenes.md @@ -32,6 +32,8 @@ Each journey says what the author does, what EditableFrames does, and how far it | 7 | **Fast motion.** Code elements that move quickly should smear like the footage does. | A shutter angle. | Renders several sub-frame samples per output frame and averages them. | Integration test: smear width and edge colour. | | 8 | **A moving camera.** The product stays put in a shot whose camera travels. | A camera path solved elsewhere. | Replays the path on a Three.js camera, with rotation interpolated correctly. | Unit tests only. Not yet tried on a real solve; solves of generated footage are approximate. | +The integration tests use a synthetic plate. [On generated footage](#on-generated-footage) says what a trial on plates from video models found. + ## Try it ```sh @@ -92,6 +94,13 @@ Rules, each refused with a message that says what to do: - A derived video must have exactly as many frames as its plate. - A depth asset must carry an encoding. Tracks and camera paths are validated when loaded. +**Conforming data from other tools.** A derived video is read by frame number: frame 40 of a matte describes frame 40 of the plate. Tools do not always return that. + +- *Fewer frames at the plate's own rate* means frames were dropped, usually at the end. Keep the frames where they are and hold the last one (or trim the plate). Stretching the video over the plate's length moves every frame in time; a depth map stretched from 112 to 121 frames ran up to five frames early. +- *Another frame rate* has to be resampled onto the plate's frame times. +- *A depth video must be grey.* Several hosted depth models return a false-colour picture. Ask for grayscale output, or map the colours back to values before importing. +- Check the result against something that moves: compare a moving edge in the plate with the same edge in the matte or depth map at a few frames. + **Depth encoding** is `{kind, near, far, packing}`. `kind` is `inverse` (what monocular depth models emit; precision is spent close to the camera) or `linear`. `near` and `far` are the distances white and black stand for, in scene units. `packing` is `gray8`, or `rg16` for 16 bits across red and green. Relative depth has no true scale, so `near` and `far` are values you tune until occlusion lands. They are not measurements. **Track** files are `{version: 1, kind: "planar" | "point", width, height, frameRate: {num, den}, frames: [{frame, quad | point, confidence?}]}`. Coordinates are plate pixels from the top-left. Quads are ordered top-left, top-right, bottom-right, bottom-left. Frames may be sparse; samples between them are interpolated, and samples outside them hold the nearest frame and say so. @@ -142,6 +151,7 @@ The host then supplies `clock.pass` (`'beauty'` unless a pass was requested). A | `createDepthOccluder(encoding)` | Lets the plate's own geometry hide the scene. Needs WebGL2, a perspective camera and the standard depth buffer. | | `createMatteHoldout()` | Punches the matted subject out of the canvas. The cheap alternative when there is no depth; it is all-or-nothing per pixel. | | `createPlateEnvironment(renderer)` | Lights the scene with the plate. | +| `paintPlatePanorama(context, source, width)` | The panorama `createPlateEnvironment` builds: the plate in front of the camera, mirrored behind it. | | `applyKeyLight(light, estimate)` | Aims a directional light from `estimateKeyLight`. | | `applyCameraSample(camera, sample)` | Replays a camera path. | | `createShadowCatcher(plane)` | An invisible plane that shows only shadows, laid on a plane from `fitGroundPlane`. | @@ -154,7 +164,7 @@ None of this narrows what a renderer may draw. A scene that uses other libraries Three helpers guess from a single view. Expose their results as controls. -- **`estimateKeyLight`** reads which side the light is on from the brightest 5% of the frame. A picture cannot say how far in front of or behind the subject the light is, so that part is a stated assumption: a small source is placed level with the subject, a broad one in front of it. +- **`estimateKeyLight`** reads which side the light is on from the brightest 5% of the frame. A picture cannot say how far in front of or behind the subject the light is, so that part is a stated assumption: a small source is placed level with the subject, a broad one in front of it. The brightest area is not always the light: a white desk under a window reads as light from below, and a low sun behind the subject reads as light from the front. A shadow cast from the estimate then falls the wrong way, so let the author set the direction. - **`createPlateEnvironment`** has only what the camera saw. It puts the plate in front and a mirrored copy behind the camera, and pushes clipped highlights above 1 so they can act as light sources. The result is plausible. It is not a measurement of the real surroundings, and the highlight boost is not recovered data. Use a real `environment` asset when you have one. - **Depth `near` and `far`** are yours to tune, as above. @@ -179,7 +189,8 @@ Professional compositing uses more steps than this. Stated plainly: |---|---| | Occlusion by plate geometry | Done, from a depth map. | | Subject in front of graphics | Done, from a matte. | -| Planar tracking and corner pin | Drawing done. The track comes from another tool. | +| Planar tracking and corner pin | Drawing done, for flat surfaces. The track comes from another tool. A surface that bends (curled paper, cloth) needs a mesh warp, which is not provided. | +| Edge clean-up of the cut-out | Not provided. A matte edge keeps some of the plate's background colour, which shows as a thin fringe over contrasting graphics. | | Reflections of the plate in the object | Approximated by `createPlateEnvironment`. | | Light direction | Estimated; editable. | | Black and white point match | Measured by `plateStats` / `matchLevels`. Applying it is left to the scene. | @@ -191,6 +202,24 @@ Professional compositing uses more steps than this. Stated plainly: | Reflection or shadow of the object in the plate's own surfaces | Not provided. It needs the plate's normals and roughness. | | Linear-light compositing | Not provided. Layers are composited by the browser on encoded values. | +## On generated footage + +The helpers were tried on twelve 5–6 second plates from four video models (Seedance 1 Pro Fast, Kling 2.5 Turbo Pro, Veo 3.1 Fast, Wan 2.2), with mattes and depth maps from hosted models and tracks from a classical planar tracker. Each scene was a renderer scene of the kind the starter shows. This is one trial, not a benchmark. + +![Four frames: an app screen pinned to a phone in a hand, with the thumb passing in front of it, and a code-rendered can on a desk beside a real can, with an arm passing in front of it.](media/hybrid-generated-plates.jpg) + +*Generated plates with code inside them. Left: an HTML screen pinned to a tracked phone; the thumb is the plate's, cut out again from a matte. Right: a code-rendered can beside the plate's own can; the arm hides it where the plate's depth map is nearer.* + +| Journey | What was found | +|---|---| +| Screen or label on a surface | Holds on rigid surfaces. A screen pinned to a phone in a moving hand stayed within 3 px of where it started on the screen, at 1088 × 1920, while the phone moved 24 px. A sheet of paper that curled is not a plane: with all four corners right, its edges missed the pin by up to 15 px. | +| Headline behind a subject | Works with a hosted matte. Hair over dark letters shows a 1–2 px light fringe. | +| Footage in front of a 3D object | Works once `near` and `far` are tuned by eye. The edge is as rough as the depth map's own edge, a few pixels. A depth model that normalises each frame separately changes an object's value when something new enters the shot; prefer one that is consistent over time. | +| Lit by the footage | The plate's colour carries over. Under strongly coloured light a bare metal object takes too much of it (aluminium read as brass in a warm kitchen). `estimateKeyLight` chose the wrong side on two of three plates, as described above. | +| Placing a 3D object without a camera solve | A real stand-in object in the plate (a plain can), tracked as a plane, gave position and scale for a code object beside it through a slow push-in. It also shows what the plate's own light and shadow look like on that object. | + +Two things made pinned graphics read as part of the surface: a `mix-blend-mode` chosen for the material (`screen` for chalk on a dark board, `multiply` for print on paper), and the plate's own frame rate for the whole project. + ## Limits - The plate, matte and depth are decoded to PNG frames before preview and export, within the existing 8 GiB budget. Three videos per shot use it three times as fast. @@ -198,4 +227,4 @@ Professional compositing uses more steps than this. Stated plainly: - `createDepthOccluder` assumes the plate and the scene share one camera. A depth map from a monocular model is consistent with itself, not with your scene units. - Antialiased edges mix values, so `id` and `depth` passes are exact only away from silhouettes. `renderPass` does not handle skinned or instanced meshes. - Results differ slightly across GPUs and browsers, as elsewhere in this framework. -- The tests use a synthetic plate. They prove that pixels land where the inputs say. They do not prove that a particular matting, depth or tracking tool gives good inputs on real footage. +- The tests use a synthetic plate. They prove that pixels land where the inputs say. They do not prove that a particular matting, depth or tracking tool gives good inputs on real footage; the trial above is the only evidence of that so far. diff --git a/docs/media/README.md b/docs/media/README.md index b47c0d0..9a3b0b6 100644 --- a/docs/media/README.md +++ b/docs/media/README.md @@ -9,3 +9,5 @@ The recording uses the standalone film study, whose edits can be saved by downlo Gallery thumbnails elsewhere in the README are existing renders from `apps/films/previews`, `apps/effects/previews` and `assets/devices/previews`. No private posts or third-party screenshots are included. Device credits are in `assets/devices/ATTRIBUTIONS.txt`. `hybrid-starter.png` and `hybrid-passes.png` are frames of the `init --hybrid` starter rendered by the CLI: frames 7 and 34 of the picture, and the clay, depth, normal and object-id passes of frame 1 over a dark backdrop. The plate in them is a synthetic diagnostic pattern generated by FFmpeg, not footage. + +`hybrid-generated-plates.jpg` shows four frames of two hybrid scenes rendered by the CLI over generated footage. The plates were made for this repository with Seedance 1 Pro Fast (the hand and phone) and Kling 2.5 Turbo Pro (the desk, the plain can and the arm) from start images made with Seedream 4. The app screen, its text, the labelled can and the price tag are code. The people in them are generated; no real person is shown. diff --git a/docs/media/hybrid-generated-plates.jpg b/docs/media/hybrid-generated-plates.jpg new file mode 100644 index 0000000000000000000000000000000000000000..7f06f0c36ae3eb83849532ceb8722d47755bc553 GIT binary patch literal 56299 zcmY(q1ymc~7d0B7xO-@E2yTJm?hqV;ODXOS#VPK^p%iFwm*T~x!QHL6Ytd5trN968 zy|>;lE19{MHFE=V&OUqZlb6Mp4FDcQPEihkfCvB}z<&TQ&j38-_g?0F+#Fyq2bhZs z@UjAs2B4v#p`)Q={v8yg1)4-X%ofRF$_fKNzBL_`Dxl9G~> zQ_#{fzrX;K001H)5(4}l|96Am6zLT*3Mv``d=x(O|C{=61`mLUfP{#MjEaJWfrgBT zf`kA-M8bcCOh5xhktEb`<$g~aoK!1C^(L_AZ(bZ^h;lS8zoQ8uNaBr<0CTkfHC7rigt0DLrr4U|MA1X=(hJ^%?H z@UjfR`nN)S_^~)(>!iXKBV)ujY^RKsq^{f9imZ`f7Si43R;;26P0t@2{I%fGsODje zPOeF#J}BF8j#EQx!6f(2o}|n|sB>O612j=YmR#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QhoP*39iiezwQJjxj9XzvW$KrA2s#1?Dm!7(f8@cM|;fskq zPQ1ArcslE%=wwSSw7Jer2CR=+P?ZV{WP8=Rw_^|x!h)0#%b~ags!I@9fP|__Q9=;Z z8?gvN6;i5E1uCZK6q2pkb_j+sprMFj2raj19NR)urBGJ8P{|5iWT#*%B@0-fDZ2w* UsIF9MHI>h#T3c)RMWqk_*?S1UQUCw| literal 0 HcmV?d00001 diff --git a/packages/three/plate.mjs b/packages/three/plate.mjs index 6dc4ed7..9fb49b0 100644 --- a/packages/three/plate.mjs +++ b/packages/three/plate.mjs @@ -64,6 +64,18 @@ export function createMatteHoldout() { const mesh = fullscreen(material, 1e9); return {mesh, update(texture) { material.uniforms.map.value = texture; }, dispose() { mesh.geometry.dispose(); material.dispose(); }}; } +/** Paint `source` into an equirectangular canvas `width` wide and `width / 2` + * high: as shot in front of the camera (u 0 to 0.5; Three's lookup puts -Z, into + * the picture, at u = 0.25) and mirrored behind it (u 0.5 to 1, centred on +Z). + * The mirror maps x to width - x, so the copy lands on the back half. A surface + * facing the camera reflects that back half, so leaving it empty turns a + * mirror-like product black. */ +export function paintPlatePanorama(context, source, width) { + const half = width / 2, height = width / 2; + context.setTransform(1, 0, 0, 1, 0, 0); context.drawImage(source, 0, 0, half, height); + context.setTransform(-1, 0, 0, 1, width, 0); context.drawImage(source, 0, 0, half, height); + context.setTransform(1, 0, 0, 1, 0, 0); +} /** Light the scene with the plate itself. The frame is wrapped into a * panorama (in front of the camera as shot, mirrored behind it), its clipped * highlights are pushed above 1, and the result is prefiltered for physically @@ -82,11 +94,7 @@ export function createPlateEnvironment(renderer, {width = 256, knee = 0.8, boost let target; return { update(source) { - const half = width / 2; - // Three's equirect lookup puts -Z (into the picture) at u = 0.25. - context.setTransform(1, 0, 0, 1, 0, 0); context.drawImage(source, 0, 0, half, height); - context.setTransform(-1, 0, 0, 1, width + half, 0); context.drawImage(source, 0, 0, half, height); - context.setTransform(1, 0, 0, 1, 0, 0); + paintPlatePanorama(context, source, width); const linear = expandHighlights(context.getImageData(0, 0, width, height).data, {knee, boost}), pixels = new Uint16Array(linear.length); for (let i = 0; i < linear.length; i++) pixels[i] = T.DataUtils.toHalfFloat(Math.min(65000, linear[i])); const texture = new T.DataTexture(pixels, width, height, T.RGBAFormat, T.HalfFloatType); diff --git a/scripts/project.mjs b/scripts/project.mjs index dc46a26..05f0447 100644 --- a/scripts/project.mjs +++ b/scripts/project.mjs @@ -86,7 +86,9 @@ export async function importAsset(dir,id,source,{type,role,of,encoding}={}){ if(['__proto__','constructor','prototype'].includes(id)||!/^[a-zA-Z0-9_-]{1,80}$/.test(id))throw Error('Invalid asset ID'); dir=await fs.realpath(dir);const lock=path.join(dir,'.editableframe-edit.lock'),fd=await fs.open(lock,'wx'); try{ - const d=await readProject(dir);if(Object.hasOwn(d.assets,id))throw Error('Asset IDs are immutable; use a new ID and swap the port'); + // Only the asset manifest is needed. Reading the whole project would refuse the + // binding the previous import changed, so a second import before rebind failed. + const d=await definition(dir);if(Object.hasOwn(d.assets,id))throw Error('Asset IDs are immutable; use a new ID and swap the port'); const ext=path.extname(source).toLowerCase();type??=(['.png','.jpg','.jpeg','.webp'].includes(ext)?'image':['.wav','.mp3','.flac','.m4a'].includes(ext)?'audio':ext==='.json'?'data':'video'); if(!['image','audio','video','data'].includes(type)||!/^\.[a-z0-9]{1,8}$/.test(ext))throw Error('Invalid asset type/extension'); // A derived asset records the hash of the take it describes, so a regenerated take cannot reuse it. diff --git a/skills/editableframes/references/hybrid.md b/skills/editableframes/references/hybrid.md index d1d642a..21f5924 100644 --- a/skills/editableframes/references/hybrid.md +++ b/skills/editableframes/references/hybrid.md @@ -28,6 +28,8 @@ Each journey says what the author does, what EditableFrames does, and how far it | 7 | **Fast motion.** Code elements that move quickly should smear like the footage does. | A shutter angle. | Renders several sub-frame samples per output frame and averages them. | Integration test: smear width and edge colour. | | 8 | **A moving camera.** The product stays put in a shot whose camera travels. | A camera path solved elsewhere. | Replays the path on a Three.js camera, with rotation interpolated correctly. | Unit tests only. Not yet tried on a real solve; solves of generated footage are approximate. | +The integration tests use a synthetic plate. [On generated footage](#on-generated-footage) says what a trial on plates from video models found. + ## Try it ```sh @@ -88,6 +90,13 @@ Rules, each refused with a message that says what to do: - A derived video must have exactly as many frames as its plate. - A depth asset must carry an encoding. Tracks and camera paths are validated when loaded. +**Conforming data from other tools.** A derived video is read by frame number: frame 40 of a matte describes frame 40 of the plate. Tools do not always return that. + +- *Fewer frames at the plate's own rate* means frames were dropped, usually at the end. Keep the frames where they are and hold the last one (or trim the plate). Stretching the video over the plate's length moves every frame in time; a depth map stretched from 112 to 121 frames ran up to five frames early. +- *Another frame rate* has to be resampled onto the plate's frame times. +- *A depth video must be grey.* Several hosted depth models return a false-colour picture. Ask for grayscale output, or map the colours back to values before importing. +- Check the result against something that moves: compare a moving edge in the plate with the same edge in the matte or depth map at a few frames. + **Depth encoding** is `{kind, near, far, packing}`. `kind` is `inverse` (what monocular depth models emit; precision is spent close to the camera) or `linear`. `near` and `far` are the distances white and black stand for, in scene units. `packing` is `gray8`, or `rg16` for 16 bits across red and green. Relative depth has no true scale, so `near` and `far` are values you tune until occlusion lands. They are not measurements. **Track** files are `{version: 1, kind: "planar" | "point", width, height, frameRate: {num, den}, frames: [{frame, quad | point, confidence?}]}`. Coordinates are plate pixels from the top-left. Quads are ordered top-left, top-right, bottom-right, bottom-left. Frames may be sparse; samples between them are interpolated, and samples outside them hold the nearest frame and say so. @@ -134,6 +143,7 @@ The host then supplies `clock.pass` (`'beauty'` unless a pass was requested). A | `createDepthOccluder(encoding)` | Lets the plate's own geometry hide the scene. Needs WebGL2, a perspective camera and the standard depth buffer. | | `createMatteHoldout()` | Punches the matted subject out of the canvas. The cheap alternative when there is no depth; it is all-or-nothing per pixel. | | `createPlateEnvironment(renderer)` | Lights the scene with the plate. | +| `paintPlatePanorama(context, source, width)` | The panorama `createPlateEnvironment` builds: the plate in front of the camera, mirrored behind it. | | `applyKeyLight(light, estimate)` | Aims a directional light from `estimateKeyLight`. | | `applyCameraSample(camera, sample)` | Replays a camera path. | | `createShadowCatcher(plane)` | An invisible plane that shows only shadows, laid on a plane from `fitGroundPlane`. | @@ -146,7 +156,7 @@ None of this narrows what a renderer may draw. A scene that uses other libraries Three helpers guess from a single view. Expose their results as controls. -- **`estimateKeyLight`** reads which side the light is on from the brightest 5% of the frame. A picture cannot say how far in front of or behind the subject the light is, so that part is a stated assumption: a small source is placed level with the subject, a broad one in front of it. +- **`estimateKeyLight`** reads which side the light is on from the brightest 5% of the frame. A picture cannot say how far in front of or behind the subject the light is, so that part is a stated assumption: a small source is placed level with the subject, a broad one in front of it. The brightest area is not always the light: a white desk under a window reads as light from below, and a low sun behind the subject reads as light from the front. A shadow cast from the estimate then falls the wrong way, so let the author set the direction. - **`createPlateEnvironment`** has only what the camera saw. It puts the plate in front and a mirrored copy behind the camera, and pushes clipped highlights above 1 so they can act as light sources. The result is plausible. It is not a measurement of the real surroundings, and the highlight boost is not recovered data. Use a real `environment` asset when you have one. - **Depth `near` and `far`** are yours to tune, as above. @@ -171,7 +181,8 @@ Professional compositing uses more steps than this. Stated plainly: |---|---| | Occlusion by plate geometry | Done, from a depth map. | | Subject in front of graphics | Done, from a matte. | -| Planar tracking and corner pin | Drawing done. The track comes from another tool. | +| Planar tracking and corner pin | Drawing done, for flat surfaces. The track comes from another tool. A surface that bends (curled paper, cloth) needs a mesh warp, which is not provided. | +| Edge clean-up of the cut-out | Not provided. A matte edge keeps some of the plate's background colour, which shows as a thin fringe over contrasting graphics. | | Reflections of the plate in the object | Approximated by `createPlateEnvironment`. | | Light direction | Estimated; editable. | | Black and white point match | Measured by `plateStats` / `matchLevels`. Applying it is left to the scene. | @@ -183,6 +194,20 @@ Professional compositing uses more steps than this. Stated plainly: | Reflection or shadow of the object in the plate's own surfaces | Not provided. It needs the plate's normals and roughness. | | Linear-light compositing | Not provided. Layers are composited by the browser on encoded values. | +## On generated footage + +The helpers were tried on twelve 5–6 second plates from four video models (Seedance 1 Pro Fast, Kling 2.5 Turbo Pro, Veo 3.1 Fast, Wan 2.2), with mattes and depth maps from hosted models and tracks from a classical planar tracker. Each scene was a renderer scene of the kind the starter shows. This is one trial, not a benchmark. + +| Journey | What was found | +|---|---| +| Screen or label on a surface | Holds on rigid surfaces. A screen pinned to a phone in a moving hand stayed within 3 px of where it started on the screen, at 1088 × 1920, while the phone moved 24 px. A sheet of paper that curled is not a plane: with all four corners right, its edges missed the pin by up to 15 px. | +| Headline behind a subject | Works with a hosted matte. Hair over dark letters shows a 1–2 px light fringe. | +| Footage in front of a 3D object | Works once `near` and `far` are tuned by eye. The edge is as rough as the depth map's own edge, a few pixels. A depth model that normalises each frame separately changes an object's value when something new enters the shot; prefer one that is consistent over time. | +| Lit by the footage | The plate's colour carries over. Under strongly coloured light a bare metal object takes too much of it (aluminium read as brass in a warm kitchen). `estimateKeyLight` chose the wrong side on two of three plates, as described above. | +| Placing a 3D object without a camera solve | A real stand-in object in the plate (a plain can), tracked as a plane, gave position and scale for a code object beside it through a slow push-in. It also shows what the plate's own light and shadow look like on that object. | + +Two things made pinned graphics read as part of the surface: a `mix-blend-mode` chosen for the material (`screen` for chalk on a dark board, `multiply` for print on paper), and the plate's own frame rate for the whole project. + ## Limits - The plate, matte and depth are decoded to PNG frames before preview and export, within the existing 8 GiB budget. Three videos per shot use it three times as fast. @@ -190,4 +215,4 @@ Professional compositing uses more steps than this. Stated plainly: - `createDepthOccluder` assumes the plate and the scene share one camera. A depth map from a monocular model is consistent with itself, not with your scene units. - Antialiased edges mix values, so `id` and `depth` passes are exact only away from silhouettes. `renderPass` does not handle skinned or instanced meshes. - Results differ slightly across GPUs and browsers, as elsewhere in this framework. -- The tests use a synthetic plate. They prove that pixels land where the inputs say. They do not prove that a particular matting, depth or tracking tool gives good inputs on real footage. +- The tests use a synthetic plate. They prove that pixels land where the inputs say. They do not prove that a particular matting, depth or tracking tool gives good inputs on real footage; the trial above is the only evidence of that so far. diff --git a/tests/hybrid-integration.mjs b/tests/hybrid-integration.mjs index e2ec0f9..e235314 100644 --- a/tests/hybrid-integration.mjs +++ b/tests/hybrid-integration.mjs @@ -47,7 +47,9 @@ try{ // --- Lighting from the plate -------------------------------------------------- // The plate's only bright area is a window on the left, so the can's left side is the lit one. - const lit=mean(a,262,150,300,260),shade=mean(a,345,150,380,260);assert.ok(lit[0]>shade[0]*1.4,'the side facing the bright window is brighter'); + const lit=mean(a,262,150,300,260),shade=mean(a,345,150,380,260);assert.ok(lit[0]>shade[0]*1.2,'the side facing the bright window is brighter'); + // The panorama's back half is the plate mirrored, so the side turned away still sees footage, not black. + assert.ok(shade[0]>90,`the shaded side reflects the footage behind the camera, not an empty half (${Math.round(shade[0])})`); await mutate(dir,d=>d.studio.execute({type:'set',clip:d.studio.doc.clips[0].id,anchor:'light',property:'fromPlate',value:false},d.studio.revision,'model')); const neutralDir=path.join(tmp,'neutral');await render(dir,neutralDir,{format:'png',frames:early+1});const n=await pixels(frameFile(neutralDir,early)); const warm=rgb=>rgb[0]/(rgb[2]+1),plateLit=mean(a,262,150,380,260),studioLit=mean(n,262,150,380,260); @@ -58,7 +60,7 @@ try{ checks.push('The product is lit by the footage: direction follows the bright area, colour follows the plate, and it is an undoable control'); // --- Control passes ------------------------------------------------------------ - const pass=async name=>{const out=path.join(tmp,name);const receipt=await render(dir,out,{format:'png',frames:1,pass:name});assert.equal(receipt.pass,name);return pixels(frameFile(out,0));}; + const pass=async(name,folder=name)=>{const out=path.join(tmp,folder);const receipt=await render(dir,out,{format:'png',frames:1,pass:name});assert.equal(receipt.pass,name);return pixels(frameFile(out,0));}; const id=await pass('id');assert.equal(id.at(5,5)[3],0,'no plate, no DOM: the pass is transparent outside the object'); assert.equal(idFromColor(id.at(320,200)),0,'the body decodes to the first declared id'); let lid=false;for(let y=80;y<140&&!lid;y++)lid=id.at(320,y)[3]===255&&idFromColor(id.at(320,y))===1;assert.ok(lid,'the lid decodes to the second'); @@ -68,7 +70,11 @@ try{ // Nothing but the object: the capture page's own chrome must not show through a transparent frame. let stray=0;for(let y=0;y410||y<70))stray++;assert.equal(stray,0,'a transparent pass contains only the scene'); const normal=await pass('normal');assert.ok(normal.at(320,200)[2]>200&&Math.abs(normal.at(320,200)[0]-128)<25,'the surface facing the camera has a camera-facing normal'); - const clay=await pass('clay'),grey=clay.at(300,200);assert.equal(grey[3],255);assert.ok(Math.max(...grey.slice(0,3))-Math.min(...grey.slice(0,3))<70&&!close(grey,can,25),'clay replaces the label with neutral shading'); + const clay=await pass('clay'),grey=clay.at(300,200),spread=p=>Math.max(...p.slice(0,3))-Math.min(...p.slice(0,3));assert.equal(grey[3],255);assert.ok(!close(grey,can,25)&&spread(grey)d.studio.execute({type:'set',clip:d.studio.doc.clips[0].id,anchor:'light',property:'fromPlate',value:false},d.studio.revision,'model')); + const studioClay=(await pass('clay','clay-neutral')).at(300,200);await mutate(dir,d=>d.studio.undo()); + assert.ok(spread(studioClay)<16,`under neutral light clay is neutral grey (${studioClay.slice(0,3)})`); await assert.rejects(render(dir,path.join(tmp,'albedo'),{format:'png',frames:1,pass:'albedo'}),/does not declare a albedo pass; it declares: clay/); checks.push('clay, depth, normal, id and matte passes export from the same scene; an undeclared pass is refused'); @@ -80,6 +86,15 @@ try{ const manifest=JSON.parse(await fs.readFile(path.join(dir,'assets.json'),'utf8'));manifest.assets['plate-matte'].derived.sourceSha256='0'.repeat(64);await fs.writeFile(path.join(dir,'assets.json'),JSON.stringify(manifest)); await assert.rejects(readProject(dir),/regenerate the matte/); checks.push('A matte from another take, a second matte, and a derived video with the wrong frame count are refused'); + // The documented import sequence: several asset-add calls, then one rebind. + const seqDir=path.join(tmp,'sequence');await init(seqDir,{template:'hybrid'});const demoAsset=name=>path.join(seqDir,'assets',name); + await importAsset(seqDir,'shot',demoAsset('plate.mp4')); + await importAsset(seqDir,'shot-matte',demoAsset('plate-matte.mp4'),{role:'matte',of:'shot'}); + await importAsset(seqDir,'shot-depth',demoAsset('plate-depth.mp4'),{role:'depth',of:'shot',encoding:demo.depth}); + await importAsset(seqDir,'shot-track',demoAsset('board-track.json'),{role:'track',of:'shot'}); + await rebind(seqDir);const seq=await readProject(seqDir); + assert.deepEqual(['shot-matte','shot-depth','shot-track'].map(id=>seq.assets[id].derived.of),['shot','shot','shot']); + checks.push('Several derived assets can be added before one rebind, as docs/hybrid-scenes.md shows'); // --- Motion blur ------------------------------------------------------------------ const blurDir=path.join(tmp,'blur-clip');await init(blurDir,{template:'renderer'}); diff --git a/tests/plate.test.mjs b/tests/plate.test.mjs index e6cb2f4..eff762b 100644 --- a/tests/plate.test.mjs +++ b/tests/plate.test.mjs @@ -174,3 +174,11 @@ test('the host hands plate services to a scene and nothing it was not given', as await instance.dispose(); await assert.rejects(mountRenderer(scene, {root, services: {derived: 'nope'}}), /Invalid derived service/); }); + +test('the plate panorama fills both halves: as shot in front, mirrored behind', async () => { + const {paintPlatePanorama} = await import('../packages/three/plate.mjs'); + const draws = [];let m = [1, 0, 0, 1, 0, 0]; + const context = {setTransform: (...a) => {m = a;}, drawImage: (_s, x, y, w) => {const xs = [x, x + w].map(v => m[0] * v + m[4]);draws.push([Math.min(...xs), Math.max(...xs), m[0]]);}}; + paintPlatePanorama(context, {}, 256); + assert.deepEqual(draws, [[0, 128, 1], [128, 256, -1]]); +}); From 0e5fc85813384555d26929af310185352e852466 Mon Sep 17 00:00:00 2001 From: lxf82dev Date: Tue, 10 Nov 2026 23:55:13 +0800 Subject: [PATCH 03/49] Hybrid test: sample the label clear of its text The label samples sat three rows above the label's text on macOS. The text is laid out with the platform's font, so on Linux a sample landed on a letter. That did not matter while the plate environment was half empty. With both halves filled, white text on the can's shaded side is lit by the warm wall and has the wall's colour, so "the product is visible beside the foreground" compared the wall with itself and failed in CI. Samples and the lit/shaded bands now use rows 112-140, plain label above the text. Checked with the software renderer CI uses, and with a taller label font standing in for another platform's: the previous test fails there and this one passes. Co-Authored-By: Claude Fable 5.2 --- tests/hybrid-integration.mjs | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/tests/hybrid-integration.mjs b/tests/hybrid-integration.mjs index e235314..3e20288 100644 --- a/tests/hybrid-integration.mjs +++ b/tests/hybrid-integration.mjs @@ -24,11 +24,13 @@ try{ const a=await pixels(frameFile(beauty,early)),b=await pixels(frameFile(beauty,late)); // Frame 6: the bar is far left; the product is in the clear. assert.ok(barAt(early)+demo.bar.width<250); - const can=a.at(300,170);assert.ok(!close(can,WALL,30)&&!close(can,BAR,30),'the product is drawn over the wall');assert.ok(can[0]>can[2]*2,'and it is the red can'); + // Label samples sit on rows 112-140: plain label above its text. The text is laid out with the platform's font, and + // white text lit by a warm plate has the plate's own colour, so a sample that lands on a letter proves nothing. + const can=a.at(300,125);assert.ok(!close(can,WALL,30)&&!close(can,BAR,30),'the product is drawn over the wall');assert.ok(can[0]>can[2]*2,'and it is the red can'); // Frame 35: the bar stands in front of the product's centre, and ONLY the plate's depth says so. assert.ok(barAt(late)<320&&barAt(late)+demo.bar.width>320); assert.ok(close(b.at(320,170),BAR),'the plate foreground hides the product where it is nearer'); - const beside=b.at(barAt(late)+demo.bar.width+12,170);assert.ok(!close(beside,WALL,30)&&!close(beside,BAR,30),'the product is still visible beside the foreground'); + const beside=b.at(barAt(late)+demo.bar.width+12,125);assert.ok(!close(beside,WALL,30)&&!close(beside,BAR,30),'the product is still visible beside the foreground'); checks.push('A 3D object is hidden by plate foreground and shown over plate background, from the depth map alone'); // The headline is DOM text; the cut-out layer puts the plate subject back over it. @@ -47,12 +49,12 @@ try{ // --- Lighting from the plate -------------------------------------------------- // The plate's only bright area is a window on the left, so the can's left side is the lit one. - const lit=mean(a,262,150,300,260),shade=mean(a,345,150,380,260);assert.ok(lit[0]>shade[0]*1.2,'the side facing the bright window is brighter'); + const lit=mean(a,262,112,300,140),shade=mean(a,345,112,380,140);assert.ok(lit[0]>shade[0]*1.2,'the side facing the bright window is brighter'); // The panorama's back half is the plate mirrored, so the side turned away still sees footage, not black. assert.ok(shade[0]>90,`the shaded side reflects the footage behind the camera, not an empty half (${Math.round(shade[0])})`); await mutate(dir,d=>d.studio.execute({type:'set',clip:d.studio.doc.clips[0].id,anchor:'light',property:'fromPlate',value:false},d.studio.revision,'model')); const neutralDir=path.join(tmp,'neutral');await render(dir,neutralDir,{format:'png',frames:early+1});const n=await pixels(frameFile(neutralDir,early)); - const warm=rgb=>rgb[0]/(rgb[2]+1),plateLit=mean(a,262,150,380,260),studioLit=mean(n,262,150,380,260); + const warm=rgb=>rgb[0]/(rgb[2]+1),plateLit=mean(a,262,112,380,140),studioLit=mean(n,262,112,380,140); assert.ok(Math.abs(plateLit[0]-studioLit[0])+Math.abs(plateLit[1]-studioLit[1])+Math.abs(plateLit[2]-studioLit[2])>12,'turning plate lighting off changes the product'); assert.ok(warm(plateLit)>warm(studioLit),'under the warm plate the product reads warmer than under neutral studio light'); assert.ok(close(n.at(20,340),a.at(20,340),2),'the footage itself is untouched by the lighting control'); From e3485f9e142dc10acda86161ff0900d59b31a66b Mon Sep 17 00:00:00 2001 From: Laurence Xavier <35849747+lxf82dev@users.noreply.github.com> Date: Wed, 11 Nov 2026 11:45:06 +0800 Subject: [PATCH 04/49] Hybrid starter: light the can at environment intensity 1, measured The starter's plate-lit environment intensity (1.5) was set while the mirrored half of the panorama was empty. With both halves filled, a plain can beside a real can in three generated plates came out, by mean linear-light brightness over the bodies (code can / real can): plate 0.8 1.0 1.2 desk, lit from front 0.83 1.05 1.28 kitchen, from front 0.84 1.06 1.29 patio, sun behind 1.35 1.63 1.89 with the lids at aluminium's reflectance (#f5f6f6, about 0.91). With the old #d9dde2 (about 0.72) the front-lit plates needed about 1.27, which is why a higher gain looked right before. Intensity 1 means the environment's light is the plate's own pixel values. The backlit plate cannot be matched by a single value, because the mirrored half also puts the sun in front of the object; the docs now give that figure. The integration test's thresholds were not changed: lit/shaded on the synthetic plate is 168/116 (was 183/140), still above both the 1.2 ratio and the shaded floor of 90, and the pre-fix environment still fails the floor (43). The two docs images showed the pre-fix black shaded side and are regenerated. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 1 + docs/hybrid-scenes.md | 4 ++-- docs/media/hybrid-passes.png | Bin 9219 -> 10032 bytes docs/media/hybrid-starter.png | Bin 28699 -> 28843 bytes skills/editableframes/references/hybrid.md | 4 ++-- templates/hybrid/clip.mjs | 7 +++++-- 6 files changed, 10 insertions(+), 6 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index cb9f9e5..4423019 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,7 @@ Hybrid scenes: code-rendered elements composited with filmed or generated footag - Add shutter motion blur at export: `render --motion-blur ANGLE [--samples N]`. - Add `init --hybrid`, a starter with a synthetic plate, and `npm run test:hybrid`. - Document a trial of the hybrid helpers on generated footage, and how to conform mattes and depth maps made by other tools. +- The hybrid starter lights its can from the footage at environment intensity 1 (was 1.5, set while half of the panorama was empty), with aluminium lids at aluminium's reflectance. Measured against real cans in generated plates. - Fix transparent DOM-root exports capturing the preview page's own header through the scene. Any transparent renderer export smaller than the header area was affected. Runtime files changed, so existing projects need their normal `rebind`. diff --git a/docs/hybrid-scenes.md b/docs/hybrid-scenes.md index d1b04b6..19d5fe9 100644 --- a/docs/hybrid-scenes.md +++ b/docs/hybrid-scenes.md @@ -165,7 +165,7 @@ None of this narrows what a renderer may draw. A scene that uses other libraries Three helpers guess from a single view. Expose their results as controls. - **`estimateKeyLight`** reads which side the light is on from the brightest 5% of the frame. A picture cannot say how far in front of or behind the subject the light is, so that part is a stated assumption: a small source is placed level with the subject, a broad one in front of it. The brightest area is not always the light: a white desk under a window reads as light from below, and a low sun behind the subject reads as light from the front. A shadow cast from the estimate then falls the wrong way, so let the author set the direction. -- **`createPlateEnvironment`** has only what the camera saw. It puts the plate in front and a mirrored copy behind the camera, and pushes clipped highlights above 1 so they can act as light sources. The result is plausible. It is not a measurement of the real surroundings, and the highlight boost is not recovered data. Use a real `environment` asset when you have one. +- **`createPlateEnvironment`** has only what the camera saw. It puts the plate in front and a mirrored copy behind the camera, and pushes clipped highlights above 1 so they can act as light sources. The result is plausible. It is not a measurement of the real surroundings, and the highlight boost is not recovered data. Use a real `environment` asset when you have one. Keep `scene.environmentIntensity` at 1, as the starter does: the light is then the plate's own pixel values with no gain, and a material should have its real reflectance (aluminium is about 0.91, `#f5f6f6`). - **Depth `near` and `far`** are yours to tune, as above. ## Frame rate @@ -215,7 +215,7 @@ The helpers were tried on twelve 5–6 second plates from four video models (See | Screen or label on a surface | Holds on rigid surfaces. A screen pinned to a phone in a moving hand stayed within 3 px of where it started on the screen, at 1088 × 1920, while the phone moved 24 px. A sheet of paper that curled is not a plane: with all four corners right, its edges missed the pin by up to 15 px. | | Headline behind a subject | Works with a hosted matte. Hair over dark letters shows a 1–2 px light fringe. | | Footage in front of a 3D object | Works once `near` and `far` are tuned by eye. The edge is as rough as the depth map's own edge, a few pixels. A depth model that normalises each frame separately changes an object's value when something new enters the shot; prefer one that is consistent over time. | -| Lit by the footage | The plate's colour carries over. Under strongly coloured light a bare metal object takes too much of it (aluminium read as brass in a warm kitchen). `estimateKeyLight` chose the wrong side on two of three plates, as described above. | +| Lit by the footage | The plate's colour carries over. Under strongly coloured light a bare metal object takes too much of it (aluminium read as brass in a warm kitchen). At environment intensity 1, a plain aluminium can was 5–6% brighter over its body than a real can standing beside it, on the two plates lit from the front. On a plate lit from behind (a low sun in the shot) it was 1.6 times too bright, because the mirrored half puts that sun in front of the object too. `estimateKeyLight` chose the wrong side on two of three plates, as described above. | | Placing a 3D object without a camera solve | A real stand-in object in the plate (a plain can), tracked as a plane, gave position and scale for a code object beside it through a slow push-in. It also shows what the plate's own light and shadow look like on that object. | Two things made pinned graphics read as part of the surface: a `mix-blend-mode` chosen for the material (`screen` for chalk on a dark board, `multiply` for print on paper), and the plate's own frame rate for the whole project. diff --git a/docs/media/hybrid-passes.png b/docs/media/hybrid-passes.png index 167b043c66856fce9043dd7d65ec2c36c04b1047..f386319fcc4dd286d7129c37afae306d5f79585e 100644 GIT binary patch literal 10032 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?2Pf)VI*OW4pC3rsHR8H@pJ@#n`bzg(%BpQLMS?H#L-_GWAv&hpRQKX!Jw zLfV19L!wndHKON@^LP|b2OM^#NJeUYil+LIh7jM(GK92y8^EwK3q3H<<=dL4q32b$ zI`kW2$tnH7x46xPb~!kuY0&WwYgHZ&cJ6a$7L^7o;3}!X}D5o)Z6o;S7+%TI+&G@)RM#<4RW2D{%Z<$lYX<&6G}H zVtBO14ULzG07LY;Fp!&8>Vy`F4tQ{LS3YzPk4DMffH0Mv%Wcz4dI0eB z?L0O&Laq=&yQersFzamR^q3MC94{Q`C0 z7y96&;+M+q1_s|f_&Hqg~1At9U2KQ_|;)Ua>iwnf9@ zFRfX>_th51StdS_$6O5wBz84Hy1^<55g0>ietnAngByrD{uq+|(@x{H+swl&cmZD( z{0U?{146B*`1e568nl}t2g@E_oW2~H0E+)g0l0MeIq-W_T-9#2vG}xhr~{N=;{z}T z;khy0wHrYH^Rj}c7XChG(fR8SC@4lC)-9H*rlDt5Q96aRXBD=^U;f+7u7s(Yg}Lm5 zP;Q4)OYLpzbKDB_H~4Kp7da3n4rJMxSR)s8sSAO-S|jeTFaxV?3mB`Jbqb8rB7AjMqmFI3bNJ0 diff --git a/skills/editableframes/references/hybrid.md b/skills/editableframes/references/hybrid.md index 21f5924..92ba384 100644 --- a/skills/editableframes/references/hybrid.md +++ b/skills/editableframes/references/hybrid.md @@ -157,7 +157,7 @@ None of this narrows what a renderer may draw. A scene that uses other libraries Three helpers guess from a single view. Expose their results as controls. - **`estimateKeyLight`** reads which side the light is on from the brightest 5% of the frame. A picture cannot say how far in front of or behind the subject the light is, so that part is a stated assumption: a small source is placed level with the subject, a broad one in front of it. The brightest area is not always the light: a white desk under a window reads as light from below, and a low sun behind the subject reads as light from the front. A shadow cast from the estimate then falls the wrong way, so let the author set the direction. -- **`createPlateEnvironment`** has only what the camera saw. It puts the plate in front and a mirrored copy behind the camera, and pushes clipped highlights above 1 so they can act as light sources. The result is plausible. It is not a measurement of the real surroundings, and the highlight boost is not recovered data. Use a real `environment` asset when you have one. +- **`createPlateEnvironment`** has only what the camera saw. It puts the plate in front and a mirrored copy behind the camera, and pushes clipped highlights above 1 so they can act as light sources. The result is plausible. It is not a measurement of the real surroundings, and the highlight boost is not recovered data. Use a real `environment` asset when you have one. Keep `scene.environmentIntensity` at 1, as the starter does: the light is then the plate's own pixel values with no gain, and a material should have its real reflectance (aluminium is about 0.91, `#f5f6f6`). - **Depth `near` and `far`** are yours to tune, as above. ## Frame rate @@ -203,7 +203,7 @@ The helpers were tried on twelve 5–6 second plates from four video models (See | Screen or label on a surface | Holds on rigid surfaces. A screen pinned to a phone in a moving hand stayed within 3 px of where it started on the screen, at 1088 × 1920, while the phone moved 24 px. A sheet of paper that curled is not a plane: with all four corners right, its edges missed the pin by up to 15 px. | | Headline behind a subject | Works with a hosted matte. Hair over dark letters shows a 1–2 px light fringe. | | Footage in front of a 3D object | Works once `near` and `far` are tuned by eye. The edge is as rough as the depth map's own edge, a few pixels. A depth model that normalises each frame separately changes an object's value when something new enters the shot; prefer one that is consistent over time. | -| Lit by the footage | The plate's colour carries over. Under strongly coloured light a bare metal object takes too much of it (aluminium read as brass in a warm kitchen). `estimateKeyLight` chose the wrong side on two of three plates, as described above. | +| Lit by the footage | The plate's colour carries over. Under strongly coloured light a bare metal object takes too much of it (aluminium read as brass in a warm kitchen). At environment intensity 1, a plain aluminium can was 5–6% brighter over its body than a real can standing beside it, on the two plates lit from the front. On a plate lit from behind (a low sun in the shot) it was 1.6 times too bright, because the mirrored half puts that sun in front of the object too. `estimateKeyLight` chose the wrong side on two of three plates, as described above. | | Placing a 3D object without a camera solve | A real stand-in object in the plate (a plain can), tracked as a plane, gave position and scale for a code object beside it through a slow push-in. It also shows what the plate's own light and shadow look like on that object. | Two things made pinned graphics read as part of the surface: a `mix-blend-mode` chosen for the material (`screen` for chalk on a dark board, `multiply` for print on paper), and the plate's own frame rate for the whole project. diff --git a/templates/hybrid/clip.mjs b/templates/hybrid/clip.mjs index c14b8ba..78ee980 100644 --- a/templates/hybrid/clip.mjs +++ b/templates/hybrid/clip.mjs @@ -55,7 +55,8 @@ export default defineRenderer({ const labelCanvas=doc.createElement('canvas');labelCanvas.width=1024;labelCanvas.height=512; const labelMap=new THREE.CanvasTexture(labelCanvas);labelMap.colorSpace=THREE.SRGBColorSpace;labelMap.anisotropy=8; const body=new THREE.Mesh(new THREE.CylinderGeometry(.33,.33,1,96,1,true),new THREE.MeshStandardMaterial({map:labelMap,metalness:.25,roughness:.36})); - const lidMaterial=new THREE.MeshStandardMaterial({color:0xd9dde2,metalness:1,roughness:.22}); + // Aluminium reflects about 91% of the light that reaches it; a darker base colour reads as grey metal. + const lidMaterial=new THREE.MeshStandardMaterial({color:0xf5f6f6,metalness:1,roughness:.22}); const lids=[.52,-.52].map(y=>{const lid=new THREE.Mesh(new THREE.CylinderGeometry(.3,.33,.04,96),lidMaterial);lid.position.y=y;lid.rotation.x=y<0?Math.PI:0;lid.userData.passId='can.lid';return lid;}); can.add(body,...lids); const occluder=createDepthOccluder(encoding),depthMap=dataTexture(doc.createElement('canvas'));scene.add(occluder.mesh); @@ -86,8 +87,10 @@ export default defineRenderer({ headline.textContent=String(props.headline); drawCutout(cutContext,plateImage,matteImage,scratch); depthMap.image=depthImage;depthMap.needsUpdate=true;occluder.update(depthMap,camera); + // Intensity 1: the environment's light is the plate's own pixel values, with no extra gain. On generated plates, + // aluminium lit this way was 5-6% brighter than a real can standing beside it, except where the light came from behind it. if(props.plateLight){ - if(litFrom!==plateImage){litFrom=plateImage;scene.environment=plateEnvironment.update(plateImage);scene.environmentIntensity=1.5;probeContext.drawImage(plateImage,0,0,64,36);applyKeyLight(key,estimateKeyLight(probeContext.getImageData(0,0,64,36).data,64,36),{target:can.position});} + if(litFrom!==plateImage){litFrom=plateImage;scene.environment=plateEnvironment.update(plateImage);scene.environmentIntensity=1;probeContext.drawImage(plateImage,0,0,64,36);applyKeyLight(key,estimateKeyLight(probeContext.getImageData(0,0,64,36).data,64,36),{target:can.position});} }else{litFrom=null;scene.environment=neutral.texture;scene.environmentIntensity=1;key.position.set(2,4,3);key.target.position.copy(can.position);key.target.updateMatrixWorld();key.color.set(0xffffff);key.intensity=1.2;} renderer.render(scene,camera); }, From abf279882ea6ca5b0c127e650350eeaeaa0392a6 Mon Sep 17 00:00:00 2001 From: Laurence Xavier <35849747+lxf82dev@users.noreply.github.com> Date: Wed, 11 Nov 2026 11:45:24 +0800 Subject: [PATCH 05/49] Media: look frames up at their exact times, not six-decimal seconds prepareMedia built each video's PTS list from ffprobe's best_effort_timestamp_time, which is printed to six decimals. Frame 1 of a 24 fps clip reads 0.041667, later than 1/24 s, so ptsIndex, which compares with a 1e-9 tolerance, returned frame 0 for it. A third of the frames of any 24 or 30 fps clip were drawn as their predecessor (0, 0, 2, 3, 3, 5, ...), in preview and export, while anything sampled on the plate's frame grid (plateFrameIndex, conformSeconds, sampleTrack) used the right frame, so a pinned element sat one frame of motion off the footage on those frames. Frame times are now integer ticks scaled by the stream's time base. A new test prepares a 24 and a 30 fps clip and looks every frame up at its own time; before the fix it failed at frames 1, 4, 7, ... (24 fps) and the 30 fps equivalent. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 1 + scripts/media.mjs | 14 ++++++++++---- tests/media-pts.test.mjs | 17 +++++++++++++++++ 3 files changed, 28 insertions(+), 4 deletions(-) create mode 100644 tests/media-pts.test.mjs diff --git a/CHANGELOG.md b/CHANGELOG.md index 4423019..dad6764 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,6 +12,7 @@ Hybrid scenes: code-rendered elements composited with filmed or generated footag - Add `init --hybrid`, a starter with a synthetic plate, and `npm run test:hybrid`. - Document a trial of the hybrid helpers on generated footage, and how to conform mattes and depth maps made by other tools. - The hybrid starter lights its can from the footage at environment intensity 1 (was 1.5, set while half of the panorama was empty), with aluminium lids at aluminium's reflectance. Measured against real cans in generated plates. +- Fix video frames looked up one frame early: media preparation read frame times as six-decimal seconds, so frame 1 of a 24 fps clip (0.041667) seemed to start after 1/24 s and a third of the frames of any 24 or 30 fps clip showed their predecessor. Frame times are now exact ticks in the stream's time base. - Fix transparent DOM-root exports capturing the preview page's own header through the scene. Any transparent renderer export smaller than the header area was affected. Runtime files changed, so existing projects need their normal `rebind`. diff --git a/scripts/media.mjs b/scripts/media.mjs index 31fbf67..9e7cf2e 100644 --- a/scripts/media.mjs +++ b/scripts/media.mjs @@ -26,12 +26,18 @@ export async function prepareMedia(assets,{signal,maxDecodedBytes=8*1024**3,maxF if(a.type!=='audio'){ if(!v)throw Error('Asset has no video/image stream: '+id); if(v.width>4096||v.height>4096)throw Error('Media exceeds 4096-pixel decode limit'); - const data=JSON.parse((await run(ffprobe(),['-v','error','-select_streams','v:0','-show_frames','-show_entries','frame=best_effort_timestamp_time,pkt_duration_time','-of','json',a.file],{signal})).toString()); + // Integer ticks in the stream's time base, not `*_time` seconds: ffprobe prints those to six + // decimals, so 1/24 s reads 0.041667, later than the frame really is, and a third of the + // frames of a 24 or 30 fps clip were looked up as their predecessor. + const [tn,td]=String(v.time_base??'').split('/').map(Number); + if(!(Number.isSafeInteger(tn)&&Number.isSafeInteger(td)&&tn>0&&td>0))throw Error('Media has no stream time base: '+id); + const data=JSON.parse((await run(ffprobe(),['-v','error','-select_streams','v:0','-show_frames','-show_entries','frame=best_effort_timestamp,duration,pkt_duration','-of','json',a.file],{signal})).toString()); const frames=data.frames??[];if(!frames.length||frames.length>maxFrames)throw Error('Media frame budget exceeded: '+id); - const first=Number(frames[0].best_effort_timestamp_time??0); - pts=frames.map(f=>Number(f.best_effort_timestamp_time??0)-first); + const first=Number(frames[0].best_effort_timestamp??0); + pts=frames.map(f=>(Number(f.best_effort_timestamp??0)-first)*tn/td); if(pts.some((t,i)=>!Number.isFinite(t)||(i&&t0?lastTicks*tn/td:1/30)); budget+=v.width*v.height*4*frames.length;if(budget>maxDecodedBytes)throw Error('Decoded media budget exceeded; trim/proxy sources or raise maxDecodedBytes'); const dest=path.join(dir,id);await fs.mkdir(dest); await run(ffmpeg(),['-v','error','-i',a.file,'-map','0:v:0','-fps_mode','passthrough','-frames:v',String(frames.length),path.join(dest,'%06d.png')],{signal,timeout:300000}); diff --git a/tests/media-pts.test.mjs b/tests/media-pts.test.mjs new file mode 100644 index 0000000..56b68de --- /dev/null +++ b/tests/media-pts.test.mjs @@ -0,0 +1,17 @@ +import test from 'node:test';import assert from 'node:assert/strict';import fs from 'node:fs/promises';import os from 'node:os';import path from 'node:path';import {createHash} from 'node:crypto'; +import {prepareMedia} from '../scripts/media.mjs';import {run,ffmpeg} from '../scripts/process.mjs';import {ptsIndex} from '../packages/media/ports.mjs'; +// ffprobe prints `*_time` values to six decimals, so frame 1 of a 24 fps clip reads 0.041667: later than +// 1/24 s. Looked up at the frame's own time, a third of the frames of a 24 or 30 fps clip resolved to +// their predecessor, so a plate showed frame n-1 while a track sampled on the plate's grid used frame n. +for(const rate of [24,30])test(`every frame of a ${rate} fps clip is found at its own frame time`,async()=>{ + const dir=await fs.mkdtemp(path.join(os.tmpdir(),'ef-pts-'));let media; + try{ + const file=path.join(dir,'clip.mp4'); + await run(ffmpeg(),['-v','error','-f','lavfi','-i',`testsrc2=size=64x48:rate=${rate}:duration=1`,'-c:v','libx264','-g',String(rate),file]); + const sha256=createHash('sha256').update(await fs.readFile(file)).digest('hex'); + media=await prepareMedia({clip:{file,type:'video',sha256}}); + const {pts}=media.catalog.clip;assert.equal(pts.length,rate); + const wrong=[];for(let n=0;n Date: Wed, 11 Nov 2026 12:44:45 +0800 Subject: [PATCH 06/49] Export: keep the drawn levels in MP4 and MOV; export opaque scenes to MOV MP4 and MOV exports converted the browser's sRGB frames to the BT.709 camera transfer curve (colorspace itrc=srgb, all=bt709). Players display BT.709 video without undoing that curve, so every export came out darker than drawn: 32 -> 16, 128 -> 115, 224 -> 220. Footage in a hybrid shot lost 10-13 levels against its source, found when a filmed plate's table top went from 114 to 101. The encoder now converts RGB to BT.709 YUV in limited range only, and tags the transfer as sRGB, which is what the values are. MOV (ProRes 4444) extracted alpha from the frames, and a scene with no transparency renders frames without an alpha channel, so its MOV export failed ("Requested planes not available"). The frames are now converted to RGBA first. The hybrid integration test exports the starter to MP4 and MOV and compares the decoded frame with the PNG the browser drew: within 2 levels per channel, and opaque in the MOV. Before, the MP4 read 123,67,41 against 134,80,55 and the MOV export failed. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 2 ++ scripts/render.mjs | 8 +++++--- tests/hybrid-integration.mjs | 19 +++++++++++++++++++ 3 files changed, 26 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index dad6764..9d7c577 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,6 +13,8 @@ Hybrid scenes: code-rendered elements composited with filmed or generated footag - Document a trial of the hybrid helpers on generated footage, and how to conform mattes and depth maps made by other tools. - The hybrid starter lights its can from the footage at environment intensity 1 (was 1.5, set while half of the panorama was empty), with aluminium lids at aluminium's reflectance. Measured against real cans in generated plates. - Fix video frames looked up one frame early: media preparation read frame times as six-decimal seconds, so frame 1 of a 24 fps clip (0.041667) seemed to start after 1/24 s and a third of the frames of any 24 or 30 fps clip showed their predecessor. Frame times are now exact ticks in the stream's time base. +- Fix MP4 and MOV exports coming out 10–13 levels darker than the frames drawn (128 became 115), footage included: the encoder converted sRGB to the BT.709 camera curve, which players do not undo. Exports now keep the drawn values (BT.709 matrix, limited range, transfer tagged as sRGB). +- Fix MOV export of a scene with no transparency, which failed extracting an alpha channel the frames did not have. - Fix transparent DOM-root exports capturing the preview page's own header through the scene. Any transparent renderer export smaller than the header area was affected. Runtime files changed, so existing projects need their normal `rebind`. diff --git a/scripts/render.mjs b/scripts/render.mjs index 32faf03..4142f80 100644 --- a/scripts/render.mjs +++ b/scripts/render.mjs @@ -51,11 +51,13 @@ export async function render(dir,output,{fps,frames,format,background='#101922', if(audio.tracks)await fs.copyFile(audioPath,path.join(frameDir,'audio.wav'));result=frameDir; }else{ result=path.join(temp,'output.'+format);const args=['-v','error','-n','-framerate',`${rate.num}/${rate.den}`,'-i',path.join(frameDir,'%06d.png')];if(audio.tracks)args.push('-i',audioPath); - const convert='scale=in_range=pc:out_range=pc:out_color_matrix=bt709,format=yuv444p,colorspace=ispace=bt709:itrc=srgb:iprimaries=bt709:irange=pc:all=bt709:range=tv:format=yuv444p'; + // RGB to BT.709 YUV in limited range, with the transfer left as drawn and tagged as sRGB. Converting it to the BT.709 + // camera curve made every export 10-13 levels darker (128 -> 115), footage included, and no player undoes it. + const convert='scale=in_range=pc:out_range=tv:out_color_matrix=bt709,format=yuv444p'; if(format==='mp4')args.push('-f','lavfi','-i',`color=c=${background.replace('#','0x')}:s=${d.studio.doc.width}x${d.studio.doc.height}:r=${rate.num}/${rate.den}`,'-filter_complex',`[${audio.tracks?2:1}:v]format=rgba[bg];[bg][0:v]overlay=shortest=1:format=rgb,${convert},format=yuv420p[v]`,'-map','[v]','-c:v','libx264','-crf','18','-pix_fmt','yuv420p','-movflags','+faststart'); - else args.push('-filter_complex',`[0:v]split[rgb][alpha];[alpha]alphaextract[a];[rgb]${convert}[color];[color][a]alphamerge,format=yuva444p10le[v]`,'-map','[v]','-c:v','prores_ks','-profile:v','4','-pix_fmt','yuva444p10le','-alpha_bits','16'); + else args.push('-filter_complex',`[0:v]format=rgba,split[rgb][alpha];[alpha]alphaextract[a];[rgb]${convert}[color];[color][a]alphamerge,format=yuva444p10le[v]`,'-map','[v]','-c:v','prores_ks','-profile:v','4','-pix_fmt','yuva444p10le','-alpha_bits','16'); if(audio.tracks)args.push('-map','1:a:0','-c:a',format==='mov'?'pcm_s16le':'aac'); - args.push('-frames:v',String(count),'-t',String(actualDuration),'-color_primaries','bt709','-color_trc','bt709','-colorspace','bt709',result); + args.push('-frames:v',String(count),'-t',String(actualDuration),'-color_range','tv','-color_primaries','bt709','-color_trc','iec61966-2-1','-colorspace','bt709',result); onProgress({phase:'encode',progress:0});await run(ffmpeg(),args,{signal,timeout:600000}); const info=JSON.parse((await run(ffprobe(),['-v','error','-show_streams','-show_format','-of','json',result],{signal})).toString()); if(!info.streams.some(s=>s.codec_type==='video')||audio.tracks&&!info.streams.some(s=>s.codec_type==='audio'))throw Error('Encoded media failed stream validation'); diff --git a/tests/hybrid-integration.mjs b/tests/hybrid-integration.mjs index 3e20288..710bd3e 100644 --- a/tests/hybrid-integration.mjs +++ b/tests/hybrid-integration.mjs @@ -22,6 +22,25 @@ try{ const beauty=path.join(tmp,'beauty');await render(dir,beauty,{format:'png',frames:40}); const early=6,late=35,barAt=frame=>demo.bar.x(frame),boardAt=frame=>demo.board.x(frame); const a=await pixels(frameFile(beauty,early)),b=await pixels(frameFile(beauty,late)); + // --- An MP4 keeps the levels the browser drew --------------------------------- + // Decoded with the matrix and range it declares, an MP4 of the starter must give the PNG frame's values: the + // footage in a hybrid shot is not re-graded on the way out. Converting to the BT.709 camera curve made it + // 10-13 levels darker (128 -> 115), which no player undoes. + const movie=path.join(tmp,'movie.mp4');await render(dir,movie,{format:'mp4',frames:early+1}); + const decoded=await run(ffmpeg(),['-v','error','-i',movie,'-vf',`select=eq(n\\,${early}),scale=in_range=tv:out_range=pc:in_color_matrix=bt709,format=rgba`,'-frames:v','1','-f','rawvideo','-'],{maxOutput:64*1024**2}); + assert.equal(decoded.length,W*H*4); + const shown={at:(x,y)=>[...decoded.subarray((y*W+x)*4,(y*W+x)*4+4)]}; + const drawn=mean(a,0,0,W,H),encoded=mean(shown,0,0,W,H); + assert.ok(drawn.every((v,i)=>Math.abs(encoded[i]-v)<=2),`MP4 levels ${encoded.map(Math.round)} differ from the drawn frame's ${drawn.map(Math.round)}`); + checks.push('An MP4 export keeps the levels of the drawn frames'); + // An opaque scene's frames have no alpha channel; the MOV (ProRes 4444) path extracted alpha from them and failed. + const prores=path.join(tmp,'movie.mov');await render(dir,prores,{format:'mov',frames:early+1}); + const proresFrame=await run(ffmpeg(),['-v','error','-i',prores,'-vf',`select=eq(n\\,${early}),scale=in_range=tv:out_range=pc:in_color_matrix=bt709,format=rgba`,'-frames:v','1','-f','rawvideo','-'],{maxOutput:64*1024**2}); + assert.equal(proresFrame.length,W*H*4); + const proresShown={at:(x,y)=>[...proresFrame.subarray((y*W+x)*4,(y*W+x)*4+4)]},proresLevels=mean(proresShown,0,0,W,H); + assert.ok(drawn.every((v,i)=>Math.abs(proresLevels[i]-v)<=2),`MOV levels ${proresLevels.map(Math.round)} differ from the drawn frame's ${drawn.map(Math.round)}`); + assert.equal(proresShown.at(W>>1,H>>1)[3],255,'an opaque scene stays opaque'); + checks.push('An opaque scene exports to MOV, at the levels of the drawn frames'); // Frame 6: the bar is far left; the product is in the clear. assert.ok(barAt(early)+demo.bar.width<250); // Label samples sit on rows 112-140: plain label above its text. The text is laid out with the platform's font, and From 2fc0c90c4354305e71baaf38b2dc40141286f987 Mon Sep 17 00:00:00 2001 From: Laurence Xavier <35849747+lxf82dev@users.noreply.github.com> Date: Wed, 11 Nov 2026 12:44:45 +0800 Subject: [PATCH 07/49] Hybrid docs: what a trial on filmed footage found Two real-camera clips (1920 x 1080, 25 fps, motion-control dolly): - A card pinned to the blank side panel of a box held within 2 px for 30 frames, then the track slid onto the box's next face as the orbit brought it into view, while the tracking tool reported confidence of 0.70-0.85 and no lost frames. - estimateKeyLight chose the side the real shadow shows but placed the light too low, and took its colour from bright blue components. The shadow catcher, a plane with no depth, drew the can's shadow over a real object on the table. The docs say both, add the light-colour and shadow-catcher limits where those helpers are described, and say how MP4 and MOV now encode colour. Occlusion was not tried on filmed footage. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 1 + docs/hybrid-scenes.md | 16 ++++++++++++++-- skills/editableframes/references/hybrid.md | 16 ++++++++++++++-- 3 files changed, 29 insertions(+), 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 9d7c577..a6dd958 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -15,6 +15,7 @@ Hybrid scenes: code-rendered elements composited with filmed or generated footag - Fix video frames looked up one frame early: media preparation read frame times as six-decimal seconds, so frame 1 of a 24 fps clip (0.041667) seemed to start after 1/24 s and a third of the frames of any 24 or 30 fps clip showed their predecessor. Frame times are now exact ticks in the stream's time base. - Fix MP4 and MOV exports coming out 10–13 levels darker than the frames drawn (128 became 115), footage included: the encoder converted sRGB to the BT.709 camera curve, which players do not undo. Exports now keep the drawn values (BT.709 matrix, limited range, transfer tagged as sRGB). - Fix MOV export of a scene with no transparency, which failed extracting an alpha channel the frames did not have. +- Document a trial of the hybrid helpers on filmed footage. - Fix transparent DOM-root exports capturing the preview page's own header through the scene. Any transparent renderer export smaller than the header area was affected. Runtime files changed, so existing projects need their normal `rebind`. diff --git a/docs/hybrid-scenes.md b/docs/hybrid-scenes.md index 19d5fe9..0ec4310 100644 --- a/docs/hybrid-scenes.md +++ b/docs/hybrid-scenes.md @@ -164,7 +164,7 @@ None of this narrows what a renderer may draw. A scene that uses other libraries Three helpers guess from a single view. Expose their results as controls. -- **`estimateKeyLight`** reads which side the light is on from the brightest 5% of the frame. A picture cannot say how far in front of or behind the subject the light is, so that part is a stated assumption: a small source is placed level with the subject, a broad one in front of it. The brightest area is not always the light: a white desk under a window reads as light from below, and a low sun behind the subject reads as light from the front. A shadow cast from the estimate then falls the wrong way, so let the author set the direction. +- **`estimateKeyLight`** reads which side the light is on from the brightest 5% of the frame. A picture cannot say how far in front of or behind the subject the light is, so that part is a stated assumption: a small source is placed level with the subject, a broad one in front of it. The brightest area is not always the light: a white desk under a window reads as light from below, and a low sun behind the subject reads as light from the front. A shadow cast from the estimate then falls the wrong way, so let the author set the direction. Its colour is the brightest area's colour, which can be an object's (blue components read as a blue light) rather than the light's. - **`createPlateEnvironment`** has only what the camera saw. It puts the plate in front and a mirrored copy behind the camera, and pushes clipped highlights above 1 so they can act as light sources. The result is plausible. It is not a measurement of the real surroundings, and the highlight boost is not recovered data. Use a real `environment` asset when you have one. Keep `scene.environmentIntensity` at 1, as the starter does: the light is then the plate's own pixel values with no gain, and a material should have its real reflectance (aluminium is about 0.91, `#f5f6f6`). - **Depth `near` and `far`** are yours to tune, as above. @@ -179,6 +179,7 @@ Video models emit a fixed rate: commonly 24 fps, sometimes 16 or 30. Two things - `render DIR OUT --pass NAME` renders a declared pass. The receipt records it. - `render DIR OUT --motion-blur ANGLE [--samples N]` opens a shutter of `ANGLE` degrees (0–360, default samples 8, range 2–64) centred on each frame. Samples are averaged as premultiplied colour, so a half-covered pixel keeps its hue. The mean is taken on encoded values, not linear light. Preview shows no motion blur. +- MP4 and MOV keep the values the browser drew: BT.709 matrix, limited range, transfer tagged as sRGB. Footage in a hybrid shot comes out at the levels it went in. - An export re-encodes its inputs. Content credentials or other provenance metadata carried by a generated plate are not copied to the output. If a law or a platform requires you to disclose AI-generated content, that remains your responsibility. ## Compared with a full compositing checklist @@ -196,7 +197,7 @@ Professional compositing uses more steps than this. Stated plainly: | Black and white point match | Measured by `plateStats` / `matchLevels`. Applying it is left to the scene. | | Grain match | Measured by `estimateNoise`; `drawGrain` adds seeded grain. Not applied by the starter. | | Motion blur | Done at export, for code layers. | -| Shadow of the object on the plate | `fitGroundPlane` and `createShadowCatcher` exist. Not exercised by the starter or the integration test. | +| Shadow of the object on the plate | `fitGroundPlane` and `createShadowCatcher` exist. Not exercised by the starter or the integration test. The catcher is a plane with no depth: a shadow it catches is also drawn over a real object standing on that plane. | | Camera match | Replay only. No solver. | | Depth of field, lens distortion, chromatic aberration, light wrap, atmospheric haze | Not provided. | | Reflection or shadow of the object in the plate's own surfaces | Not provided. It needs the plate's normals and roughness. | @@ -220,6 +221,17 @@ The helpers were tried on twelve 5–6 second plates from four video models (See Two things made pinned graphics read as part of the surface: a `mix-blend-mode` chosen for the material (`screen` for chalk on a dark board, `multiply` for print on paper), and the plate's own frame rate for the whole project. +## On filmed footage + +Two clips from a real camera (1920 × 1080, 25 fps, on a slow motion-control dolly) were tried the same way. It is a smaller trial than the one on generated plates, and it had no mattes or depth maps, so occlusion is not covered. + +| Journey | What was found | +|---|---| +| Screen or label on a surface | A card pinned to the blank side panel of a box held within 2 px of the panel for 30 frames. Then the dolly's orbit brought the box's next face into view, and the track slid onto it. The tracking tool reported confidence of 0.70–0.85 and no lost frames. A blank surface is tracked by the detail around its edges, and on a solid object an orbit changes what is there. Check the pinned element at several frames, not only the first. | +| Lit by the footage | `estimateKeyLight` chose the side that the real shadow shows (front-left) but placed the light too low, so a cast shadow came out too long. Its colour came from bright blue components, not from the light. A light set by hand from the real shadow matched its direction. The shadow catcher drew the can's shadow across a real object standing on the table. Beside real metal, the plain aluminium can read as dull grey. | + +The same trial found that MP4 and MOV exports came out 10–13 levels darker than the frames drawn (128 became 115), footage included, and that a scene with no transparency could not be exported to MOV. Both are fixed. + ## Limits - The plate, matte and depth are decoded to PNG frames before preview and export, within the existing 8 GiB budget. Three videos per shot use it three times as fast. diff --git a/skills/editableframes/references/hybrid.md b/skills/editableframes/references/hybrid.md index 92ba384..746c824 100644 --- a/skills/editableframes/references/hybrid.md +++ b/skills/editableframes/references/hybrid.md @@ -156,7 +156,7 @@ None of this narrows what a renderer may draw. A scene that uses other libraries Three helpers guess from a single view. Expose their results as controls. -- **`estimateKeyLight`** reads which side the light is on from the brightest 5% of the frame. A picture cannot say how far in front of or behind the subject the light is, so that part is a stated assumption: a small source is placed level with the subject, a broad one in front of it. The brightest area is not always the light: a white desk under a window reads as light from below, and a low sun behind the subject reads as light from the front. A shadow cast from the estimate then falls the wrong way, so let the author set the direction. +- **`estimateKeyLight`** reads which side the light is on from the brightest 5% of the frame. A picture cannot say how far in front of or behind the subject the light is, so that part is a stated assumption: a small source is placed level with the subject, a broad one in front of it. The brightest area is not always the light: a white desk under a window reads as light from below, and a low sun behind the subject reads as light from the front. A shadow cast from the estimate then falls the wrong way, so let the author set the direction. Its colour is the brightest area's colour, which can be an object's (blue components read as a blue light) rather than the light's. - **`createPlateEnvironment`** has only what the camera saw. It puts the plate in front and a mirrored copy behind the camera, and pushes clipped highlights above 1 so they can act as light sources. The result is plausible. It is not a measurement of the real surroundings, and the highlight boost is not recovered data. Use a real `environment` asset when you have one. Keep `scene.environmentIntensity` at 1, as the starter does: the light is then the plate's own pixel values with no gain, and a material should have its real reflectance (aluminium is about 0.91, `#f5f6f6`). - **Depth `near` and `far`** are yours to tune, as above. @@ -171,6 +171,7 @@ Video models emit a fixed rate: commonly 24 fps, sometimes 16 or 30. Two things - `render DIR OUT --pass NAME` renders a declared pass. The receipt records it. - `render DIR OUT --motion-blur ANGLE [--samples N]` opens a shutter of `ANGLE` degrees (0–360, default samples 8, range 2–64) centred on each frame. Samples are averaged as premultiplied colour, so a half-covered pixel keeps its hue. The mean is taken on encoded values, not linear light. Preview shows no motion blur. +- MP4 and MOV keep the values the browser drew: BT.709 matrix, limited range, transfer tagged as sRGB. Footage in a hybrid shot comes out at the levels it went in. - An export re-encodes its inputs. Content credentials or other provenance metadata carried by a generated plate are not copied to the output. If a law or a platform requires you to disclose AI-generated content, that remains your responsibility. ## Compared with a full compositing checklist @@ -188,7 +189,7 @@ Professional compositing uses more steps than this. Stated plainly: | Black and white point match | Measured by `plateStats` / `matchLevels`. Applying it is left to the scene. | | Grain match | Measured by `estimateNoise`; `drawGrain` adds seeded grain. Not applied by the starter. | | Motion blur | Done at export, for code layers. | -| Shadow of the object on the plate | `fitGroundPlane` and `createShadowCatcher` exist. Not exercised by the starter or the integration test. | +| Shadow of the object on the plate | `fitGroundPlane` and `createShadowCatcher` exist. Not exercised by the starter or the integration test. The catcher is a plane with no depth: a shadow it catches is also drawn over a real object standing on that plane. | | Camera match | Replay only. No solver. | | Depth of field, lens distortion, chromatic aberration, light wrap, atmospheric haze | Not provided. | | Reflection or shadow of the object in the plate's own surfaces | Not provided. It needs the plate's normals and roughness. | @@ -208,6 +209,17 @@ The helpers were tried on twelve 5–6 second plates from four video models (See Two things made pinned graphics read as part of the surface: a `mix-blend-mode` chosen for the material (`screen` for chalk on a dark board, `multiply` for print on paper), and the plate's own frame rate for the whole project. +## On filmed footage + +Two clips from a real camera (1920 × 1080, 25 fps, on a slow motion-control dolly) were tried the same way. It is a smaller trial than the one on generated plates, and it had no mattes or depth maps, so occlusion is not covered. + +| Journey | What was found | +|---|---| +| Screen or label on a surface | A card pinned to the blank side panel of a box held within 2 px of the panel for 30 frames. Then the dolly's orbit brought the box's next face into view, and the track slid onto it. The tracking tool reported confidence of 0.70–0.85 and no lost frames. A blank surface is tracked by the detail around its edges, and on a solid object an orbit changes what is there. Check the pinned element at several frames, not only the first. | +| Lit by the footage | `estimateKeyLight` chose the side that the real shadow shows (front-left) but placed the light too low, so a cast shadow came out too long. Its colour came from bright blue components, not from the light. A light set by hand from the real shadow matched its direction. The shadow catcher drew the can's shadow across a real object standing on the table. Beside real metal, the plain aluminium can read as dull grey. | + +The same trial found that MP4 and MOV exports came out 10–13 levels darker than the frames drawn (128 became 115), footage included, and that a scene with no transparency could not be exported to MOV. Both are fixed. + ## Limits - The plate, matte and depth are decoded to PNG frames before preview and export, within the existing 8 GiB budget. Three videos per shot use it three times as fast. From c9d37fc7cb96a0c805285901d6f9433ad70f2cb7 Mon Sep 17 00:00:00 2001 From: Laurence Xavier <35849747+lxf82dev@users.noreply.github.com> Date: Wed, 11 Nov 2026 13:11:09 +0800 Subject: [PATCH 08/49] Media: draw colour-tagged footage, mattes and depth at their values FFmpeg writes cICP, cHRM and gAMA chunks into a PNG decoded from a clip whose primaries and transfer are tagged BT.709, which most camera footage is. The browser then draws the frame through that curve rather than as the values it holds: footage came out darker than its source, and a matte or depth map tagged the same way reached the scene with changed data. Found on filmed footage: a board pixel stored as (142, 117, 73) drew as (136, 109, 63); without the three chunks it drew exactly. prepareMedia now clears the primaries and transfer tags before the PNG encoder; they do not change the decoded values. A new test decodes a tagged clip and checks for no colour chunks and the values of a plain decode; before the fix it found all three chunks. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 1 + scripts/media.mjs | 5 ++++- tests/media-pts.test.mjs | 21 ++++++++++++++++++++- 3 files changed, 25 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index a6dd958..8749da4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -14,6 +14,7 @@ Hybrid scenes: code-rendered elements composited with filmed or generated footag - The hybrid starter lights its can from the footage at environment intensity 1 (was 1.5, set while half of the panorama was empty), with aluminium lids at aluminium's reflectance. Measured against real cans in generated plates. - Fix video frames looked up one frame early: media preparation read frame times as six-decimal seconds, so frame 1 of a 24 fps clip (0.041667) seemed to start after 1/24 s and a third of the frames of any 24 or 30 fps clip showed their predecessor. Frame times are now exact ticks in the stream's time base. - Fix MP4 and MOV exports coming out 10–13 levels darker than the frames drawn (128 became 115), footage included: the encoder converted sRGB to the BT.709 camera curve, which players do not undo. Exports now keep the drawn values (BT.709 matrix, limited range, transfer tagged as sRGB). +- Fix footage tagged with BT.709 primaries and transfer (most camera footage) drawing darker than its values, and mattes and depth maps tagged the same way drawing changed data: decoded frames carried colour chunks the browser applied. Frames are now decoded without them. - Fix MOV export of a scene with no transparency, which failed extracting an alpha channel the frames did not have. - Document a trial of the hybrid helpers on filmed footage. - Fix transparent DOM-root exports capturing the preview page's own header through the scene. Any transparent renderer export smaller than the header area was affected. diff --git a/scripts/media.mjs b/scripts/media.mjs index 9e7cf2e..c518470 100644 --- a/scripts/media.mjs +++ b/scripts/media.mjs @@ -40,7 +40,10 @@ export async function prepareMedia(assets,{signal,maxDecodedBytes=8*1024**3,maxF duration=Math.max(duration,pts.at(-1)+(lastTicks>0?lastTicks*tn/td:1/30)); budget+=v.width*v.height*4*frames.length;if(budget>maxDecodedBytes)throw Error('Decoded media budget exceeded; trim/proxy sources or raise maxDecodedBytes'); const dest=path.join(dir,id);await fs.mkdir(dest); - await run(ffmpeg(),['-v','error','-i',a.file,'-map','0:v:0','-fps_mode','passthrough','-frames:v',String(frames.length),path.join(dest,'%06d.png')],{signal,timeout:300000}); + // A PNG from a clip tagged with BT.709 primaries and transfer (most camera footage) carries cICP, cHRM and gAMA + // chunks, and the browser then draws it through that curve: footage drew darker, and a matte or depth map's data + // changed. The tags do not change the decoded values; clearing them keeps the chunks out. + await run(ffmpeg(),['-v','error','-i',a.file,'-map','0:v:0','-vf','setparams=color_primaries=unknown:color_trc=unknown','-fps_mode','passthrough','-frames:v',String(frames.length),path.join(dest,'%06d.png')],{signal,timeout:300000}); const files=await fs.readdir(dest);if(files.length!==pts.length)throw Error('Decoded frame count differs from PTS index: '+id); } if(a.type==='audio'&&!audio)throw Error('Asset has no audio: '+id); diff --git a/tests/media-pts.test.mjs b/tests/media-pts.test.mjs index 56b68de..8928acb 100644 --- a/tests/media-pts.test.mjs +++ b/tests/media-pts.test.mjs @@ -1,5 +1,5 @@ import test from 'node:test';import assert from 'node:assert/strict';import fs from 'node:fs/promises';import os from 'node:os';import path from 'node:path';import {createHash} from 'node:crypto'; -import {prepareMedia} from '../scripts/media.mjs';import {run,ffmpeg} from '../scripts/process.mjs';import {ptsIndex} from '../packages/media/ports.mjs'; +import {prepareMedia} from '../scripts/media.mjs';import {run,ffmpeg,ffprobe} from '../scripts/process.mjs';import {ptsIndex} from '../packages/media/ports.mjs'; // ffprobe prints `*_time` values to six decimals, so frame 1 of a 24 fps clip reads 0.041667: later than // 1/24 s. Looked up at the frame's own time, a third of the frames of a 24 or 30 fps clip resolved to // their predecessor, so a plate showed frame n-1 while a track sampled on the plate's grid used frame n. @@ -15,3 +15,22 @@ for(const rate of [24,30])test(`every frame of a ${rate} fps clip is found at it assert.deepEqual(wrong,[],`frames looked up as another frame at ${rate} fps`); }finally{await media?.close();await fs.rm(dir,{recursive:true,force:true})} }); +// FFmpeg writes cICP, cHRM and gAMA chunks into a PNG decoded from a clip whose primaries and transfer are tagged +// BT.709, as most camera footage is. The browser then draws the frame through that curve instead of as the values +// it holds, so footage, and a matte or depth map tagged the same way, drew darker than its data. +const colourChunks=png=>{const found=[];for(let i=8;i+8<=png.length;){const length=png.readUInt32BE(i),type=png.toString('latin1',i+4,i+8);if(['cICP','cHRM','gAMA','iCCP','sRGB'].includes(type))found.push(type);i+=12+length;}return found;}; +test('frames of a colour-tagged clip hold their values with no colour chunks for the browser to apply',async()=>{ + const dir=await fs.mkdtemp(path.join(os.tmpdir(),'ef-tagged-'));let media; + try{ + const file=path.join(dir,'tagged.mp4'); + await run(ffmpeg(),['-v','error','-f','lavfi','-i','testsrc2=size=64x48:rate=25:duration=1','-vf','setparams=color_primaries=bt709:color_trc=bt709:colorspace=bt709','-c:v','libx264','-pix_fmt','yuv420p',file]); + const tags=(await run(ffprobe(),['-v','error','-select_streams','v:0','-show_entries','stream=color_transfer,color_primaries','-of','csv=p=0',file])).toString().trim(); + assert.equal(tags,'bt709,bt709','the fixture must carry the tags real footage does'); + const sha256=createHash('sha256').update(await fs.readFile(file)).digest('hex'); + media=await prepareMedia({clip:{file,type:'video',sha256}}); + const frame=path.join(media.dir,'clip','000011.png'); + assert.deepEqual(colourChunks(await fs.readFile(frame)),[]); + const raw=args=>run(ffmpeg(),['-v','error',...args,'-f','rawvideo','-pix_fmt','rgb24','-']); + assert.ok((await raw(['-i',frame])).equals(await raw(['-i',file,'-vf','select=eq(n\\,10)','-frames:v','1'])),'the frame keeps the values a plain decode gives'); + }finally{await media?.close();await fs.rm(dir,{recursive:true,force:true})} +}); From f58666f2cd43952e2d38e56980a7e72b2e6c9f8d Mon Sep 17 00:00:00 2001 From: Laurence Xavier <35849747+lxf82dev@users.noreply.github.com> Date: Wed, 11 Nov 2026 13:11:09 +0800 Subject: [PATCH 09/49] Hybrid docs: occlusion on filmed footage A tripod shot of a board with a forearm sweeping in front, with a hosted matte and depth map: - The headline behind the arm works, except while the arm enters fast (up to 460 px per frame): the matte lags it by 1-2 frames. - The depth map as delivered was normalised per frame, so the board read as near until the arm came in and hid the 3D object until then. Rescaled per frame against static parts of the shot, the arm hid the object with a 3-4 px edge and nothing leaked onto the arm. The filmed-footage section now covers all three journeys, and lists the three export defects the trial found, all fixed. Co-Authored-By: Claude Opus 5.5 --- docs/hybrid-scenes.md | 10 ++++++++-- skills/editableframes/references/hybrid.md | 10 ++++++++-- 2 files changed, 16 insertions(+), 4 deletions(-) diff --git a/docs/hybrid-scenes.md b/docs/hybrid-scenes.md index 0ec4310..6ab582c 100644 --- a/docs/hybrid-scenes.md +++ b/docs/hybrid-scenes.md @@ -223,14 +223,20 @@ Two things made pinned graphics read as part of the surface: a `mix-blend-mode` ## On filmed footage -Two clips from a real camera (1920 × 1080, 25 fps, on a slow motion-control dolly) were tried the same way. It is a smaller trial than the one on generated plates, and it had no mattes or depth maps, so occlusion is not covered. +Three clips from a real camera (1920 × 1080, 25 fps; two on a slow motion-control dolly, one on a tripod) were tried the same way, with a hosted matte and depth map for the third. It is a smaller trial than the one on generated plates. | Journey | What was found | |---|---| | Screen or label on a surface | A card pinned to the blank side panel of a box held within 2 px of the panel for 30 frames. Then the dolly's orbit brought the box's next face into view, and the track slid onto it. The tracking tool reported confidence of 0.70–0.85 and no lost frames. A blank surface is tracked by the detail around its edges, and on a solid object an orbit changes what is there. Check the pinned element at several frames, not only the first. | | Lit by the footage | `estimateKeyLight` chose the side that the real shadow shows (front-left) but placed the light too low, so a cast shadow came out too long. Its colour came from bright blue components, not from the light. A light set by hand from the real shadow matched its direction. The shadow catcher drew the can's shadow across a real object standing on the table. Beside real metal, the plain aluminium can read as dull grey. | +| Headline behind a subject | Works with a hosted matte, except while a fast arm enters the shot (up to 460 px per frame): the matte lagged it by 1–2 frames, and the headline showed through the arm on those frames. The matte's edge along the forearm was soft, about 10 px from 10% to 90%. | +| Footage in front of a 3D object | Failed with the hosted depth map as delivered: the model normalised each frame separately, so the board read as near until the arm came in and as far after it, and hid the object until then. Rescaled per frame against parts of the shot that do not move (the wall and the board), the arm hid the object with an edge 3–4 px wide and nothing leaked onto the arm. | -The same trial found that MP4 and MOV exports came out 10–13 levels darker than the frames drawn (128 became 115), footage included, and that a scene with no transparency could not be exported to MOV. Both are fixed. +The same trial found three export defects, all fixed: + +- MP4 and MOV exports came out 10–13 levels darker than the frames drawn (128 became 115), footage included. +- A scene with no transparency could not be exported to MOV. +- Footage tagged with BT.709 primaries and transfer, as most camera footage is, was drawn darker than its values before it ever reached the encoder. A board pixel stored as (142, 117, 73) drew as (136, 109, 63). ## Limits diff --git a/skills/editableframes/references/hybrid.md b/skills/editableframes/references/hybrid.md index 746c824..5320989 100644 --- a/skills/editableframes/references/hybrid.md +++ b/skills/editableframes/references/hybrid.md @@ -211,14 +211,20 @@ Two things made pinned graphics read as part of the surface: a `mix-blend-mode` ## On filmed footage -Two clips from a real camera (1920 × 1080, 25 fps, on a slow motion-control dolly) were tried the same way. It is a smaller trial than the one on generated plates, and it had no mattes or depth maps, so occlusion is not covered. +Three clips from a real camera (1920 × 1080, 25 fps; two on a slow motion-control dolly, one on a tripod) were tried the same way, with a hosted matte and depth map for the third. It is a smaller trial than the one on generated plates. | Journey | What was found | |---|---| | Screen or label on a surface | A card pinned to the blank side panel of a box held within 2 px of the panel for 30 frames. Then the dolly's orbit brought the box's next face into view, and the track slid onto it. The tracking tool reported confidence of 0.70–0.85 and no lost frames. A blank surface is tracked by the detail around its edges, and on a solid object an orbit changes what is there. Check the pinned element at several frames, not only the first. | | Lit by the footage | `estimateKeyLight` chose the side that the real shadow shows (front-left) but placed the light too low, so a cast shadow came out too long. Its colour came from bright blue components, not from the light. A light set by hand from the real shadow matched its direction. The shadow catcher drew the can's shadow across a real object standing on the table. Beside real metal, the plain aluminium can read as dull grey. | +| Headline behind a subject | Works with a hosted matte, except while a fast arm enters the shot (up to 460 px per frame): the matte lagged it by 1–2 frames, and the headline showed through the arm on those frames. The matte's edge along the forearm was soft, about 10 px from 10% to 90%. | +| Footage in front of a 3D object | Failed with the hosted depth map as delivered: the model normalised each frame separately, so the board read as near until the arm came in and as far after it, and hid the object until then. Rescaled per frame against parts of the shot that do not move (the wall and the board), the arm hid the object with an edge 3–4 px wide and nothing leaked onto the arm. | -The same trial found that MP4 and MOV exports came out 10–13 levels darker than the frames drawn (128 became 115), footage included, and that a scene with no transparency could not be exported to MOV. Both are fixed. +The same trial found three export defects, all fixed: + +- MP4 and MOV exports came out 10–13 levels darker than the frames drawn (128 became 115), footage included. +- A scene with no transparency could not be exported to MOV. +- Footage tagged with BT.709 primaries and transfer, as most camera footage is, was drawn darker than its values before it ever reached the encoder. A board pixel stored as (142, 117, 73) drew as (136, 109, 63). ## Limits From 177ceedea360f82fb33a917fc004e68058f329c4 Mon Sep 17 00:00:00 2001 From: Laurence Xavier <35849747+lxf82dev@users.noreply.github.com> Date: Wed, 11 Nov 2026 13:46:21 +0800 Subject: [PATCH 10/49] Preserve footage clocks and scene state in hybrid renders Separate output-frame media time from code shutter samples, retain float precision when averaging samples, and use the fixed media clock in the bundled starters. Restore hidden meshes and clear scene overrides during control passes. Add pixel and state regressions and document the media clock. --- docs/hybrid-scenes.md | 2 +- docs/renderer-contract.md | 12 +++++++ packages/runtime/compositor.mjs | 7 ++-- packages/runtime/editor.mjs | 4 +-- packages/runtime/renderer-compositor.mjs | 7 ++-- packages/three/plate.mjs | 4 +-- scripts/render.mjs | 10 ++++-- skills/editableframes/SKILL.md | 2 +- skills/editableframes/references/hybrid.md | 2 +- skills/editableframes/references/renderer.md | 12 +++++++ templates/hybrid/clip.mjs | 2 +- templates/media/clip.mjs | 4 +-- tests/hybrid-integration.mjs | 32 ++++++++++++++++++ tests/plate.test.mjs | 34 +++++++++++++++++++ tests/renderer-scheduling.test.mjs | 35 ++++++++++++++++++++ 15 files changed, 150 insertions(+), 19 deletions(-) diff --git a/docs/hybrid-scenes.md b/docs/hybrid-scenes.md index 6ab582c..60d14b7 100644 --- a/docs/hybrid-scenes.md +++ b/docs/hybrid-scenes.md @@ -172,7 +172,7 @@ Three helpers guess from a single view. Expose their results as controls. Video models emit a fixed rate: commonly 24 fps, sometimes 16 or 30. Two things follow. -- Anything locked to the footage should move on the footage's frame grid. `conformSeconds(seconds, plate.frameRate)` gives the time of the plate frame on screen; sample tracks, mattes and depth at that time. Otherwise a pinned element slides against the picture between plate frames. +- Anything locked to the footage should move on the footage's frame grid. Use `seconds = clock.mediaTime ?? clock.frame / clock.fps` for footage and its derived data: this clock stays at the output frame during shutter sampling. `conformSeconds(seconds, plate.frameRate)` gives the time of the plate frame on screen; sample tracks, mattes and depth at that time. Otherwise a pinned element slides against the picture between plate frames. - A plate inside a timeline of another rate repeats frames unevenly. `cadence({num: 24, den: 1}, {num: 30, den: 1})` reports the pattern `2,1,1,1`, which is visible as judder on any move. Render the project at the plate's rate, or interpolate the plate before importing it. ## Export diff --git a/docs/renderer-contract.md b/docs/renderer-contract.md index 13c0966..daa2185 100644 --- a/docs/renderer-contract.md +++ b/docs/renderer-contract.md @@ -177,3 +177,15 @@ These tests do not establish a native application's integration or agent reliabi For optional object parents, locked/hidden policy and bounded direct-manipulation proposals, read [the interaction contract](interaction-contract.md). The renderer hook returns sparse control values; a host owns one atomic commit and cancellation. + +### Footage during shutter sampling + +`clock.mediaTime` is source seconds at the output frame's time, after the clip's +trim and playback rate. Without a shutter it equals `clock.frame / clock.fps`. +During motion blur, `clock.frame` advances through the shutter samples while +`clock.mediaTime` stays fixed. Use `clock.mediaTime ?? clock.frame / clock.fps` +for footage, mattes, depth and tracks attached to it; use `clock.frame` for code +animation. `mediaFrame(id, seconds)` still honors the exact time requested, so +custom scenes must choose the appropriate clock. Legacy renderers receive +`mediaTime` alongside `time`; pass `mediaTime` to `host.portFrame` for footage. +The media starter uses this clock too; authored media offsets remain explicit. diff --git a/packages/runtime/compositor.mjs b/packages/runtime/compositor.mjs index 208b35a..3777a08 100644 --- a/packages/runtime/compositor.mjs +++ b/packages/runtime/compositor.mjs @@ -7,15 +7,16 @@ export function evaluateClip(studio,clip,time){ } export function createCompositor(canvas,{templates,createRenderer,host}){ const ctx=canvas.getContext('2d',{alpha:true}),renderers=new Map();let chain=Promise.resolve(),generation=0; - const draw=async(studio,time,{selected,timeline=false}={})=>{ - if(!Number.isFinite(time)||time<0)throw Error('Invalid render time'); + const draw=async(studio,time,{selected,timeline=false,mediaTime=time}={})=>{ + if(!Number.isFinite(time)||time<0||!Number.isFinite(mediaTime)||mediaTime<0)throw Error('Invalid render time'); const clips=timeline?studio.doc.clips.filter(c=>time>=c.start/HZ&&time<(c.start+c.duration)/HZ):[studio.clip(selected)]; const active=new Set(clips.map(c=>c.id));for(const [id,r]of renderers)if(!active.has(id)){await r.instance.dispose?.();renderers.delete(id)} const first=clips[0],t=first&&templates[first.template];canvas.width=timeline?studio.doc.width:(t?.width??1280);canvas.height=timeline?studio.doc.height:(t?.height??720);ctx.clearRect(0,0,canvas.width,canvas.height); for(const clip of clips){ const spec=templates[clip.template];let r=renderers.get(clip.id);if(!r){const surface=document.createElement('canvas');surface.width=spec.width??1280;surface.height=spec.height??720;const instance=await createRenderer(surface,{host,template:spec});if(typeof instance?.render!=='function')throw Error('Renderer must implement render(frame)');r={surface,instance};renderers.set(clip.id,r)} const evaluated=evaluateClip(studio,clip,timeline?time:clip.start/HZ+time); - const output=await r.instance.render({template:spec,time:evaluated.sourceTime,projectTime:time,nodes:evaluated.nodes,ports:evaluated.ports,host,clip}); + const mediaSourceTime=evaluateClip(studio,clip,timeline?mediaTime:clip.start/HZ+mediaTime).sourceTime; + const output=await r.instance.render({template:spec,time:evaluated.sourceTime,mediaTime:mediaSourceTime,projectTime:time,nodes:evaluated.nodes,ports:evaluated.ports,host,clip}); const image=await r.instance.capture?.()??output??r.surface; if(typeof image?.width!=='number'||typeof image?.height!=='number')throw Error('Renderer needs an image surface or capture() adapter'); ctx.save();const tr=clip.transform;ctx.globalAlpha=tr.opacity;ctx.translate(tr.x,tr.y);ctx.scale(tr.scale,tr.scale);ctx.drawImage(image,0,0,canvas.width,canvas.height); diff --git a/packages/runtime/editor.mjs b/packages/runtime/editor.mjs index 897f2cf..43b8756 100644 --- a/packages/runtime/editor.mjs +++ b/packages/runtime/editor.mjs @@ -33,7 +33,7 @@ export async function mount({templates,createRenderer,scene,binding,initial,medi const keySelection=event=>{if(scene&&selection&&(event.key==='Escape'||event.altKey&&event.key==='ArrowUp')){event.preventDefault();selectParent();}}; if(scene)document.addEventListener('keydown',keySelection); const fail=e=>{$('#status').textContent=e.message;playing=false;audio.stop();$('#play').textContent='Play'}; - function draw(){selectionVersion++;const hadSelection=selection!==null;selection=null;if(hadSelection)refresh();const at=time,mode=timeline,id=selected;return renderer.render(studio,at,{selected:id,timeline:mode,playing,...(scene?{pass}:{})})} + function draw({mediaTime}={}){selectionVersion++;const hadSelection=selection!==null;selection=null;if(hadSelection)refresh();const at=time,mode=timeline,id=selected;return renderer.render(studio,at,{selected:id,timeline:mode,playing,mediaTime,...(scene?{pass}:{})})} function context(){return {...studio.capabilities(selected),baseRevision:persistence?revision:studio.revision,...(scene?{selection,objects:objectRows(),capture:{kind:'dom',selector:'#screen'}}:{})}} function refresh(){ if(!studio.doc.clips.some(c=>c.id===selected))selected=studio.doc.clips[0]?.id; @@ -73,5 +73,5 @@ export async function mount({templates,createRenderer,scene,binding,initial,medi $('#open').onchange=async e=>{try{studio=Studio.restore(await e.target.files[0].text(),templates,binding);refresh();await draw()}catch(e){fail(e)}}; $('#apply').onclick=()=>{try{const p=JSON.parse($('#proposal').value);edit(p.command,p.baseRevision,'model').catch(fail)}catch(e){fail(e)}}; async function loop(now){if(disposed)return;if(playing){try{time=(time+Math.max(0,Math.min(.1,(now-last)/1000)))%duration();$('#seek').value=time;await draw();let s=studio,t=time;if(!timeline){s=Object.create(studio);s.doc={...studio.doc,clips:[{...clip(),start:0}]}}if(playing)await audio.update(s,t,true);else audio.stop()}catch(e){fail(e)}}last=now;requestAnimationFrame(loop)}requestAnimationFrame(loop); - refresh();await draw();window.editableframes=window.editableframe={ready:true,get studio(){return studio},get selected(){return selected},templates,binding,context,selectObject,selectParent,select(id){selected=studio.doc.clips.find(c=>c.template===id||c.id===id)?.id??selected;time=0;playing=false;audio.stop();refresh();return draw()},async seek(t,options={}){playing=false;audio.stop();time=t;timeline=options.timeline??timeline;if(options.pass!==undefined){if(!scene&&options.pass!=='beauty')throw Error('Only renderer scenes draw control passes');pass=options.pass;}await draw()},edit,undo:()=>change('undo'),redo:()=>change('redo'),serialize:()=>studio.serialize(),captureTarget:scene?{kind:'dom',selector:'#screen'}:{kind:'canvas',selector:'#screen'},png:()=>{if(scene)throw Error('This renderer uses DOM-root capture; screenshot captureTarget after seek');return canvas.toDataURL('image/png')} ,stats:()=>({...host.stats(),audio:audio.stats()}),async dispose(){disposed=true;document.removeEventListener('keydown',keySelection);await audio.dispose();await renderer.dispose()}}; + refresh();await draw();window.editableframes=window.editableframe={ready:true,get studio(){return studio},get selected(){return selected},templates,binding,context,selectObject,selectParent,select(id){selected=studio.doc.clips.find(c=>c.template===id||c.id===id)?.id??selected;time=0;playing=false;audio.stop();refresh();return draw()},async seek(t,options={}){playing=false;audio.stop();time=t;timeline=options.timeline??timeline;if(options.pass!==undefined){if(!scene&&options.pass!=='beauty')throw Error('Only renderer scenes draw control passes');pass=options.pass;}await draw({mediaTime:options.mediaTime})},edit,undo:()=>change('undo'),redo:()=>change('redo'),serialize:()=>studio.serialize(),captureTarget:scene?{kind:'dom',selector:'#screen'}:{kind:'canvas',selector:'#screen'},png:()=>{if(scene)throw Error('This renderer uses DOM-root capture; screenshot captureTarget after seek');return canvas.toDataURL('image/png')} ,stats:()=>({...host.stats(),audio:audio.stats()}),async dispose(){disposed=true;document.removeEventListener('keydown',keySelection);await audio.dispose();await renderer.dispose()}}; } diff --git a/packages/runtime/renderer-compositor.mjs b/packages/runtime/renderer-compositor.mjs index 03bce24..40ee079 100644 --- a/packages/runtime/renderer-compositor.mjs +++ b/packages/runtime/renderer-compositor.mjs @@ -8,10 +8,10 @@ export function createRendererCompositor(stage,{scene,templates,services={},capt const residents=new Map();let chain=Promise.resolve(),disposed=false,lastRequest,renderVersion=0,pickVersion=0,activeJob,pendingJob,disposal; stage.style.position=capture?'fixed':'relative';stage.style.overflow='hidden'; if(capture){stage.style.left='0';stage.style.top='0';stage.style.zIndex='2147483647';} - async function draw(studio,time,{selected,timeline=false,playing=false,pass='beauty'}={}) { + async function draw(studio,time,{selected,timeline=false,playing=false,pass='beauty',mediaTime=time}={}) { if(disposed)throw Error('Compositor disposed'); if(pass!=='beauty'&&!(scene.passes??[]).includes(pass))throw Error(`This scene does not declare a ${pass} pass`); - if(!Number.isFinite(time)||time<0)throw Error('Invalid source time'); + if(!Number.isFinite(time)||time<0||!Number.isFinite(mediaTime)||mediaTime<0)throw Error('Invalid source time'); const clips=timeline?studio.doc.clips.filter(c=>time>=c.start/HZ&&time<(c.start+c.duration)/HZ):[studio.clip(selected)]; const active=new Set(clips.map(c=>c.id)); for(const [id,r] of residents)if(!active.has(id)){await r.instance.dispose();r.layer.remove();residents.delete(id);} @@ -32,7 +32,8 @@ export function createRendererCompositor(stage,{scene,templates,services={},capt const tr=clip.transform;resident.layer.style.opacity=String(tr.opacity);resident.layer.style.transform=`translate(${tr.x/width*100}%,${tr.y/height*100}%) scale(${tr.scale})`; resident.root.style.transform=`scale(${stage.clientWidth/scene.width},${stage.clientHeight/scene.height})`; const evaluated=evaluateClip(studio,clip,timeline?time:clip.start/HZ+time); - const clock={frame:evaluated.sourceTime*scene.fps,fps:scene.fps,frameRate:rendererFrameRate(scene),width:scene.width,height:scene.height,durationInFrames:scene.durationInFrames,capture,playing,pass}; + const mediaSourceTime=evaluateClip(studio,clip,timeline?mediaTime:clip.start/HZ+mediaTime).sourceTime; + const clock={frame:evaluated.sourceTime*scene.fps,mediaTime:mediaSourceTime,fps:scene.fps,frameRate:rendererFrameRate(scene),width:scene.width,height:scene.height,durationInFrames:scene.durationInFrames,capture,playing,pass}; resident.clock=clock; try {await resident.instance.render(clock,sampledRendererProps(scene,templates[clip.template],clip,evaluated.nodes));} catch(error){residents.delete(clip.id);resident.layer.remove();await resident.instance.dispose().catch(()=>{});throw error;} diff --git a/packages/three/plate.mjs b/packages/three/plate.mjs index 9fb49b0..21285c3 100644 --- a/packages/three/plate.mjs +++ b/packages/three/plate.mjs @@ -154,7 +154,7 @@ export function renderPass(renderer, scene, camera, pass, {ids = [], encoding} = const passId = object => { for (let o = object; o; o = o.parent) if (typeof o.userData?.passId === 'string') return o.userData.passId; return object.name; }; const use = (mesh, material) => { swapped.push([mesh, mesh.material]); mesh.material = material; }; try { - scene.background = null; renderer.setClearColor(0x000000, 0); + scene.background = null; scene.overrideMaterial = null; renderer.setClearColor(0x000000, 0); const shared = pass === 'clay' ? new T.MeshStandardMaterial({color: 0xb8b8b8, roughness: 0.85, metalness: 0}) : pass === 'normal' ? new T.MeshNormalMaterial() : pass === 'matte' ? rawColor([1, 1, 1]) @@ -168,7 +168,7 @@ export function renderPass(renderer, scene, camera, pass, {ids = [], encoding} = if (object.userData.plateHelper || object.userData.passExclude || !object.isMesh) { if (object.visible) { hidden.push(object); object.visible = false; } return; } if (shared) { use(object, shared); return; } const index = ids.indexOf(passId(object)); - if (index < 0) { hidden.push(object); object.visible = false; return; } + if (index < 0) { if (object.visible) { hidden.push(object); object.visible = false; } return; } if (!byId.has(index)) { const material = rawColor(idColor(index).map(v => v / 255)); byId.set(index, material); made.push(material); } use(object, byId.get(index)); }); diff --git a/scripts/render.mjs b/scripts/render.mjs index 4142f80..ee14bb4 100644 --- a/scripts/render.mjs +++ b/scripts/render.mjs @@ -31,17 +31,21 @@ export async function render(dir,output,{fps,frames,format,background='#101922', const times=shutter?shutterSamples(frame,shutter):[frame]; for(let sample=0;samplewindow.editableframe.seek(t,{timeline:true,pass}),[seconds,pass]);bytes=await page.locator('#screen').screenshot({omitBackground:true,timeout:30000});} - else{const png=await page.evaluate(async t=>{await window.editableframe.seek(t,{timeline:true});return window.editableframe.png()},seconds);bytes=Buffer.from(png.split(',')[1],'base64');} + // Footage already has a shutter. Keep its output-frame time separate from + // code's sub-frame sample, including through source trims and retiming. + const mediaTime=frame*rate.den/rate.num; + if(d.kind==='renderer'){await page.evaluate(([t,pass,mediaTime])=>window.editableframe.seek(t,{timeline:true,pass,mediaTime}),[seconds,pass,mediaTime]);bytes=await page.locator('#screen').screenshot({omitBackground:true,timeout:30000});} + else{const png=await page.evaluate(async ([t,mediaTime])=>{await window.editableframe.seek(t,{timeline:true,mediaTime});return window.editableframe.png()},[seconds,mediaTime]);bytes=Buffer.from(png.split(',')[1],'base64');} await fs.writeFile(shutter?path.join(sampleDir,String(frame*shutter.samples+sample+1).padStart(8,'0')+'.png'):path.join(frameDir,String(frame+1).padStart(6,'0')+'.png'),bytes); } onProgress({phase:'frames',frame:frame+1,total:count,progress:(frame+1)/count}); } if(shutter){ // Average each frame's samples as premultiplied colour, so a half-covered pixel keeps its hue instead of darkening. + // Float intermediates avoid losing a code value even when every sample is identical. // The mean is taken on encoded (display) values, not linear light. onProgress({phase:'shutter',progress:0}); - await run(ffmpeg(),['-v','error','-n','-framerate','1','-i',path.join(sampleDir,'%08d.png'),'-vf',`format=gbrap,premultiply=inplace=1,tmix=frames=${shutter.samples},select='not(mod(n+1\\,${shutter.samples}))',unpremultiply=inplace=1,format=rgba`,'-fps_mode','passthrough','-frames:v',String(count),path.join(frameDir,'%06d.png')],{signal,timeout:600000}); + await run(ffmpeg(),['-v','error','-n','-framerate','1','-i',path.join(sampleDir,'%08d.png'),'-vf',`format=gbrapf32le,premultiply=inplace=1,tmix=frames=${shutter.samples},select='not(mod(n+1\\,${shutter.samples}))',unpremultiply=inplace=1,format=rgba`,'-fps_mode','passthrough','-frames:v',String(count),path.join(frameDir,'%06d.png')],{signal,timeout:600000}); if((await fs.readdir(frameDir)).length!==count)throw Error('Motion blur produced the wrong number of frames'); await fs.rm(sampleDir,{recursive:true,force:true}); } diff --git a/skills/editableframes/SKILL.md b/skills/editableframes/SKILL.md index eb0f0b2..d88cdda 100644 --- a/skills/editableframes/SKILL.md +++ b/skills/editableframes/SKILL.md @@ -25,7 +25,7 @@ The bundled `studio` has effect and creative studies plus the device library. St ## Code inside footage -When a shot mixes code with filmed or generated video, let footage supply what only has to look real (people, places, light) and code supply what must be exactly right (the product, labels, prices, interfaces, captions). Read [references/hybrid.md](references/hybrid.md) before authoring. `init --hybrid` creates a working example. A matte, depth map, track or camera path is an input made by another tool: import it with `asset-add --role --of `, never invent one, and say so when a shot needs one that is missing. Replacing the footage invalidates data derived from it. Sample anything locked to the footage at `conformSeconds(seconds, plate.frameRate)`, and render the project at the footage's frame rate. `render --pass ` exports a declared control pass; `render --motion-blur 180` adds a shutter. Light and depth scale are estimates: expose them as controls and check real frames. +When a shot mixes code with filmed or generated video, let footage supply what only has to look real (people, places, light) and code supply what must be exactly right (the product, labels, prices, interfaces, captions). Read [references/hybrid.md](references/hybrid.md) before authoring. `init --hybrid` creates a working example. A matte, depth map, track or camera path is an input made by another tool: import it with `asset-add --role --of `, never invent one, and say so when a shot needs one that is missing. Replacing the footage invalidates data derived from it. Sample anything locked to the footage at `conformSeconds(clock.mediaTime ?? clock.frame / clock.fps, plate.frameRate)`, and render the project at the footage's frame rate. `render --pass ` exports a declared control pass; `render --motion-blur 180` adds a shutter. Light and depth scale are estimates: expose them as controls and check real frames. ## Spatial objects diff --git a/skills/editableframes/references/hybrid.md b/skills/editableframes/references/hybrid.md index 5320989..a74fb42 100644 --- a/skills/editableframes/references/hybrid.md +++ b/skills/editableframes/references/hybrid.md @@ -164,7 +164,7 @@ Three helpers guess from a single view. Expose their results as controls. Video models emit a fixed rate: commonly 24 fps, sometimes 16 or 30. Two things follow. -- Anything locked to the footage should move on the footage's frame grid. `conformSeconds(seconds, plate.frameRate)` gives the time of the plate frame on screen; sample tracks, mattes and depth at that time. Otherwise a pinned element slides against the picture between plate frames. +- Anything locked to the footage should move on the footage's frame grid. Use `seconds = clock.mediaTime ?? clock.frame / clock.fps` for footage and its derived data: this clock stays at the output frame during shutter sampling. `conformSeconds(seconds, plate.frameRate)` gives the time of the plate frame on screen; sample tracks, mattes and depth at that time. Otherwise a pinned element slides against the picture between plate frames. - A plate inside a timeline of another rate repeats frames unevenly. `cadence({num: 24, den: 1}, {num: 30, den: 1})` reports the pattern `2,1,1,1`, which is visible as judder on any move. Render the project at the plate's rate, or interpolate the plate before importing it. ## Export diff --git a/skills/editableframes/references/renderer.md b/skills/editableframes/references/renderer.md index 13c0966..daa2185 100644 --- a/skills/editableframes/references/renderer.md +++ b/skills/editableframes/references/renderer.md @@ -177,3 +177,15 @@ These tests do not establish a native application's integration or agent reliabi For optional object parents, locked/hidden policy and bounded direct-manipulation proposals, read [the interaction contract](interaction-contract.md). The renderer hook returns sparse control values; a host owns one atomic commit and cancellation. + +### Footage during shutter sampling + +`clock.mediaTime` is source seconds at the output frame's time, after the clip's +trim and playback rate. Without a shutter it equals `clock.frame / clock.fps`. +During motion blur, `clock.frame` advances through the shutter samples while +`clock.mediaTime` stays fixed. Use `clock.mediaTime ?? clock.frame / clock.fps` +for footage, mattes, depth and tracks attached to it; use `clock.frame` for code +animation. `mediaFrame(id, seconds)` still honors the exact time requested, so +custom scenes must choose the appropriate clock. Legacy renderers receive +`mediaTime` alongside `time`; pass `mediaTime` to `host.portFrame` for footage. +The media starter uses this clock too; authored media offsets remain explicit. diff --git a/templates/hybrid/clip.mjs b/templates/hybrid/clip.mjs index 78ee980..2e8a967 100644 --- a/templates/hybrid/clip.mjs +++ b/templates/hybrid/clip.mjs @@ -76,7 +76,7 @@ export default defineRenderer({ async render(clock){ const pass=clock.pass??'beauty',seconds=clock.frame/clock.fps; // Anything locked to the footage moves on the footage's own frame grid. - const plateTime=conformSeconds(Math.min(seconds,plate.duration-1e-6),plate.frameRate); + const plateTime=conformSeconds(Math.min(clock.mediaTime??seconds,plate.duration-1e-6),plate.frameRate); const [plateImage,matteImage,depthImage]=await Promise.all([plateTime,plateTime,plateTime].map((t,i)=>frames.load(mediaFrame(['plate',matteId,depthId][i],t)))); paintLabel(); can.position.set(props.offset,-.12,-props.distance);can.rotation.y=seconds*.9+.6; diff --git a/templates/media/clip.mjs b/templates/media/clip.mjs index 8172d45..7fb3e53 100644 --- a/templates/media/clip.mjs +++ b/templates/media/clip.mjs @@ -2,12 +2,12 @@ export const template={id:'media-explainer',title:'Signals / editable media stud nodes:[{id:'design',type:'design',label:'Art direction',props:{headline:'THE SIGNAL IS MOVING',accent:'#9ceaac',transparent:true},keys:{}},{id:'presenter',type:'media',label:'Embedded video + audio',props:{asset:'demo',gain:.3,muted:false,sourceIn:0,rate:1,offset:0,end:'hold',size:150},keys:{}}], schemas:{design:{headline:{type:'text',maxLength:50,label:'Headline'},accent:{type:'color',label:'Accent'},transparent:{type:'boolean',label:'Transparent background'}},media:{asset:{type:'text',maxLength:80,label:'Asset ID'},gain:{type:'number',min:0,max:1,label:'Voice volume',keyframe:false},muted:{type:'boolean',label:'Mute voice'},sourceIn:{type:'number',min:0,max:3,label:'Video in point',keyframe:false},rate:{type:'number',min:.5,max:2,label:'Video speed',keyframe:false},offset:{type:'number',min:0,max:3,label:'Start delay',keyframe:false},end:{type:'enum',values:['hold','loop','transparent'],label:'After video ends'},size:{type:'number',min:80,max:190,label:'Video size'}}}, media:{presenter:{anchor:'presenter',bindings:{asset:'asset',gain:'gain',muted:'muted',sourceIn:'sourceIn',rate:'rate',offset:'offset',end:'end'}}}}; -export function createRenderer(canvas){canvas.width=960;canvas.height=540;const c=canvas.getContext('2d',{alpha:true});return {async render({time,nodes,ports,host}){ +export function createRenderer(canvas){canvas.width=960;canvas.height=540;const c=canvas.getContext('2d',{alpha:true});return {async render({time,mediaTime=time,nodes,ports,host}){ const p=nodes.find(n=>n.id==='design').props,m=nodes.find(n=>n.id==='presenter').props;c.clearRect(0,0,960,540); if(!p.transparent){c.fillStyle='#12252d';c.fillRect(0,0,960,540)} c.fillStyle='#18333fe6';c.beginPath();c.roundRect(32,32,896,476,28);c.fill();c.fillStyle=p.accent;c.font='12px sans-serif';c.fillText('EDITABLEFRAMES / VIDEO + AUDIO + ALPHA',64, 70);c.fillStyle='#f3f7ee';c.font='bold 32px sans-serif';c.fillText(p.headline,64,124); c.strokeStyle='#365461';c.lineWidth=1;for(let i=0;i<4;i++){c.beginPath();c.moveTo(64,210+i*65);c.lineTo(570,210+i*65);c.stroke()} c.strokeStyle=p.accent;c.lineWidth=4;c.beginPath();for(let i=0;i<110;i++){const x=64+i*4.6,y=385-i*1.6-Math.sin(i*.16-time*1.7)*28;i?c.lineTo(x,y):c.moveTo(x,y)}c.stroke(); - const frame=await host.portFrame(ports.presenter,time);if(frame){c.save();c.beginPath();c.arc(744,296,m.size,0,Math.PI*2);c.clip();c.drawImage(frame,744-m.size,296-m.size,m.size*2,m.size*2);c.restore()} + const frame=await host.portFrame(ports.presenter,mediaTime);if(frame){c.save();c.beginPath();c.arc(744,296,m.size,0,Math.PI*2);c.clip();c.drawImage(frame,744-m.size,296-m.size,m.size*2,m.size*2);c.restore()} c.fillStyle='#d1dfde';c.font='14px sans-serif';c.fillText('Original test footage • replace Asset ID with your presenter',64,471);c.fillStyle=p.accent;c.fillText(time.toFixed(2)+' s',828,471);return canvas; },dispose(){}}} diff --git a/tests/hybrid-integration.mjs b/tests/hybrid-integration.mjs index 710bd3e..76b2a22 100644 --- a/tests/hybrid-integration.mjs +++ b/tests/hybrid-integration.mjs @@ -118,6 +118,13 @@ try{ checks.push('Several derived assets can be added before one rebind, as docs/hybrid-scenes.md shows'); // --- Motion blur ------------------------------------------------------------------ + // The bundled hybrid scene must freeze its footage and attached pin too. + const hybridSoft=path.join(tmp,'hybrid-shutter'); + await render(seqDir,hybridSoft,{format:'png',frames:3,motionBlur:{angle:180,samples:8}}); + const hybridSharp=await pixels(frameFile(beauty,2)),hybridBlurred=await pixels(frameFile(hybridSoft,2)); + assert.ok(hybridSharp.data.subarray(10*W*4,11*W*4).equals(hybridBlurred.data.subarray(10*W*4,11*W*4)),'the moving foreground stays on one footage frame'); + for(let y=50;y<140;y++)assert.ok(hybridSharp.data.subarray((y*W+430)*4,(y*W+620)*4).equals(hybridBlurred.data.subarray((y*W+430)*4,(y*W+620)*4)),'the screen pin stays locked to the fixed plate'); + checks.push('The hybrid starter keeps footage and its tracked card fixed during shutter sampling'); const blurDir=path.join(tmp,'blur-clip');await init(blurDir,{template:'renderer'}); await fs.writeFile(path.join(blurDir,'clip.mjs'),`import {defineRenderer} from 'editableframes/renderer';export default defineRenderer({id:'mover',renderer:'dom',width:160,height:90,fps:24,durationInFrames:24,async create({root}){const box=document.createElement('div');box.style.cssText='position:absolute;top:30px;width:30px;height:30px;background:#00ff00';root.append(box);return {render(clock){box.style.left=(clock.frame*20)+'px';},dispose(){box.remove();}};}});`); await rebind(blurDir,{reset:true}); @@ -132,5 +139,30 @@ try{ assert.equal(soft.filter(p=>p[3]>0).length-sharp.filter(p=>p[3]>0).length,8); assert.ok(partial.every(p=>p[1]>=245&&p[0]<=10&&p[2]<=10),'a half-covered pixel keeps the pure colour: samples are averaged premultiplied'); checks.push('Shutter motion blur averages sub-frame samples with correct edge colour'); + + // A real moving plate stays on its output frame, while code still smears. + // Use the same fixture at a tiny angle too: previously any positive angle + // mixed the previous/current plate 50/50, regardless of the shutter width. + const plateFile=path.join(tmp,'moving-plate.mp4'); + await run(ffmpeg(),['-v','error','-f','lavfi','-i','testsrc2=size=160x90:rate=24:duration=1','-c:v','libx264','-qp','0',plateFile]); + await importAsset(blurDir,'moving-plate',plateFile); + await fs.writeFile(path.join(blurDir,'clip.mjs'),`import {defineRenderer} from 'editableframes/renderer'; + import {createFrameLoader} from 'editableframes/plate'; + export default defineRenderer({id:'mover',renderer:'dom',width:160,height:90,fps:24,durationInFrames:24,async create({root,mediaFrame}){ + const canvas=document.createElement('canvas');canvas.width=160;canvas.height=90;root.append(canvas);const ctx=canvas.getContext('2d'),loader=createFrameLoader(); + const box=document.createElement('div');box.style.cssText='position:absolute;top:30px;width:30px;height:30px;background:#00ff00';root.append(box); + return {async render(clock){ctx.drawImage(await loader.load(mediaFrame('moving-plate',clock.mediaTime)),0,0);box.style.left=(clock.frame*20)+'px';},dispose(){loader.dispose();canvas.remove();box.remove();}};}});`); + await rebind(blurDir,{reset:true}); + const footageSharp=path.join(tmp,'footage-sharp');await render(blurDir,footageSharp,{format:'png',frames:4}); + const decode=folder=>run(ffmpeg(),['-v','error','-i',frameFile(folder,2),'-pix_fmt','rgba','-f','rawvideo','-']); + const sharpPixels=await decode(footageSharp); + for(const angle of [180,1]){ + const folder=path.join(tmp,'footage-blur-'+angle);await render(blurDir,folder,{format:'png',frames:4,motionBlur:{angle,samples:8}}); + const blurred=await decode(folder); + // Every pixel outside the code's rows must be byte-identical to the sharp export. + for(let y=0;y<90;y++)if(y<30||y>=60)assert.ok(blurred.subarray(y*160*4,(y+1)*160*4).equals(sharpPixels.subarray(y*160*4,(y+1)*160*4)),`footage changed at row ${y}, shutter ${angle}`); + if(angle===180)assert.ok(!blurred.subarray(40*160*4,50*160*4).equals(sharpPixels.subarray(40*160*4,50*160*4)),'code still blurs over the fixed plate'); + } + checks.push('Shutter samples hold actual footage fixed while code blurs'); console.log(JSON.stringify({checks},null,2)); }finally{await fs.rm(tmp,{recursive:true,force:true});} diff --git a/tests/plate.test.mjs b/tests/plate.test.mjs index eff762b..7427607 100644 --- a/tests/plate.test.mjs +++ b/tests/plate.test.mjs @@ -182,3 +182,37 @@ test('the plate panorama fills both halves: as shot in front, mirrored behind', paintPlatePanorama(context, {}, 256); assert.deepEqual(draws, [[0, 128, 1], [128, 256, -1]]); }); + +test('control passes restore visibility and override materials, even when rendering throws', async () => { + const T = await import('three'); + const {renderPass} = await import('../packages/three/plate.mjs'); + for (const fail of [false, true]) for (const pass of ['id', 'matte', 'depth', 'normal', 'clay']) { + const scene = new T.Scene(), camera = new T.PerspectiveCamera(); + const original = new T.MeshBasicMaterial(), override = new T.MeshBasicMaterial({color: 0xff0000}); + scene.overrideMaterial = override; + const visible = new T.Mesh(new T.BoxGeometry(), original); visible.name = 'included'; + const hidden = new T.Mesh(new T.BoxGeometry(), original); hidden.visible = false; + const excluded = new T.Mesh(new T.BoxGeometry(), original); + scene.add(visible, hidden, excluded); + let calls = 0; + const renderer = {toneMapping: T.NeutralToneMapping, getClearColor: c => c.set(0x123456), getClearAlpha: () => .5, setClearColor() {}, + render(s) { + calls++; + assert.equal(s.overrideMaterial, null, 'the pass material must reach Three.js'); + assert.notEqual(visible.material, original); + assert.equal(hidden.visible, false); + if (pass === 'id') assert.equal(excluded.visible, false); + if (fail) throw Error('GPU failure'); + }}; + const draw = () => renderPass(renderer, scene, camera, pass, {ids: ['included']}); + if (fail) assert.throws(draw, /GPU failure/); else draw(); + assert.equal(calls, 1); + assert.equal(hidden.visible, false, 'an invisible mesh stays invisible after the pass'); + assert.equal(excluded.visible, true); + assert.equal(scene.overrideMaterial, override); + assert.equal(visible.material, original); + assert.equal(renderer.toneMapping, T.NeutralToneMapping); + for (const mesh of [visible, hidden, excluded]) mesh.geometry.dispose(); + original.dispose(); override.dispose(); + } +}); diff --git a/tests/renderer-scheduling.test.mjs b/tests/renderer-scheduling.test.mjs index 76c18ee..fe53f50 100644 --- a/tests/renderer-scheduling.test.mjs +++ b/tests/renderer-scheduling.test.mjs @@ -43,3 +43,38 @@ test('a failed resident is removed and retries create a new instance',async()=>{ await compositor.render(studio,0,options);await assert.rejects(compositor.render(studio,1/30,options),/frame failed/); assert.equal(stage.children.length,0);assert.equal(disposed,1);await compositor.render(studio,2/30,options);assert.equal(created,2);assert.equal(stage.children.length,1);await compositor.dispose();assert.equal(disposed,2); }); + +test('shutter samples carry a fixed media clock through trims, retiming and backward seeks', async () => { + const clocks=[]; + const {compositor,studio,options}=setup({capture:true,render:clock=>clocks.push(clock)}); + const clip=studio.doc.clips[0]; + // Clip offsets use document ticks; evaluate both clocks through the same clip mapping. + const {HZ}=await import('../packages/core/index.mjs'); + clip.start=HZ;clip.sourceIn=HZ/2;clip.rate=2; + for(const time of [1.49,1.51,1.49])await compositor.render(studio,time,{...options,timeline:true,mediaTime:1.5}); + assert.deepEqual(clocks.map(c=>c.mediaTime),[1.5,1.5,1.5]); + assert.ok(clocks[0].frame { + const {createCompositor}=await import('../packages/runtime/compositor.mjs'); + const {HZ}=await import('../packages/core/index.mjs'); + const scene=defineRenderer({id:'legacy-clock',renderer:'dom',width:320,height:180,fps:30,durationInFrames:90,create(){}}); + const d=normalizeClipModule({default:scene}),studio=new Studio(d.templates); + const clip=studio.make(scene.id);studio.doc.clips=[clip];clip.start=HZ;clip.sourceIn=HZ/2;clip.rate=2; + const context={clearRect(){},save(){},restore(){},translate(){},scale(){},drawImage(){}}; + const canvas={getContext:()=>context},calls=[],clocks=[],host={portFrame:(port,time)=>calls.push(time)}; + const compositor=createCompositor(canvas,{templates:d.templates,host,createRenderer(surface,{host:initialHost}){ + return {render(frame){assert.equal(frame.host,initialHost);clocks.push(frame); + frame.host.portFrame(null,frame.mediaTime+.25);return surface;}}; + }}); + for(const time of [1.49,1.51,1.49])await compositor.render(studio,time,{timeline:true,mediaTime:1.5}); + assert.deepEqual(calls,[1.75,1.75,1.75]);assert.ok(clocks[0].time Date: Wed, 11 Nov 2026 15:26:02 +0800 Subject: [PATCH 11/49] Plan reliable occlusion, surface wrapping and kinetic typography --- docs/hybrid-compositing-plan.md | 101 ++++++++++++++++++++++++++++++++ docs/hybrid-scenes.md | 24 ++++---- 2 files changed, 114 insertions(+), 11 deletions(-) create mode 100644 docs/hybrid-compositing-plan.md diff --git a/docs/hybrid-compositing-plan.md b/docs/hybrid-compositing-plan.md new file mode 100644 index 0000000..752b539 --- /dev/null +++ b/docs/hybrid-compositing-plan.md @@ -0,0 +1,101 @@ +# Reliable hybrid compositing and motion design + +Status: proposed next work, 2026-11-11. This is a design and acceptance plan, not an implemented API. It supersedes any inference that a successful render or a few attractive frames establish a usable hybrid clip. Existing primitives and their tested scope remain documented in [hybrid-scenes.md](hybrid-scenes.md). + +## What the failed shots teach us + +| Observed failure | Diagnosis supported by the authored scenes | Required correction | +|---|---|---| +| A phone screen paints over a thumb, leaving a detached skin patch | The supplied matte loses the hand: foreground area drops from 12.44% at frame 59 to 0.18% at frame 60 and stays below 0.25% through frame 70. This is a missing foreground input, not just a rough edge. | Inspect plate, matte and composite together across the entire crossing; correct the subject track and correspondence, then refine its alpha edges. | +| Menu text crosses a person's forehead | The menu scene has no subject matte. Its footer is clipped at the board's lower boundary in the inspected frames. Screen blending preserves board texture but cannot infer who is in front. | Fit the entire animated layout within the actual surface, then clip it; protect the person with a foreground holdout. | +| An opaque price card erases the person's hair/head | There is no foreground holdout. Good planar tracking cannot fix layer order. | Treat all intersecting foreground subjects as required inputs. A plausible-looking board is not a passing result. | +| A hand appears sliced through an added can | The example inserts a second can at an offset from the tracked original. Relative depth with hand-tuned near/far is being used as if it were registered scene geometry. | First distinguish insertion from reskinning. For a hand known to be in front, use its coherent alpha as the foreground constraint. | +| A small labeled can sits over a larger generated can | Generating a world from a clay still did not preserve the product silhouette or proportions. | Reject the take for exact-object recomposition, or solve an explicit replacement workflow including removal of the original. Do not hide the mismatch with a smaller overlay. | + +These clips fail final-quality acceptance. The phone's 121 matte frames were measured using decoded grayscale coverage above 127/255, with zero-based frame indices. The other failures were verified in sampled frames and the authored scenes, not an exhaustive pixel audit. Earlier tracking numbers remain measurements of tracking, not evidence of correct occlusion, placement, materials or whole-shot quality. No new implementation or corrected full-length video is claimed by this plan. + +## Architecture decision: analyze, correct, cache, then render + +Keep the core model-neutral. A host or optional analysis package produces versioned masks, tracks, surface mappings and diagnostic reports. An author can correct them. Preview and export consume the same immutable artifacts. No model runs implicitly inside `render(clock)` and no model weights become a mandatory library dependency. + +Real-time compositing and real-time inference are different budgets. GPU/CPU acceleration can make preparation faster and enable interactive draft masks; it does not supply reliable geometry or physics by itself. Start with prepared per-frame data and GPU composition. Offer live draft inference only after profiling actual devices, with conspicuous provisional results and explicit promotion to a frozen render artifact. + +Bilibili provides a concrete live-inference precedent: its 2024 web.dev case study describes on-device MediaPipe Selfie Segmenter, worker/offscreen processing, reduced-resolution masks and CSS `mask-image` for comments behind people. Its older W3C presentation also describes mask-based rendering. These demonstrate a person-silhouette feature, not hair-level export alpha or collision simulation. Our choice to freeze reviewed masks for export is an architectural recommendation, not a claim that Bilibili precomputes everything. These are published primary sources; no authenticated production reverse engineering was performed. [Bilibili case study](https://web.dev/case-studies/bilibili-web-ai-improvements), [W3C presentation](https://www.w3.org/2019/03/23-chinese-web-zhaoxin-bilibili.pdf) + +### Proposed prepared-data contract + +Extend the existing derived-asset relationship with a versioned manifest. Names below are proposed fields, not accepted CLI flags: + +- Identity: source content digest, exact decoded dimensions/orientation/crop, frame count, rational time base and per-frame presentation timestamps; subject/surface IDs; model/checkpoint digest, preprocessing version and correction revision. +- Semantics: `subject-alpha`, `foreground-color` where available, `surface-coverage`, `surface-map`, `depth`, `confidence` and `validity`. A binary segmentation probability is not silently relabeled as an alpha matte. Foreground alpha is white for foreground; linear alpha/data is not color-managed as display RGB. +- Time: explicit source-frame correspondence and valid ranges. Plate, mask and track are fetched through one source-frame mapping, including trim, speed and reverse. Equal duration/FPS/count alone does not establish correspondence. +- Storage: bounded, chunked cache; stream/prefetch under the existing decoded-memory budget. Use lossless data for final alpha and sufficiently precise depth/maps; lossy MP4 is diagnostic input, not the canonical final data format. +- Failure: missing, stale, out-of-range, invalid or wrong-sized data fails final validation. Draft rendering can show the original plate plus a diagnostic. Never silently replace a missing holdout with an all-background mask, repeat a moving matte's last frame, or stretch a short matte to fit. + +Changing source bytes, orientation, crop or interpretation invalidates dependent analysis. Changing only the timeline edit map reuses analysis through an explicitly verified remap. Text edits reuse approved geometry/alpha, but invalidate content-dependent layout and occlusion review if the visible region changes. + +## Foreground preservation and layer order + +Start with explicit relationships such as `person in front of title` and `hand in front of screen`. Scope a holdout to the affected layer/group; a hand protecting the phone need not hide a separate foreground caption. Validate cycles and contradictory depth/ordering constraints. Occlusion state can change over a shot, but that change needs a tracked spatial relationship or an authored interval, not unrelated per-pixel guesses. + +For known foreground crossings, subject alpha owns the silhouette. Use temporally consistent, calibrated depth for ordering genuinely interleaved objects; raw per-frame normalized monocular depth must not slice fingers or faces. Depth confidence is separate from alpha confidence. One global foreground matte also cannot solve a hand that is simultaneously behind one object and in front of another. + +The preparation workflow is prompted video segmentation → tracked identity → positive/negative corrections at difficult frames → temporal propagation → alpha refinement around hair/fingers/motion blur → review. Track through disappearance/reappearance; reset temporal state at cuts. Sudden area collapse triggers a review/re-seeding candidate, not blind automatic acceptance: genuine occlusion or leaving the frame can also shrink a subject. Preserve legitimate holes between fingers and never assume every disconnected component is an error. Do not blur consecutive masks indiscriminately: that creates lag and ghost hands. + +Composite with explicit premultiplied-alpha and color-space conventions. Opaque protected interiors must preserve source pixels. At soft edges, copying `alpha × original plate` over a new background can retain the old background in hair and create a double edge. High-quality edge replacement requires decontaminated foreground color or a credible original-background estimate; document the approximation when those are absent. A soft mask alone does not prove a clean composite. + +Add diagnostic views for source, subject alpha, surface coverage, correspondence, confidence, final composite and difference inside protected regions. Provide brush/polygon corrections and an event-range view. Start with people in front of a title/board, then a separately gated close-up hand correction workflow; a portrait matting model is not proven on isolated fingers. + +## Four different placement operations + +1. **Planar insert:** board or phone. Render animated artwork in surface coordinates, project it with the track, clip to surface coverage, then apply foreground visibility. Explicitly exclude the bezel and check the full animated text bounds. +2. **Reskin an existing rigid curved object:** select the original can, identify its body/silhouette and cap, estimate its pose/axis/radius and camera relationship, and fit a cylindrical UV or mesh mapping over time. Map the editable label into that surface; preserve lids, highlights, existing silhouette and contact shadow where appropriate. Reapply hand visibility. A featureless cylinder has ambiguous rotation; allow an authored seam/pose constraint and mark unobservable ranges. +3. **Replace or insert a 3D object:** requires explicit camera/scale/contact placement and foreground ordering. If replacing an object whose silhouette changes, remove the old object's exposed pixels and recover newly revealed background. Clean-plate/inpainting work is separate, reviewed, and cannot be substituted by an extra mesh on top. Added objects need their own shadows/reflections; reskinning normally retains the original contact evidence. +4. **Deforming surface:** cloth/skin needs a tracked mesh, dense UV correspondence or an atlas with visibility and disocclusion handling. A homography or cylinder is not sufficient. Start with a short cloth patch and a correction/import path; leave arbitrary bodies and loose folds experimental until tested. + +No mask fixes an impossible placement: if the recorded hand sweeps through the volume of an inserted can, making the whole hand foreground only changes the visible contradiction. Move the insert to a collision-free location, choose another take, or regenerate blocking. Reskinning the existing can avoids creating that new volume. Preserving shading during a reskin also needs an appearance model: a simple multiply blend retains the old albedo and cannot freely change a dark label into a light one. Begin with a blank neutral can, fit a shading/specular residual, and document where exact material recovery is ambiguous. + +Existing tools demonstrate the video surface-editing route. Mocha Pro documents PowerMesh-driven inserts, grid warps and tracked motion blur. Layered Neural Atlases learns per-shot mappings/alpha to propagate an atlas edit; CoDeF fits a canonical field and temporal deformation. These are evidence for feasibility, not drop-in real-time browser solutions or licenses to copy proprietary engines. [Mocha](https://borisfx.com/products/mocha-pro/), [Neural Atlases](https://layered-neural-atlases.github.io/), [CoDeF](https://qiuyu96.github.io/CoDeF/) + +Lovart advertises texture generation and image editing. Its public page does not establish which model implements an observed wrap effect or that exact artwork can be transferred through video with temporal geometry guarantees. Use it as a visual reference, not an inferred backend architecture. [Lovart texture feature](https://www.lovart.ai/features/ai-3d-texture) + +## Motion design is part of acceptance + +Every authored example declares its attachment space and timing: screen-space graphic, surface-attached artwork, or world-space object with a camera. Surface-attached text inherits the observed perspective; world text requires a real solve or an explicitly labeled authored approximation. Static printed labels should remain attached naturally; expressive animation belongs in a reveal, digital display or surrounding title when the brief calls for it. + +Deliver editable examples covering: staggered word/character reveals with readable holds; masked wipes and line draws; spring-like scale/rotation settles; text-on-path/orbits; tracked perspective titles; and a foreground-aware headline passing behind a person. Include at least one 3D/extruded or shader-treated title. Expose timing, stagger, easing, amplitude, path, typography, palette and attachment controls without restricting arbitrary renderer code. + +All code motion is a deterministic function of explicit clip animation time and seeded parameters, with any source/timeline mapping authored explicitly. Analytic curves or baked simulation caches make reverse/random seeks reproducible; never integrate a spring from the previous requested frame. Paused Web Animations can be driven through `currentTime` rather than wall-clock playback. Load fonts before measurement and verify script shaping, fallback and localized wrapping. [Web Animations clock](https://developer.mozilla.org/en-US/docs/Web/API/Animation/currentTime) + +Compose the local animation before surface/camera projection, then visibility. Preserve the existing fixed `clock.mediaTime` for held footage/derived frames while code samples the shutter. Evaluate holdout against each code shutter sample so blurred letters cannot trail onto a protected face. This keeps correspondence; it does not reconstruct sub-frame subject motion absent from the plate. Label that physical limit and test moving masks rather than promising perfect motion-blurred edges. + +## Candidate analysis runtimes and evidence + +| Candidate | Intended role | Evidence and decision | +|---|---|---| +| SAM 2 / SAM 3.1 | Prompted object identity and temporal masks | SAM 2 code/checkpoints are Apache-2.0. SAM 3.1 is released, but uses SAM-specific terms and documented CUDA prerequisites; do not assume it runs in the target webview or inherits SAM 2's license. Neither automatically supplies hair alpha. [SAM 2](https://github.com/facebookresearch/sam2), [SAM 3](https://github.com/facebookresearch/sam3), [SAM license](https://github.com/facebookresearch/sam3/blob/main/LICENSE) | +| EdgeTAM | Optional lightweight tracked-mask candidate | Apache-2.0 code/checkpoints; upstream includes CoreML export and reports 16 FPS on iPhone 15 Pro Max. This is a segmentation benchmark, not a measured desktop export rate or alpha-quality guarantee. [Repository](https://github.com/facebookresearch/EdgeTAM) | +| Robust Video Matting | Human-alpha benchmark and candidate adapter | Temporal recurrence; upstream provides ONNX, CoreML and TF.js variants. Reported RTX 3090 HD throughput is 172 FPS with FP16, downsample ratio .25, batch/chunk 1, excluding the video conversion pipeline. This is not a measured app speed. GPL-3.0 requires a deliberate distribution/compliance decision; it is not a permissive drop-in. [RVM](https://github.com/PeterL1n/RobustVideoMatting) | +| MatAnyone family | Quality comparator for temporal matting | MatAnyone's S-Lab terms restrict ordinary use to non-commercial purposes; separately negotiate rights before commercial integration. Do not mistake a hosted listing for a redistribution grant. [License](https://github.com/pq-yang/MatAnyone/blob/main/LICENSE), [MatAnyone2 license](https://github.com/pq-yang/MatAnyone2/blob/main/LICENSE.txt) | +| Video Depth Anything Small | Coarse temporally coherent depth | Upstream Small is Apache-2.0, Base/Large CC-BY-NC-4.0. Pin the exact checkpoint and verify its terms. Relative depth still needs registration/calibration and cannot be the sole skin-edge matte. [Repository](https://github.com/DepthAnything/Video-Depth-Anything) | +| ONNX Runtime Web / native adapters | Optional execution backends | WebGPU where supported; WASM CPU fallback for validated small models. CoreML/native GPU candidates belong behind a host adapter. Probe operators, memory, webview support and seek/reset behavior; API support does not establish model portability. [ORT WebGPU](https://onnxruntime.ai/docs/tutorials/web/ep-webgpu.html) | + +No model is selected for distribution yet. Benchmark host-native and browser paths on actual Apple Silicon, Windows discrete/integrated GPU and CPU-only systems. Record decode + resize + inference + transfer + composition + encode, cold/warm latency, p50/p95, memory and energy, plus edge/temporal quality. Target cached 1080p playback at the project's 24/30 FPS; real-time inference is a measured optional tier, not a prerequisite for final export. + +## Ordered milestones and release gates + +| Phase | Deliverable | Exit evidence | +|---|---|---| +| H0 | Reclassify failed examples; retain originals; establish regression fixtures and source-frame annotations | Each reported failure has a reproducible source/mask/composite range; no production-ready badge on an unreviewed shot. | +| H1a | Versioned correspondence/validity contract, shared frame access, explicit per-group holdout, correction import; human foreground first | Person crossing board/title passes every crossing frame in preview and export; missing/stale/short data fails safely. Include one kinetic headline now. | +| H1b | Close-up hand segmentation, collapse detection and correction propagation | Thumb remains whole through entry, tap, lift and exit; all-frame correspondence, visibility and edge checks pass. Portrait-model success cannot waive this gate. | +| H2 | Rigid-cylinder surface mapping and appearance-preserving label wrap | One original can, correct scale and placement, readable exact label, no exposed duplicate body, hand fully coherent through the crossing. | +| H3 | Full kinetic typography examples and controls | At least three distinct treatments, random-seek/reverse/shutter checks, localization, readable holds and correct occlusion for every treatment. | +| H4 | Optional accelerated analysis adapters | Actual device/end-to-end benchmark plus license/checkpoint receipts; cached fallback remains usable. | +| H5 | Deformable meshes/atlases, calibrated 3D insertion and controlled generation | Separate experimental gates for cloth folds, camera/geometry consistency, clean background recovery and material fidelity. | + +Use generated and filmed examples; static, pan/push and handheld; fast finger entry, loose hair, motion blur, full occlusion/reappearance, crops, reverse/retime, and missing frames. For short clips, inspect every decoded output frame in contact sheets and full-resolution crossing crops, plus normal/slow playback. For longer clips, automated all-frame checks and reviewed event ranges supplement a complete playback; disclose unreviewed frames. Three-frame checks are smoke tests only. + +Proposed measurable gates: zero missing correspondence entries; no overlay pixels in annotated opaque foreground interiors before encoding; no detached/erased finger or head in any reviewed frame; measured boundary error on annotated events (target p95 ≤2 output pixels at 1080p, any >4 triggers correction); surface landmark drift and silhouette mismatch reported separately from tracker confidence; no unplanned subject-depth flips; layout bounds valid throughout animation. These are engineering targets to calibrate against annotations, not achieved benchmark results. Semi-transparent hair is evaluated with alpha/edge-color and temporal metrics, not a binary zero-overlap test. Flow-warp residuals, sudden area changes and components flag review, but cannot establish truth without annotations. + +The acceptance report records exact revisions, frame ranges, assets, model/correction provenance, annotated failures, best and worst frames, the full playable clip, and separate **render correctness**, **analysis correctness**, **art direction** and **final usability** verdicts. An export that completes can still fail the shot. diff --git a/docs/hybrid-scenes.md b/docs/hybrid-scenes.md index 60d14b7..97672ac 100644 --- a/docs/hybrid-scenes.md +++ b/docs/hybrid-scenes.md @@ -1,5 +1,7 @@ # Hybrid scenes: code inside footage +**Quality correction, 2026-11-11:** later review found erased fingers/heads, incorrect can placement and mismatched generated geometry in the example videos. Successful rendering and tracking do not establish whole-shot quality. See the [revised compositing and motion-design plan](hybrid-compositing-plan.md) for diagnoses, model/runtime research and proposed release gates. Those new features are planned, not implemented. + A hybrid scene combines two kinds of picture in one shot: - **Footage** (a "plate"): filmed, or made by a video model. It supplies what only has to look real: people, places, weather, light. @@ -96,12 +98,12 @@ Rules, each refused with a message that says what to do: **Conforming data from other tools.** A derived video is read by frame number: frame 40 of a matte describes frame 40 of the plate. Tools do not always return that. -- *Fewer frames at the plate's own rate* means frames were dropped, usually at the end. Keep the frames where they are and hold the last one (or trim the plate). Stretching the video over the plate's length moves every frame in time; a depth map stretched from 112 to 121 frames ran up to five frames early. +- *Fewer frames at the plate's own rate* means correspondence is incomplete; do not assume the missing frames are all at the end. Verify which source frame each output describes, then recompute/correct missing data or trim the shot to a verified range. Do not hold the tail of a moving matte/depth map to satisfy the frame-count check. Stretching the video over the plate's length moves every frame in time; a depth map stretched from 112 to 121 frames ran up to five frames early. - *Another frame rate* has to be resampled onto the plate's frame times. - *A depth video must be grey.* Several hosted depth models return a false-colour picture. Ask for grayscale output, or map the colours back to values before importing. -- Check the result against something that moves: compare a moving edge in the plate with the same edge in the matte or depth map at a few frames. +- Check the result against moving edges throughout each crossing. Inspect every decoded frame of short final clips, including full-resolution crossing crops and normal/slow playback. A few matching frames are only a smoke test. -**Depth encoding** is `{kind, near, far, packing}`. `kind` is `inverse` (what monocular depth models emit; precision is spent close to the camera) or `linear`. `near` and `far` are the distances white and black stand for, in scene units. `packing` is `gray8`, or `rg16` for 16 bits across red and green. Relative depth has no true scale, so `near` and `far` are values you tune until occlusion lands. They are not measurements. +**Depth encoding** is `{kind, near, far, packing}`. `kind` is `inverse` (what monocular depth models emit; precision is spent close to the camera) or `linear`. `near` and `far` are the distances white and black stand for, in scene units. `packing` is `gray8`, or `rg16` for 16 bits across red and green. Relative depth has no true scale: tuning `near` and `far` can create a plausible ordering in some frames, but does not establish shared geometry or correct hand/face edges. They are not measurements. Prefer an explicit subject holdout for a known foreground crossing. **Track** files are `{version: 1, kind: "planar" | "point", width, height, frameRate: {num, den}, frames: [{frame, quad | point, confidence?}]}`. Coordinates are plate pixels from the top-left. Quads are ordered top-left, top-right, bottom-right, bottom-left. Frames may be sparse; samples between them are interpolated, and samples outside them hold the nearest frame and say so. @@ -207,17 +209,17 @@ Professional compositing uses more steps than this. Stated plainly: The helpers were tried on twelve 5–6 second plates from four video models (Seedance 1 Pro Fast, Kling 2.5 Turbo Pro, Veo 3.1 Fast, Wan 2.2), with mattes and depth maps from hosted models and tracks from a classical planar tracker. Each scene was a renderer scene of the kind the starter shows. This is one trial, not a benchmark. -![Four frames: an app screen pinned to a phone in a hand, with the thumb passing in front of it, and a code-rendered can on a desk beside a real can, with an arm passing in front of it.](media/hybrid-generated-plates.jpg) +![Historical sampled frames from the phone and inserted-can experiments; later full-shot review found foreground and placement failures.](media/hybrid-generated-plates.jpg) -*Generated plates with code inside them. Left: an HTML screen pinned to a tracked phone; the thumb is the plate's, cut out again from a matte. Right: a code-rendered can beside the plate's own can; the arm hides it where the plate's depth map is nearer.* +*Historical samples, not passing clips. The phone matte collapses during the tap/lift, and the added can has inconsistent hand ordering and does not reskin the original can. Retained to document the experiment; see the corrected verdicts below.* | Journey | What was found | |---|---| -| Screen or label on a surface | Holds on rigid surfaces. A screen pinned to a phone in a moving hand stayed within 3 px of where it started on the screen, at 1088 × 1920, while the phone moved 24 px. A sheet of paper that curled is not a plane: with all four corners right, its edges missed the pin by up to 15 px. | -| Headline behind a subject | Works with a hosted matte. Hair over dark letters shows a 1–2 px light fringe. | -| Footage in front of a 3D object | Works once `near` and `far` are tuned by eye. The edge is as rough as the depth map's own edge, a few pixels. A depth model that normalises each frame separately changes an object's value when something new enters the shot; prefer one that is consistent over time. | +| Screen or label on a surface | Tracking held the phone within 3 px at 1088 × 1920 while it moved 24 px, but the composite fails: its thumb matte collapses at frames 60–70 of 121. The café menu also fails because no foreground matte protects the person and the footer overflows. A curled sheet missed the planar pin by up to 15 px. | +| Headline behind a subject | Sampled frames demonstrate the layer effect, with a 1–2 px light fringe at hair. Whole-shot acceptance was not established by those samples. | +| Footage in front of a 3D object | Fails final quality in the can example: the hand is split across the inserted object. Hand-tuned relative depth does not share its scale/camera, and no mask resolves a hand moving through the volume chosen for the new object. | | Lit by the footage | The plate's colour carries over. Under strongly coloured light a bare metal object takes too much of it (aluminium read as brass in a warm kitchen). At environment intensity 1, a plain aluminium can was 5–6% brighter over its body than a real can standing beside it, on the two plates lit from the front. On a plate lit from behind (a low sun in the shot) it was 1.6 times too bright, because the mirrored half puts that sun in front of the object too. `estimateKeyLight` chose the wrong side on two of three plates, as described above. | -| Placing a 3D object without a camera solve | A real stand-in object in the plate (a plain can), tracked as a plane, gave position and scale for a code object beside it through a slow push-in. It also shows what the plate's own light and shadow look like on that object. | +| Placing a 3D object without a camera solve | A tracked stand-in provides an approximate screen anchor, not a metric camera/pose solve. The example adds a second can; it fails the intended original-can reskin. A separate code-first take also exposes a larger generated can beneath the code object: one conditioning still did not preserve geometry. | Two things made pinned graphics read as part of the surface: a `mix-blend-mode` chosen for the material (`screen` for chalk on a dark board, `multiply` for print on paper), and the plate's own frame rate for the whole project. @@ -229,7 +231,7 @@ Three clips from a real camera (1920 × 1080, 25 fps; two on a slow motion-contr |---|---| | Screen or label on a surface | A card pinned to the blank side panel of a box held within 2 px of the panel for 30 frames. Then the dolly's orbit brought the box's next face into view, and the track slid onto it. The tracking tool reported confidence of 0.70–0.85 and no lost frames. A blank surface is tracked by the detail around its edges, and on a solid object an orbit changes what is there. Check the pinned element at several frames, not only the first. | | Lit by the footage | `estimateKeyLight` chose the side that the real shadow shows (front-left) but placed the light too low, so a cast shadow came out too long. Its colour came from bright blue components, not from the light. A light set by hand from the real shadow matched its direction. The shadow catcher drew the can's shadow across a real object standing on the table. Beside real metal, the plain aluminium can read as dull grey. | -| Headline behind a subject | Works with a hosted matte, except while a fast arm enters the shot (up to 460 px per frame): the matte lagged it by 1–2 frames, and the headline showed through the arm on those frames. The matte's edge along the forearm was soft, about 10 px from 10% to 90%. | +| Headline behind a subject | Fails whole-shot acceptance: while a fast arm enters (up to 460 px per frame), the matte lags by 1–2 frames and the headline shows through it. Its forearm edge is about 10 px wide from 10% to 90%. Other frames demonstrate the layer effect. | | Footage in front of a 3D object | Failed with the hosted depth map as delivered: the model normalised each frame separately, so the board read as near until the arm came in and as far after it, and hid the object until then. Rescaled per frame against parts of the shot that do not move (the wall and the board), the arm hid the object with an edge 3–4 px wide and nothing leaked onto the arm. | The same trial found three export defects, all fixed: @@ -245,4 +247,4 @@ The same trial found three export defects, all fixed: - `createDepthOccluder` assumes the plate and the scene share one camera. A depth map from a monocular model is consistent with itself, not with your scene units. - Antialiased edges mix values, so `id` and `depth` passes are exact only away from silhouettes. `renderPass` does not handle skinned or instanced meshes. - Results differ slightly across GPUs and browsers, as elsewhere in this framework. -- The tests use a synthetic plate. They prove that pixels land where the inputs say. They do not prove that a particular matting, depth or tracking tool gives good inputs on real footage; the trial above is the only evidence of that so far. +- The tests use a synthetic plate. They prove that pixels land where the inputs say. They do not prove that a particular matting, depth or tracking tool gives good inputs on real footage. The trials and subsequent failure audit above establish current limitations; all-frame quality gates remain proposed work. From 3f274330a19da53cbe406c20147ab2a4eed8adea Mon Sep 17 00:00:00 2001 From: Laurence Xavier <35849747+lxf82dev@users.noreply.github.com> Date: Wed, 11 Nov 2026 15:32:02 +0800 Subject: [PATCH 12/49] Sync packaged hybrid guidance and quality roadmap --- skills/editableframes/SKILL.md | 2 + .../references/hybrid-compositing-plan.md | 101 ++++++++++++++++++ skills/editableframes/references/hybrid.md | 20 ++-- 3 files changed, 114 insertions(+), 9 deletions(-) create mode 100644 skills/editableframes/references/hybrid-compositing-plan.md diff --git a/skills/editableframes/SKILL.md b/skills/editableframes/SKILL.md index d88cdda..130cbb9 100644 --- a/skills/editableframes/SKILL.md +++ b/skills/editableframes/SKILL.md @@ -27,6 +27,8 @@ The bundled `studio` has effect and creative studies plus the device library. St When a shot mixes code with filmed or generated video, let footage supply what only has to look real (people, places, light) and code supply what must be exactly right (the product, labels, prices, interfaces, captions). Read [references/hybrid.md](references/hybrid.md) before authoring. `init --hybrid` creates a working example. A matte, depth map, track or camera path is an input made by another tool: import it with `asset-add --role --of `, never invent one, and say so when a shot needs one that is missing. Replacing the footage invalidates data derived from it. Sample anything locked to the footage at `conformSeconds(clock.mediaTime ?? clock.frame / clock.fps, plate.frameRate)`, and render the project at the footage's frame rate. `render --pass ` exports a declared control pass; `render --motion-blur 180` adds a shutter. Light and depth scale are estimates: expose them as controls and check real frames. +For final short clips, inspect every decoded frame, crossing crops and playback; tracking confidence and three sampled frames do not certify quality. A missing or collapsed hand/person mask is a failed shot, not merely an edge to soften. Recompute/correct missing derived frames or trim to verified ranges; never stretch or hold a moving matte’s tail. Distinguish planar insertion, original-object reskin, 3D insertion/replacement and deforming cloth before authoring. Plan readable motion and attachment space for typography using explicit animation time. Read the [quality and motion-design roadmap](references/hybrid-compositing-plan.md) for proposed improvements; its new contracts and features are not implemented APIs. + ## Spatial objects For separately editable spatial objects expose one animatable vec3 with role position and explicit coordinateSpace/unit, plus one positive number with role scale. Use editableframes/manipulation (or editableframes/three-manipulation) and consume the same props in rendering. Publish working per-object manipulationCapabilities and measurement; roles alone cannot make a renderer draggable. Nonspatial lighting parameters need no invented transforms. Keep the 200-control budget; arbitrary renderer code and future libraries remain supported. Read docs/object-manipulation.md for source tick identity, first-key holding and gesture write policy. Preserve existing split-number tracks; migrate them explicitly rather than relabeling their type. diff --git a/skills/editableframes/references/hybrid-compositing-plan.md b/skills/editableframes/references/hybrid-compositing-plan.md new file mode 100644 index 0000000..3339a0e --- /dev/null +++ b/skills/editableframes/references/hybrid-compositing-plan.md @@ -0,0 +1,101 @@ +# Reliable hybrid compositing and motion design + +Status: proposed next work, 2026-11-11. This is a design and acceptance plan, not an implemented API. It supersedes any inference that a successful render or a few attractive frames establish a usable hybrid clip. Existing primitives and their tested scope remain documented in [hybrid guide](hybrid.md). + +## What the failed shots teach us + +| Observed failure | Diagnosis supported by the authored scenes | Required correction | +|---|---|---| +| A phone screen paints over a thumb, leaving a detached skin patch | The supplied matte loses the hand: foreground area drops from 12.44% at frame 59 to 0.18% at frame 60 and stays below 0.25% through frame 70. This is a missing foreground input, not just a rough edge. | Inspect plate, matte and composite together across the entire crossing; correct the subject track and correspondence, then refine its alpha edges. | +| Menu text crosses a person's forehead | The menu scene has no subject matte. Its footer is clipped at the board's lower boundary in the inspected frames. Screen blending preserves board texture but cannot infer who is in front. | Fit the entire animated layout within the actual surface, then clip it; protect the person with a foreground holdout. | +| An opaque price card erases the person's hair/head | There is no foreground holdout. Good planar tracking cannot fix layer order. | Treat all intersecting foreground subjects as required inputs. A plausible-looking board is not a passing result. | +| A hand appears sliced through an added can | The example inserts a second can at an offset from the tracked original. Relative depth with hand-tuned near/far is being used as if it were registered scene geometry. | First distinguish insertion from reskinning. For a hand known to be in front, use its coherent alpha as the foreground constraint. | +| A small labeled can sits over a larger generated can | Generating a world from a clay still did not preserve the product silhouette or proportions. | Reject the take for exact-object recomposition, or solve an explicit replacement workflow including removal of the original. Do not hide the mismatch with a smaller overlay. | + +These clips fail final-quality acceptance. The phone's 121 matte frames were measured using decoded grayscale coverage above 127/255, with zero-based frame indices. The other failures were verified in sampled frames and the authored scenes, not an exhaustive pixel audit. Earlier tracking numbers remain measurements of tracking, not evidence of correct occlusion, placement, materials or whole-shot quality. No new implementation or corrected full-length video is claimed by this plan. + +## Architecture decision: analyze, correct, cache, then render + +Keep the core model-neutral. A host or optional analysis package produces versioned masks, tracks, surface mappings and diagnostic reports. An author can correct them. Preview and export consume the same immutable artifacts. No model runs implicitly inside `render(clock)` and no model weights become a mandatory library dependency. + +Real-time compositing and real-time inference are different budgets. GPU/CPU acceleration can make preparation faster and enable interactive draft masks; it does not supply reliable geometry or physics by itself. Start with prepared per-frame data and GPU composition. Offer live draft inference only after profiling actual devices, with conspicuous provisional results and explicit promotion to a frozen render artifact. + +Bilibili provides a concrete live-inference precedent: its 2024 web.dev case study describes on-device MediaPipe Selfie Segmenter, worker/offscreen processing, reduced-resolution masks and CSS `mask-image` for comments behind people. Its older W3C presentation also describes mask-based rendering. These demonstrate a person-silhouette feature, not hair-level export alpha or collision simulation. Our choice to freeze reviewed masks for export is an architectural recommendation, not a claim that Bilibili precomputes everything. These are published primary sources; no authenticated production reverse engineering was performed. [Bilibili case study](https://web.dev/case-studies/bilibili-web-ai-improvements), [W3C presentation](https://www.w3.org/2019/03/23-chinese-web-zhaoxin-bilibili.pdf) + +### Proposed prepared-data contract + +Extend the existing derived-asset relationship with a versioned manifest. Names below are proposed fields, not accepted CLI flags: + +- Identity: source content digest, exact decoded dimensions/orientation/crop, frame count, rational time base and per-frame presentation timestamps; subject/surface IDs; model/checkpoint digest, preprocessing version and correction revision. +- Semantics: `subject-alpha`, `foreground-color` where available, `surface-coverage`, `surface-map`, `depth`, `confidence` and `validity`. A binary segmentation probability is not silently relabeled as an alpha matte. Foreground alpha is white for foreground; linear alpha/data is not color-managed as display RGB. +- Time: explicit source-frame correspondence and valid ranges. Plate, mask and track are fetched through one source-frame mapping, including trim, speed and reverse. Equal duration/FPS/count alone does not establish correspondence. +- Storage: bounded, chunked cache; stream/prefetch under the existing decoded-memory budget. Use lossless data for final alpha and sufficiently precise depth/maps; lossy MP4 is diagnostic input, not the canonical final data format. +- Failure: missing, stale, out-of-range, invalid or wrong-sized data fails final validation. Draft rendering can show the original plate plus a diagnostic. Never silently replace a missing holdout with an all-background mask, repeat a moving matte's last frame, or stretch a short matte to fit. + +Changing source bytes, orientation, crop or interpretation invalidates dependent analysis. Changing only the timeline edit map reuses analysis through an explicitly verified remap. Text edits reuse approved geometry/alpha, but invalidate content-dependent layout and occlusion review if the visible region changes. + +## Foreground preservation and layer order + +Start with explicit relationships such as `person in front of title` and `hand in front of screen`. Scope a holdout to the affected layer/group; a hand protecting the phone need not hide a separate foreground caption. Validate cycles and contradictory depth/ordering constraints. Occlusion state can change over a shot, but that change needs a tracked spatial relationship or an authored interval, not unrelated per-pixel guesses. + +For known foreground crossings, subject alpha owns the silhouette. Use temporally consistent, calibrated depth for ordering genuinely interleaved objects; raw per-frame normalized monocular depth must not slice fingers or faces. Depth confidence is separate from alpha confidence. One global foreground matte also cannot solve a hand that is simultaneously behind one object and in front of another. + +The preparation workflow is prompted video segmentation → tracked identity → positive/negative corrections at difficult frames → temporal propagation → alpha refinement around hair/fingers/motion blur → review. Track through disappearance/reappearance; reset temporal state at cuts. Sudden area collapse triggers a review/re-seeding candidate, not blind automatic acceptance: genuine occlusion or leaving the frame can also shrink a subject. Preserve legitimate holes between fingers and never assume every disconnected component is an error. Do not blur consecutive masks indiscriminately: that creates lag and ghost hands. + +Composite with explicit premultiplied-alpha and color-space conventions. Opaque protected interiors must preserve source pixels. At soft edges, copying `alpha × original plate` over a new background can retain the old background in hair and create a double edge. High-quality edge replacement requires decontaminated foreground color or a credible original-background estimate; document the approximation when those are absent. A soft mask alone does not prove a clean composite. + +Add diagnostic views for source, subject alpha, surface coverage, correspondence, confidence, final composite and difference inside protected regions. Provide brush/polygon corrections and an event-range view. Start with people in front of a title/board, then a separately gated close-up hand correction workflow; a portrait matting model is not proven on isolated fingers. + +## Four different placement operations + +1. **Planar insert:** board or phone. Render animated artwork in surface coordinates, project it with the track, clip to surface coverage, then apply foreground visibility. Explicitly exclude the bezel and check the full animated text bounds. +2. **Reskin an existing rigid curved object:** select the original can, identify its body/silhouette and cap, estimate its pose/axis/radius and camera relationship, and fit a cylindrical UV or mesh mapping over time. Map the editable label into that surface; preserve lids, highlights, existing silhouette and contact shadow where appropriate. Reapply hand visibility. A featureless cylinder has ambiguous rotation; allow an authored seam/pose constraint and mark unobservable ranges. +3. **Replace or insert a 3D object:** requires explicit camera/scale/contact placement and foreground ordering. If replacing an object whose silhouette changes, remove the old object's exposed pixels and recover newly revealed background. Clean-plate/inpainting work is separate, reviewed, and cannot be substituted by an extra mesh on top. Added objects need their own shadows/reflections; reskinning normally retains the original contact evidence. +4. **Deforming surface:** cloth/skin needs a tracked mesh, dense UV correspondence or an atlas with visibility and disocclusion handling. A homography or cylinder is not sufficient. Start with a short cloth patch and a correction/import path; leave arbitrary bodies and loose folds experimental until tested. + +No mask fixes an impossible placement: if the recorded hand sweeps through the volume of an inserted can, making the whole hand foreground only changes the visible contradiction. Move the insert to a collision-free location, choose another take, or regenerate blocking. Reskinning the existing can avoids creating that new volume. Preserving shading during a reskin also needs an appearance model: a simple multiply blend retains the old albedo and cannot freely change a dark label into a light one. Begin with a blank neutral can, fit a shading/specular residual, and document where exact material recovery is ambiguous. + +Existing tools demonstrate the video surface-editing route. Mocha Pro documents PowerMesh-driven inserts, grid warps and tracked motion blur. Layered Neural Atlases learns per-shot mappings/alpha to propagate an atlas edit; CoDeF fits a canonical field and temporal deformation. These are evidence for feasibility, not drop-in real-time browser solutions or licenses to copy proprietary engines. [Mocha](https://borisfx.com/products/mocha-pro/), [Neural Atlases](https://layered-neural-atlases.github.io/), [CoDeF](https://qiuyu96.github.io/CoDeF/) + +Lovart advertises texture generation and image editing. Its public page does not establish which model implements an observed wrap effect or that exact artwork can be transferred through video with temporal geometry guarantees. Use it as a visual reference, not an inferred backend architecture. [Lovart texture feature](https://www.lovart.ai/features/ai-3d-texture) + +## Motion design is part of acceptance + +Every authored example declares its attachment space and timing: screen-space graphic, surface-attached artwork, or world-space object with a camera. Surface-attached text inherits the observed perspective; world text requires a real solve or an explicitly labeled authored approximation. Static printed labels should remain attached naturally; expressive animation belongs in a reveal, digital display or surrounding title when the brief calls for it. + +Deliver editable examples covering: staggered word/character reveals with readable holds; masked wipes and line draws; spring-like scale/rotation settles; text-on-path/orbits; tracked perspective titles; and a foreground-aware headline passing behind a person. Include at least one 3D/extruded or shader-treated title. Expose timing, stagger, easing, amplitude, path, typography, palette and attachment controls without restricting arbitrary renderer code. + +All code motion is a deterministic function of explicit clip animation time and seeded parameters, with any source/timeline mapping authored explicitly. Analytic curves or baked simulation caches make reverse/random seeks reproducible; never integrate a spring from the previous requested frame. Paused Web Animations can be driven through `currentTime` rather than wall-clock playback. Load fonts before measurement and verify script shaping, fallback and localized wrapping. [Web Animations clock](https://developer.mozilla.org/en-US/docs/Web/API/Animation/currentTime) + +Compose the local animation before surface/camera projection, then visibility. Preserve the existing fixed `clock.mediaTime` for held footage/derived frames while code samples the shutter. Evaluate holdout against each code shutter sample so blurred letters cannot trail onto a protected face. This keeps correspondence; it does not reconstruct sub-frame subject motion absent from the plate. Label that physical limit and test moving masks rather than promising perfect motion-blurred edges. + +## Candidate analysis runtimes and evidence + +| Candidate | Intended role | Evidence and decision | +|---|---|---| +| SAM 2 / SAM 3.1 | Prompted object identity and temporal masks | SAM 2 code/checkpoints are Apache-2.0. SAM 3.1 is released, but uses SAM-specific terms and documented CUDA prerequisites; do not assume it runs in the target webview or inherits SAM 2's license. Neither automatically supplies hair alpha. [SAM 2](https://github.com/facebookresearch/sam2), [SAM 3](https://github.com/facebookresearch/sam3), [SAM license](https://github.com/facebookresearch/sam3/blob/main/LICENSE) | +| EdgeTAM | Optional lightweight tracked-mask candidate | Apache-2.0 code/checkpoints; upstream includes CoreML export and reports 16 FPS on iPhone 15 Pro Max. This is a segmentation benchmark, not a measured desktop export rate or alpha-quality guarantee. [Repository](https://github.com/facebookresearch/EdgeTAM) | +| Robust Video Matting | Human-alpha benchmark and candidate adapter | Temporal recurrence; upstream provides ONNX, CoreML and TF.js variants. Reported RTX 3090 HD throughput is 172 FPS with FP16, downsample ratio .25, batch/chunk 1, excluding the video conversion pipeline. This is not a measured app speed. GPL-3.0 requires a deliberate distribution/compliance decision; it is not a permissive drop-in. [RVM](https://github.com/PeterL1n/RobustVideoMatting) | +| MatAnyone family | Quality comparator for temporal matting | MatAnyone's S-Lab terms restrict ordinary use to non-commercial purposes; separately negotiate rights before commercial integration. Do not mistake a hosted listing for a redistribution grant. [License](https://github.com/pq-yang/MatAnyone/blob/main/LICENSE), [MatAnyone2 license](https://github.com/pq-yang/MatAnyone2/blob/main/LICENSE.txt) | +| Video Depth Anything Small | Coarse temporally coherent depth | Upstream Small is Apache-2.0, Base/Large CC-BY-NC-4.0. Pin the exact checkpoint and verify its terms. Relative depth still needs registration/calibration and cannot be the sole skin-edge matte. [Repository](https://github.com/DepthAnything/Video-Depth-Anything) | +| ONNX Runtime Web / native adapters | Optional execution backends | WebGPU where supported; WASM CPU fallback for validated small models. CoreML/native GPU candidates belong behind a host adapter. Probe operators, memory, webview support and seek/reset behavior; API support does not establish model portability. [ORT WebGPU](https://onnxruntime.ai/docs/tutorials/web/ep-webgpu.html) | + +No model is selected for distribution yet. Benchmark host-native and browser paths on actual Apple Silicon, Windows discrete/integrated GPU and CPU-only systems. Record decode + resize + inference + transfer + composition + encode, cold/warm latency, p50/p95, memory and energy, plus edge/temporal quality. Target cached 1080p playback at the project's 24/30 FPS; real-time inference is a measured optional tier, not a prerequisite for final export. + +## Ordered milestones and release gates + +| Phase | Deliverable | Exit evidence | +|---|---|---| +| H0 | Reclassify failed examples; retain originals; establish regression fixtures and source-frame annotations | Each reported failure has a reproducible source/mask/composite range; no production-ready badge on an unreviewed shot. | +| H1a | Versioned correspondence/validity contract, shared frame access, explicit per-group holdout, correction import; human foreground first | Person crossing board/title passes every crossing frame in preview and export; missing/stale/short data fails safely. Include one kinetic headline now. | +| H1b | Close-up hand segmentation, collapse detection and correction propagation | Thumb remains whole through entry, tap, lift and exit; all-frame correspondence, visibility and edge checks pass. Portrait-model success cannot waive this gate. | +| H2 | Rigid-cylinder surface mapping and appearance-preserving label wrap | One original can, correct scale and placement, readable exact label, no exposed duplicate body, hand fully coherent through the crossing. | +| H3 | Full kinetic typography examples and controls | At least three distinct treatments, random-seek/reverse/shutter checks, localization, readable holds and correct occlusion for every treatment. | +| H4 | Optional accelerated analysis adapters | Actual device/end-to-end benchmark plus license/checkpoint receipts; cached fallback remains usable. | +| H5 | Deformable meshes/atlases, calibrated 3D insertion and controlled generation | Separate experimental gates for cloth folds, camera/geometry consistency, clean background recovery and material fidelity. | + +Use generated and filmed examples; static, pan/push and handheld; fast finger entry, loose hair, motion blur, full occlusion/reappearance, crops, reverse/retime, and missing frames. For short clips, inspect every decoded output frame in contact sheets and full-resolution crossing crops, plus normal/slow playback. For longer clips, automated all-frame checks and reviewed event ranges supplement a complete playback; disclose unreviewed frames. Three-frame checks are smoke tests only. + +Proposed measurable gates: zero missing correspondence entries; no overlay pixels in annotated opaque foreground interiors before encoding; no detached/erased finger or head in any reviewed frame; measured boundary error on annotated events (target p95 ≤2 output pixels at 1080p, any >4 triggers correction); surface landmark drift and silhouette mismatch reported separately from tracker confidence; no unplanned subject-depth flips; layout bounds valid throughout animation. These are engineering targets to calibrate against annotations, not achieved benchmark results. Semi-transparent hair is evaluated with alpha/edge-color and temporal metrics, not a binary zero-overlap test. Flow-warp residuals, sudden area changes and components flag review, but cannot establish truth without annotations. + +The acceptance report records exact revisions, frame ranges, assets, model/correction provenance, annotated failures, best and worst frames, the full playable clip, and separate **render correctness**, **analysis correctness**, **art direction** and **final usability** verdicts. An export that completes can still fail the shot. diff --git a/skills/editableframes/references/hybrid.md b/skills/editableframes/references/hybrid.md index a74fb42..2ab8de5 100644 --- a/skills/editableframes/references/hybrid.md +++ b/skills/editableframes/references/hybrid.md @@ -1,5 +1,7 @@ # Hybrid scenes: code inside footage +**Quality correction, 2026-11-11:** later review found erased fingers/heads, incorrect can placement and mismatched generated geometry in the example videos. Successful rendering and tracking do not establish whole-shot quality. See the [revised compositing and motion-design plan](hybrid-compositing-plan.md) for diagnoses, model/runtime research and proposed release gates. Those new features are planned, not implemented. + A hybrid scene combines two kinds of picture in one shot: - **Footage** (a "plate"): filmed, or made by a video model. It supplies what only has to look real: people, places, weather, light. @@ -92,12 +94,12 @@ Rules, each refused with a message that says what to do: **Conforming data from other tools.** A derived video is read by frame number: frame 40 of a matte describes frame 40 of the plate. Tools do not always return that. -- *Fewer frames at the plate's own rate* means frames were dropped, usually at the end. Keep the frames where they are and hold the last one (or trim the plate). Stretching the video over the plate's length moves every frame in time; a depth map stretched from 112 to 121 frames ran up to five frames early. +- *Fewer frames at the plate's own rate* means correspondence is incomplete; do not assume the missing frames are all at the end. Verify which source frame each output describes, then recompute/correct missing data or trim the shot to a verified range. Do not hold the tail of a moving matte/depth map to satisfy the frame-count check. Stretching the video over the plate's length moves every frame in time; a depth map stretched from 112 to 121 frames ran up to five frames early. - *Another frame rate* has to be resampled onto the plate's frame times. - *A depth video must be grey.* Several hosted depth models return a false-colour picture. Ask for grayscale output, or map the colours back to values before importing. -- Check the result against something that moves: compare a moving edge in the plate with the same edge in the matte or depth map at a few frames. +- Check the result against moving edges throughout each crossing. Inspect every decoded frame of short final clips, including full-resolution crossing crops and normal/slow playback. A few matching frames are only a smoke test. -**Depth encoding** is `{kind, near, far, packing}`. `kind` is `inverse` (what monocular depth models emit; precision is spent close to the camera) or `linear`. `near` and `far` are the distances white and black stand for, in scene units. `packing` is `gray8`, or `rg16` for 16 bits across red and green. Relative depth has no true scale, so `near` and `far` are values you tune until occlusion lands. They are not measurements. +**Depth encoding** is `{kind, near, far, packing}`. `kind` is `inverse` (what monocular depth models emit; precision is spent close to the camera) or `linear`. `near` and `far` are the distances white and black stand for, in scene units. `packing` is `gray8`, or `rg16` for 16 bits across red and green. Relative depth has no true scale: tuning `near` and `far` can create a plausible ordering in some frames, but does not establish shared geometry or correct hand/face edges. They are not measurements. Prefer an explicit subject holdout for a known foreground crossing. **Track** files are `{version: 1, kind: "planar" | "point", width, height, frameRate: {num, den}, frames: [{frame, quad | point, confidence?}]}`. Coordinates are plate pixels from the top-left. Quads are ordered top-left, top-right, bottom-right, bottom-left. Frames may be sparse; samples between them are interpolated, and samples outside them hold the nearest frame and say so. @@ -201,11 +203,11 @@ The helpers were tried on twelve 5–6 second plates from four video models (See | Journey | What was found | |---|---| -| Screen or label on a surface | Holds on rigid surfaces. A screen pinned to a phone in a moving hand stayed within 3 px of where it started on the screen, at 1088 × 1920, while the phone moved 24 px. A sheet of paper that curled is not a plane: with all four corners right, its edges missed the pin by up to 15 px. | -| Headline behind a subject | Works with a hosted matte. Hair over dark letters shows a 1–2 px light fringe. | -| Footage in front of a 3D object | Works once `near` and `far` are tuned by eye. The edge is as rough as the depth map's own edge, a few pixels. A depth model that normalises each frame separately changes an object's value when something new enters the shot; prefer one that is consistent over time. | +| Screen or label on a surface | Tracking held the phone within 3 px at 1088 × 1920 while it moved 24 px, but the composite fails: its thumb matte collapses at frames 60–70 of 121. The café menu also fails because no foreground matte protects the person and the footer overflows. A curled sheet missed the planar pin by up to 15 px. | +| Headline behind a subject | Sampled frames demonstrate the layer effect, with a 1–2 px light fringe at hair. Whole-shot acceptance was not established by those samples. | +| Footage in front of a 3D object | Fails final quality in the can example: the hand is split across the inserted object. Hand-tuned relative depth does not share its scale/camera, and no mask resolves a hand moving through the volume chosen for the new object. | | Lit by the footage | The plate's colour carries over. Under strongly coloured light a bare metal object takes too much of it (aluminium read as brass in a warm kitchen). At environment intensity 1, a plain aluminium can was 5–6% brighter over its body than a real can standing beside it, on the two plates lit from the front. On a plate lit from behind (a low sun in the shot) it was 1.6 times too bright, because the mirrored half puts that sun in front of the object too. `estimateKeyLight` chose the wrong side on two of three plates, as described above. | -| Placing a 3D object without a camera solve | A real stand-in object in the plate (a plain can), tracked as a plane, gave position and scale for a code object beside it through a slow push-in. It also shows what the plate's own light and shadow look like on that object. | +| Placing a 3D object without a camera solve | A tracked stand-in provides an approximate screen anchor, not a metric camera/pose solve. The example adds a second can; it fails the intended original-can reskin. A separate code-first take also exposes a larger generated can beneath the code object: one conditioning still did not preserve geometry. | Two things made pinned graphics read as part of the surface: a `mix-blend-mode` chosen for the material (`screen` for chalk on a dark board, `multiply` for print on paper), and the plate's own frame rate for the whole project. @@ -217,7 +219,7 @@ Three clips from a real camera (1920 × 1080, 25 fps; two on a slow motion-contr |---|---| | Screen or label on a surface | A card pinned to the blank side panel of a box held within 2 px of the panel for 30 frames. Then the dolly's orbit brought the box's next face into view, and the track slid onto it. The tracking tool reported confidence of 0.70–0.85 and no lost frames. A blank surface is tracked by the detail around its edges, and on a solid object an orbit changes what is there. Check the pinned element at several frames, not only the first. | | Lit by the footage | `estimateKeyLight` chose the side that the real shadow shows (front-left) but placed the light too low, so a cast shadow came out too long. Its colour came from bright blue components, not from the light. A light set by hand from the real shadow matched its direction. The shadow catcher drew the can's shadow across a real object standing on the table. Beside real metal, the plain aluminium can read as dull grey. | -| Headline behind a subject | Works with a hosted matte, except while a fast arm enters the shot (up to 460 px per frame): the matte lagged it by 1–2 frames, and the headline showed through the arm on those frames. The matte's edge along the forearm was soft, about 10 px from 10% to 90%. | +| Headline behind a subject | Fails whole-shot acceptance: while a fast arm enters (up to 460 px per frame), the matte lags by 1–2 frames and the headline shows through it. Its forearm edge is about 10 px wide from 10% to 90%. Other frames demonstrate the layer effect. | | Footage in front of a 3D object | Failed with the hosted depth map as delivered: the model normalised each frame separately, so the board read as near until the arm came in and as far after it, and hid the object until then. Rescaled per frame against parts of the shot that do not move (the wall and the board), the arm hid the object with an edge 3–4 px wide and nothing leaked onto the arm. | The same trial found three export defects, all fixed: @@ -233,4 +235,4 @@ The same trial found three export defects, all fixed: - `createDepthOccluder` assumes the plate and the scene share one camera. A depth map from a monocular model is consistent with itself, not with your scene units. - Antialiased edges mix values, so `id` and `depth` passes are exact only away from silhouettes. `renderPass` does not handle skinned or instanced meshes. - Results differ slightly across GPUs and browsers, as elsewhere in this framework. -- The tests use a synthetic plate. They prove that pixels land where the inputs say. They do not prove that a particular matting, depth or tracking tool gives good inputs on real footage; the trial above is the only evidence of that so far. +- The tests use a synthetic plate. They prove that pixels land where the inputs say. They do not prove that a particular matting, depth or tracking tool gives good inputs on real footage. The trials and subsequent failure audit above establish current limitations; all-frame quality gates remain proposed work. From 209850d483a7b08bb1bd80d07ac7419765fd7ce3 Mon Sep 17 00:00:00 2001 From: Laurence Xavier <35849747+lxf82dev@users.noreply.github.com> Date: Wed, 11 Nov 2026 16:00:36 +0800 Subject: [PATCH 13/49] Add prepared foreground, surface mapping and kinetic text primitives --- packages/plate/foreground.mjs | 51 +++++++++++++++ packages/plate/index.mjs | 4 ++ packages/plate/manifest.mjs | 4 ++ packages/plate/prepared.mjs | 99 ++++++++++++++++++++++++++++++ packages/plate/surface.mjs | 73 ++++++++++++++++++++++ packages/plate/typography.mjs | 28 +++++++++ packages/runtime/editor.mjs | 5 +- packages/runtime/renderer-host.mjs | 2 +- scripts/media.mjs | 10 ++- scripts/project.mjs | 3 +- tests/hybrid-prepared.test.mjs | 46 ++++++++++++++ 11 files changed, 319 insertions(+), 6 deletions(-) create mode 100644 packages/plate/foreground.mjs create mode 100644 packages/plate/prepared.mjs create mode 100644 packages/plate/surface.mjs create mode 100644 packages/plate/typography.mjs create mode 100644 tests/hybrid-prepared.test.mjs diff --git a/packages/plate/foreground.mjs b/packages/plate/foreground.mjs new file mode 100644 index 0000000..e71ed45 --- /dev/null +++ b/packages/plate/foreground.mjs @@ -0,0 +1,51 @@ +import {sampleMaskCorrections} from './prepared.mjs'; + +/** A holdout protects one authored DOM/Canvas/WebGL group. It clips the code + * layer itself, so no screenshot/readback of arbitrary code content is needed. + * Alpha is treated as linear coverage. Soft edges retain the source plate's + * observed colors; foreground color decontamination is a separate input. */ +export function createForegroundHoldout({root,width,height,document:doc=root.ownerDocument}) { + if(!Number.isSafeInteger(width)||!Number.isSafeInteger(height)||width<1||height<1)throw Error('Holdout needs positive raster dimensions'); + const content=doc.createElement('div'); + content.style.cssText='position:absolute;inset:0;overflow:hidden';root.append(content); + const canvas=doc.createElement('canvas');canvas.width=width;canvas.height=height; + const c=canvas.getContext('2d',{willReadFrequently:true}); + let disposed=false; + return { + root:content, + update(mask,{channel='luminance',corrections,frame=0,sourceSha256,subject}={}) { + if(disposed)throw Error('Holdout disposed'); + if(!mask)throw Error(`Required foreground mask missing at source frame ${frame}`); + if((mask.naturalWidth??mask.width)!==width||(mask.naturalHeight??mask.height)!==height)throw Error('Holdout mask does not match the source raster'); + if(!['luminance','alpha'].includes(channel))throw Error('Unknown foreground channel'); + c.globalCompositeOperation='copy';c.drawImage(mask,0,0,width,height); + const image=c.getImageData(0,0,width,height),d=image.data; + for(let i=0;i>8;d[i]=d[i+1]=d[i+2]=255;d[i+3]=a;} + c.putImageData(image,0,0); + if(corrections){ + if(corrections.sourceSha256!==sourceSha256||corrections.subject!==subject)throw Error('Corrections belong to a different source or subject'); + for(const p of sampleMaskCorrections(corrections,frame)){ + if(p.operation==='replace'){c.clearRect(0,0,width,height);c.globalCompositeOperation='source-over';} + else c.globalCompositeOperation=p.operation==='subtract'?'destination-out':'source-over'; + c.fillStyle='#fff';c.beginPath();p.points.forEach(([x,y],i)=>i?c.lineTo(x,y):c.moveTo(x,y));c.closePath();c.fill(); + } + } + // Invert foreground coverage to visibility for the affected code group. + const corrected=c.getImageData(0,0,width,height); + for(let i=3;i=opaque){protectedPixels++;const e=Math.max(...[0,1,2].map(c=>Math.abs(source[i+c]-composite[i+c])));maxError=Math.max(maxError,e);if(e>tolerance)leakedPixels++;} + return {protectedPixels,leakedPixels,maxError}; +} diff --git a/packages/plate/index.mjs b/packages/plate/index.mjs index 00749e5..72e273d 100644 --- a/packages/plate/index.mjs +++ b/packages/plate/index.mjs @@ -11,3 +11,7 @@ export * from './color.mjs'; export * from './passes.mjs'; export * from './manifest.mjs'; export * from './canvas.mjs'; +export * from './prepared.mjs'; +export * from './foreground.mjs'; +export * from './surface.mjs'; +export * from './typography.mjs'; diff --git a/packages/plate/manifest.mjs b/packages/plate/manifest.mjs index add80e7..6e96fcf 100644 --- a/packages/plate/manifest.mjs +++ b/packages/plate/manifest.mjs @@ -9,6 +9,10 @@ * mismatch is refused instead of being composited a few pixels off. */ import {validateDepthEncoding} from './depth.mjs'; export const DERIVED_ROLES = Object.freeze({ + analysis: ['data'], // prepared source correspondence/review receipt + surface: ['data'], // UV mesh/pose correspondence + coverage: ['video', 'image'], // visible target surface, not subject alpha + foreground: ['video', 'image'], // decontaminated foreground color, when available matte: ['video', 'image'], // white = keep (subject), black = drop depth: ['video', 'image'], // see depth.mjs; needs `encoding` normals: ['video', 'image'], // camera-space normals, (n+1)/2 in RGB diff --git a/packages/plate/prepared.mjs b/packages/plate/prepared.mjs new file mode 100644 index 0000000..a88f77f --- /dev/null +++ b/packages/plate/prepared.mjs @@ -0,0 +1,99 @@ +/** Model-neutral, immutable analysis receipts. Frame numbers are source frames, + * never timeline frames. A receipt records correspondence, not pixel truth. */ +const hash = x => typeof x === 'string' && /^[a-f0-9]{64}$/.test(x); +const integer = x => Number.isSafeInteger(x) && x >= 0; +const finite = x => typeof x === 'number' && Number.isFinite(x); +export function validatePreparedAnalysis(data, source) { + if (!data || data.version !== 1 || data.kind !== 'prepared-plate') throw Error('Prepared analysis needs version 1, kind prepared-plate'); + const s = data.source; + if (!s || typeof s.asset!=='string' || !s.asset || !hash(s.sha256) || !integer(s.width) || !s.width || !integer(s.height) || !s.height || !integer(s.frames) || !s.frames || s.frames > 100000) throw Error('Prepared analysis needs a bounded source digest, dimensions and frame count'); + const rate = s.frameRate; + if (!rate || !integer(rate.num) || !rate.num || !integer(rate.den) || !rate.den) throw Error('Prepared analysis needs a rational source frame rate'); + if (s.orientation !== 0 || !Array.isArray(s.crop) || s.crop.length !== 4 || !s.crop.every(integer) || s.crop.join() !== [0,0,s.width,s.height].join()) throw Error('Prepare analysis from the decoded, oriented full source raster'); + if (!Array.isArray(s.pts) || s.pts.length !== s.frames || s.pts.some((t,i) => !finite(t) || t < 0 || (i && t <= s.pts[i-1])) || s.pts[0] !== 0) throw Error('Prepared analysis needs strictly increasing source presentation times starting at zero'); + if (source) { + for (const key of ['sha256','width','height','frames']) if (source[key] !== s[key]) throw Error(`Prepared analysis source ${key} changed; prepare this take again`); + if (source.frameRate && source.frameRate.num * rate.den !== rate.num * source.frameRate.den) throw Error('Prepared source frame rate changed'); + if (source.pts && (source.pts.length !== s.frames || source.pts.some((t,i) => Math.abs(t-s.pts[i]) > 1e-7))) throw Error('Prepared source presentation times changed'); + } + if (typeof data.subject !== 'string' || !/^[\w.-]{1,80}$/.test(data.subject) || !hash(data.revision)) throw Error('Prepared analysis needs a subject and correction revision digest'); + if (!data.provenance || typeof data.provenance.method !== 'string' || !data.provenance.method || typeof data.provenance.preprocess !== 'string' || !data.provenance.preprocess) throw Error('Prepared analysis needs method and preprocessing provenance'); + if (data.provenance.checkpoint !== undefined && !hash(data.provenance.checkpoint)) throw Error('Checkpoint identity must be a content digest'); + if (!data.alpha || typeof data.alpha.asset !== 'string' || !hash(data.alpha.sha256) || !['luminance','alpha'].includes(data.alpha.channel) || !['segmentation','alpha'].includes(data.alpha.semantics)) throw Error('Prepared analysis needs a pinned alpha/segmentation asset and channel'); + if (!Array.isArray(data.frames) || data.frames.length !== s.frames) throw Error('Prepared analysis is missing source-frame correspondence'); + data.frames.forEach((f,i) => { + if (f.sourceFrame !== i || !integer(f.maskFrame) || f.maskFrame >= s.frames || typeof f.valid !== 'boolean' || typeof f.reviewed !== 'boolean') throw Error(`Invalid prepared correspondence at source frame ${i}`); + if (f.issues !== undefined && (!Array.isArray(f.issues) || f.issues.some(x => typeof x !== 'string'))) throw Error(`Invalid issues at source frame ${i}`); + }); + return data; +} + +/** Explicit source mapping handles trim/reverse; out-of-range never holds a tail. */ +export function preparedFrame(data, seconds, {start = 0, speed = 1, requireReviewed = true} = {}) { + if (![seconds,start,speed].every(finite)) throw Error('Prepared sampling needs finite time, trim and speed'); + const time = start + seconds * speed, pts = data.source.pts; + const end = pts.at(-1) + data.source.frameRate.den / data.source.frameRate.num; + if (time < -1e-9 || time >= end - 1e-9) throw Error(`Prepared source time ${time} is outside 0..${end}`); + let lo=0, hi=pts.length; + while (lo+1>1; if(pts[mid]<=time+1e-9)lo=mid;else hi=mid; } + const f=data.frames[lo]; + if (!f.valid || (requireReviewed && !f.reviewed)) throw Error(`Prepared subject ${data.subject} needs correction/review at source frame ${lo}${f.issues?.length ? ': '+f.issues.join(', ') : ''}`); + return {...f, seconds:pts[lo], maskSeconds:pts[f.maskFrame]}; +} + +/** Bounded diagnostics. Area collapse flags review, not automatic deletion or + * identity reassignment: a real subject can leave the shot. */ +export function analyzeMask(rgba, width, height, {channel='luminance', previousCoverage, collapseRatio=.2} = {}) { + if (!integer(width) || !width || !integer(height) || !height || rgba.length !== width*height*4) throw Error('Mask raster dimensions do not match'); + if (!['luminance','alpha'].includes(channel)) throw Error('Mask channel must be luminance or alpha'); + let area=0, opaque=0, left=width,top=height,right=-1,bottom=-1; + for(let p=0;p127){opaque++;const x=p%width,y=Math.floor(p/width);left=Math.min(left,x);right=Math.max(right,x);top=Math.min(top,y);bottom=Math.max(bottom,y);} + } + const coverage=opaque/(width*height), issues=[]; + if(finite(previousCoverage) && previousCoverage>.001 && coverage10000)throw Error('Invalid subject correction book'); + let last=-1; + for(const k of book.keys){ + if(!integer(k.frame)||k.frame<=last||!Array.isArray(k.polygons)||k.polygons.length>128)throw Error('Correction keys must have increasing whole frames and bounded polygons');last=k.frame; + for(const p of k.polygons){ + if(!['add','subtract','replace'].includes(p.operation)||!Array.isArray(p.points)||p.points.length<3||p.points.length>4096||p.points.some(v=>!Array.isArray(v)||v.length!==2||!v.every(finite)))throw Error('Correction polygon needs finite source-raster points and an operation'); + } + } + return book; +} + +/** Propagation is explicit and bounded between matching authored polygon keys. + * No extrapolation beyond them, and no blind optical-flow identity guess. */ +export function sampleMaskCorrections(book, frame) { + validateMaskCorrections(book); + if(!integer(frame))throw Error('Correction sample needs a whole source frame'); + const exact=book.keys.find(k=>k.frame===frame);if(exact)return structuredClone(exact.polygons); + const next=book.keys.findIndex(k=>k.frame>frame);if(next<=0)return []; + const a=book.keys[next-1],b=book.keys[next];if(a.interpolation!=='linear')return []; + if(a.polygons.length!==b.polygons.length||a.polygons.some((p,i)=>p.operation!==b.polygons[i].operation||p.points.length!==b.polygons[i].points.length))throw Error(`Correction topology changes across ${a.frame}..${b.frame}`); + const t=(frame-a.frame)/(b.frame-a.frame); + return a.polygons.map((p,i)=>({...p,points:p.points.map((v,j)=>v.map((n,c)=>n+(b.polygons[i].points[j][c]-n)*t))})); +} + +/** Layout is tested in surface coordinates before projective mapping. */ +export function assertSurfaceLayout(boxes, {width,height,padding=0}) { + for(const b of boxes)if(![b.x,b.y,b.width,b.height].every(finite)||b.width<0||b.height<0||b.xwidth-padding||b.y+b.height>height-padding)throw Error(`Artwork ${b.id??''} exceeds the surface safe area`); + return true; +} + +export async function loadPreparedAnalysis({asset,mediaInfo}, id) { + if(!asset||!mediaInfo)throw Error('Prepared media requires asset and mediaInfo host services'); + const response=await fetch(asset(id));if(!response.ok)throw Error(`Cannot load prepared analysis ${id}`); + const data=await response.json(), source=mediaInfo(data.source.asset); + validatePreparedAnalysis(data,source); + const mask=mediaInfo(data.alpha.asset); + if(mask.sha256!==data.alpha.sha256 || mask.frames!==data.source.frames || mask.width!==data.source.width || mask.height!==data.source.height)throw Error('Prepared mask bytes, dimensions or frame count changed'); + return data; +} diff --git a/packages/plate/surface.mjs b/packages/plate/surface.mjs new file mode 100644 index 0000000..0cf74a3 --- /dev/null +++ b/packages/plate/surface.mjs @@ -0,0 +1,73 @@ +import {solveHomography,applyHomography,rectQuad,quadArea} from './homography.mjs'; +const point=p=>Array.isArray(p)&&p.length===2&&p.every(Number.isFinite); + +/** A rigid cylindrical body in an authored/tracked projected quad. This is an + * image-space surface fit, not an inferred metric camera or hidden geometry. + * The axis/seam is authored when a blank cylinder makes rotation unobservable. */ +export function cylinderMesh(quad,{columns=64,rows=8,seam=0,arc=Math.PI*2}={}) { + if(!Number.isSafeInteger(columns)||columns<2||columns>256||!Number.isSafeInteger(rows)||rows<1||rows>128||!Number.isFinite(seam)||!(arc>0&&arc<=Math.PI*2))throw Error('Invalid cylinder tessellation or seam'); + if(quadArea(quad)<=0)throw Error('Cylinder body quad is mirrored or degenerate'); + const h=solveHomography(rectQuad(1,1),quad),vertices=[],uv=[],triangles=[]; + for(let y=0;y<=rows;y++)for(let x=0;x<=columns;x++){ + const nx=x/columns*2-1; + vertices.push(applyHomography(h,[(nx+1)/2,y/rows])); + uv.push([.5+Math.asin(Math.max(-1,Math.min(1,nx)))/arc+seam,y/rows]); + } + for(let y=0;y40000||!mesh.vertices.every(point)||!Array.isArray(mesh.uv)||mesh.uv.length!==mesh.vertices.length||!mesh.uv.every(point)||!Array.isArray(mesh.triangles)||mesh.triangles.length>80000)throw Error('Surface needs bounded vertices, UVs and triangles'); + for(const t of mesh.triangles)if(!Array.isArray(t)||t.length!==3||t.some(i=>!Number.isSafeInteger(i)||i<0||i>=mesh.vertices.length)||new Set(t).size!==3)throw Error('Invalid surface triangle'); + return mesh; +} + +/** Tracked cloth/mesh import path: each key supplies corresponding vertices. + * Visibility and tracking quality remain prepared inputs. No extrapolation. */ +export function sampleSurface(track,frame) { + if(!track||track.version!==1||!Array.isArray(track.frames)||!track.frames.length||!Number.isFinite(frame))throw Error('Invalid surface track'); + let previous=-1; + for(const f of track.frames){if(!Number.isSafeInteger(f.frame)||f.frame<=previous)throw Error('Surface frames must increase');previous=f.frame;validateSurfaceMesh(f);} + const exact=track.frames.find(f=>f.frame===frame);if(exact){if(exact.valid===false)throw Error(`Invalid surface at ${frame}`);return exact;} + const next=track.frames.findIndex(f=>f.frame>frame);if(next<=0)throw Error(`Surface frame ${frame} outside tracked range`); + const a=track.frames[next-1],b=track.frames[next]; + if(a.valid===false||b.valid===false||JSON.stringify(a.triangles)!==JSON.stringify(b.triangles)||a.vertices.length!==b.vertices.length||JSON.stringify(a.uv)!==JSON.stringify(b.uv))throw Error('Surface visibility/topology changes require an explicit key'); + const t=(frame-a.frame)/(b.frame-a.frame); + return {...a,frame,vertices:a.vertices.map((p,i)=>p.map((v,j)=>v+(b.vertices[i][j]-v)*t))}; +} + +/** Triangulated UV artwork warp. The caller supplies surface coverage and + * foreground holdouts. Lids/contact shadows remain in the unmodified plate. */ +export function drawSurfaceArtwork(context,artwork,mesh,{wrap=false}={}) { + validateSurfaceMesh(mesh); + const w=artwork.naturalWidth??artwork.width,h=artwork.naturalHeight??artwork.height; + if(!(w>0&&h>0))throw Error('Artwork has no decoded dimensions'); + for(const triangle of mesh.triangles){ + const to=triangle.map(i=>mesh.vertices[i]),from=triangle.map(i=>[mesh.uv[i][0]*w,mesh.uv[i][1]*h]); + const [[x0,y0],[x1,y1],[x2,y2]]=from,det=(x1-x0)*(y2-y0)-(x2-x0)*(y1-y0); + if(Math.abs(det)<1e-8)continue; + const coeff=axis=>{const [v0,v1,v2]=to.map(p=>p[axis]);const a=((v1-v0)*(y2-y0)-(v2-v0)*(y1-y0))/det,b=((x1-x0)*(v2-v0)-(x2-x0)*(v1-v0))/det;return[a,b,v0-a*x0-b*y0];}; + const [a,c,e]=coeff(0),[b,d,f]=coeff(1); + context.save();context.beginPath();to.forEach(([x,y],i)=>i?context.lineTo(x,y):context.moveTo(x,y));context.closePath();context.clip();context.transform(a,b,c,d,e,f); + if(wrap){context.fillStyle=context.createPattern(artwork,'repeat-x');context.fillRect(-w*4,0,w*9,h);}else context.drawImage(artwork,0,0); + context.restore(); + } +} + +/** Preserve observed shading on a neutral original body. `reference` is the + * original albedo (0..255); arbitrary old printing needs an independent clean + * albedo/shading estimate, rather than pretending multiplication removes it. */ +export function relightArtwork(artwork,plate,{reference=180,strength=1}={}) { + if(artwork.length!==plate.length||artwork.length%4||!(reference>0&&reference<=255)||!(strength>=0&&strength<=1))throw Error('Invalid reskin rasters or neutral reference'); + const out=new Uint8ClampedArray(artwork); + for(let i=0;iMath.hypot(p[0]-actual[i][0],p[1]-actual[i][1])).sort((a,b)=>a-b); + return {max:errors.at(-1),p95:errors[Math.ceil(errors.length*.95)-1],mean:errors.reduce((a,b)=>a+b,0)/errors.length}; +} diff --git a/packages/plate/typography.mjs b/packages/plate/typography.mjs new file mode 100644 index 0000000..f84259a --- /dev/null +++ b/packages/plate/typography.mjs @@ -0,0 +1,28 @@ +/** Seekable motion design. Curves are analytic functions of explicit seconds; + * no animation depends on the previously requested frame. */ +const clamp=x=>Math.max(0,Math.min(1,x)); +export function typeMotion(seconds,{start=0,duration=.65,hold=2,exit=.35,index=0,stagger=.06,effect='rise',distance=60,turn=0,pathRadius=80}={}) { + if(![seconds,start,duration,hold,exit,index,stagger,distance,turn,pathRadius].every(Number.isFinite)||duration<=0||hold<0||exit<0||index<0||stagger<0)throw Error('Invalid typography timing'); + if(!['rise','wipe','spring','orbit','extrude'].includes(effect))throw Error('Unknown typography treatment'); + const t=seconds-start-index*stagger,p=clamp(t/duration),q=exit===0?(t>duration+hold?1:0):clamp((t-duration-hold)/exit),ease=1-(1-p)**3; + let x=0,y=(1-ease)*distance,scale=1,rotate=(1-ease)*turn; + if(effect==='spring'){scale=p===1?1:1-Math.exp(-7*p)*Math.cos(11*p);y=(1-p)*distance*Math.exp(-3*p);} + if(effect==='orbit'){const angle=(1-ease)*Math.PI; x=Math.sin(angle)*pathRadius;y=(1-Math.cos(angle))*pathRadius;rotate+=(1-ease)*90;} + if(effect==='wipe')y=0; + return {opacity:t<0?0:(effect==='wipe'?1:ease)*(1-q),x,y:y-q*distance,scale,rotate,clip:effect==='wipe'?`inset(0 ${(1-ease)*100}% 0 0)`:undefined,extrusion:effect==='extrude'?8*(1-q):0}; +} + +export function createKineticText({root,text='',effect='rise',split='words',document:doc=root.ownerDocument}) { + const group=doc.createElement('span');group.style.cssText='display:inline;white-space:pre-wrap';root.append(group); + let signature='',nodes=[]; + return { + render(seconds,{text:next=text,effect:treatment=effect,split:mode=split,...options}={}){ + const key=JSON.stringify([next,mode]); + if(key!==signature){signature=key;group.replaceChildren();const units=mode==='characters'?(typeof Intl.Segmenter==='function'?[...new Intl.Segmenter(undefined,{granularity:'grapheme'}).segment(String(next))].map(s=>s.segment):Array.from(String(next))):String(next).split(/(\s+)/);nodes=units.map(unit=>{const node=doc.createElement('span');node.textContent=unit;node.style.cssText='display:inline-block;white-space:pre;transform-origin:50% 70%';group.append(node);return node;});} + let index=0; + for(const node of nodes){const blank=/^\s*$/.test(node.textContent),m=typeMotion(seconds,{...options,effect:treatment,index:blank?Math.max(0,index-1):index++});Object.assign(node.style,{opacity:String(m.opacity),transform:`translate(${m.x}px,${m.y}px) rotate(${m.rotate}deg) scale(${m.scale})`,clipPath:m.clip??'none',textShadow:m.extrusion?Array.from({length:Math.round(m.extrusion)},(_,i)=>`${i+1}px ${i+1}px 0 rgba(0,0,0,.32)`).join(','):'none'});} + }, + bounds(){return nodes.filter(n=>n.textContent.trim()).map((n,i)=>({id:String(i),x:n.offsetLeft,y:n.offsetTop,width:n.offsetWidth,height:n.offsetHeight}));}, + dispose(){group.remove();}, + }; +} diff --git a/packages/runtime/editor.mjs b/packages/runtime/editor.mjs index 43b8756..4b53419 100644 --- a/packages/runtime/editor.mjs +++ b/packages/runtime/editor.mjs @@ -13,10 +13,11 @@ export async function mount({templates,createRenderer,scene,binding,initial,medi if(assetIds.length)services.asset=id=>{if(!assetIds.includes(id))throw Error('Undeclared asset: '+id);return '/__ef/source/'+encodeURIComponent(id);}; if(Object.keys(mediaCatalog).length){ // Facts about a declared asset, and the data derived from it (matte, depth, track, camera). - services.mediaInfo=id=>{const a=mediaCatalog[id];if(!a)throw Error('Undeclared asset: '+id);return {type:a.type,width:a.width,height:a.height,duration:a.duration,frames:a.pts?.length??0,frameRate:a.frameRate?{...a.frameRate}:undefined,derived:a.derived?structuredClone(a.derived):undefined};}; + services.mediaInfo=id=>{const a=mediaCatalog[id];if(!a)throw Error('Undeclared asset: '+id);return {sha256:a.sha256,pts:[...(a.pts??[])],type:a.type,width:a.width,height:a.height,duration:a.duration,frames:a.pts?.length??0,frameRate:a.frameRate?{...a.frameRate}:undefined,derived:a.derived?structuredClone(a.derived):undefined};}; services.derived=(id,role)=>{if(!mediaCatalog[id])throw Error('Undeclared asset: '+id);return Object.keys(mediaCatalog).find(key=>mediaCatalog[key].derived?.of===id&&mediaCatalog[key].derived.role===role);}; } - if(Object.keys(mediaCatalog).length)services.mediaFrame=(id,time)=>{const a=mediaCatalog[id];if(!a||a.type==='audio'||a.type==='data')throw Error('Missing visual asset: '+id);const index=ptsIndex(a.pts,time);return index<0?undefined:a.url+String(index+1).padStart(6,'0')+'.png';}; + if(Object.keys(mediaCatalog).length)services.mediaFrame=(id,time)=>{const a=mediaCatalog[id];if(!a||a.type==='audio'||a.type==='data')throw Error('Missing visual asset: '+id);const index=ptsIndex(a.derived&&mediaCatalog[a.derived.of]?.type==='video'?mediaCatalog[a.derived.of].pts:a.pts,time);return index<0?undefined:a.url+String(index+1).padStart(6,'0')+'.png';}; + services.sourceFrame=(id,index)=>{const a=mediaCatalog[id];if(!a||!Number.isSafeInteger(index)||index<0||index>=a.pts.length)throw Error('Invalid declared source frame: '+id+':'+index);return a.url+String(index+1).padStart(6,'0')+'.png';}; const renderer=scene?createRendererCompositor(canvas,{scene,templates,services,capture}):createCompositor(canvas,{templates,createRenderer,host}),audio=createAudioPlayback(mediaCatalog);let selection=null,selectionVersion=0; if(scene)canvas.addEventListener('pointerdown',async event=>{ const ticket=++selectionVersion; diff --git a/packages/runtime/renderer-host.mjs b/packages/runtime/renderer-host.mjs index f0b9ae0..779d12e 100644 --- a/packages/runtime/renderer-host.mjs +++ b/packages/runtime/renderer-host.mjs @@ -11,7 +11,7 @@ export async function mountRenderer(scene,{root,props={},services={},timeoutMs=3 if (!root?.ownerDocument?.createElement || !root.append || !Number.isFinite(timeoutMs) || timeoutMs<=0) throw Error('Renderer host needs a DOM root and positive deadline'); const current=mergeProps(scene.defaultProps??{},props),readiness=new Readiness(),controller=new AbortController(); const supplied={}; - for (const key of ['asset','mediaFrame','captureSurface','mediaInfo','derived']) if (services[key]!==undefined) {if(typeof services[key]!=='function')throw Error(`Invalid ${key} service`);supplied[key]=services[key];} + for (const key of ['asset','mediaFrame','captureSurface','mediaInfo','derived','sourceFrame']) if (services[key]!==undefined) {if(typeof services[key]!=='function')throw Error(`Invalid ${key} service`);supplied[key]=services[key];} // Each mount owns a replaceable surface. A late async frame can only write // into its detached surface, never a retry's DOM. This is not a code sandbox. const surface=root.ownerDocument.createElement('div'); diff --git a/scripts/media.mjs b/scripts/media.mjs index c518470..af4c90f 100644 --- a/scripts/media.mjs +++ b/scripts/media.mjs @@ -1,5 +1,5 @@ import fs from 'node:fs/promises';import path from 'node:path';import os from 'node:os';import {createHash} from 'node:crypto';import {createReadStream} from 'node:fs'; -import {run,ffmpeg,ffprobe} from './process.mjs';import {validateDerived} from '../packages/plate/manifest.mjs';import {validateTrack} from '../packages/plate/track.mjs';import {validateCameraPath} from '../packages/plate/camera.mjs'; +import {run,ffmpeg,ffprobe} from './process.mjs';import {validateDerived} from '../packages/plate/manifest.mjs';import {validateTrack} from '../packages/plate/track.mjs';import {validatePreparedAnalysis} from '../packages/plate/prepared.mjs';import {validateCameraPath} from '../packages/plate/camera.mjs'; export async function fileHash(file){const h=createHash('sha256');for await(const chunk of createReadStream(file))h.update(chunk);return h.digest('hex')} export async function readAssets(dir){ let manifest;try{manifest=JSON.parse(await fs.readFile(path.join(dir,'assets.json'),'utf8'))}catch(e){if(e.code==='ENOENT')return {};throw e} @@ -9,7 +9,7 @@ export async function readAssets(dir){ const file=await fs.realpath(path.join(dir,a.src));if(!file.startsWith(dir+path.sep))throw Error('Asset escapes project: '+id); if(await fileHash(file)!==a.sha256)throw Error('Asset content changed: '+id+'; import it as a new immutable asset'); // `data` is small JSON a renderer reads (a track, a camera path); it is never decoded as media. - if(a.type==='data'){if((await fs.stat(file)).size>8*1024**2)throw Error('Data asset exceeds 8 MiB: '+id);let json;try{json=JSON.parse(await fs.readFile(file,'utf8'))}catch{throw Error('Data asset is not JSON: '+id)}if(a.derived?.role==='track')validateTrack(json);if(a.derived?.role==='camera')validateCameraPath(json);} + if(a.type==='data'){if((await fs.stat(file)).size>8*1024**2)throw Error('Data asset exceeds 8 MiB: '+id);let json;try{json=JSON.parse(await fs.readFile(file,'utf8'))}catch{throw Error('Data asset is not JSON: '+id)}if(a.derived?.role==='analysis')validatePreparedAnalysis(json);if(a.derived?.role==='track')validateTrack(json);if(a.derived?.role==='camera')validateCameraPath(json);} assets[id]={...a,file}; } // Mattes, depth, tracks and camera paths are pinned to the exact bytes they were computed from. @@ -53,6 +53,12 @@ export async function prepareMedia(assets,{signal,maxDecodedBytes=8*1024**3,maxF } // A per-frame matte or depth map only lines up when it has exactly the plate's frames. for(const [id,entry]of Object.entries(catalog)){const d=entry.derived;if(!d||entry.type!=='video')continue;const parent=catalog[d.of];if(parent.type==='video'&&parent.pts.length!==entry.pts.length)throw Error(`${id} has ${entry.pts.length} frames but ${d.of} has ${parent.pts.length}; a ${d.role} must match its plate frame for frame`)} + for(const [id,a]of Object.entries(frozenAssets))if(a.derived?.role==='analysis'){ + const receipt=JSON.parse(await fs.readFile(a.file,'utf8')),parent=catalog[a.derived.of]; + validatePreparedAnalysis(receipt,{...parent,frames:parent.pts.length}); + const mask=catalog[receipt.alpha.asset]; + if(!mask||mask.sha256!==receipt.alpha.sha256||mask.pts.length!==parent.pts.length||mask.width!==parent.width||mask.height!==parent.height)throw Error('Prepared alpha identity/raster differs: '+id); + } return {dir,catalog,assets:frozenAssets,close:()=>fs.rm(dir,{recursive:true,force:true})}; }catch(e){await fs.rm(dir,{recursive:true,force:true});throw e} } diff --git a/scripts/project.mjs b/scripts/project.mjs index 05f0447..10e5e6c 100644 --- a/scripts/project.mjs +++ b/scripts/project.mjs @@ -1,3 +1,4 @@ +import {validatePreparedAnalysis} from '../packages/plate/prepared.mjs'; import fs from 'node:fs/promises';import path from 'node:path';import {pathToFileURL} from 'node:url';import {createHash,randomUUID} from 'node:crypto';import {build} from 'esbuild'; import {root} from './build.mjs';import {Studio,clone} from '../packages/core/index.mjs';import {serve,sendFile} from './server.mjs';import {readAssets,prepareMedia,fileHash} from './media.mjs'; import {normalizeClipModule} from '../packages/core/definition.mjs';import {validateDerived} from '../packages/plate/manifest.mjs';import {validateTrack} from '../packages/plate/track.mjs';import {validateCameraPath} from '../packages/plate/camera.mjs'; @@ -97,7 +98,7 @@ export async function importAsset(dir,id,source,{type,role,of,encoding}={}){ const sha256=await fileHash(source),src='assets/'+sha256+ext;await fs.mkdir(path.join(dir,'assets'),{recursive:true});await fs.copyFile(source,path.join(dir,src)); const manifest={version:1,assets:{...d.assetIdentity,[id]:{src,type,sha256,...(derived?{derived}:{})}}}; // Validate the whole manifest before publishing it; a refused import leaves assets.json unchanged. - validateDerived(manifest.assets);if(type==='data'&&role){const json=JSON.parse(await fs.readFile(source,'utf8'));if(role==='track')validateTrack(json);if(role==='camera')validateCameraPath(json);} + validateDerived(manifest.assets);if(type==='data'&&role){const json=JSON.parse(await fs.readFile(source,'utf8'));if(role==='analysis')validatePreparedAnalysis(json);if(role==='track')validateTrack(json);if(role==='camera')validateCameraPath(json);} const file=path.join(dir,'assets.json'),tmp=file+'.'+randomUUID()+'.tmp';await fs.writeFile(tmp,JSON.stringify(manifest,null,2));await fs.rename(tmp,file); // Rebinding is separate and explicit; the old project/source snapshot is retained. return {id,sha256,next:'Run rebind to accept the added asset; set a media port to its ID.'}; diff --git a/tests/hybrid-prepared.test.mjs b/tests/hybrid-prepared.test.mjs new file mode 100644 index 0000000..b23e44a --- /dev/null +++ b/tests/hybrid-prepared.test.mjs @@ -0,0 +1,46 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import {validatePreparedAnalysis,preparedFrame,analyzeMask,sampleMaskCorrections,assertSurfaceLayout,cylinderMesh,sampleSurface,surfaceError,typeMotion} from '../packages/plate/index.mjs'; +const hash='a'.repeat(64),maskHash='b'.repeat(64); +const receipt=()=>({version:1,kind:'prepared-plate',subject:'hand',revision:'c'.repeat(64),source:{asset:'plate',sha256:hash,width:100,height:80,frames:3,frameRate:{num:24,den:1},pts:[0,1/24,2/24],orientation:0,crop:[0,0,100,80]},alpha:{asset:'mask',sha256:maskHash,channel:'luminance',semantics:'segmentation'},provenance:{method:'manual','preprocess':'test/1'},frames:[0,1,2].map(i=>({sourceFrame:i,maskFrame:i,valid:true,reviewed:true}))}); +test('prepared source identity, correspondence and review survive trims/reverse/random seeks',()=>{ + const r=validatePreparedAnalysis(receipt()); + assert.equal(preparedFrame(r,1/24).sourceFrame,1); + assert.equal(preparedFrame(r,1/24,{start:2/24,speed:-1}).sourceFrame,1); + assert.equal(preparedFrame(r,0).sourceFrame,0); + assert.throws(()=>preparedFrame(r,3/24),/outside/); + const stale=receipt();assert.throws(()=>validatePreparedAnalysis(stale,{...stale.source,sha256:maskHash}),/changed/); + const missing=receipt();missing.frames.pop();assert.throws(()=>validatePreparedAnalysis(missing),/correspondence/); + const bad=receipt();bad.frames[1].valid=false;assert.throws(()=>preparedFrame(bad,1/24),/frame 1/); + bad.frames[1].valid=true;bad.frames[1].reviewed=false;assert.throws(()=>preparedFrame(bad,1/24),/review/); +}); +test('mask collapse is flagged without erasing disconnected finger components',()=>{ + const pixels=new Uint8ClampedArray(4*100);for(const p of [1,3,10,99])pixels.fill(255,p*4,p*4+4); + const a=analyzeMask(pixels,10,10,{previousCoverage:.5}); + assert.equal(a.coverage,.04);assert.deepEqual(a.bounds,[0,0,10,10]);assert.deepEqual(a.issues,['foreground-area-collapse']); +}); +test('corrections propagate only inside authored matching intervals',()=>{ + const polygon=x=>({operation:'add',points:[[x,0],[x+4,0],[x+4,4],[x,4]]}); + const b={version:1,sourceSha256:hash,subject:'hand',keys:[{frame:10,interpolation:'linear',polygons:[polygon(0)]},{frame:20,polygons:[polygon(10)]}]}; + assert.equal(sampleMaskCorrections(b,15)[0].points[0][0],5);assert.deepEqual(sampleMaskCorrections(b,21),[]); + b.keys[1].polygons[0].operation='subtract';assert.throws(()=>sampleMaskCorrections(b,15),/topology/); +}); +test('surface layout rejects overflowing footer rather than silently clipping it',()=>{ + assertSurfaceLayout([{x:10,y:10,width:80,height:30}],{width:100,height:60}); + assert.throws(()=>assertSurfaceLayout([{id:'footer',x:0,y:58,width:100,height:10}],{width:100,height:60}),/footer/); +}); +test('cylindrical mapping keeps the original body bounds and non-linear UV spacing',()=>{ + const m=cylinderMesh([[10,20],[110,20],[110,220],[10,220]],{columns:4,rows:1}); + assert.deepEqual(m.vertices[0],[10,20]);assert.deepEqual(m.vertices[4],[110,20]);assert.equal(m.vertices.at(-1)[1],220); + assert.equal(m.uv[2][0],.5);assert.ok(m.uv[1][0]>.25,'surface curvature compresses the edge texture'); + assert.equal(surfaceError(m.vertices,m.vertices).max,0); + const a={frame:0,...m},b={frame:10,...m,vertices:m.vertices.map(([x,y])=>[x+20,y])}; + assert.equal(sampleSurface({version:1,frames:[a,b]},5).vertices[0][0],20); + assert.throws(()=>sampleSurface({version:1,frames:[a,b]},11),/outside/); +}); +test('all text treatments reproduce after reverse/random seeks and retain readable holds',()=>{ + for(const effect of ['rise','wipe','spring','orbit','extrude']){ + const first=typeMotion(.3,{effect});typeMotion(2,{effect});typeMotion(0,{effect});assert.deepEqual(typeMotion(.3,{effect}),first); + assert.equal(typeMotion(-1,{effect}).opacity,0);assert.equal(typeMotion(1.5,{effect}).opacity,1);assert.equal(typeMotion(4,{effect}).opacity,0); + } +}); From c1160c9ed94866ca4eb121c48a62f63a8dac5859 Mon Sep 17 00:00:00 2001 From: Laurence Xavier <35849747+lxf82dev@users.noreply.github.com> Date: Wed, 11 Nov 2026 16:35:46 +0800 Subject: [PATCH 14/49] Add correction authoring, exact alpha playback and original-object reskin --- bin/editableframe.mjs | 4 +- docs/hybrid-compositing-plan.md | 2 + docs/hybrid-scenes.md | 2 + docs/prepared-plates.md | 35 +++++++++++ examples/hybrid-surfaces/clip.mjs | 61 +++++++++++++++++++ package.json | 3 +- packages/plate/correction-session.mjs | 29 +++++++++ packages/plate/foreground.mjs | 17 +++++- packages/plate/index.mjs | 2 + packages/plate/manifest.mjs | 7 ++- packages/plate/prepared.mjs | 24 +++++++- packages/plate/raster-surface.mjs | 25 ++++++++ packages/plate/surface.mjs | 20 +++--- packages/runtime/editor.mjs | 2 +- scripts/project.mjs | 4 +- .../references/hybrid-compositing-plan.md | 2 + skills/editableframes/references/hybrid.md | 2 + .../references/prepared-plates.md | 35 +++++++++++ tests/hybrid-prepared.test.mjs | 29 ++++++++- tests/prepared-integration.mjs | 32 ++++++++++ 20 files changed, 314 insertions(+), 23 deletions(-) create mode 100644 docs/prepared-plates.md create mode 100644 examples/hybrid-surfaces/clip.mjs create mode 100644 packages/plate/correction-session.mjs create mode 100644 packages/plate/raster-surface.mjs create mode 100644 skills/editableframes/references/prepared-plates.md create mode 100644 tests/prepared-integration.mjs diff --git a/bin/editableframe.mjs b/bin/editableframe.mjs index edad244..accf3f5 100755 --- a/bin/editableframe.mjs +++ b/bin/editableframe.mjs @@ -7,7 +7,7 @@ try{ if(cmd==='init')out(await init(args[0]||'my-clip',{template:args.includes('--media')?'media':args.includes('--renderer')?'renderer':args.includes('--hybrid')?'hybrid':'canvas'})); else if(cmd==='inspect'){const d=await readProject(args[0]),cap=d.studio.capabilities(d.studio.doc.clips[0].id);out({...cap,baseRevision:d.revision,history:{length:d.studio.history.length,cursor:d.studio.cursor}})} else if(cmd==='apply'){const p=JSON.parse(await fs.readFile(args[1],'utf8'));out(await mutate(args[0],d=>{if(p.baseRevision!==d.revision)throw Error('Stale revision: inspect again');d.studio.execute(p.command,d.studio.revision,'model')}))} - else if(cmd==='asset-add'){const depth=flag('--depth');out(await importAsset(args[0],args[1],args[2],{role:flag('--role'),of:flag('--of'),encoding:depth?{kind:depth,near:Number(flag('--near')),far:Number(flag('--far')),packing:flag('--packing')??'gray8'}:undefined}));} + else if(cmd==='asset-add'){const depth=flag('--depth');out(await importAsset(args[0],args[1],args[2],{role:flag('--role'),of:flag('--of'),subject:flag('--subject'),encoding:depth?{kind:depth,near:Number(flag('--near')),far:Number(flag('--far')),packing:flag('--packing')??'gray8'}:undefined}));} else if(cmd==='rebind')out(await rebind(args[0],{reset:args.includes('--reset')})); else if(cmd==='undo'||cmd==='redo')out(await mutate(args[0],d=>d.studio[cmd]())); else if(cmd==='preview'){const h=await preview(args[0],{port:Number(args[1]||8791)});console.log(h.url);for(const signal of ['SIGINT','SIGTERM'])process.once(signal,async()=>{h.server.closeAllConnections?.();await h.close();process.exit(0)})} @@ -16,6 +16,6 @@ try{ else if(cmd==='assets'){const {run}=await import('../scripts/assets.mjs');await run(args)} else if(cmd==='install-skill'){const {install}=await import('../scripts/install-skill.mjs');out(await install(args[0],args[1]))} else if(cmd==='doctor'){const {run,ffmpeg,ffprobe}=await import('../scripts/process.mjs');const {chromium}=await import('playwright');const checks={};for(const [name,command]of [['ffmpeg',ffmpeg()],['ffprobe',ffprobe()]]){try{checks[name]=(await run(command,['-version'])).toString().split('\n')[0]}catch(e){checks[name]='MISSING: '+e.message}}try{await fs.access(chromium.executablePath());checks.browser='installed'}catch{checks.browser='MISSING: run npx playwright install chromium'}out({node:process.version,version:'0.1.0-beta.1',platform:process.platform,checks,ready:Object.values(checks).every(x=>!x.startsWith('MISSING')),trust:'Local trusted source; not an untrusted-code sandbox',distribution:'source-checkout',npmPublished:false})} - else if(!cmd||cmd==='help'||cmd==='--help')console.log(`EditableFrames 0.1.0-beta.1\n\n init DIR [--media|--renderer|--hybrid] Create an editable clip (media and hybrid demos need FFmpeg)\n rebind DIR [--reset] Accept edited source; archive prior project\n inspect DIR JSON controls + current file revision\n apply DIR proposal.json Revision-checked atomic edit\n undo DIR | redo DIR Saved edit history\n preview DIR [PORT] Preview trusted code on loopback\n render DIR OUTPUT [--frames N] [--fps 30000/1001] [--format png]\n [--pass clay|depth|normal|id|matte] [--motion-blur ANGLE [--samples N]]\n .mp4 = opaque; .mov = alpha ProRes4444\n asset-add DIR ID FILE Pin local media; rebind then swap a port\n [--role matte|depth|normals|track|camera|environment --of PLATE_ID]\n [--depth inverse|linear --near N --far F] Data derived from a plate\n studio [PORT] Open all bundled studies and device library\n assets list|verify|pack|install-pack [FILE]\n install-skill codex|claude|grok|generic TARGET\n doctor Show environment requirements\n\nCustom clip modules are executable JavaScript. Use trusted projects.\nNo model, account, cloud service, or Stitchable installation required.`); + else if(!cmd||cmd==='help'||cmd==='--help')console.log(`EditableFrames 0.1.0-beta.1\n\n init DIR [--media|--renderer|--hybrid] Create an editable clip (media and hybrid demos need FFmpeg)\n rebind DIR [--reset] Accept edited source; archive prior project\n inspect DIR JSON controls + current file revision\n apply DIR proposal.json Revision-checked atomic edit\n undo DIR | redo DIR Saved edit history\n preview DIR [PORT] Preview trusted code on loopback\n render DIR OUTPUT [--frames N] [--fps 30000/1001] [--format png]\n [--pass clay|depth|normal|id|matte] [--motion-blur ANGLE [--samples N]]\n .mp4 = opaque; .mov = alpha ProRes4444\n asset-add DIR ID FILE Pin local media; rebind then swap a port\n [--role alpha|matte|depth|normals|track|camera|environment|analysis|surface|coverage|foreground --of PLATE_ID [--subject ID]]\n [--depth inverse|linear --near N --far F] Data derived from a plate\n studio [PORT] Open all bundled studies and device library\n assets list|verify|pack|install-pack [FILE]\n install-skill codex|claude|grok|generic TARGET\n doctor Show environment requirements\n\nCustom clip modules are executable JavaScript. Use trusted projects.\nNo model, account, cloud service, or Stitchable installation required.`); else throw Error('Unknown command. Run editableframes help'); }catch(e){console.error(e.message);process.exitCode=1} diff --git a/docs/hybrid-compositing-plan.md b/docs/hybrid-compositing-plan.md index 752b539..a0d12ab 100644 --- a/docs/hybrid-compositing-plan.md +++ b/docs/hybrid-compositing-plan.md @@ -2,6 +2,8 @@ Status: proposed next work, 2026-11-11. This is a design and acceptance plan, not an implemented API. It supersedes any inference that a successful render or a few attractive frames establish a usable hybrid clip. Existing primitives and their tested scope remain documented in [hybrid-scenes.md](hybrid-scenes.md). +Implementation update: the [prepared-media primitives](prepared-plates.md) now implement receipts, exact frame access, holdouts, corrections, cylinder/mesh replay and kinetic text. These mechanisms have synthetic regression coverage; the real-shot acceptance gates below still require full visual QA. Automatic geometry solving and production model selection remain research. + ## What the failed shots teach us | Observed failure | Diagnosis supported by the authored scenes | Required correction | diff --git a/docs/hybrid-scenes.md b/docs/hybrid-scenes.md index 97672ac..e514f0f 100644 --- a/docs/hybrid-scenes.md +++ b/docs/hybrid-scenes.md @@ -13,6 +13,8 @@ Stacking one on top of the other is easy and already worked. This document cover *The hybrid starter, frames 7 and 34. The plate is a synthetic diagnostic pattern, not footage. The can, its label, the price screen and the headline are code.* +See [prepared foreground and surface artwork](prepared-plates.md) for the implemented receipt, correction, holdout and motion APIs, and their verification limits. + ## Goal Make a code-rendered element belong to the footage it is placed in, while keeping what EditableFrames is for: the code part stays an editable document. Changing the label, the price or the language re-renders the same frames with only that change. Nothing is regenerated and the footage is not touched. diff --git a/docs/prepared-plates.md b/docs/prepared-plates.md new file mode 100644 index 0000000..2a039e2 --- /dev/null +++ b/docs/prepared-plates.md @@ -0,0 +1,35 @@ +# Prepared foreground and surface artwork + +The plate utilities now include versioned analysis receipts, explicit source-frame sampling, foreground holdouts, source-space corrections, cylinder/mesh artwork mapping and deterministic kinetic text. These are rendering and authoring primitives. Real footage still requires a reviewed subject mask and surface track; model success does not certify either. + +## Frozen analysis + +`validatePreparedAnalysis(receipt, sourceInfo)` checks source content identity, decoded raster, rational frame rate, presentation times, correspondence, mask identity, correction revision and preparation provenance. A receipt has `version:1`, `kind:"prepared-plate"`, `source`, `alpha`, `subject`, `revision`, `provenance` and one entry per source frame in `frames`. Each entry contains `sourceFrame`, `maskFrame`, `valid`, `reviewed` and optional diagnostic `issues`. + +`preparedFrame(receipt, seconds, {start, speed})` maps explicit clip time to a source frame, including trim and reverse. Final sampling rejects unreviewed, invalid and out-of-range data. Correction tools can explicitly opt into draft sampling with `requireReviewed:false, allowInvalid:true`; this is not export approval. Missing data never repeats its last frame. + +Import a receipt as a data asset with `--role analysis --of plate`, and its explicit-alpha media with `--role alpha --of plate`. `--subject ID` distinguishes derived assets for multiple subjects. `derived(plate, role, subject)` resolves that subject; the original two-argument form still resolves an unqualified role. The CLI verifies content hashes, while media preparation checks the receipt against the actual decoded plate and mask. + +The optional `sourceFrame(id, index, info)` host service returns the exact decoded frame. Prepared media uses indices even when lossless container timestamps have different precision. `mediaInfo` includes digest and presentation times. Existing `mediaFrame` calls on derived videos now follow the parent plate's frame index. + +## Foreground and corrections + +`createForegroundHoldout({root,width,height})` creates a child `root` for the affected code layers. Call `update(decodedMask,{channel,frame,...})` before capturing. `channel` is `alpha` or `luminance`; missing or wrong-sized masks throw. An uncorrected explicit-alpha image uses CSS GPU masking where supported. Luminance masks and live corrections use the CPU fallback. No model runs inside the renderer. + +Correction books bind `sourceSha256`, `subject` and increasing frame keys. Each key has polygons with `operation:"add"|"subtract"|"replace"` and source-raster `points`. `interpolation:"linear"` propagates only between matching polygon keys; it never extrapolates beyond them. `createMaskCorrectionSession` turns renderer gestures into immutable book proposals. The host applies revision checks and Undo. Re-prepare and review the corrected result before final export. + +`analyzeMask` reports coverage, bounds and collapse flags without deleting components. `foregroundLeakage` measures changed pixels inside an annotated opaque foreground. `diagnosticMask()` exposes the current subject coverage as a green overlay for a source/mask review view. These diagnostics flag work to review; they do not infer ground truth. + +## Surface mapping and motion + +`cylinderMesh` maps a label to an authored/tracked projected body quad. It preserves that body's screen bounds; the seam is an author control when a blank cylinder makes rotation unobservable. `sampleSurface` accepts externally tracked deforming UV meshes. `drawSurfaceArtwork` rasterizes UV triangles without translucent clip seams. `relightArtwork` preserves observed shading under a specified neutral-albedo assumption. Arbitrary old printing requires a separate clean albedo/shading estimate. + +The [surface example](../examples/hybrid-surfaces/clip.mjs) combines exact source frames, a selected original body, foreground protection, editable labeling and a motion headline. Supply assets named `plate`, `foreground`, `analysis` and `track`, or pass a prepared receipt/track and declared source/mask IDs as props. The body track must describe the original object's body, excluding lids, rims and background. + +`createKineticText` and `typeMotion` provide staggered rise, wipe, spring-like settle, orbit and CSS extrusion treatments. Timing, text, stagger, easing treatment and displacement are explicit inputs; random/reverse seeks reproduce the same state. Character splitting uses grapheme clusters where available. Font readiness and surface safe-area checks remain part of layout acceptance. + +## Verification and limits + +`npm run test:prepared` checks real pixels through the CLI: all protected opaque interiors survive every frame of an animated crossing, using both alpha and luminance paths, and missing masks reject capture. `tests/hybrid-prepared.test.mjs` checks identity, correspondence, reverse seeks, correction history, layout overflow and seam-free UV coverage. + +The primitives do not solve a camera, infer cloth geometry, remove an old object or recover uncontaminated hair colors automatically. The mesh and camera import paths accept externally prepared data. A physically impossible insertion still needs changed blocking or a different plate. The [delivery plan](hybrid-compositing-plan.md) retains separate quality gates for these tasks; device performance and real-shot usability require measurement. diff --git a/examples/hybrid-surfaces/clip.mjs b/examples/hybrid-surfaces/clip.mjs new file mode 100644 index 0000000..6279d82 --- /dev/null +++ b/examples/hybrid-surfaces/clip.mjs @@ -0,0 +1,61 @@ +import {defineRenderer} from 'editableframes/renderer'; +import {createFrameLoader,createForegroundHoldout,validatePreparedAnalysis,preparedFrame,sampleTrack,scalePoints,cylinderMesh,sampleSurface,drawSurfaceArtwork,relightArtwork,createKineticText,loadPreparedAnalysis,pendingMaskCorrections} from 'editableframes/plate'; + +export const controls={version:1,fields:[ + {key:'foregroundSource',anchor:'surface',path:'/foregroundSource',type:'media',mediaKind:'video',default:'plate',label:'Original object footage'}, + {key:'foregroundMask',anchor:'foreground',path:'/foregroundMask',type:'media',mediaKind:'video',default:'foreground',label:'Prepared foreground'}, + {key:'prepared',anchor:'foreground',path:'/prepared',type:'json',default:null,label:'Prepared analysis'}, + {key:'corrections',anchor:'foreground',path:'/corrections',type:'json',default:null,label:'Subject corrections'}, + {key:'track',anchor:'surface',path:'/track',type:'json',default:null,label:'Original body track'}, + {key:'meshTrack',anchor:'surface',path:'/meshTrack',type:'json',default:null,label:'Optional deforming UV mesh'}, + {key:'label',anchor:'label',path:'/label',type:'string',default:'LUMA',label:'Exact label'}, + {key:'detail',anchor:'label',path:'/detail',type:'string',default:'BLOOD ORANGE',label:'Small print'}, + {key:'color',anchor:'label',path:'/color',type:'color',default:'#ed5426',label:'Body colour'}, + {key:'seam',anchor:'surface',path:'/seam',type:'number',min:-1,max:1,default:0,animatable:true,label:'Authored label rotation'}, + {key:'reference',anchor:'lighting',path:'/reference',type:'number',min:1,max:255,default:180,label:'Neutral body reference'}, + {key:'shading',anchor:'lighting',path:'/shading',type:'number',min:0,max:1,default:1,label:'Preserve observed shading'}, + {key:'headline',anchor:'headline',path:'/headline',type:'string',default:'MADE TO MOVE.',label:'Motion title'}, + {key:'motion',anchor:'headline',path:'/motion',type:'string',default:'rise',label:'Text treatment'}, + {key:'plateStartFrame',anchor:'surface',path:'/plateStartFrame',type:'number',min:0,max:18000,default:0,label:'Source frame at start'}, + {key:'plateSpeed',anchor:'surface',path:'/plateSpeed',type:'number',min:-8,max:8,default:1,label:'Source speed'}, +]}; +const defaults=Object.fromEntries(controls.fields.map(f=>[f.key,f.default])); +export default defineRenderer({id:'surface-reskin',renderer:'canvas+dom',width:1920,height:1080,fps:24,durationInFrames:108000,controls,defaultProps:{...defaults,foregroundRequired:true}, + async create({root,props,sourceFrame,asset,mediaInfo}){ + if(!sourceFrame)throw Error('Surface reskin needs the host exact source-frame service'); + const initialPrepared=props.prepared??(mediaInfo?await loadPreparedAnalysis({asset,mediaInfo},'analysis'):null); + const initialTrack=props.track??(mediaInfo?await (await fetch(asset('track'))).json():null); + const doc=root.ownerDocument,stage=doc.createElement('div');stage.style.cssText='position:absolute;inset:0;overflow:hidden';root.append(stage); + const canvas=()=>{const c=doc.createElement('canvas');c.style.cssText='position:absolute;inset:0;width:100%;height:100%';return c;}; + const plate=canvas(),ink=canvas(),art=canvas();art.width=1024;art.height=1024;stage.append(plate); + const title=doc.createElement('div');title.style.cssText='position:absolute;left:5%;top:8%;width:88%;font:900 72px/1.05 system-ui;color:white'; + const kinetic=createKineticText({root:title}),frames=createFrameLoader({document:doc,max:6});let holdout=null,identity='',labelKey=''; + return { + async render(clock){ + if(props.preparedError)throw Error(props.preparedError); + const receipt=validatePreparedAnalysis(props.prepared??initialPrepared),s=receipt.source,track=props.track??initialTrack; + const pending=pendingMaskCorrections(props.corrections,receipt.provenance.appliedCorrections); + if(pending)throw Error('Corrections changed; prepare and review a new mask revision before rendering'); + if(!props.foregroundSource||!props.foregroundMask||!track)throw Error('Reskin needs the original source, foreground and original-body track'); + if(track.sourceSha256&&track.sourceSha256!==s.sha256)throw Error('Surface track belongs to a different take'); + const at=preparedFrame(receipt,clock.frame/clock.fps,{start:Number(props.plateStartFrame)*s.frameRate.den/s.frameRate.num,speed:Number(props.plateSpeed)}); + const w=root.clientWidth||clock.width,h=root.clientHeight||clock.height; + for(const c of [plate,ink])if(c.width!==w||c.height!==h){c.width=w;c.height=h;} + if(identity!==s.sha256){identity=s.sha256;holdout?.dispose();holdout=createForegroundHoldout({root:stage,width:s.width,height:s.height});holdout.root.append(ink,title);} + const info={width:s.width,height:s.height,seconds:at.seconds}; + const [image,mask]=await Promise.all([frames.load(sourceFrame(String(props.foregroundSource),at.sourceFrame,info)),frames.load(sourceFrame(String(props.foregroundMask),at.maskFrame,{...info,seconds:at.maskSeconds}))]); + const pc=plate.getContext('2d',{willReadFrequently:true});pc.drawImage(image,0,0,w,h); + const key=JSON.stringify([props.label,props.detail,props.color]); + if(key!==labelKey){labelKey=key;const c=art.getContext('2d');c.fillStyle=props.color;c.fillRect(0,0,1024,1024);c.fillStyle='white';c.textAlign='center';c.textBaseline='middle';c.font='900 130px system-ui';c.fillText(String(props.label),512,470,480);c.font='700 30px system-ui';c.fillText(String(props.detail),512,650,480);} + const pin=sampleTrack(track,at.seconds);if(pin.held||pin.confidence<=0)throw Error('Original body track is missing at source frame '+at.sourceFrame); + const fitted=props.meshTrack?sampleSurface(props.meshTrack,at.sourceFrame):null; + const mesh=fitted?{...fitted,vertices:scalePoints(fitted.vertices,track,w,h)}:cylinderMesh(scalePoints(pin.quad,track,w,h),{seam:Number(props.seam)}); + const ic=ink.getContext('2d',{willReadFrequently:true});ic.clearRect(0,0,w,h);drawSurfaceArtwork(ic,art,mesh,{wrap:true}); + const pixels=ic.getImageData(0,0,w,h);pixels.data.set(relightArtwork(pixels.data,pc.getImageData(0,0,w,h).data,{reference:Number(props.reference),strength:Number(props.shading)}));ic.putImageData(pixels,0,0); + holdout.update(mask,{channel:receipt.alpha.channel,corrections:pending,frame:at.sourceFrame,sourceSha256:s.sha256,subject:receipt.subject}); + kinetic.render(clock.frame/clock.fps,{text:String(props.headline),effect:String(props.motion),hold:3600,stagger:.08}); + }, + dispose(){frames.dispose();kinetic.dispose();holdout?.dispose();stage.remove();}, + }; + } +}); diff --git a/package.json b/package.json index c122474..a1c86c8 100644 --- a/package.json +++ b/package.json @@ -49,7 +49,8 @@ "build:scene": "node examples/scene-editor/build.mjs", "dev:scene": "node examples/scene-editor/serve.mjs", "test:scene": "node tests/scene-editor-browser.mjs", - "test:hybrid": "node tests/hybrid-integration.mjs" + "test:hybrid": "node tests/hybrid-integration.mjs", + "test:prepared": "node tests/prepared-integration.mjs" }, "dependencies": { "esbuild": "0.25.10", diff --git a/packages/plate/correction-session.mjs b/packages/plate/correction-session.mjs new file mode 100644 index 0000000..c78d4ba --- /dev/null +++ b/packages/plate/correction-session.mjs @@ -0,0 +1,29 @@ +/** A renderer gesture proposes an immutable correction book; the embedding + * editor owns commit/revision checks and Undo. No disk or model side effects. */ +export function createMaskCorrectionSession(){ + let active=null; + return { + gesture(event,{book,sourceSha256,subject,sourceFrame,sourceWidth,sourceHeight,width,height,operation='add',radius=12}={}){ + if(!['add','subtract','replace'].includes(operation)||![sourceWidth,sourceHeight,width,height,radius].every(n=>Number.isFinite(n)&&n>0)||!Number.isSafeInteger(sourceFrame)||sourceFrame<0)throw Error('Invalid correction gesture context'); + const point=p=>[Math.max(0,Math.min(sourceWidth,p.x/width*sourceWidth)),Math.max(0,Math.min(sourceHeight,p.y/height*sourceHeight))]; + if(event.phase==='cancel'){active=null;return null;} + if(event.phase==='begin'){ + if(book&&(book.sourceSha256!==sourceSha256||book.subject!==subject))throw Error('Correction source/subject changed'); + active={id:event.id,frame:sourceFrame,points:[point(event.start)],book:structuredClone(book??{version:1,sourceSha256,subject,keys:[]})};return null; + } + if(!active||active.id!==event.id)return null; + if(active.frame!==sourceFrame){active=null;throw Error('Source frame changed during correction');} + const p=point(event.point),last=active.points.at(-1); + if(Math.hypot(p[0]-last[0],p[1]-last[1])>1 && active.points.length<4096)active.points.push(p); + if(event.phase!=='commit')return null; + const pending=active;active=null; + const points=pending.points.length<3?Array.from({length:20},(_,i)=>{const a=i/20*Math.PI*2;return[p[0]+Math.cos(a)*radius,p[1]+Math.sin(a)*radius];}):pending.points; + const next=pending.book,existing=next.keys.find(k=>k.frame===sourceFrame); + const polygon={operation,points}; + if(existing)existing.polygons.push(polygon);else next.keys.push({frame:sourceFrame,polygons:[polygon]}); + next.keys.sort((a,b)=>a.frame-b.frame); + return {values:{corrections:next}}; + }, + cancel(){active=null;}, + }; +} diff --git a/packages/plate/foreground.mjs b/packages/plate/foreground.mjs index e71ed45..8926de4 100644 --- a/packages/plate/foreground.mjs +++ b/packages/plate/foreground.mjs @@ -10,14 +10,27 @@ export function createForegroundHoldout({root,width,height,document:doc=root.own content.style.cssText='position:absolute;inset:0;overflow:hidden';root.append(content); const canvas=doc.createElement('canvas');canvas.width=width;canvas.height=height; const c=canvas.getContext('2d',{willReadFrequently:true}); - let disposed=false; + let disposed=false,directMask=null; return { root:content, + diagnosticMask(){ + if(directMask){c.globalCompositeOperation='copy';c.drawImage(directMask,0,0,width,height);} + const image=c.getImageData(0,0,width,height); + for(let i=0;i>8;d[i]=d[i+1]=d[i+2]=255;d[i+3]=a;} @@ -35,7 +48,7 @@ export function createForegroundHoldout({root,width,height,document:doc=root.own for(let i=3;i>1; if(pts[mid]<=time+1e-9)lo=mid;else hi=mid; } const f=data.frames[lo]; - if (!f.valid || (requireReviewed && !f.reviewed)) throw Error(`Prepared subject ${data.subject} needs correction/review at source frame ${lo}${f.issues?.length ? ': '+f.issues.join(', ') : ''}`); + if ((!f.valid && !allowInvalid) || (requireReviewed && !f.reviewed)) throw Error(`Prepared subject ${data.subject} needs correction/review at source frame ${lo}${f.issues?.length ? ': '+f.issues.join(', ') : ''}`); return {...f, seconds:pts[lo], maskSeconds:pts[f.maskFrame]}; } @@ -97,3 +97,23 @@ export async function loadPreparedAnalysis({asset,mediaInfo}, id) { if(mask.sha256!==data.alpha.sha256 || mask.frames!==data.source.frames || mask.width!==data.source.width || mask.height!==data.source.height)throw Error('Prepared mask bytes, dimensions or frame count changed'); return data; } + +const ordered=value=>Array.isArray(value)?value.map(ordered):value&&typeof value==='object'?Object.fromEntries(Object.keys(value).sort().map(k=>[k,ordered(value[k])])):value; +/** Canonical masks already contain approved corrections. Live strokes are + * provisional; only an append-only delta can be previewed without raw input. */ +export function pendingMaskCorrections(book,applied){ + if(!book)return null; + validateMaskCorrections(book); + const equal=(a,b)=>JSON.stringify(ordered(a))===JSON.stringify(ordered(b)); + if(equal(book,applied))return null; + if(!applied)return book.keys.some(k=>k.polygons.length)?structuredClone(book):null; + validateMaskCorrections(applied); + if(book.sourceSha256!==applied.sourceSha256||book.subject!==applied.subject)throw Error('Correction identity changed'); + const pending=structuredClone(book);pending.keys=[]; + for(const old of applied.keys)if(!book.keys.some(k=>k.frame===old.frame))throw Error('Re-prepare from the original mask to remove baked corrections'); + for(const key of book.keys){const old=applied.keys.find(k=>k.frame===key.frame);const count=old?.polygons.length??0; + if(old&&(!equal(key.polygons.slice(0,count),old.polygons)||key.interpolation!==old.interpolation))throw Error('Re-prepare from the original mask to change baked corrections'); + if(key.polygons.length>count)pending.keys.push({...structuredClone(key),polygons:structuredClone(key.polygons.slice(count))}); + } + return pending.keys.length?pending:null; +} diff --git a/packages/plate/raster-surface.mjs b/packages/plate/raster-surface.mjs new file mode 100644 index 0000000..0cbe0a9 --- /dev/null +++ b/packages/plate/raster-surface.mjs @@ -0,0 +1,25 @@ +/** Rasterize a UV mesh once per output pixel without Canvas clip seams. + * The inverse barycentric map keeps adjacent triangles from double-blending + * antialiased clip edges. Output is straight RGBA; interpolation is premultiplied. */ +export function rasterizeSurface(pixels,sourceWidth,sourceHeight,mesh,width,height,{wrap=false}={}){ + if(pixels.length!==sourceWidth*sourceHeight*4||![sourceWidth,sourceHeight,width,height].every(n=>Number.isSafeInteger(n)&&n>0)||width*height>4096*4096)throw Error('Invalid surface raster dimensions'); + const out=new Uint8ClampedArray(width*height*4); + for(const t of mesh.triangles){ + const [a,b,c]=t.map(i=>mesh.vertices[i]),[ua,ub,uc]=t.map(i=>mesh.uv[i]); + const det=(b[1]-c[1])*(a[0]-c[0])+(c[0]-b[0])*(a[1]-c[1]);if(Math.abs(det)<1e-9)continue; + const x0=Math.max(0,Math.floor(Math.min(a[0],b[0],c[0]))),x1=Math.min(width,Math.ceil(Math.max(a[0],b[0],c[0]))),y0=Math.max(0,Math.floor(Math.min(a[1],b[1],c[1]))),y1=Math.min(height,Math.ceil(Math.max(a[1],b[1],c[1]))); + for(let y=y0;y1)continue; + if(v<0||v>1)continue; + const sx=u*(sourceWidth-1),sy=v*(sourceHeight-1),ix=Math.floor(sx),iy=Math.floor(sy),fx=sx-ix,fy=sy-iy; + const indices=[iy*sourceWidth+ix,iy*sourceWidth+Math.min(ix+1,sourceWidth-1),Math.min(iy+1,sourceHeight-1)*sourceWidth+ix,Math.min(iy+1,sourceHeight-1)*sourceWidth+Math.min(ix+1,sourceWidth-1)],weights=[(1-fx)*(1-fy),fx*(1-fy),(1-fx)*fy,fx*fy]; + let alpha=0;const rgb=[0,0,0]; + for(let i=0;i<4;i++){const j=indices[i]*4,aw=pixels[j+3]/255*weights[i];alpha+=aw;for(let k=0;k<3;k++)rgb[k]+=pixels[j+k]*aw;} + const dest=(y*width+x)*4;if(alpha>0){for(let k=0;k<3;k++)out[dest+k]=rgb[k]/alpha;out[dest+3]=alpha*255;} + } + } + return out; +} diff --git a/packages/plate/surface.mjs b/packages/plate/surface.mjs index 0cf74a3..3914d6d 100644 --- a/packages/plate/surface.mjs +++ b/packages/plate/surface.mjs @@ -1,3 +1,4 @@ +import {rasterizeSurface} from './raster-surface.mjs'; import {solveHomography,applyHomography,rectQuad,quadArea} from './homography.mjs'; const point=p=>Array.isArray(p)&&p.length===2&&p.every(Number.isFinite); @@ -39,20 +40,19 @@ export function sampleSurface(track,frame) { /** Triangulated UV artwork warp. The caller supplies surface coverage and * foreground holdouts. Lids/contact shadows remain in the unmodified plate. */ +const scratchCanvases=new WeakMap(); export function drawSurfaceArtwork(context,artwork,mesh,{wrap=false}={}) { validateSurfaceMesh(mesh); const w=artwork.naturalWidth??artwork.width,h=artwork.naturalHeight??artwork.height; if(!(w>0&&h>0))throw Error('Artwork has no decoded dimensions'); - for(const triangle of mesh.triangles){ - const to=triangle.map(i=>mesh.vertices[i]),from=triangle.map(i=>[mesh.uv[i][0]*w,mesh.uv[i][1]*h]); - const [[x0,y0],[x1,y1],[x2,y2]]=from,det=(x1-x0)*(y2-y0)-(x2-x0)*(y1-y0); - if(Math.abs(det)<1e-8)continue; - const coeff=axis=>{const [v0,v1,v2]=to.map(p=>p[axis]);const a=((v1-v0)*(y2-y0)-(v2-v0)*(y1-y0))/det,b=((x1-x0)*(v2-v0)-(x2-x0)*(v1-v0))/det;return[a,b,v0-a*x0-b*y0];}; - const [a,c,e]=coeff(0),[b,d,f]=coeff(1); - context.save();context.beginPath();to.forEach(([x,y],i)=>i?context.lineTo(x,y):context.moveTo(x,y));context.closePath();context.clip();context.transform(a,b,c,d,e,f); - if(wrap){context.fillStyle=context.createPattern(artwork,'repeat-x');context.fillRect(-w*4,0,w*9,h);}else context.drawImage(artwork,0,0); - context.restore(); - } + let scratch=scratchCanvases.get(context); + if(!scratch){const doc=context.canvas.ownerDocument;scratch={source:doc.createElement('canvas'),target:doc.createElement('canvas')};scratchCanvases.set(context,scratch);} + scratch.source.width=w;scratch.source.height=h; + const input=scratch.source.getContext('2d',{willReadFrequently:true});input.drawImage(artwork,0,0); + const width=context.canvas.width,height=context.canvas.height; + scratch.target.width=width;scratch.target.height=height; + const target=scratch.target.getContext('2d'),image=target.createImageData(width,height); + image.data.set(rasterizeSurface(input.getImageData(0,0,w,h).data,w,h,mesh,width,height,{wrap}));target.putImageData(image,0,0);context.drawImage(scratch.target,0,0); } /** Preserve observed shading on a neutral original body. `reference` is the diff --git a/packages/runtime/editor.mjs b/packages/runtime/editor.mjs index 4b53419..a05ed6c 100644 --- a/packages/runtime/editor.mjs +++ b/packages/runtime/editor.mjs @@ -14,7 +14,7 @@ export async function mount({templates,createRenderer,scene,binding,initial,medi if(Object.keys(mediaCatalog).length){ // Facts about a declared asset, and the data derived from it (matte, depth, track, camera). services.mediaInfo=id=>{const a=mediaCatalog[id];if(!a)throw Error('Undeclared asset: '+id);return {sha256:a.sha256,pts:[...(a.pts??[])],type:a.type,width:a.width,height:a.height,duration:a.duration,frames:a.pts?.length??0,frameRate:a.frameRate?{...a.frameRate}:undefined,derived:a.derived?structuredClone(a.derived):undefined};}; - services.derived=(id,role)=>{if(!mediaCatalog[id])throw Error('Undeclared asset: '+id);return Object.keys(mediaCatalog).find(key=>mediaCatalog[key].derived?.of===id&&mediaCatalog[key].derived.role===role);}; + services.derived=(id,role,subject)=>{if(!mediaCatalog[id])throw Error('Undeclared asset: '+id);return Object.keys(mediaCatalog).find(key=>mediaCatalog[key].derived?.of===id&&mediaCatalog[key].derived.role===role&&mediaCatalog[key].derived.subject===subject);}; } if(Object.keys(mediaCatalog).length)services.mediaFrame=(id,time)=>{const a=mediaCatalog[id];if(!a||a.type==='audio'||a.type==='data')throw Error('Missing visual asset: '+id);const index=ptsIndex(a.derived&&mediaCatalog[a.derived.of]?.type==='video'?mediaCatalog[a.derived.of].pts:a.pts,time);return index<0?undefined:a.url+String(index+1).padStart(6,'0')+'.png';}; services.sourceFrame=(id,index)=>{const a=mediaCatalog[id];if(!a||!Number.isSafeInteger(index)||index<0||index>=a.pts.length)throw Error('Invalid declared source frame: '+id+':'+index);return a.url+String(index+1).padStart(6,'0')+'.png';}; diff --git a/scripts/project.mjs b/scripts/project.mjs index 10e5e6c..71a5078 100644 --- a/scripts/project.mjs +++ b/scripts/project.mjs @@ -83,7 +83,7 @@ export async function rebind(dir,{reset=false}={}){ }finally{await fd.close();await fs.rm(lock,{force:true})} } -export async function importAsset(dir,id,source,{type,role,of,encoding}={}){ +export async function importAsset(dir,id,source,{type,role,of,encoding,subject}={}){ if(['__proto__','constructor','prototype'].includes(id)||!/^[a-zA-Z0-9_-]{1,80}$/.test(id))throw Error('Invalid asset ID'); dir=await fs.realpath(dir);const lock=path.join(dir,'.editableframe-edit.lock'),fd=await fs.open(lock,'wx'); try{ @@ -94,7 +94,7 @@ export async function importAsset(dir,id,source,{type,role,of,encoding}={}){ if(!['image','audio','video','data'].includes(type)||!/^\.[a-z0-9]{1,8}$/.test(ext))throw Error('Invalid asset type/extension'); // A derived asset records the hash of the take it describes, so a regenerated take cannot reuse it. if((role===undefined)!==(of===undefined))throw Error('Use --role and --of together'); - let derived;if(role){if(!Object.hasOwn(d.assets,of))throw Error('Unknown --of asset: '+of);derived={of,role,sourceSha256:d.assets[of].sha256,...(encoding?{encoding}:{})};} + let derived;if(role){if(!Object.hasOwn(d.assets,of))throw Error('Unknown --of asset: '+of);derived={of,role,sourceSha256:d.assets[of].sha256,...(subject?{subject}:{}),...(encoding?{encoding}:{})};} const sha256=await fileHash(source),src='assets/'+sha256+ext;await fs.mkdir(path.join(dir,'assets'),{recursive:true});await fs.copyFile(source,path.join(dir,src)); const manifest={version:1,assets:{...d.assetIdentity,[id]:{src,type,sha256,...(derived?{derived}:{})}}}; // Validate the whole manifest before publishing it; a refused import leaves assets.json unchanged. diff --git a/skills/editableframes/references/hybrid-compositing-plan.md b/skills/editableframes/references/hybrid-compositing-plan.md index 3339a0e..c77e5b9 100644 --- a/skills/editableframes/references/hybrid-compositing-plan.md +++ b/skills/editableframes/references/hybrid-compositing-plan.md @@ -2,6 +2,8 @@ Status: proposed next work, 2026-11-11. This is a design and acceptance plan, not an implemented API. It supersedes any inference that a successful render or a few attractive frames establish a usable hybrid clip. Existing primitives and their tested scope remain documented in [hybrid guide](hybrid.md). +Implementation update: the [prepared-media primitives](prepared-plates.md) now implement receipts, exact frame access, holdouts, corrections, cylinder/mesh replay and kinetic text. These mechanisms have synthetic regression coverage; the real-shot acceptance gates below still require full visual QA. Automatic geometry solving and production model selection remain research. + ## What the failed shots teach us | Observed failure | Diagnosis supported by the authored scenes | Required correction | diff --git a/skills/editableframes/references/hybrid.md b/skills/editableframes/references/hybrid.md index 2ab8de5..4abf112 100644 --- a/skills/editableframes/references/hybrid.md +++ b/skills/editableframes/references/hybrid.md @@ -9,6 +9,8 @@ A hybrid scene combines two kinds of picture in one shot: Stacking one on top of the other is easy and already worked. This document covers the harder case, where the two must agree with each other: a hand passes in front of a code-rendered product, a headline sits behind a presenter, a price stays stuck to a moving sign, the product is lit by the room it stands in. +See [prepared foreground and surface artwork](prepared-plates.md) for the implemented receipt, correction, holdout and motion APIs, and their verification limits. + ## Goal Make a code-rendered element belong to the footage it is placed in, while keeping what EditableFrames is for: the code part stays an editable document. Changing the label, the price or the language re-renders the same frames with only that change. Nothing is regenerated and the footage is not touched. diff --git a/skills/editableframes/references/prepared-plates.md b/skills/editableframes/references/prepared-plates.md new file mode 100644 index 0000000..1051622 --- /dev/null +++ b/skills/editableframes/references/prepared-plates.md @@ -0,0 +1,35 @@ +# Prepared foreground and surface artwork + +The plate utilities now include versioned analysis receipts, explicit source-frame sampling, foreground holdouts, source-space corrections, cylinder/mesh artwork mapping and deterministic kinetic text. These are rendering and authoring primitives. Real footage still requires a reviewed subject mask and surface track; model success does not certify either. + +## Frozen analysis + +`validatePreparedAnalysis(receipt, sourceInfo)` checks source content identity, decoded raster, rational frame rate, presentation times, correspondence, mask identity, correction revision and preparation provenance. A receipt has `version:1`, `kind:"prepared-plate"`, `source`, `alpha`, `subject`, `revision`, `provenance` and one entry per source frame in `frames`. Each entry contains `sourceFrame`, `maskFrame`, `valid`, `reviewed` and optional diagnostic `issues`. + +`preparedFrame(receipt, seconds, {start, speed})` maps explicit clip time to a source frame, including trim and reverse. Final sampling rejects unreviewed, invalid and out-of-range data. Correction tools can explicitly opt into draft sampling with `requireReviewed:false, allowInvalid:true`; this is not export approval. Missing data never repeats its last frame. + +Import a receipt as a data asset with `--role analysis --of plate`, and its explicit-alpha media with `--role alpha --of plate`. `--subject ID` distinguishes derived assets for multiple subjects. `derived(plate, role, subject)` resolves that subject; the original two-argument form still resolves an unqualified role. The CLI verifies content hashes, while media preparation checks the receipt against the actual decoded plate and mask. + +The optional `sourceFrame(id, index, info)` host service returns the exact decoded frame. Prepared media uses indices even when lossless container timestamps have different precision. `mediaInfo` includes digest and presentation times. Existing `mediaFrame` calls on derived videos now follow the parent plate's frame index. + +## Foreground and corrections + +`createForegroundHoldout({root,width,height})` creates a child `root` for the affected code layers. Call `update(decodedMask,{channel,frame,...})` before capturing. `channel` is `alpha` or `luminance`; missing or wrong-sized masks throw. An uncorrected explicit-alpha image uses CSS GPU masking where supported. Luminance masks and live corrections use the CPU fallback. No model runs inside the renderer. + +Correction books bind `sourceSha256`, `subject` and increasing frame keys. Each key has polygons with `operation:"add"|"subtract"|"replace"` and source-raster `points`. `interpolation:"linear"` propagates only between matching polygon keys; it never extrapolates beyond them. `createMaskCorrectionSession` turns renderer gestures into immutable book proposals. The host applies revision checks and Undo. Re-prepare and review the corrected result before final export. + +`analyzeMask` reports coverage, bounds and collapse flags without deleting components. `foregroundLeakage` measures changed pixels inside an annotated opaque foreground. `diagnosticMask()` exposes the current subject coverage as a green overlay for a source/mask review view. These diagnostics flag work to review; they do not infer ground truth. + +## Surface mapping and motion + +`cylinderMesh` maps a label to an authored/tracked projected body quad. It preserves that body's screen bounds; the seam is an author control when a blank cylinder makes rotation unobservable. `sampleSurface` accepts externally tracked deforming UV meshes. `drawSurfaceArtwork` rasterizes UV triangles without translucent clip seams. `relightArtwork` preserves observed shading under a specified neutral-albedo assumption. Arbitrary old printing requires a separate clean albedo/shading estimate. + +The [surface example](https://github.com/Stitchable-ai/editable-frames/blob/feat/hybrid-scenes/examples/hybrid-surfaces/clip.mjs) combines exact source frames, a selected original body, foreground protection, editable labeling and a motion headline. Supply assets named `plate`, `foreground`, `analysis` and `track`, or pass a prepared receipt/track and declared source/mask IDs as props. The body track must describe the original object's body, excluding lids, rims and background. + +`createKineticText` and `typeMotion` provide staggered rise, wipe, spring-like settle, orbit and CSS extrusion treatments. Timing, text, stagger, easing treatment and displacement are explicit inputs; random/reverse seeks reproduce the same state. Character splitting uses grapheme clusters where available. Font readiness and surface safe-area checks remain part of layout acceptance. + +## Verification and limits + +`npm run test:prepared` checks real pixels through the CLI: all protected opaque interiors survive every frame of an animated crossing, using both alpha and luminance paths, and missing masks reject capture. `tests/hybrid-prepared.test.mjs` checks identity, correspondence, reverse seeks, correction history, layout overflow and seam-free UV coverage. + +The primitives do not solve a camera, infer cloth geometry, remove an old object or recover uncontaminated hair colors automatically. The mesh and camera import paths accept externally prepared data. A physically impossible insertion still needs changed blocking or a different plate. The [delivery plan](hybrid-compositing-plan.md) retains separate quality gates for these tasks; device performance and real-shot usability require measurement. diff --git a/tests/hybrid-prepared.test.mjs b/tests/hybrid-prepared.test.mjs index b23e44a..d6c0fa9 100644 --- a/tests/hybrid-prepared.test.mjs +++ b/tests/hybrid-prepared.test.mjs @@ -1,6 +1,6 @@ import test from 'node:test'; import assert from 'node:assert/strict'; -import {validatePreparedAnalysis,preparedFrame,analyzeMask,sampleMaskCorrections,assertSurfaceLayout,cylinderMesh,sampleSurface,surfaceError,typeMotion} from '../packages/plate/index.mjs'; +import {validatePreparedAnalysis,preparedFrame,analyzeMask,sampleMaskCorrections,assertSurfaceLayout,cylinderMesh,sampleSurface,surfaceError,typeMotion,createMaskCorrectionSession,rasterizeSurface,validateDerived,pendingMaskCorrections} from '../packages/plate/index.mjs'; const hash='a'.repeat(64),maskHash='b'.repeat(64); const receipt=()=>({version:1,kind:'prepared-plate',subject:'hand',revision:'c'.repeat(64),source:{asset:'plate',sha256:hash,width:100,height:80,frames:3,frameRate:{num:24,den:1},pts:[0,1/24,2/24],orientation:0,crop:[0,0,100,80]},alpha:{asset:'mask',sha256:maskHash,channel:'luminance',semantics:'segmentation'},provenance:{method:'manual','preprocess':'test/1'},frames:[0,1,2].map(i=>({sourceFrame:i,maskFrame:i,valid:true,reviewed:true}))}); test('prepared source identity, correspondence and review survive trims/reverse/random seeks',()=>{ @@ -44,3 +44,30 @@ test('all text treatments reproduce after reverse/random seeks and retain readab assert.equal(typeMotion(-1,{effect}).opacity,0);assert.equal(typeMotion(1.5,{effect}).opacity,1);assert.equal(typeMotion(4,{effect}).opacity,0); } }); + +test('correction gestures propose reversible books without mutating an existing revision',()=>{ + const session=createMaskCorrectionSession(),book={version:1,sourceSha256:hash,subject:'hand',keys:[]}; + const options={book,sourceSha256:hash,subject:'hand',sourceFrame:1,sourceWidth:100,sourceHeight:80,width:200,height:160}; + session.gesture({phase:'begin',id:'stroke',start:{x:50,y:50}},options); + const proposal=session.gesture({phase:'commit',id:'stroke',point:{x:50,y:50}},options); + assert.equal(book.keys.length,0);assert.equal(proposal.values.corrections.keys[0].frame,1);assert.equal(proposal.values.corrections.keys[0].polygons[0].points.length,20); +}); +test('adjacent surface triangles cover every interior pixel without transparency seams',()=>{ + const art=new Uint8ClampedArray(4*16);for(let i=0;i{ + const asset={type:'video',sha256:hash},derived=subject=>({type:'video',sha256:maskHash,derived:{of:'plate',role:'matte',sourceSha256:hash,subject}}); + validateDerived({plate:asset,hand:derived('hand'),person:derived('person')}); + assert.throws(()=>validateDerived({plate:asset,hand:derived('hand'),another:derived('hand')}),/two matte/); +}); + +test('baked corrections are applied once and subsequent edits remain provisional',()=>{ + const p={operation:'add',points:[[0,0],[5,0],[5,5]]},book={version:1,sourceSha256:hash,subject:'hand',keys:[{frame:0,polygons:[p]}]}; + assert.equal(pendingMaskCorrections(book,structuredClone(book)),null); + const edited=structuredClone(book);edited.keys[0].polygons.push({...p,operation:'subtract'}); + assert.equal(pendingMaskCorrections(edited,book).keys[0].polygons.length,1); + assert.throws(()=>pendingMaskCorrections({...book,keys:[]},book),/original mask/); +}); diff --git a/tests/prepared-integration.mjs b/tests/prepared-integration.mjs new file mode 100644 index 0000000..b3c4d2e --- /dev/null +++ b/tests/prepared-integration.mjs @@ -0,0 +1,32 @@ +// Real pixels: foreground preservation over animated DOM, through the CLI. +import assert from 'node:assert/strict'; +import fs from 'node:fs/promises'; +import os from 'node:os'; +import path from 'node:path'; +import {init,rebind} from '../scripts/project.mjs'; +import {render} from '../scripts/render.mjs'; +import {run,ffmpeg} from '../scripts/process.mjs'; +const tmp=await fs.mkdtemp(path.join(os.tmpdir(),'ef-prepared-')),dir=path.join(tmp,'scene'); +const source=`import {defineRenderer} from 'editableframes/renderer'; +import {createForegroundHoldout,createKineticText} from 'editableframes/plate'; +export default defineRenderer({id:'foreground-regression',renderer:'dom',width:160,height:90,fps:12,durationInFrames:12,defaultProps:{badFrame:-1}, + create({root,props}){ + root.style.background='#162432'; + const hold=createForegroundHoldout({root,width:160,height:90}),box=document.createElement('div'); + box.style.cssText='position:absolute;inset:0;background:#ff0000;color:white;font:900 20px system-ui;overflow:hidden';hold.root.append(box); + const title=createKineticText({root:box,text:'EXACT WORDS'}),mask=document.createElement('canvas');mask.width=160;mask.height=90; + return {async render(clock){const c=mask.getContext('2d');c.fillStyle='black';c.fillRect(0,0,160,90);c.fillStyle='white';c.fillRect(clock.frame*6,20,35,55);title.render(clock.frame/clock.fps,{effect:'spring',hold:10});let sample=mask,channel='luminance';if(clock.frame%2){const d=c.getImageData(0,0,160,90);for(let i=0;irender(dir,path.join(tmp,'bad'),{format:'png',frames:6}),/Required foreground mask missing/); + console.log('PASS: every protected interior pixel stays unchanged across all 12 animated frames; missing required data rejects capture.'); +}finally{await fs.rm(tmp,{recursive:true,force:true});} From c6a1d78e98ffbcb9ffe48806a13840986897903a Mon Sep 17 00:00:00 2001 From: Laurence Xavier <35849747+lxf82dev@users.noreply.github.com> Date: Wed, 11 Nov 2026 17:06:12 +0800 Subject: [PATCH 15/49] Reject empty foregrounds and invalid baked correction deltas --- packages/plate/prepared.mjs | 10 +++++++++- tests/hybrid-prepared.test.mjs | 6 ++++++ 2 files changed, 15 insertions(+), 1 deletion(-) diff --git a/packages/plate/prepared.mjs b/packages/plate/prepared.mjs index 0a1f3be..27f126b 100644 --- a/packages/plate/prepared.mjs +++ b/packages/plate/prepared.mjs @@ -43,7 +43,7 @@ export function preparedFrame(data, seconds, {start = 0, speed = 1, requireRevie /** Bounded diagnostics. Area collapse flags review, not automatic deletion or * identity reassignment: a real subject can leave the shot. */ -export function analyzeMask(rgba, width, height, {channel='luminance', previousCoverage, collapseRatio=.2} = {}) { +export function analyzeMask(rgba, width, height, {channel='luminance', previousCoverage, collapseRatio=.2,expected=true} = {}) { if (!integer(width) || !width || !integer(height) || !height || rgba.length !== width*height*4) throw Error('Mask raster dimensions do not match'); if (!['luminance','alpha'].includes(channel)) throw Error('Mask channel must be luminance or alpha'); let area=0, opaque=0, left=width,top=height,right=-1,bottom=-1; @@ -53,6 +53,7 @@ export function analyzeMask(rgba, width, height, {channel='luminance', previousC if(a>127){opaque++;const x=p%width,y=Math.floor(p/width);left=Math.min(left,x);right=Math.max(right,x);top=Math.min(top,y);bottom=Math.max(bottom,y);} } const coverage=opaque/(width*height), issues=[]; + if(expected&&opaque===0)issues.push('foreground-absent'); if(finite(previousCoverage) && previousCoverage>.001 && coveragek.polygons.length)?structuredClone(book):null; validateMaskCorrections(applied); if(book.sourceSha256!==applied.sourceSha256||book.subject!==applied.subject)throw Error('Correction identity changed'); + // Editing either endpoint or inserting inside a baked interpolation interval + // changes its whole span, which cannot be represented as a live delta. + for(let i=0;ik.frame>a.frame&&k.frame!equal(book.keys.find(k=>k.frame===old.frame),old)))throw Error('Re-prepare from the original mask to change a baked interpolation interval'); + } const pending=structuredClone(book);pending.keys=[]; for(const old of applied.keys)if(!book.keys.some(k=>k.frame===old.frame))throw Error('Re-prepare from the original mask to remove baked corrections'); for(const key of book.keys){const old=applied.keys.find(k=>k.frame===key.frame);const count=old?.polygons.length??0; diff --git a/tests/hybrid-prepared.test.mjs b/tests/hybrid-prepared.test.mjs index d6c0fa9..5b2a548 100644 --- a/tests/hybrid-prepared.test.mjs +++ b/tests/hybrid-prepared.test.mjs @@ -71,3 +71,9 @@ test('baked corrections are applied once and subsequent edits remain provisional assert.equal(pendingMaskCorrections(edited,book).keys[0].polygons.length,1); assert.throws(()=>pendingMaskCorrections({...book,keys:[]},book),/original mask/); }); + +test('changing a baked interpolated span requires preparation from the raw mask',()=>{ + const p={operation:'add',points:[[0,0],[5,0],[5,5]]},a={version:1,sourceSha256:hash,subject:'hand',keys:[{frame:0,interpolation:'linear',polygons:[p]},{frame:10,polygons:[p]}]}; + const edited=structuredClone(a);edited.keys.splice(1,0,{frame:5,polygons:[p]});assert.throws(()=>pendingMaskCorrections(edited,a),/interpolation interval/); + const appended=structuredClone(a);appended.keys[0].polygons.push(p);assert.throws(()=>pendingMaskCorrections(appended,a),/interpolation interval/); +}); From 7aaf22bbc846bf2e58ebf7f40891a05545712c89 Mon Sep 17 00:00:00 2001 From: Laurence Xavier <35849747+lxf82dev@users.noreply.github.com> Date: Wed, 11 Nov 2026 17:35:44 +0800 Subject: [PATCH 16/49] Fit original surface artwork and keep exact geometry on clean plates --- docs/hybrid-compositing-plan.md | 6 ++--- docs/prepared-plates.md | 6 +++++ examples/hybrid-code-first/clip.mjs | 38 +++++++++++++++++++++++++++++ examples/hybrid-surfaces/clip.mjs | 12 ++++++--- packages/plate/prepared.mjs | 2 +- 5 files changed, 57 insertions(+), 7 deletions(-) create mode 100644 examples/hybrid-code-first/clip.mjs diff --git a/docs/hybrid-compositing-plan.md b/docs/hybrid-compositing-plan.md index a0d12ab..a7bae44 100644 --- a/docs/hybrid-compositing-plan.md +++ b/docs/hybrid-compositing-plan.md @@ -1,8 +1,8 @@ # Reliable hybrid compositing and motion design -Status: proposed next work, 2026-11-11. This is a design and acceptance plan, not an implemented API. It supersedes any inference that a successful render or a few attractive frames establish a usable hybrid clip. Existing primitives and their tested scope remain documented in [hybrid-scenes.md](hybrid-scenes.md). +Status: implementation and acceptance plan, 2026-11-11. Implemented APIs are documented separately below; research gates remain explicit. It supersedes any inference that a successful render or a few attractive frames establish a usable hybrid clip. Existing primitives and their tested scope remain documented in [hybrid-scenes.md](hybrid-scenes.md). -Implementation update: the [prepared-media primitives](prepared-plates.md) now implement receipts, exact frame access, holdouts, corrections, cylinder/mesh replay and kinetic text. These mechanisms have synthetic regression coverage; the real-shot acceptance gates below still require full visual QA. Automatic geometry solving and production model selection remain research. +Implementation update: the [prepared-media primitives](prepared-plates.md) now implement receipts, exact frame access, holdouts, corrections, cylinder/mesh replay and kinetic text. These mechanisms have synthetic regression coverage and retained real-shot QA in progress for people, close-up hands, original-object reskin and clean-background code composition. Automatic geometry solving and production model selection remain research. ## What the failed shots teach us @@ -14,7 +14,7 @@ Implementation update: the [prepared-media primitives](prepared-plates.md) now i | A hand appears sliced through an added can | The example inserts a second can at an offset from the tracked original. Relative depth with hand-tuned near/far is being used as if it were registered scene geometry. | First distinguish insertion from reskinning. For a hand known to be in front, use its coherent alpha as the foreground constraint. | | A small labeled can sits over a larger generated can | Generating a world from a clay still did not preserve the product silhouette or proportions. | Reject the take for exact-object recomposition, or solve an explicit replacement workflow including removal of the original. Do not hide the mismatch with a smaller overlay. | -These clips fail final-quality acceptance. The phone's 121 matte frames were measured using decoded grayscale coverage above 127/255, with zero-based frame indices. The other failures were verified in sampled frames and the authored scenes, not an exhaustive pixel audit. Earlier tracking numbers remain measurements of tracking, not evidence of correct occlusion, placement, materials or whole-shot quality. No new implementation or corrected full-length video is claimed by this plan. +These clips fail final-quality acceptance. The phone's 121 matte frames were measured using decoded grayscale coverage above 127/255, with zero-based frame indices. The other failures were verified in sampled frames and the authored scenes, not an exhaustive pixel audit. Earlier tracking numbers remain measurements of tracking, not evidence of correct occlusion, placement, materials or whole-shot quality. Those historical verdicts describe the original exports. Current implementation and repair evidence must name the new revisions separately. ## Architecture decision: analyze, correct, cache, then render diff --git a/docs/prepared-plates.md b/docs/prepared-plates.md index 2a039e2..ff1903c 100644 --- a/docs/prepared-plates.md +++ b/docs/prepared-plates.md @@ -33,3 +33,9 @@ The [surface example](../examples/hybrid-surfaces/clip.mjs) combines exact sourc `npm run test:prepared` checks real pixels through the CLI: all protected opaque interiors survive every frame of an animated crossing, using both alpha and luminance paths, and missing masks reject capture. `tests/hybrid-prepared.test.mjs` checks identity, correspondence, reverse seeks, correction history, layout overflow and seam-free UV coverage. The primitives do not solve a camera, infer cloth geometry, remove an old object or recover uncontaminated hair colors automatically. The mesh and camera import paths accept externally prepared data. A physically impossible insertion still needs changed blocking or a different plate. The [delivery plan](hybrid-compositing-plan.md) retains separate quality gates for these tasks; device performance and real-shot usability require measurement. + +## Exact geometry with a generated environment + +The [code-first example](../examples/hybrid-code-first/clip.mjs) keeps the exact foreground cylinder or optional imported GLB in code, over a clean background asset named `world`. A native host can bind `world` and supply verified `worldInfo` (width, height, frames, rational frameRate). The scene adds an authored contact shadow, plate-derived reflection approximation, control passes and an analytic orbit title. The background must have no original foreground object; this avoids a mismatched generated silhouette behind the exact object. It does not solve a camera or prove that a video model consumed 3D control passes. Imported photo geometry/material fidelity is a separate acceptance task. + +`surface-reskin` exposes `bodyInset` and `rimCurve` to fit a rigid body without painting over its rims. These are authored fit parameters, not a shape solve. Imported `meshTrack` vertices replace that approximation for a measured deforming surface. diff --git a/examples/hybrid-code-first/clip.mjs b/examples/hybrid-code-first/clip.mjs new file mode 100644 index 0000000..a523bce --- /dev/null +++ b/examples/hybrid-code-first/clip.mjs @@ -0,0 +1,38 @@ +// Keep exact foreground geometry out of unconstrained background generation. +// Supply a clean background asset named world, or world/worldInfo props in a host. +import * as T from 'three'; +import {GLTFLoader} from 'three/examples/jsm/loaders/GLTFLoader.js'; +import {defineRenderer} from 'editableframes/renderer'; +import {createKineticText,createFrameLoader,conformSeconds} from 'editableframes/plate'; +import {renderPass,createPlateEnvironment} from 'editableframes/three-plate'; +export default defineRenderer({id:'code-first-product',renderer:'three+html',width:832,height:480,fps:16,durationInFrames:81, + passes:['clay','depth','normal','id','matte'],defaultProps:{label:'LUMA',model:'',world:'world',worldInfo:null,backplate:true,spin:false}, + controls:{version:1,fields:[{key:'world',anchor:'background',type:'media',mediaKind:'video',default:'world',label:'Empty background'},{key:'worldInfo',anchor:'background',type:'json',default:null,label:'Background frame metadata'},{key:'model',anchor:'product',type:'model',default:'',label:'Optional photo model'},{key:'label',type:'string',label:'Exact label'},{key:'spin',type:'bool',label:'Rotate model'}]}, + async create({root,props,asset,mediaInfo,mediaFrame,sourceFrame}){ + root.style.background='#d6dcd6'; + const canvas=document.createElement('canvas');root.append(canvas); + const r=new T.WebGLRenderer({canvas,alpha:true,antialias:true,preserveDrawingBuffer:true});r.setSize(832,480);r.shadowMap.enabled=true;r.shadowMap.type=T.PCFSoftShadowMap;r.setClearColor(0,0);r.outputColorSpace=T.SRGBColorSpace;r.toneMapping=T.NeutralToneMapping; + const scene=new T.Scene(),camera=new T.PerspectiveCamera(35,832/480,.1,30);camera.position.set(0,.1,4.5);camera.lookAt(0,0,0); + scene.add(new T.HemisphereLight(0xf4fff8,0x646b71,2));const key=new T.DirectionalLight(0xffffff,3);key.position.set(-3,5,4);key.castShadow=true;key.shadow.mapSize.set(1024,1024);key.shadow.camera.left=-3;key.shadow.camera.right=3;key.shadow.camera.top=3;key.shadow.camera.bottom=-3;key.shadow.bias=-.0002;scene.add(key); + const product=new T.Group();product.userData.passId='product';product.position.set(.55,-.13,0);scene.add(product); + if(props.model){ + const gltf=await new GLTFLoader().loadAsync(asset(props.model));const model=gltf.scene; + const box=new T.Box3().setFromObject(model),size=box.getSize(new T.Vector3()),centre=box.getCenter(new T.Vector3()); + model.position.sub(centre);const fit=new T.Group();fit.add(model);fit.scale.setScalar(1.25/size.y);product.add(fit); + }else{ + const label=document.createElement('canvas');label.width=1024;label.height=512;const ctx=label.getContext('2d');ctx.fillStyle='#ef633f';ctx.fillRect(0,0,1024,512);ctx.fillStyle='white';ctx.textAlign='center';ctx.font='900 95px Arial';for(const x of [256,768])ctx.fillText(props.label,x,280); + const tex=new T.CanvasTexture(label);tex.colorSpace=T.SRGBColorSpace; + product.add(new T.Mesh(new T.CylinderGeometry(.31,.31,1.18,64),new T.MeshStandardMaterial({map:tex,metalness:.2,roughness:.36}))); + for(const y of [-.61,.61]){const lid=new T.Mesh(new T.CylinderGeometry(.30,.31,.04,64),new T.MeshStandardMaterial({color:0xb9bfc0,metalness:.9,roughness:.22}));lid.position.y=y;product.add(lid);} + } + product.traverse(o=>{if(o.isMesh)o.castShadow=true;});const floor=new T.Mesh(new T.PlaneGeometry(20,20),new T.ShadowMaterial({opacity:.32}));floor.receiveShadow=true;floor.userData.passExclude=true;floor.rotation.x=-Math.PI/2;floor.position.y=-.76;scene.add(floor); + const title=document.createElement('div');title.style.cssText='position:absolute;left:46px;top:42px;color:#17251e;font:800 32px/1.05 Arial;letter-spacing:-1px;max-width:310px';root.append(title); + const sub=document.createElement('div');sub.style.cssText='position:absolute;left:46px;bottom:42px;color:#17251e;font:600 13px Arial;letter-spacing:2px';root.append(sub); + const kinetic=createKineticText({root:title});let bg,bgctx;const loader=createFrameLoader(),env=createPlateEnvironment(r);if(props.backplate){bg=document.createElement('canvas');bg.width=832;bg.height=480;root.prepend(bg);bg.style.cssText='position:absolute;inset:0';canvas.style.cssText='position:absolute;inset:0';bgctx=bg.getContext('2d');} + return {async render(clock){ + const time=clock.frame/clock.fps;product.rotation.y=props.spin?time*.65:-1.3;kinetic.render(time,{text:'BUILT IN CODE. SET IN MOTION.',effect:'orbit',stagger:.09,duration:.8,hold:3600,pathRadius:30});sub.textContent=props.model?'PHOTO → GLB → EDITABLE HTML':'LUMA / BLOOD ORANGE'; + if(props.backplate){const info=props.worldInfo??mediaInfo?.(String(props.world));if(!info?.frameRate||!info.frames)throw Error('Supply verified empty-background metadata');const at=conformSeconds(clock.mediaTime??time,info.frameRate),index=Math.floor(at*info.frameRate.num/info.frameRate.den+1e-6);if(index<0||index>=info.frames)throw Error('Empty background frame outside source range');const image=await loader.load(sourceFrame?sourceFrame(String(props.world),index,{width:info.width,height:info.height,seconds:at}):mediaFrame(String(props.world),at));bgctx.drawImage(image,0,0,832,480);scene.environment=env.update(image);scene.environmentIntensity=1;floor.visible=true;title.style.color=sub.style.color='white';} + const pass=clock.pass??'beauty';title.style.visibility=sub.style.visibility=pass==='beauty'?'visible':'hidden';if(bg)bg.style.visibility=pass==='beauty'?'visible':'hidden'; + if(pass!=='beauty'){root.style.background='transparent';renderPass(r,scene,camera,pass,{ids:['product']});}else{root.style.background=props.backplate?'#202620':'#d6dcd6';r.render(scene,camera);} + },dispose(){kinetic.dispose();loader.dispose();env.dispose();r.dispose();r.forceContextLoss();root.replaceChildren();}}; + }}); diff --git a/examples/hybrid-surfaces/clip.mjs b/examples/hybrid-surfaces/clip.mjs index 6279d82..bfcc55e 100644 --- a/examples/hybrid-surfaces/clip.mjs +++ b/examples/hybrid-surfaces/clip.mjs @@ -12,6 +12,8 @@ export const controls={version:1,fields:[ {key:'detail',anchor:'label',path:'/detail',type:'string',default:'BLOOD ORANGE',label:'Small print'}, {key:'color',anchor:'label',path:'/color',type:'color',default:'#ed5426',label:'Body colour'}, {key:'seam',anchor:'surface',path:'/seam',type:'number',min:-1,max:1,default:0,animatable:true,label:'Authored label rotation'}, + {key:'bodyInset',anchor:'surface',path:'/bodyInset',type:'number',min:0,max:.1,default:.02,label:'Body edge inset'}, + {key:'rimCurve',anchor:'surface',path:'/rimCurve',type:'number',min:0,max:.1,default:.03,label:'Lower body curvature'}, {key:'reference',anchor:'lighting',path:'/reference',type:'number',min:1,max:255,default:180,label:'Neutral body reference'}, {key:'shading',anchor:'lighting',path:'/shading',type:'number',min:0,max:1,default:1,label:'Preserve observed shading'}, {key:'headline',anchor:'headline',path:'/headline',type:'string',default:'MADE TO MOVE.',label:'Motion title'}, @@ -27,7 +29,7 @@ export default defineRenderer({id:'surface-reskin',renderer:'canvas+dom',width:1 const initialTrack=props.track??(mediaInfo?await (await fetch(asset('track'))).json():null); const doc=root.ownerDocument,stage=doc.createElement('div');stage.style.cssText='position:absolute;inset:0;overflow:hidden';root.append(stage); const canvas=()=>{const c=doc.createElement('canvas');c.style.cssText='position:absolute;inset:0;width:100%;height:100%';return c;}; - const plate=canvas(),ink=canvas(),art=canvas();art.width=1024;art.height=1024;stage.append(plate); + const plate=canvas(),ink=canvas(),art=canvas();art.width=2048;art.height=1024;stage.append(plate); const title=doc.createElement('div');title.style.cssText='position:absolute;left:5%;top:8%;width:88%;font:900 72px/1.05 system-ui;color:white'; const kinetic=createKineticText({root:title}),frames=createFrameLoader({document:doc,max:6});let holdout=null,identity='',labelKey=''; return { @@ -46,10 +48,14 @@ export default defineRenderer({id:'surface-reskin',renderer:'canvas+dom',width:1 const [image,mask]=await Promise.all([frames.load(sourceFrame(String(props.foregroundSource),at.sourceFrame,info)),frames.load(sourceFrame(String(props.foregroundMask),at.maskFrame,{...info,seconds:at.maskSeconds}))]); const pc=plate.getContext('2d',{willReadFrequently:true});pc.drawImage(image,0,0,w,h); const key=JSON.stringify([props.label,props.detail,props.color]); - if(key!==labelKey){labelKey=key;const c=art.getContext('2d');c.fillStyle=props.color;c.fillRect(0,0,1024,1024);c.fillStyle='white';c.textAlign='center';c.textBaseline='middle';c.font='900 130px system-ui';c.fillText(String(props.label),512,470,480);c.font='700 30px system-ui';c.fillText(String(props.detail),512,650,480);} + if(key!==labelKey){labelKey=key;const c=art.getContext('2d');c.fillStyle=props.color;c.fillRect(0,0,2048,1024);c.fillStyle='white';c.textAlign='center';c.textBaseline='middle';c.font='900 190px system-ui';c.fillText(String(props.label),1024,470,900);c.font='700 38px system-ui';c.fillText(String(props.detail),1024,650,900);} const pin=sampleTrack(track,at.seconds);if(pin.held||pin.confidence<=0)throw Error('Original body track is missing at source frame '+at.sourceFrame); const fitted=props.meshTrack?sampleSurface(props.meshTrack,at.sourceFrame):null; - const mesh=fitted?{...fitted,vertices:scalePoints(fitted.vertices,track,w,h)}:cylinderMesh(scalePoints(pin.quad,track,w,h),{seam:Number(props.seam)}); + const quad=scalePoints(pin.quad,track,w,h),inset=Number(props.bodyInset),curve=Number(props.rimCurve); + if(!Number.isFinite(inset)||inset<0||inset>.1||!Number.isFinite(curve)||curve<0||curve>.1)throw Error('Invalid body inset/curvature'); + const fittedQuad=[quad[0].map((v,i)=>v+(quad[1][i]-v)*inset),quad[1].map((v,i)=>v+(quad[0][i]-v)*inset),quad[2].map((v,i)=>v+(quad[3][i]-v)*inset),quad[3].map((v,i)=>v+(quad[2][i]-v)*inset)]; + const mesh=fitted?{...fitted,vertices:scalePoints(fitted.vertices,track,w,h)}:cylinderMesh(fittedQuad,{seam:Number(props.seam)}); + if(!fitted){const bodyHeight=(Math.hypot(quad[3][0]-quad[0][0],quad[3][1]-quad[0][1])+Math.hypot(quad[2][0]-quad[1][0],quad[2][1]-quad[1][1]))/2;mesh.vertices=mesh.vertices.map(([x,y],i)=>{const u=i%65/64,v=Math.floor(i/65)/8;return [x,y-bodyHeight*curve*(2*u-1)**2*v**6];});} const ic=ink.getContext('2d',{willReadFrequently:true});ic.clearRect(0,0,w,h);drawSurfaceArtwork(ic,art,mesh,{wrap:true}); const pixels=ic.getImageData(0,0,w,h);pixels.data.set(relightArtwork(pixels.data,pc.getImageData(0,0,w,h).data,{reference:Number(props.reference),strength:Number(props.shading)}));ic.putImageData(pixels,0,0); holdout.update(mask,{channel:receipt.alpha.channel,corrections:pending,frame:at.sourceFrame,sourceSha256:s.sha256,subject:receipt.subject}); diff --git a/packages/plate/prepared.mjs b/packages/plate/prepared.mjs index 27f126b..f797d30 100644 --- a/packages/plate/prepared.mjs +++ b/packages/plate/prepared.mjs @@ -54,7 +54,7 @@ export function analyzeMask(rgba, width, height, {channel='luminance', previousC } const coverage=opaque/(width*height), issues=[]; if(expected&&opaque===0)issues.push('foreground-absent'); - if(finite(previousCoverage) && previousCoverage>.001 && coverage.001 && coverage Date: Wed, 11 Nov 2026 17:40:20 +0800 Subject: [PATCH 17/49] Hold source samples during code shutter rendering --- examples/hybrid-surfaces/clip.mjs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/examples/hybrid-surfaces/clip.mjs b/examples/hybrid-surfaces/clip.mjs index bfcc55e..ecd2ac9 100644 --- a/examples/hybrid-surfaces/clip.mjs +++ b/examples/hybrid-surfaces/clip.mjs @@ -40,7 +40,7 @@ export default defineRenderer({id:'surface-reskin',renderer:'canvas+dom',width:1 if(pending)throw Error('Corrections changed; prepare and review a new mask revision before rendering'); if(!props.foregroundSource||!props.foregroundMask||!track)throw Error('Reskin needs the original source, foreground and original-body track'); if(track.sourceSha256&&track.sourceSha256!==s.sha256)throw Error('Surface track belongs to a different take'); - const at=preparedFrame(receipt,clock.frame/clock.fps,{start:Number(props.plateStartFrame)*s.frameRate.den/s.frameRate.num,speed:Number(props.plateSpeed)}); + const at=preparedFrame(receipt,clock.mediaTime??clock.frame/clock.fps,{start:Number(props.plateStartFrame)*s.frameRate.den/s.frameRate.num,speed:Number(props.plateSpeed)}); const w=root.clientWidth||clock.width,h=root.clientHeight||clock.height; for(const c of [plate,ink])if(c.width!==w||c.height!==h){c.width=w;c.height=h;} if(identity!==s.sha256){identity=s.sha256;holdout?.dispose();holdout=createForegroundHoldout({root:stage,width:s.width,height:s.height});holdout.root.append(ink,title);} From 8d49f7e391fd128e443f50e288fcbf9a46a67d13 Mon Sep 17 00:00:00 2001 From: Laurence Xavier <35849747+lxf82dev@users.noreply.github.com> Date: Wed, 11 Nov 2026 17:55:43 +0800 Subject: [PATCH 18/49] Document full-shot foreground and exact-geometry QA --- docs/prepared-plates.md | 8 ++++++++ .../editableframes/references/prepared-plates.md | 16 +++++++++++++++- 2 files changed, 23 insertions(+), 1 deletion(-) diff --git a/docs/prepared-plates.md b/docs/prepared-plates.md index ff1903c..2f75890 100644 --- a/docs/prepared-plates.md +++ b/docs/prepared-plates.md @@ -39,3 +39,11 @@ The primitives do not solve a camera, infer cloth geometry, remove an old object The [code-first example](../examples/hybrid-code-first/clip.mjs) keeps the exact foreground cylinder or optional imported GLB in code, over a clean background asset named `world`. A native host can bind `world` and supply verified `worldInfo` (width, height, frames, rational frameRate). The scene adds an authored contact shadow, plate-derived reflection approximation, control passes and an analytic orbit title. The background must have no original foreground object; this avoids a mismatched generated silhouette behind the exact object. It does not solve a camera or prove that a video model consumed 3D control passes. Imported photo geometry/material fidelity is a separate acceptance task. `surface-reskin` exposes `bodyInset` and `rimCurve` to fit a rigid body without painting over its rims. These are authored fit parameters, not a shape solve. Imported `meshTrack` vertices replace that approximation for a measured deforming surface. + +## Retained generated-footage QA (2026-11-11) + +The new primitives were exercised on complete short clips, keeping the original failed renders separately. Reviewed source/mask contact sheets and every output event crop covered 121 frames each for a café board, close-up phone, opaque board card and original-can reskin; the exact-geometry scene covered 81 frames. The board footer was moved inside its safe area, the phone subject mask was replaced after collapse, and the label was fit to the original neutral can body. These shots work with reviewed inputs and manual surface/material tuning. They do not establish automatic segmentation or camera solving. + +Before video encoding, each of the four foreground composites preserved every tested opaque interior pixel: alpha at least 254/255, eroded by two source pixels, with at most one RGB code-value tolerance. This is a scoped leakage check against the supplied reviewed mask, not annotated boundary accuracy or fractional-hair color validation. All 81 exact-geometry control mattes were byte-identical; the generated background contained no product to mismatch. The label stayed on the original can and retained its rims/contact shadow. That shot's hand did not cross the original left can, so it is not a can-crossing stress test. + +The motion examples include staggered text, a footer wipe, a spring-like card entrance, extruded lettering and an orbit title. Analytic random/reverse seek behavior is tested independently. Current checks: 131 unit tests plus real-pixel prepared alpha/luminance capture and rejection of missing foregrounds. Static, pan and handheld stress footage, annotated edge-error measurements and actual-device inference benchmarks remain separate acceptance work. diff --git a/skills/editableframes/references/prepared-plates.md b/skills/editableframes/references/prepared-plates.md index 1051622..2f75890 100644 --- a/skills/editableframes/references/prepared-plates.md +++ b/skills/editableframes/references/prepared-plates.md @@ -24,7 +24,7 @@ Correction books bind `sourceSha256`, `subject` and increasing frame keys. Each `cylinderMesh` maps a label to an authored/tracked projected body quad. It preserves that body's screen bounds; the seam is an author control when a blank cylinder makes rotation unobservable. `sampleSurface` accepts externally tracked deforming UV meshes. `drawSurfaceArtwork` rasterizes UV triangles without translucent clip seams. `relightArtwork` preserves observed shading under a specified neutral-albedo assumption. Arbitrary old printing requires a separate clean albedo/shading estimate. -The [surface example](https://github.com/Stitchable-ai/editable-frames/blob/feat/hybrid-scenes/examples/hybrid-surfaces/clip.mjs) combines exact source frames, a selected original body, foreground protection, editable labeling and a motion headline. Supply assets named `plate`, `foreground`, `analysis` and `track`, or pass a prepared receipt/track and declared source/mask IDs as props. The body track must describe the original object's body, excluding lids, rims and background. +The [surface example](../examples/hybrid-surfaces/clip.mjs) combines exact source frames, a selected original body, foreground protection, editable labeling and a motion headline. Supply assets named `plate`, `foreground`, `analysis` and `track`, or pass a prepared receipt/track and declared source/mask IDs as props. The body track must describe the original object's body, excluding lids, rims and background. `createKineticText` and `typeMotion` provide staggered rise, wipe, spring-like settle, orbit and CSS extrusion treatments. Timing, text, stagger, easing treatment and displacement are explicit inputs; random/reverse seeks reproduce the same state. Character splitting uses grapheme clusters where available. Font readiness and surface safe-area checks remain part of layout acceptance. @@ -33,3 +33,17 @@ The [surface example](https://github.com/Stitchable-ai/editable-frames/blob/feat `npm run test:prepared` checks real pixels through the CLI: all protected opaque interiors survive every frame of an animated crossing, using both alpha and luminance paths, and missing masks reject capture. `tests/hybrid-prepared.test.mjs` checks identity, correspondence, reverse seeks, correction history, layout overflow and seam-free UV coverage. The primitives do not solve a camera, infer cloth geometry, remove an old object or recover uncontaminated hair colors automatically. The mesh and camera import paths accept externally prepared data. A physically impossible insertion still needs changed blocking or a different plate. The [delivery plan](hybrid-compositing-plan.md) retains separate quality gates for these tasks; device performance and real-shot usability require measurement. + +## Exact geometry with a generated environment + +The [code-first example](../examples/hybrid-code-first/clip.mjs) keeps the exact foreground cylinder or optional imported GLB in code, over a clean background asset named `world`. A native host can bind `world` and supply verified `worldInfo` (width, height, frames, rational frameRate). The scene adds an authored contact shadow, plate-derived reflection approximation, control passes and an analytic orbit title. The background must have no original foreground object; this avoids a mismatched generated silhouette behind the exact object. It does not solve a camera or prove that a video model consumed 3D control passes. Imported photo geometry/material fidelity is a separate acceptance task. + +`surface-reskin` exposes `bodyInset` and `rimCurve` to fit a rigid body without painting over its rims. These are authored fit parameters, not a shape solve. Imported `meshTrack` vertices replace that approximation for a measured deforming surface. + +## Retained generated-footage QA (2026-11-11) + +The new primitives were exercised on complete short clips, keeping the original failed renders separately. Reviewed source/mask contact sheets and every output event crop covered 121 frames each for a café board, close-up phone, opaque board card and original-can reskin; the exact-geometry scene covered 81 frames. The board footer was moved inside its safe area, the phone subject mask was replaced after collapse, and the label was fit to the original neutral can body. These shots work with reviewed inputs and manual surface/material tuning. They do not establish automatic segmentation or camera solving. + +Before video encoding, each of the four foreground composites preserved every tested opaque interior pixel: alpha at least 254/255, eroded by two source pixels, with at most one RGB code-value tolerance. This is a scoped leakage check against the supplied reviewed mask, not annotated boundary accuracy or fractional-hair color validation. All 81 exact-geometry control mattes were byte-identical; the generated background contained no product to mismatch. The label stayed on the original can and retained its rims/contact shadow. That shot's hand did not cross the original left can, so it is not a can-crossing stress test. + +The motion examples include staggered text, a footer wipe, a spring-like card entrance, extruded lettering and an orbit title. Analytic random/reverse seek behavior is tested independently. Current checks: 131 unit tests plus real-pixel prepared alpha/luminance capture and rejection of missing foregrounds. Static, pan and handheld stress footage, annotated edge-error measurements and actual-device inference benchmarks remain separate acceptance work. From 0354a6de779ce54c65b2f74902f928c34fcfd01b Mon Sep 17 00:00:00 2001 From: Laurence Xavier <35849747+lxf82dev@users.noreply.github.com> Date: Wed, 11 Nov 2026 18:01:29 +0800 Subject: [PATCH 19/49] Run prepared foreground pixel checks in CI --- .github/workflows/ci.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index bd0a260..8b63be6 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -22,6 +22,7 @@ jobs: - run: npm run test:beta - run: npm run test:renderer - run: npm run test:hybrid + - run: npm run test:prepared - run: npm run test:browser website: name: Website validation From 530e56b3da2870ad1f09d27d1336ac1880ba77e6 Mon Sep 17 00:00:00 2001 From: Laurence Xavier <35849747+lxf82dev@users.noreply.github.com> Date: Wed, 11 Nov 2026 18:40:06 +0800 Subject: [PATCH 20/49] Fix hybrid source-frame alignment and live product edits --- docs/hybrid-scenes.md | 2 +- docs/prepared-plates.md | 8 +++--- examples/hybrid-code-first/clip.mjs | 37 +++++++++++++++++--------- examples/hybrid-surfaces/clip.mjs | 6 ++--- package.json | 2 +- packages/media/frames.mjs | 11 ++++++++ packages/plate/prepared.mjs | 6 +++-- packages/plate/track.mjs | 8 +++++- packages/runtime/editor.mjs | 4 +-- tests/hybrid-editing.mjs | 40 +++++++++++++++++++++++++++++ tests/hybrid-prepared.test.mjs | 11 +++++++- tests/media-pts.test.mjs | 17 ++++++++++++ 12 files changed, 126 insertions(+), 26 deletions(-) create mode 100644 packages/media/frames.mjs create mode 100644 tests/hybrid-editing.mjs diff --git a/docs/hybrid-scenes.md b/docs/hybrid-scenes.md index e514f0f..5181142 100644 --- a/docs/hybrid-scenes.md +++ b/docs/hybrid-scenes.md @@ -139,7 +139,7 @@ The host then supplies `clock.pass` (`'beauty'` unless a pass was requested). A | Area | Functions | |---|---| | Corner pin | `solveHomography`, `applyHomography`, `invertHomography`, `cornerPinTransform`, `cssMatrix3d`, `quadArea` | -| Tracks | `validateTrack`, `sampleTrack`, `scalePoints` | +| Tracks | `validateTrack`, `sampleTrack`, `sampleTrackFrame`, `scalePoints` | | Camera | `validateCameraPath`, `sampleCameraPath`, `slerp` | | Frame rate | `plateFrameIndex`, `conformSeconds`, `cadence` | | Depth | `validateDepthEncoding`, `decodeDepth`, `encodeDepth`, `packDepth`, `unpackDepth`, `depthGlsl`, `unprojectDepth`, `fitGroundPlane` | diff --git a/docs/prepared-plates.md b/docs/prepared-plates.md index 2f75890..4ea0ab2 100644 --- a/docs/prepared-plates.md +++ b/docs/prepared-plates.md @@ -6,11 +6,11 @@ The plate utilities now include versioned analysis receipts, explicit source-fra `validatePreparedAnalysis(receipt, sourceInfo)` checks source content identity, decoded raster, rational frame rate, presentation times, correspondence, mask identity, correction revision and preparation provenance. A receipt has `version:1`, `kind:"prepared-plate"`, `source`, `alpha`, `subject`, `revision`, `provenance` and one entry per source frame in `frames`. Each entry contains `sourceFrame`, `maskFrame`, `valid`, `reviewed` and optional diagnostic `issues`. -`preparedFrame(receipt, seconds, {start, speed})` maps explicit clip time to a source frame, including trim and reverse. Final sampling rejects unreviewed, invalid and out-of-range data. Correction tools can explicitly opt into draft sampling with `requireReviewed:false, allowInvalid:true`; this is not export approval. Missing data never repeats its last frame. +`preparedFrame(receipt, seconds, {start, startFrame, speed})` maps explicit clip time to a source frame, including trim and reverse. `start` is a time in seconds; an optional integer `startFrame` instead anchors the trim to that frame's actual presentation time. Use `sampleTrackFrame(track, sample.sourceFrame)` to sample matching geometry without converting quantized timestamps back through nominal fps. Final sampling rejects unreviewed, invalid and out-of-range data. Correction tools can explicitly opt into draft sampling with `requireReviewed:false, allowInvalid:true`; this is not export approval. Missing data never repeats its last frame. Import a receipt as a data asset with `--role analysis --of plate`, and its explicit-alpha media with `--role alpha --of plate`. `--subject ID` distinguishes derived assets for multiple subjects. `derived(plate, role, subject)` resolves that subject; the original two-argument form still resolves an unqualified role. The CLI verifies content hashes, while media preparation checks the receipt against the actual decoded plate and mask. -The optional `sourceFrame(id, index, info)` host service returns the exact decoded frame. Prepared media uses indices even when lossless container timestamps have different precision. `mediaInfo` includes digest and presentation times. Existing `mediaFrame` calls on derived videos now follow the parent plate's frame index. +The optional `sourceFrame(id, index, info)` host service returns the exact decoded frame. Prepared media uses indices even when lossless container timestamps have different precision. `mediaInfo` includes digest and presentation times. Existing `mediaFrame` calls on derived videos now follow the parent plate's frame index. A derived still mask retains its own single frame throughout the video. ## Foreground and corrections @@ -40,10 +40,12 @@ The [code-first example](../examples/hybrid-code-first/clip.mjs) keeps the exact `surface-reskin` exposes `bodyInset` and `rimCurve` to fit a rigid body without painting over its rims. These are authored fit parameters, not a shape solve. Imported `meshTrack` vertices replace that approximation for a measured deforming surface. +The code-first scene applies `label` and `model` changes on each render. Live edits and Undo produce the same product as a fresh capture instance; switching models releases the previous geometry, materials and textures. + ## Retained generated-footage QA (2026-11-11) The new primitives were exercised on complete short clips, keeping the original failed renders separately. Reviewed source/mask contact sheets and every output event crop covered 121 frames each for a café board, close-up phone, opaque board card and original-can reskin; the exact-geometry scene covered 81 frames. The board footer was moved inside its safe area, the phone subject mask was replaced after collapse, and the label was fit to the original neutral can body. These shots work with reviewed inputs and manual surface/material tuning. They do not establish automatic segmentation or camera solving. Before video encoding, each of the four foreground composites preserved every tested opaque interior pixel: alpha at least 254/255, eroded by two source pixels, with at most one RGB code-value tolerance. This is a scoped leakage check against the supplied reviewed mask, not annotated boundary accuracy or fractional-hair color validation. All 81 exact-geometry control mattes were byte-identical; the generated background contained no product to mismatch. The label stayed on the original can and retained its rims/contact shadow. That shot's hand did not cross the original left can, so it is not a can-crossing stress test. -The motion examples include staggered text, a footer wipe, a spring-like card entrance, extruded lettering and an orbit title. Analytic random/reverse seek behavior is tested independently. Current checks: 131 unit tests plus real-pixel prepared alpha/luminance capture and rejection of missing foregrounds. Static, pan and handheld stress footage, annotated edge-error measurements and actual-device inference benchmarks remain separate acceptance work. +The motion examples include staggered text, a footer wipe, a spring-like card entrance, extruded lettering and an orbit title. Analytic random/reverse seek behavior is tested independently. Current checks: 133 unit tests plus real-pixel prepared alpha/luminance capture, rejection of missing foregrounds, live label/GLB edit parity and quantized final-frame reskin rendering. Static, pan and handheld stress footage, annotated edge-error measurements and actual-device inference benchmarks remain separate acceptance work. diff --git a/examples/hybrid-code-first/clip.mjs b/examples/hybrid-code-first/clip.mjs index a523bce..79325bb 100644 --- a/examples/hybrid-code-first/clip.mjs +++ b/examples/hybrid-code-first/clip.mjs @@ -15,24 +15,37 @@ export default defineRenderer({id:'code-first-product',renderer:'three+html',wid const scene=new T.Scene(),camera=new T.PerspectiveCamera(35,832/480,.1,30);camera.position.set(0,.1,4.5);camera.lookAt(0,0,0); scene.add(new T.HemisphereLight(0xf4fff8,0x646b71,2));const key=new T.DirectionalLight(0xffffff,3);key.position.set(-3,5,4);key.castShadow=true;key.shadow.mapSize.set(1024,1024);key.shadow.camera.left=-3;key.shadow.camera.right=3;key.shadow.camera.top=3;key.shadow.camera.bottom=-3;key.shadow.bias=-.0002;scene.add(key); const product=new T.Group();product.userData.passId='product';product.position.set(.55,-.13,0);scene.add(product); - if(props.model){ - const gltf=await new GLTFLoader().loadAsync(asset(props.model));const model=gltf.scene; - const box=new T.Box3().setFromObject(model),size=box.getSize(new T.Vector3()),centre=box.getCenter(new T.Vector3()); - model.position.sub(centre);const fit=new T.Group();fit.add(model);fit.scale.setScalar(1.25/size.y);product.add(fit); - }else{ - const label=document.createElement('canvas');label.width=1024;label.height=512;const ctx=label.getContext('2d');ctx.fillStyle='#ef633f';ctx.fillRect(0,0,1024,512);ctx.fillStyle='white';ctx.textAlign='center';ctx.font='900 95px Arial';for(const x of [256,768])ctx.fillText(props.label,x,280); - const tex=new T.CanvasTexture(label);tex.colorSpace=T.SRGBColorSpace; - product.add(new T.Mesh(new T.CylinderGeometry(.31,.31,1.18,64),new T.MeshStandardMaterial({map:tex,metalness:.2,roughness:.36}))); - for(const y of [-.61,.61]){const lid=new T.Mesh(new T.CylinderGeometry(.30,.31,.04,64),new T.MeshStandardMaterial({color:0xb9bfc0,metalness:.9,roughness:.22}));lid.position.y=y;product.add(lid);} + let modelKey,labelKey,labelCanvas,labelTexture; + const release=object=>{const resources=new Set();object.traverse(o=>{if(o.geometry)resources.add(o.geometry);for(const m of o.material?(Array.isArray(o.material)?o.material:[o.material]):[]){resources.add(m);for(const value of Object.values(m))if(value?.isTexture)resources.add(value);}});for(const resource of resources)resource.dispose();}; + async function updateProduct(){ + const next=String(props.model??''); + if(next!==modelKey){ + const replacement=new T.Group();let canvas,texture; + if(next){ + const gltf=await new GLTFLoader().loadAsync(asset(next)),model=gltf.scene; + const box=new T.Box3().setFromObject(model),size=box.getSize(new T.Vector3()),centre=box.getCenter(new T.Vector3()); + if(!Number.isFinite(size.y)||size.y<=0){release(model);throw Error('Product model has no finite height');} + model.position.sub(centre);const fit=new T.Group();fit.add(model);fit.scale.setScalar(1.25/size.y);replacement.add(fit); + }else{ + canvas=document.createElement('canvas');canvas.width=1024;canvas.height=512;texture=new T.CanvasTexture(canvas);texture.colorSpace=T.SRGBColorSpace; + replacement.add(new T.Mesh(new T.CylinderGeometry(.31,.31,1.18,64),new T.MeshStandardMaterial({map:texture,metalness:.2,roughness:.36}))); + for(const y of [-.61,.61]){const lid=new T.Mesh(new T.CylinderGeometry(.30,.31,.04,64),new T.MeshStandardMaterial({color:0xb9bfc0,metalness:.9,roughness:.22}));lid.position.y=y;replacement.add(lid);} + } + replacement.traverse(o=>{if(o.isMesh)o.castShadow=true;});release(product);product.clear();product.add(replacement); + modelKey=next;labelCanvas=canvas;labelTexture=texture;labelKey=undefined; + } + const label=String(props.label??''); + if(labelCanvas&&label!==labelKey){const ctx=labelCanvas.getContext('2d');ctx.fillStyle='#ef633f';ctx.fillRect(0,0,1024,512);ctx.fillStyle='white';ctx.textAlign='center';ctx.font='900 95px Arial';for(const x of [256,768])ctx.fillText(label,x,280);labelTexture.needsUpdate=true;labelKey=label;} } - product.traverse(o=>{if(o.isMesh)o.castShadow=true;});const floor=new T.Mesh(new T.PlaneGeometry(20,20),new T.ShadowMaterial({opacity:.32}));floor.receiveShadow=true;floor.userData.passExclude=true;floor.rotation.x=-Math.PI/2;floor.position.y=-.76;scene.add(floor); + const floor=new T.Mesh(new T.PlaneGeometry(20,20),new T.ShadowMaterial({opacity:.32}));floor.receiveShadow=true;floor.userData.passExclude=true;floor.rotation.x=-Math.PI/2;floor.position.y=-.76;scene.add(floor); const title=document.createElement('div');title.style.cssText='position:absolute;left:46px;top:42px;color:#17251e;font:800 32px/1.05 Arial;letter-spacing:-1px;max-width:310px';root.append(title); const sub=document.createElement('div');sub.style.cssText='position:absolute;left:46px;bottom:42px;color:#17251e;font:600 13px Arial;letter-spacing:2px';root.append(sub); const kinetic=createKineticText({root:title});let bg,bgctx;const loader=createFrameLoader(),env=createPlateEnvironment(r);if(props.backplate){bg=document.createElement('canvas');bg.width=832;bg.height=480;root.prepend(bg);bg.style.cssText='position:absolute;inset:0';canvas.style.cssText='position:absolute;inset:0';bgctx=bg.getContext('2d');} return {async render(clock){ - const time=clock.frame/clock.fps;product.rotation.y=props.spin?time*.65:-1.3;kinetic.render(time,{text:'BUILT IN CODE. SET IN MOTION.',effect:'orbit',stagger:.09,duration:.8,hold:3600,pathRadius:30});sub.textContent=props.model?'PHOTO → GLB → EDITABLE HTML':'LUMA / BLOOD ORANGE'; + await updateProduct(); + const time=clock.frame/clock.fps;product.rotation.y=props.spin?time*.65:-1.3;kinetic.render(time,{text:'BUILT IN CODE. SET IN MOTION.',effect:'orbit',stagger:.09,duration:.8,hold:3600,pathRadius:30});sub.textContent=props.model?'PHOTO → GLB → EDITABLE HTML':String(props.label)+' / BLOOD ORANGE'; if(props.backplate){const info=props.worldInfo??mediaInfo?.(String(props.world));if(!info?.frameRate||!info.frames)throw Error('Supply verified empty-background metadata');const at=conformSeconds(clock.mediaTime??time,info.frameRate),index=Math.floor(at*info.frameRate.num/info.frameRate.den+1e-6);if(index<0||index>=info.frames)throw Error('Empty background frame outside source range');const image=await loader.load(sourceFrame?sourceFrame(String(props.world),index,{width:info.width,height:info.height,seconds:at}):mediaFrame(String(props.world),at));bgctx.drawImage(image,0,0,832,480);scene.environment=env.update(image);scene.environmentIntensity=1;floor.visible=true;title.style.color=sub.style.color='white';} const pass=clock.pass??'beauty';title.style.visibility=sub.style.visibility=pass==='beauty'?'visible':'hidden';if(bg)bg.style.visibility=pass==='beauty'?'visible':'hidden'; if(pass!=='beauty'){root.style.background='transparent';renderPass(r,scene,camera,pass,{ids:['product']});}else{root.style.background=props.backplate?'#202620':'#d6dcd6';r.render(scene,camera);} - },dispose(){kinetic.dispose();loader.dispose();env.dispose();r.dispose();r.forceContextLoss();root.replaceChildren();}}; + },dispose(){kinetic.dispose();loader.dispose();env.dispose();release(product);release(floor);r.dispose();r.forceContextLoss();root.replaceChildren();}}; }}); diff --git a/examples/hybrid-surfaces/clip.mjs b/examples/hybrid-surfaces/clip.mjs index ecd2ac9..b2eca0b 100644 --- a/examples/hybrid-surfaces/clip.mjs +++ b/examples/hybrid-surfaces/clip.mjs @@ -1,5 +1,5 @@ import {defineRenderer} from 'editableframes/renderer'; -import {createFrameLoader,createForegroundHoldout,validatePreparedAnalysis,preparedFrame,sampleTrack,scalePoints,cylinderMesh,sampleSurface,drawSurfaceArtwork,relightArtwork,createKineticText,loadPreparedAnalysis,pendingMaskCorrections} from 'editableframes/plate'; +import {createFrameLoader,createForegroundHoldout,validatePreparedAnalysis,preparedFrame,sampleTrackFrame,scalePoints,cylinderMesh,sampleSurface,drawSurfaceArtwork,relightArtwork,createKineticText,loadPreparedAnalysis,pendingMaskCorrections} from 'editableframes/plate'; export const controls={version:1,fields:[ {key:'foregroundSource',anchor:'surface',path:'/foregroundSource',type:'media',mediaKind:'video',default:'plate',label:'Original object footage'}, @@ -40,7 +40,7 @@ export default defineRenderer({id:'surface-reskin',renderer:'canvas+dom',width:1 if(pending)throw Error('Corrections changed; prepare and review a new mask revision before rendering'); if(!props.foregroundSource||!props.foregroundMask||!track)throw Error('Reskin needs the original source, foreground and original-body track'); if(track.sourceSha256&&track.sourceSha256!==s.sha256)throw Error('Surface track belongs to a different take'); - const at=preparedFrame(receipt,clock.mediaTime??clock.frame/clock.fps,{start:Number(props.plateStartFrame)*s.frameRate.den/s.frameRate.num,speed:Number(props.plateSpeed)}); + const at=preparedFrame(receipt,clock.mediaTime??clock.frame/clock.fps,{startFrame:Number(props.plateStartFrame),speed:Number(props.plateSpeed)}); const w=root.clientWidth||clock.width,h=root.clientHeight||clock.height; for(const c of [plate,ink])if(c.width!==w||c.height!==h){c.width=w;c.height=h;} if(identity!==s.sha256){identity=s.sha256;holdout?.dispose();holdout=createForegroundHoldout({root:stage,width:s.width,height:s.height});holdout.root.append(ink,title);} @@ -49,7 +49,7 @@ export default defineRenderer({id:'surface-reskin',renderer:'canvas+dom',width:1 const pc=plate.getContext('2d',{willReadFrequently:true});pc.drawImage(image,0,0,w,h); const key=JSON.stringify([props.label,props.detail,props.color]); if(key!==labelKey){labelKey=key;const c=art.getContext('2d');c.fillStyle=props.color;c.fillRect(0,0,2048,1024);c.fillStyle='white';c.textAlign='center';c.textBaseline='middle';c.font='900 190px system-ui';c.fillText(String(props.label),1024,470,900);c.font='700 38px system-ui';c.fillText(String(props.detail),1024,650,900);} - const pin=sampleTrack(track,at.seconds);if(pin.held||pin.confidence<=0)throw Error('Original body track is missing at source frame '+at.sourceFrame); + const pin=sampleTrackFrame(track,at.sourceFrame);if(pin.held||pin.confidence<=0)throw Error('Original body track is missing at source frame '+at.sourceFrame); const fitted=props.meshTrack?sampleSurface(props.meshTrack,at.sourceFrame):null; const quad=scalePoints(pin.quad,track,w,h),inset=Number(props.bodyInset),curve=Number(props.rimCurve); if(!Number.isFinite(inset)||inset<0||inset>.1||!Number.isFinite(curve)||curve<0||curve>.1)throw Error('Invalid body inset/curvature'); diff --git a/package.json b/package.json index a1c86c8..0dab374 100644 --- a/package.json +++ b/package.json @@ -50,7 +50,7 @@ "dev:scene": "node examples/scene-editor/serve.mjs", "test:scene": "node tests/scene-editor-browser.mjs", "test:hybrid": "node tests/hybrid-integration.mjs", - "test:prepared": "node tests/prepared-integration.mjs" + "test:prepared": "node tests/prepared-integration.mjs && node tests/hybrid-editing.mjs" }, "dependencies": { "esbuild": "0.25.10", diff --git a/packages/media/frames.mjs b/packages/media/frames.mjs new file mode 100644 index 0000000..4a0f195 --- /dev/null +++ b/packages/media/frames.mjs @@ -0,0 +1,11 @@ +import {ptsIndex} from './ports.mjs'; + +/** Derived videos share the plate's frame correspondence. A derived still + * supplies one raster for every source frame, regardless of the plate clock. */ +export function mediaFrameUrl(catalog,id,time){ + const asset=catalog[id]; + if(!asset||asset.type==='audio'||asset.type==='data')throw Error('Missing visual asset: '+id); + const parent=asset.derived&&catalog[asset.derived.of]; + const index=ptsIndex(asset.type==='video'&&parent?.type==='video'?parent.pts:asset.pts,time); + return index<0?undefined:asset.url+String(index+1).padStart(6,'0')+'.png'; +} diff --git a/packages/plate/prepared.mjs b/packages/plate/prepared.mjs index f797d30..f00d04f 100644 --- a/packages/plate/prepared.mjs +++ b/packages/plate/prepared.mjs @@ -29,9 +29,11 @@ export function validatePreparedAnalysis(data, source) { } /** Explicit source mapping handles trim/reverse; out-of-range never holds a tail. */ -export function preparedFrame(data, seconds, {start = 0, speed = 1, requireReviewed = true, allowInvalid = false} = {}) { +export function preparedFrame(data, seconds, {start = 0, startFrame, speed = 1, requireReviewed = true, allowInvalid = false} = {}) { if (![seconds,start,speed].every(finite)) throw Error('Prepared sampling needs finite time, trim and speed'); - const time = start + seconds * speed, pts = data.source.pts; + const pts = data.source.pts; + if (startFrame !== undefined && (!integer(startFrame) || startFrame >= pts.length)) throw Error('Prepared trim needs a source frame inside the plate'); + const time = (startFrame === undefined ? start : pts[startFrame]) + seconds * speed; const end = pts.at(-1) + data.source.frameRate.den / data.source.frameRate.num; if (time < -1e-9 || time >= end - 1e-9) throw Error(`Prepared source time ${time} is outside 0..${end}`); let lo=0, hi=pts.length; diff --git a/packages/plate/track.mjs b/packages/plate/track.mjs index ec4816f..0725cbd 100644 --- a/packages/plate/track.mjs +++ b/packages/plate/track.mjs @@ -29,7 +29,13 @@ const mix = (a, b, t) => a + (b - a) * t; * nearest tracked frame is held and `held` says so. */ export function sampleTrack(track, seconds) { if (!finite(seconds)) throw Error('Track sample needs finite seconds'); - const frames = track.frames, position = seconds * track.frameRate.num / track.frameRate.den; + return sampleTrackFrame(track, seconds * track.frameRate.num / track.frameRate.den); +} +/** Sample a known decoded source frame without converting its quantized PTS + * back through nominal fps. Fractional positions remain available to authors. */ +export function sampleTrackFrame(track, position) { + if (!finite(position)) throw Error('Track sample needs a finite frame'); + const frames = track.frames; let lo = 0, hi = frames.length - 1; if (position <= frames[0].frame) hi = 0; else if (position >= frames[hi].frame) lo = hi; diff --git a/packages/runtime/editor.mjs b/packages/runtime/editor.mjs index a05ed6c..9dbf7f0 100644 --- a/packages/runtime/editor.mjs +++ b/packages/runtime/editor.mjs @@ -1,5 +1,5 @@ import {normalizeObjectHierarchy,selectableObject,parentObjectId} from '../core/objects.mjs'; -import {createRendererCompositor} from './renderer-compositor.mjs';import {ptsIndex} from '../media/ports.mjs'; +import {createRendererCompositor} from './renderer-compositor.mjs';import {mediaFrameUrl} from '../media/frames.mjs'; import {Studio,clone,HZ} from '../core/index.mjs';import {createMediaHost} from '../media/browser.mjs';import {createAudioPlayback} from '../media/playback.mjs';import {createCompositor} from './compositor.mjs'; export async function mount({templates,createRenderer,scene,binding,initial,mediaCatalog={},assetIds=[],persistence=null,capture=false}){ const $=s=>document.querySelector(s);let canvas=$('#screen'); @@ -16,7 +16,7 @@ export async function mount({templates,createRenderer,scene,binding,initial,medi services.mediaInfo=id=>{const a=mediaCatalog[id];if(!a)throw Error('Undeclared asset: '+id);return {sha256:a.sha256,pts:[...(a.pts??[])],type:a.type,width:a.width,height:a.height,duration:a.duration,frames:a.pts?.length??0,frameRate:a.frameRate?{...a.frameRate}:undefined,derived:a.derived?structuredClone(a.derived):undefined};}; services.derived=(id,role,subject)=>{if(!mediaCatalog[id])throw Error('Undeclared asset: '+id);return Object.keys(mediaCatalog).find(key=>mediaCatalog[key].derived?.of===id&&mediaCatalog[key].derived.role===role&&mediaCatalog[key].derived.subject===subject);}; } - if(Object.keys(mediaCatalog).length)services.mediaFrame=(id,time)=>{const a=mediaCatalog[id];if(!a||a.type==='audio'||a.type==='data')throw Error('Missing visual asset: '+id);const index=ptsIndex(a.derived&&mediaCatalog[a.derived.of]?.type==='video'?mediaCatalog[a.derived.of].pts:a.pts,time);return index<0?undefined:a.url+String(index+1).padStart(6,'0')+'.png';}; + if(Object.keys(mediaCatalog).length)services.mediaFrame=(id,time)=>mediaFrameUrl(mediaCatalog,id,time); services.sourceFrame=(id,index)=>{const a=mediaCatalog[id];if(!a||!Number.isSafeInteger(index)||index<0||index>=a.pts.length)throw Error('Invalid declared source frame: '+id+':'+index);return a.url+String(index+1).padStart(6,'0')+'.png';}; const renderer=scene?createRendererCompositor(canvas,{scene,templates,services,capture}):createCompositor(canvas,{templates,createRenderer,host}),audio=createAudioPlayback(mediaCatalog);let selection=null,selectionVersion=0; if(scene)canvas.addEventListener('pointerdown',async event=>{ diff --git a/tests/hybrid-editing.mjs b/tests/hybrid-editing.mjs new file mode 100644 index 0000000..313a7b2 --- /dev/null +++ b/tests/hybrid-editing.mjs @@ -0,0 +1,40 @@ +// Live instances must render edits exactly as newly mounted capture instances. +import assert from 'node:assert/strict'; +import {build} from 'esbuild'; +import {chromium} from 'playwright'; +const {outputFiles}=await build({stdin:{contents:` + import product from './examples/hybrid-code-first/clip.mjs'; + import surface from './examples/hybrid-surfaces/clip.mjs'; + import {mountRenderer} from './packages/runtime/renderer-host.mjs'; + import * as T from 'three'; + import {GLTFExporter} from 'three/examples/jsm/exporters/GLTFExporter.js'; + window.proof={product,surface,mountRenderer,T,GLTFExporter};`,resolveDir:new URL('..',import.meta.url).pathname},bundle:true,write:false,format:'iife'}); +const browser=await chromium.launch({headless:true,args:['--enable-webgl',process.platform==='darwin'?'--use-angle=metal':'--use-angle=swiftshader']}); +try{ + const page=await browser.newPage();await page.setContent('
');await page.addScriptTag({content:outputFiles[0].text}); + const result=await page.evaluate(async()=>{ + const {product,surface,mountRenderer,T,GLTFExporter}=window.proof,clock={frame:16,fps:16,width:832,height:480,pass:'beauty'}; + const urls=[]; + for(const color of [0x2255ff,0xffcc22]){const mesh=new T.Mesh(new T.BoxGeometry(.7,1,.5),new T.MeshStandardMaterial({color}));const bytes=await new GLTFExporter().parseAsync(mesh,{binary:true});urls.push(URL.createObjectURL(new Blob([bytes])));mesh.geometry.dispose();mesh.material.dispose();} + const root=document.querySelector('#live'),services={asset:id=>urls[Number(id)]}; + const live=await mountRenderer(product,{root,props:{backplate:false},services}); + const pixels=node=>node.querySelector('canvas').toDataURL();const states=[]; + for(const values of [{label:'FIRST',model:''},{label:'SECOND',model:''},{label:'SECOND',model:'0'},{label:'SECOND',model:'1'},{label:'FIRST',model:''}]){ + const props={...values,backplate:false};await live.render(clock,props);const shown=pixels(root); + const freshRoot=document.querySelector('#fresh'),fresh=await mountRenderer(product,{root:freshRoot,props,services});await fresh.render(clock); + states.push({same:shown===pixels(freshRoot),pixels:shown});await fresh.dispose(); + } + await live.dispose();urls.forEach(url=>URL.revokeObjectURL(url)); + const source={asset:'plate',sha256:'a'.repeat(64),width:100,height:80,frames:8,frameRate:{num:24,den:1},pts:[0,.042,.083,.125,.167,.208,.25,.292],orientation:0,crop:[0,0,100,80]}; + const prepared={version:1,kind:'prepared-plate',subject:'hand',revision:'c'.repeat(64),source,alpha:{asset:'mask',sha256:'b'.repeat(64),channel:'alpha',semantics:'alpha'},provenance:{method:'test',preprocess:'test/1'},frames:source.pts.map((_,i)=>({sourceFrame:i,maskFrame:i,valid:true,reviewed:true}))}; + const track={version:1,kind:'planar',sourceSha256:source.sha256,width:100,height:80,frameRate:source.frameRate,frames:source.pts.map((_,frame)=>({frame,quad:[[10,10],[30,10],[30,70],[10,70]],confidence:1}))}; + const canvas=document.createElement('canvas');canvas.width=100;canvas.height=80;const empty=canvas.toDataURL(),ctx=canvas.getContext('2d');ctx.fillStyle='#aaa';ctx.fillRect(0,0,100,80);const original=canvas.toDataURL(); + root.style.cssText='position:relative;width:100px;height:80px'; + const props={...surface.defaultProps,prepared,track,foregroundSource:'plate',foregroundMask:'mask',headline:''}; + const instance=await surface.create({root,props,sourceFrame:id=>id==='plate'?original:empty}); + for(const frame of [0,9,1,9])await instance.render({frame,fps:30,width:100,height:80});await instance.dispose(); + return {freshParity:states.every(s=>s.same),labelChanged:states[0].pixels!==states[1].pixels,modelChanged:states[2].pixels!==states[3].pixels,undoRestored:states[0].pixels===states[4].pixels,reskinLastFrame:true}; + }); + assert.deepEqual(result,{freshParity:true,labelChanged:true,modelChanged:true,undoRestored:true,reskinLastFrame:true}); + console.log('PASS: live label/model edits and Undo match fresh renders; quantized final-frame reskin renders after reverse seeks.'); +}finally{await browser.close();} diff --git a/tests/hybrid-prepared.test.mjs b/tests/hybrid-prepared.test.mjs index 5b2a548..d185485 100644 --- a/tests/hybrid-prepared.test.mjs +++ b/tests/hybrid-prepared.test.mjs @@ -1,8 +1,17 @@ import test from 'node:test'; import assert from 'node:assert/strict'; -import {validatePreparedAnalysis,preparedFrame,analyzeMask,sampleMaskCorrections,assertSurfaceLayout,cylinderMesh,sampleSurface,surfaceError,typeMotion,createMaskCorrectionSession,rasterizeSurface,validateDerived,pendingMaskCorrections} from '../packages/plate/index.mjs'; +import {validatePreparedAnalysis,preparedFrame,sampleTrackFrame,analyzeMask,sampleMaskCorrections,assertSurfaceLayout,cylinderMesh,sampleSurface,surfaceError,typeMotion,createMaskCorrectionSession,rasterizeSurface,validateDerived,pendingMaskCorrections} from '../packages/plate/index.mjs'; const hash='a'.repeat(64),maskHash='b'.repeat(64); const receipt=()=>({version:1,kind:'prepared-plate',subject:'hand',revision:'c'.repeat(64),source:{asset:'plate',sha256:hash,width:100,height:80,frames:3,frameRate:{num:24,den:1},pts:[0,1/24,2/24],orientation:0,crop:[0,0,100,80]},alpha:{asset:'mask',sha256:maskHash,channel:'luminance',semantics:'segmentation'},provenance:{method:'manual','preprocess':'test/1'},frames:[0,1,2].map(i=>({sourceFrame:i,maskFrame:i,valid:true,reviewed:true}))}); +test('quantized container times retain exact tracked corners through trim and reverse',()=>{ + const r=receipt();r.source.pts=[0,.042,.083]; + const track={kind:'planar',frameRate:r.source.frameRate,frames:[0,1,2].map(frame=>({frame,quad:[[frame,0],[frame+5,0],[frame+5,5],[frame,5]],confidence:1}))}; + for(const [time,options,expected] of [[1/24,{},0],[.042,{},1],[.1,{},2],[0,{startFrame:1},1],[.042,{startFrame:1,speed:-1},0],[1,{startFrame:2,speed:0},2]]){ + const selected=preparedFrame(r,time,options),pin=sampleTrackFrame(track,selected.sourceFrame); + assert.equal(selected.sourceFrame,expected);assert.equal(pin.quad[0][0],expected);assert.equal(pin.held,false); + } + assert.throws(()=>preparedFrame(r,0,{startFrame:3}),/trim/); +}); test('prepared source identity, correspondence and review survive trims/reverse/random seeks',()=>{ const r=validatePreparedAnalysis(receipt()); assert.equal(preparedFrame(r,1/24).sourceFrame,1); diff --git a/tests/media-pts.test.mjs b/tests/media-pts.test.mjs index 8928acb..a7c8850 100644 --- a/tests/media-pts.test.mjs +++ b/tests/media-pts.test.mjs @@ -1,5 +1,22 @@ import test from 'node:test';import assert from 'node:assert/strict';import fs from 'node:fs/promises';import os from 'node:os';import path from 'node:path';import {createHash} from 'node:crypto'; import {prepareMedia} from '../scripts/media.mjs';import {run,ffmpeg,ffprobe} from '../scripts/process.mjs';import {ptsIndex} from '../packages/media/ports.mjs'; +import {mediaFrameUrl} from '../packages/media/frames.mjs'; +test('a static derived matte stays available throughout its moving parent',async()=>{ + const dir=await fs.mkdtemp(path.join(os.tmpdir(),'ef-static-matte-'));let media; + try{ + const plate=path.join(dir,'plate.mp4'),mask=path.join(dir,'mask.png'); + await run(ffmpeg(),['-v','error','-f','lavfi','-i','testsrc2=size=64x48:rate=24:duration=1','-c:v','libx264',plate]); + await run(ffmpeg(),['-v','error','-f','lavfi','-i','color=c=white:s=64x48','-frames:v','1',mask]); + const sha=async file=>createHash('sha256').update(await fs.readFile(file)).digest('hex'),source=await sha(plate); + media=await prepareMedia({plate:{file:plate,type:'video',sha256:source},mask:{file:mask,type:'image',sha256:await sha(mask),derived:{of:'plate',role:'matte',sourceSha256:source}}}); + assert.equal(mediaFrameUrl(media.catalog,'mask',-1),undefined,'a still retains its own presentation clock'); + for(const frame of [0,1,12,23]){ + const url=mediaFrameUrl(media.catalog,'mask',frame/24); + assert.ok(url.endsWith('/000001.png'));await fs.access(path.join(media.dir,'mask',path.basename(url))); + assert.ok(mediaFrameUrl(media.catalog,'plate',frame/24).endsWith(String(frame+1).padStart(6,'0')+'.png')); + } + }finally{await media?.close();await fs.rm(dir,{recursive:true,force:true});} +}); // ffprobe prints `*_time` values to six decimals, so frame 1 of a 24 fps clip reads 0.041667: later than // 1/24 s. Looked up at the frame's own time, a third of the frames of a 24 or 30 fps clip resolved to // their predecessor, so a plate showed frame n-1 while a track sampled on the plate's grid used frame n. From 58318cb7419e5f6132a03212f40522d11bd55c59 Mon Sep 17 00:00:00 2001 From: Laurence Xavier <35849747+lxf82dev@users.noreply.github.com> Date: Thu, 12 Nov 2026 11:24:15 +0800 Subject: [PATCH 21/49] Document human foreground lighting routes and acceptance gates --- docs/avatar-lighting.md | 48 +++++++++++++++++++++++++++++++++ docs/hybrid-compositing-plan.md | 2 ++ 2 files changed, 50 insertions(+) create mode 100644 docs/avatar-lighting.md diff --git a/docs/avatar-lighting.md b/docs/avatar-lighting.md new file mode 100644 index 0000000..2b8fb3c --- /dev/null +++ b/docs/avatar-lighting.md @@ -0,0 +1,48 @@ +# Human foreground lighting + +Status: design and isolated still-image evaluation, not a shipped avatar relighting feature. Existing prepared-media primitives provide source-bound alpha and exact frame sampling; they do not recover a person's geometry or original illumination. Continuous speech, hands, multiple people, temporal stability and native preview/export parity still need video acceptance. + +## Route by the foreground's representation + +| Foreground | Default | Escalation | +| --- | --- | --- | +| Authored 3D geometry and materials | Editable lights, environment and physically based raster shading | Opt-in higher-quality transport where glass, indirect light or shadows justify it | +| Filmed or generated human RGB + alpha | Preserve source pixels; bounded linear-light exposure/colour harmonisation | Prepared video-aware inverse-rendering passes or a reviewed video relight when light direction must change substantially | +| Truly relightable 3D human asset | Use its authored geometry/material/skin transport model | Validate eyes, hair and subsurface scattering separately; an RGB avatar video is not such an asset | +| Circular presenter inset | Treat as a screen-space UI layer; preserve the intentional frame | Relight only when explicitly intended to occupy the scene | + +Transparent output makes composition easier; it does not remove lighting baked into skin and clothing. A Three.js light cannot physically relight an ordinary video texture. A soft mask is not a normal map. Do not use subject depth as a substitute for facial normals or observed alpha. + +## Lighting is continuous, not a style enum + +Names such as office, daylight and neon are example recipes. The underlying editable description can contain arbitrary supported lights, directions, colours, intensity, source size, fill, environment, exposure and time tracks. A host may propose a new recipe from each background instead of choosing from a finite catalogue. Colour alone cannot identify incident illumination: a warm wall may be painted warm, and the brightest patch may be a surface rather than a light. Record observations, assumptions, confidence and user overrides separately. Keep scene estimates stable across a shot; freeze or interpolate authored tracks rather than re-estimating independently on every export frame. + +A common lighting description expresses intent across layers. Each renderer implements the subset its representation supports. RGB harmonisation must report that directional shadows/specular changes are unsupported; it must not silently present a colour ramp as a physical light solve. + +## Prepared human data contract (proposed extension) + +Retain current source identity, raster, rational rate, PTS, correspondence, validity/review and revision gates. Per subject, additionally identify foreground colour, alpha convention (straight/premultiplied), transfer function/primaries, any shading/gain map, normals/albedo/roughness/depth where actually provided, model/version/licence and source-to-output mapping. Missing passes are absent, never fabricated defaults. Map signed normal vectors and linear data explicitly; do not treat them as sRGB. + +Prefer native provider alpha and foreground colour over re-segmenting a flattened scene. Decontaminated edge colour matters when replacing the background. In an already-composited image, a masked colour delta can leave the old background unchanged, but cannot recover uncontaminated hair or unseen background. For multiple people, maintain subject IDs, separate adjustments and explicit overlap ordering; a union person mask cannot support independent lighting or depth relationships. + +Run models during preparation, outside the renderer clock. Cache reviewed outputs with hashes. Deterministic rendering samples those frozen artifacts at the exact source frame, including random/reverse seeks. A new background or lighting recipe invalidates lighting-dependent artifacts, not unrelated source audio or alpha. Generated outputs that change timing must be re-aligned or rejected; preserve the original speech track and verify lip sync. + +## Isolated evidence and rejected shortcuts + +Two high-resolution presenter screenshots and a separate small circular inset were evaluated locally. They are independent stills, not a continuous sequence. RVM MobileNetV3 separated the body but visibly damaged small headphone/cable features and left edge contamination. CPU execution is feasible on the tested Apple machine; that does not establish real-time video quality or cross-device throughput. RVM is GPL-3.0 and was evaluated separately, not bundled or selected for production distribution. + +Bounded linear-light gain preserved background pixels outside the supplied mask. It preserved source geometry by construction but did not create geometrically correct directional facial shadows. IC-Light SD1.5 FBC, run locally with the same seed on two stills, produced stronger light while changing facial and accessory detail. Raw generative replacement was rejected for faithful avatar rendering. A blurred, clamped luminance-ratio hint applied back to original pixels avoided substituting generated facial pixels, but remains experimental: incorrect inferred shapes can still imply incorrect shading, and temporal consistency was not tested. + +Do not interpret zero background change, equal frame counts or deterministic output as a likeness or photorealism score. Keep numerical integrity, boundary quality, identity/expression, illumination plausibility and temporal quality separate. + +## Next video acceptance + +Use a short alpha-capable talking clip with head turns, blink, open/closed mouth and a hand near the face. Compare unchanged source, conservative harmonisation and any stronger relighter against a fixed warm/cool background pair. Inspect every transition and alpha edge, speech timing, hair, headphones, teeth, skin texture, hands and clothing. Test a second person with overlaps independently. Export and native preview must agree on source mapping and approved revisions. A slideshow of supplied screenshots cannot pass this gate. + +## Provider and research notes + +- [HeyGen transparent output](https://developers.heygen.com/transparent-background-videos): the documented avatar route requests WebM using a matting-enabled avatar look. Verify eligibility and actual decoded alpha. This supplies a foreground, not relighting passes. Keep provider-specific requests in the host, outside the rendering library. +- [Google Portrait Light](https://www.research.google/blog/portrait-light-enhancing-portrait-lighting-with-machine-learning/) predicts a low-frequency quotient applied to source pixels. This motivates detail-preserving gain control; it does not validate a handcrafted or diffusion-derived gain map. +- [RVM](https://github.com/PeterL1n/RobustVideoMatting) provides recurrent foreground/matte inference, with GPL-3.0 licensing. Licence review and benchmark evidence are required before distribution. +- [IC-Light](https://github.com/lllyasviel/IC-Light) is an image relighting candidate. Independent image inference is not a temporally validated video relighter. +- [Beeble](https://developer.beeble.ai/) offers hosted transformation; account-gated product passes and a generative output are different contracts. No hosted pass/relight was tested in this evaluation. Assess output fidelity and current access before choosing it. diff --git a/docs/hybrid-compositing-plan.md b/docs/hybrid-compositing-plan.md index a7bae44..71dfdba 100644 --- a/docs/hybrid-compositing-plan.md +++ b/docs/hybrid-compositing-plan.md @@ -1,5 +1,7 @@ # Reliable hybrid compositing and motion design +Human foreground extension: [avatar lighting](avatar-lighting.md) records the representation-dependent routing, still-image findings and pending video acceptance. This is a design addition, not a claim of shipped portrait relighting. + Status: implementation and acceptance plan, 2026-11-11. Implemented APIs are documented separately below; research gates remain explicit. It supersedes any inference that a successful render or a few attractive frames establish a usable hybrid clip. Existing primitives and their tested scope remain documented in [hybrid-scenes.md](hybrid-scenes.md). Implementation update: the [prepared-media primitives](prepared-plates.md) now implement receipts, exact frame access, holdouts, corrections, cylinder/mesh replay and kinetic text. These mechanisms have synthetic regression coverage and retained real-shot QA in progress for people, close-up hands, original-object reskin and clean-background code composition. Automatic geometry solving and production model selection remain research. From a6b49dbb44489bb0ba9e6325fb7a34bb5174ddb2 Mon Sep 17 00:00:00 2001 From: Laurence Xavier <35849747+lxf82dev@users.noreply.github.com> Date: Thu, 12 Nov 2026 21:18:14 +0800 Subject: [PATCH 22/49] Skill reference: list sampleTrackFrame, as the hybrid doc does The hybrid doc's helper table gained sampleTrackFrame without its packaged skill copy, so the CLI test that pins the copy to the doc failed. Co-Authored-By: Claude Opus 5.5 --- skills/editableframes/references/hybrid.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/skills/editableframes/references/hybrid.md b/skills/editableframes/references/hybrid.md index 4abf112..8688036 100644 --- a/skills/editableframes/references/hybrid.md +++ b/skills/editableframes/references/hybrid.md @@ -131,7 +131,7 @@ The host then supplies `clock.pass` (`'beauty'` unless a pass was requested). A | Area | Functions | |---|---| | Corner pin | `solveHomography`, `applyHomography`, `invertHomography`, `cornerPinTransform`, `cssMatrix3d`, `quadArea` | -| Tracks | `validateTrack`, `sampleTrack`, `scalePoints` | +| Tracks | `validateTrack`, `sampleTrack`, `sampleTrackFrame`, `scalePoints` | | Camera | `validateCameraPath`, `sampleCameraPath`, `slerp` | | Frame rate | `plateFrameIndex`, `conformSeconds`, `cadence` | | Depth | `validateDepthEncoding`, `decodeDepth`, `encodeDepth`, `packDepth`, `unpackDepth`, `depthGlsl`, `unprojectDepth`, `fitGroundPlane` | From def66d7d590d49af9addaee24de925eb67a85bf7 Mon Sep 17 00:00:00 2001 From: Laurence Xavier <35849747+lxf82dev@users.noreply.github.com> Date: Thu, 12 Nov 2026 21:18:14 +0800 Subject: [PATCH 23/49] Docs: product photographs versus models, and presenters handling products From trials on 2026-11-12: - Lighting: an official product photograph keeps exact branding but can only be colour-matched; its highlights are baked in and turn with the image. A 3D model responds to moving light only as well as its materials allow; two phone models were too flat for close-ups. Notes on grading a case but not its display, explicit downsampling, and environment strength washing out metal. - Overlap: object-id passes at 35 crossing poses of two moving copies found no wrong ordering; axis-aligned boxes reported collisions a tight footprint ruled out. - Presenters: a generated presenter can point at, pick up and carry a product, best from an explicit first frame, but the output is one flattened picture and the product is redrawn. Drawing the exact product needs separate background, presenter and hand layers, a product pose whose anchor moves from table to hand, a 3D or multi-view asset, and narration timed with the action. Proposed, not implemented. Co-Authored-By: Claude Opus 5.5 --- docs/avatar-lighting.md | 20 ++++++++++++++++++++ docs/lighting.md | 16 ++++++++++++++++ 2 files changed, 36 insertions(+) diff --git a/docs/avatar-lighting.md b/docs/avatar-lighting.md index 2b8fb3c..ec8cdfd 100644 --- a/docs/avatar-lighting.md +++ b/docs/avatar-lighting.md @@ -39,6 +39,26 @@ Do not interpret zero background change, equal frame counts or deterministic out Use a short alpha-capable talking clip with head turns, blink, open/closed mouth and a hand near the face. Compare unchanged source, conservative harmonisation and any stronger relighter against a fixed warm/cool background pair. Inspect every transition and alpha edge, speech timing, hair, headphones, teeth, skin texture, hands and clothing. Test a second person with overlaps independently. Export and native preview must agree on source mapping and approved revisions. A slideshow of supplied screenshots cannot pass this gate. +## A presenter who handles a product (proposed) + +A generated presenter clip is one flattened picture. Imported as media it takes layer edits only: timing, crop, position, an overall grade, and code drawn over it. Her pose, the product in her hand, the grip, the room's light and the camera cannot be changed separately, because they are not separate in the file. Pilots on 2026-11-12 with hosted avatar and video models confirmed the useful half and the missing half: + +- **A model can perform the action.** From a supplied still of the presenter in a room, one take pointed and swept a hand toward the product, and another approached a table, gripped headphones by the headband, lifted them and stepped while holding them. +- **The first frame controls the shot; the prompt does not.** Pose, framing and product orientation followed the supplied image. A take started from an explicitly composed standing frame gave the best result. Text instructions to lock the camera or stand were ignored in other takes. +- **The product does not survive.** The generated headphones drifted toward generic ones. For an exact product, treat the generated performance as a reference and draw the product in code. +- **Timing needs its own stage.** Speech meant to announce the lift started after it. Sliding audio against a face that is already speaking does not fix lip sync. + +To draw an exact product into such a shot, a scene needs inputs that do not exist yet: + +| Input | Why | +|---|---| +| Background, presenter colour + alpha, and hand holdout as separate source-bound layers | A product held in front of the torso but behind the fingers; a room that can change independently | +| Product pose for every frame, with an anchor that changes | A pickup has phases: on the table (anchored to it, with contact shadow), grip, lift (anchor moves from table to hand with no jump), carry (follows the hand through changing light) | +| A 3D or multi-view product asset | A lifted product shows sides a single photograph does not have | +| Narration aligned before generation, or a tested lip-sync stage | Speech that names the action has to happen with it | + +Bad anatomy in a grip is repaired by another take or a reference performance, not by compositing. Until these exist, a generated pickup is a reference, not an editable shot. + ## Provider and research notes - [HeyGen transparent output](https://developers.heygen.com/transparent-background-videos): the documented avatar route requests WebM using a matting-enabled avatar look. Verify eligibility and actual decoded alpha. This supplies a foreground, not relighting passes. Keep provider-specific requests in the host, outside the rendering library. diff --git a/docs/lighting.md b/docs/lighting.md index 97f5f0d..4d9f694 100644 --- a/docs/lighting.md +++ b/docs/lighting.md @@ -27,3 +27,19 @@ For generated geometry, use `createDeviceMaterial` on every chassis, and use sep The website exposes **Body finish** and **Reflection angle** through its normal editable schema and undo/redo. The library viewer's **Satin aluminium bodies** toggle is saved with its existing appearance history. Screen content uses a separate unlit material so exposure does not alter interface colors. Look profiles record device, camera, HDR identity and material policy. Lighting cannot recover missing geometry or separate parts merged in the source model. These are fan-made models with varying fidelity, not calibrated scans. New renderers may use other lighting and materials without changing the core document. + +## Photographs versus models + +A real product can enter a scene two ways, and they light differently. A trial on 2026-11-12 used official photographs of four products and third-party models of three. + +| Route | Can | Cannot | +|---|---|---| +| Product photograph on an alpha plane | Keep the exact logo, controls and proportions; take restrained colour and exposure matching from the scene | Respond to a moving light. Its highlights and shadows are baked in and turn with the image, and it has no unseen sides. | +| 3D model | Respond to moving lights and environment: at a fixed pose, moving the lights changed a neutral patch from about 106 to 193 RGB | Look better than its materials. Two phone models read flat beside product photography and were unsuitable for close-ups. | + +Name the operation the scene performs: on a photograph it is colour matching, not relighting. Keep a device's display out of the grade applied to its case. Downsample a large photograph explicitly before drawing it small; a fine grille aliased until it was downsampled in steps, which cut its error against a Lanczos reference by 58%. When a metal model washes out, check the environment before the lights: in the trial the pale plateau came from environment strength, and 0.8 → 0.2 restored the surface. Moving, correct highlights on a product only available as photographs need CAD with material maps, a photogrammetry capture, or photographs taken under several lights. + +## Checking overlap between moving products + +Two copies of each product in one scene, one turning and one orbiting behind and in front of it, were checked with separate object-id passes (A only, B only, both) at 35 crossing poses: no wrong foreground assignment over 353,771 interior pixels, antialiased edges excluded. Axis-aligned bounding boxes flagged 36 collisions between the two laptops that a rotation-invariant footprint showed were at least 0.44 scene units apart. Use a tight bound before reporting a collision. The photographed products rotated only in the image plane, with their baked highlights turning too; draw order cannot repair that. Reflections of one copy in the other, bounce light and area-light shadows were not simulated. + From 6b2de0f6de871615b034206090bf3b8b041c59ea Mon Sep 17 00:00:00 2001 From: Laurence Xavier <35849747+lxf82dev@users.noreply.github.com> Date: Fri, 13 Nov 2026 13:08:57 +0800 Subject: [PATCH 24/49] Plan reference-conditioned handling shots and record video mask feasibility --- docs/avatar-lighting.md | 16 +++++-- docs/hybrid-analysis-study-2026-11-13.md | 54 ++++++++++++++++++++++++ docs/hybrid-scenes.md | 2 + 3 files changed, 69 insertions(+), 3 deletions(-) create mode 100644 docs/hybrid-analysis-study-2026-11-13.md diff --git a/docs/avatar-lighting.md b/docs/avatar-lighting.md index ec8cdfd..5707779 100644 --- a/docs/avatar-lighting.md +++ b/docs/avatar-lighting.md @@ -44,8 +44,8 @@ Use a short alpha-capable talking clip with head turns, blink, open/closed mouth A generated presenter clip is one flattened picture. Imported as media it takes layer edits only: timing, crop, position, an overall grade, and code drawn over it. Her pose, the product in her hand, the grip, the room's light and the camera cannot be changed separately, because they are not separate in the file. Pilots on 2026-11-12 with hosted avatar and video models confirmed the useful half and the missing half: - **A model can perform the action.** From a supplied still of the presenter in a room, one take pointed and swept a hand toward the product, and another approached a table, gripped headphones by the headband, lifted them and stepped while holding them. -- **The first frame controls the shot; the prompt does not.** Pose, framing and product orientation followed the supplied image. A take started from an explicitly composed standing frame gave the best result. Text instructions to lock the camera or stand were ignored in other takes. -- **The product does not survive.** The generated headphones drifted toward generic ones. For an exact product, treat the generated performance as a reference and draw the product in code. +- **Explicit first-frame composition helped in these takes.** Pose, framing and product orientation followed the supplied image. A take started from an explicitly composed standing frame gave the best result. Text instructions to lock the camera or stand were ignored in other takes. +- **The product does not survive.** The generated headphones drifted toward generic ones. Exact code replacement is one fallback; it needs the additional inputs below. The default experiment now tests a richer reference set first, without claiming exact product preservation. - **Timing needs its own stage.** Speech meant to announce the lift started after it. Sliding audio against a face that is already speaking does not fix lip sync. To draw an exact product into such a shot, a scene needs inputs that do not exist yet: @@ -57,7 +57,7 @@ To draw an exact product into such a shot, a scene needs inputs that do not exis | A 3D or multi-view product asset | A lifted product shows sides a single photograph does not have | | Narration aligned before generation, or a tested lip-sync stage | Speech that names the action has to happen with it | -Bad anatomy in a grip is repaired by another take or a reference performance, not by compositing. Until these exist, a generated pickup is a reference, not an editable shot. +Bad anatomy in a grip is repaired by another take or a reference performance, not by compositing. Without these inputs, a generated pickup supports edits to the footage layer and code overlays, not independent edits to the product or grip. ## Provider and research notes @@ -66,3 +66,13 @@ Bad anatomy in a grip is repaired by another take or a reference performance, no - [RVM](https://github.com/PeterL1n/RobustVideoMatting) provides recurrent foreground/matte inference, with GPL-3.0 licensing. Licence review and benchmark evidence are required before distribution. - [IC-Light](https://github.com/lllyasviel/IC-Light) is an image relighting candidate. Independent image inference is not a temporally validated video relighter. - [Beeble](https://developer.beeble.ai/) offers hosted transformation; account-gated product passes and a generative output are different contracts. No hosted pass/relight was tested in this evaluation. Assess output fidelity and current access before choosing it. + +## Reference-conditioned handling shots (2026-11-13) + +The next experiment generates presenter, product, hands and room together from multi-angle references, then prepares subject masks and suitable surface tracks for editable code. The shared visual context may improve contact, lighting and identity; those remain measured acceptance criteria. A whole-shot output is flattened footage. Code can expose timing, crop, transform, grade and overlay controls, but cannot independently change the generated grip, product pose, physical light or camera. Changing a generation reference means a new take and invalidates derived data. + +Use separate foreground generation when an exact or code-driven background is required. Compare native alpha where verified, neutral-background matting and suitable chroma-key acquisition; none automatically supplies shadows, uncontaminated hair or relightable geometry. Preserve separate subject IDs and corrections. Segmentation is not fractional alpha or surface depth. + +Product fidelity must be checked against references through the entire turn and grip. A tracked label can repair print only on a supported surface with valid visibility; a planar pin is not a solver for arbitrary curved products. Bad anatomy needs another take or reference performance. Audio references may influence speech or rhythm but do not guarantee lip sync, verbatim speech or action timing. Do not slide speech against an already-speaking face as a repair. + +Keep model jobs outside the rendering clock and provider-specific APIs outside the framework. Record actual decoded frame correspondence instead of requested duration, and retain the prior reviewed take until its replacement passes acceptance. The optional exact replacement contract above remains necessary when independent product geometry is required. See [video segmentation and tracking findings](hybrid-analysis-study-2026-11-13.md). These experiments are not new renderer APIs or a production approval. diff --git a/docs/hybrid-analysis-study-2026-11-13.md b/docs/hybrid-analysis-study-2026-11-13.md new file mode 100644 index 0000000..7d4069c --- /dev/null +++ b/docs/hybrid-analysis-study-2026-11-13.md @@ -0,0 +1,54 @@ +# Video segmentation and tracker study — 2026-11-13 + +Status: isolated feasibility tests and one tracker correctness fix. No new hosted generation, no production segmentation integration, and no new independent Fable approval. Existing generated clips were reused. H4 preparation and H6 reference-conditioned shots are the next work; general camera solving, deformable surfaces and generated 3D worlds remain deferred. + +## SAM 2: actual Mac video tests + +Official SAM 2.1 Hiera Tiny, code revision `2b90b9f5ceec907a1c18123530e92e794ad901a4`, checkpoint SHA-256 `7402e0d864fa82708a20fbd15bc84245c2f26dff0eb43a4b5b93452deb34be69`. PyTorch 2.15.0, float32, four CPU threads, Apple Metal (MPS) on a 16 GiB Mac (`Mac18,5`); no NVIDIA GPU. Video/state storage offloaded to CPU. Optional model postprocessing disabled, so these are raw thresholded segmentation masks, not refined alpha. + +Two contiguous intervals, each starting 3.5 seconds into an existing generated clip: + +| Case | Frames / rate / decoded test size | Prompted instances | Propagation wall time | Steady-step median / p95 | +|---|---|---|---|---| +| Full-body pickup, Metal | 48 / 24 fps / 630 × 360 | Person, headphones, gripping hand | 50.78 s | 1.108 / 1.120 s | +| Seated talking gesture, Metal | 48 / 25 fps / 640 × 360 | Person, image-left hand, image-right hand | 53.08 s | 1.180 / 1.195 s | +| Pickup CPU fallback smoke test | First 8 / 24 fps / 630 × 360 | Same three prompts | 9.63 s | 1.350 / 1.739 s | + +The model internally uses 1024 × 1024 input. Manual positive/negative clicks were supplied only on interval frame 0; no correction clicks were added afterwards. All requested frames produced masks for all three IDs. CPU and Metal binary masks were identical over the eight shared frames; this is a narrow observation, not a cross-device determinism promise. The CPU timing sample is too short for a robust hardware ranking. Propagation wall time includes saved outputs; steady-step measurements exclude file saving, include output transfer, and omit the first yielded frame. Model load, decode/initialization and prompt time are recorded separately in the local receipts. This is not end-to-end app export throughput. + +Visual inspection of nine sampled overlays per clip found broad subject identity retained through lift/reach. The hand mask includes some wrist/sleeve and product boundaries need review. Binary masks cannot resolve fractional hair alpha, motion blur, edge colour contamination or the depth of individual fingers. Up to four pixels belonged to both product and hand masks in the pickup interval; this is an overlap diagnostic, not measured ground-truth error. No annotated boundary accuracy, real-time playback approval, complete original-clip review, multiple-person test or native preview/export parity is claimed. The historical failed phone-thumb sequence was not rerun. + +**Decision:** SAM 2 is a viable optional preparation adapter on this Mac. Cache reviewed masks before playback; do not infer on every render/seek. This performance is far from real-time 24/25 fps and says nothing about ordinary Windows/Linux hardware. Keep manual corrections and a separate alpha-refinement step. A model probability/logit is not physical alpha. + +## SAM 3: access and device gate, not a quality result + +The official repository supports text/visual prompting and temporal instance tracking, with SAM 3.1 multiplex checkpoints also available. This makes it a relevant candidate for finding and following several subjects, not a proven matting or contact-physics solution. Its documented installation requires CUDA; the inspected `Sam3VideoPredictorMultiGPU` selects a CUDA device and checks CUDA GPU IDs. No native MPS video route was validated. The official checkpoint request returned HTTP 401 without accepted/authenticated access. No credentials were requested or exposed and no paid endpoint was called. + +**Decision:** do not ship a SAM 3 default or claim a SAM 2-versus-SAM 3 accuracy winner. Next comparison requires an approved checkpoint and supported runtime, or an accessible hosted endpoint with a quoted capped test. Run the same retained source intervals, prompt identities and annotated boundary protocol. Check checkpoint-specific licensing before distribution; SAM 3 uses its own SAM license, not SAM 2's Apache assumption. + +Primary sources: [SAM 2](https://github.com/facebookresearch/sam2), [SAM 3 installation and examples](https://github.com/facebookresearch/sam3), [SAM 3 video predictor](https://github.com/facebookresearch/sam3/blob/main/sam3/model/sam3_video_predictor.py). + +## Preparation architecture + +An image encoder/interactive decoder split is useful: cache heavy image features, then allow quick positive/negative point corrections. Video needs more than repeated image inference: memory propagation, stable instance IDs, cuts, disappearance/reappearance and correction-range invalidation. The model and checkpoint, preprocessing transform, source digest, frame mapping and correction revision must accompany cached data. Different models cannot share embeddings merely because tensor dimensions match. + +Produce separate subject/hand/product masks, optional refined foreground colour and alpha, and explicit review ranges. A union person mask is insufficient for independent hands or multiple presenters. Keep semantic segmentation, fractional alpha, surface registration and depth order distinct. Stale or incomplete required intervals must fail final composition; never stretch a short mask or hold a moving tail to fit a requested duration. Preparing a cropped test interval does not certify the full source. + +H6 can generate the whole shot and use these masks for editable titles, screen inserts and bounded colour adjustments. The masks do not separate baked light, recover hidden background or expose editable generated product geometry. + +## Tracker anomalies: what is known + +The original S1 board and filmed orbit source videos could not be found among the retained local assets after the earlier temporary-file loss. Their written measurements remain available; the following reproductions are deliberately new synthetic fixtures, not reruns of those shots. + +1. **S1: about 8 px error at confidence ≥0.976.** The exact cause is still unconfirmed. The tracker fits one homography to a low-resolution patch that normally includes a 25% margin. Texture or lighting outside the target can dominate; a blank interior supplies little constraint. A stationary synthetic panel with independently moving surrounding texture reproduced 6.86 px corner error, confidence 0.956 and zero lost frames. With the same surround fixed, error was 0 px and confidence 1.0. A weak-border variant reached 6.86 px at 0.959. These demonstrate the failure mechanism, not the historical shot's cause. +2. **Orbit: switching to the next box face at confidence ≥0.703.** The original report says reducing the margin produced 43–124 lost frames because the selected panel was blank. This is consistent with competing planes entering the shared template. The code has no semantic face identity, visibility test or independent corner evidence: it accepts correlation ≥0.6 plus a broad finite-coordinate sanity check. The existing evidence supports a wrong-plane failure; it does not establish exactly which pixels drove the optimizer without the original source. + +Normalized correlation measures appearance agreement, not corner accuracy, subject identity, rigidity or visibility. Raising the threshold alone cannot solve this: the synthetic failure passes even 0.95. A segmentation mask may constrain the target but cannot provide texture or recover metric pose. Face changes, out-of-plane rotation and full occlusion need explicit rejection/reseeding or a more capable tracker, rather than silently inheriting the next surface. + +### Separate preparation-tracker correctness bug + +The external preparation tracker (not an EditableFrames runtime service) returned its updated homography with correlation measured before the last update. In a one-step diagnostic the returned warp had correlation 0.978855 while the reported score was 0.618937. Re-scoring the final warp fixes that mismatch; a regression independently samples the returned transform and compares the score. Its 13 plate-tools tests pass; no tracker implementation is added to this rendering library. The moving-surround fixture still fails by 6.86 px after this fix: it is not presented as a repair of S1 or the orbit. + +### Next acceptance gate + +Preserve source-level repeats and add annotated corner trajectories, surface masks and visibility intervals for static/pan/orbit footage. Record per-corner residuals, support distribution, local boundary agreement and forward/backward consistency alongside correlation; none alone certifies correctness. Inspect every crossing and face transition. Require correction or rejection when the intended surface disappears or independent evidence disagrees. Do not freeze a confidently wrong overlay and call the shot passed. Broader tracker redesign remains pending these measurements. diff --git a/docs/hybrid-scenes.md b/docs/hybrid-scenes.md index 5181142..702d814 100644 --- a/docs/hybrid-scenes.md +++ b/docs/hybrid-scenes.md @@ -1,5 +1,7 @@ # Hybrid scenes: code inside footage +Research update (2026-11-13): [video segmentation and tracking findings](hybrid-analysis-study-2026-11-13.md) and [reference-conditioned handling shots](avatar-lighting.md#reference-conditioned-handling-shots-2026-11-13) define the next experiments and the editability boundary of flattened footage. These do not claim new implemented renderer services. + **Quality correction, 2026-11-11:** later review found erased fingers/heads, incorrect can placement and mismatched generated geometry in the example videos. Successful rendering and tracking do not establish whole-shot quality. See the [revised compositing and motion-design plan](hybrid-compositing-plan.md) for diagnoses, model/runtime research and proposed release gates. Those new features are planned, not implemented. A hybrid scene combines two kinds of picture in one shot: From 790283159ed8d81ac3f03543b55e3dea722213b4 Mon Sep 17 00:00:00 2001 From: Laurence Xavier <35849747+lxf82dev@users.noreply.github.com> Date: Fri, 13 Nov 2026 16:21:58 +0800 Subject: [PATCH 25/49] Route avatar-object interactions through reference-conditioned generation --- docs/avatar-lighting.md | 22 +++++++++++++++++++ docs/hybrid-compositing-plan.md | 2 ++ docs/hybrid-scenes.md | 2 ++ .../references/hybrid-compositing-plan.md | 2 ++ 4 files changed, 28 insertions(+) diff --git a/docs/avatar-lighting.md b/docs/avatar-lighting.md index 5707779..2b334d5 100644 --- a/docs/avatar-lighting.md +++ b/docs/avatar-lighting.md @@ -76,3 +76,25 @@ Use separate foreground generation when an exact or code-driven background is re Product fidelity must be checked against references through the entire turn and grip. A tracked label can repair print only on a supported surface with valid visibility; a planar pin is not a solver for arbitrary curved products. Bad anatomy needs another take or reference performance. Audio references may influence speech or rhythm but do not guarantee lip sync, verbatim speech or action timing. Do not slide speech against an already-speaking face as a repair. Keep model jobs outside the rendering clock and provider-specific APIs outside the framework. Record actual decoded frame correspondence instead of requested duration, and retain the prior reviewed take until its replacement passes acceptance. The optional exact replacement contract above remains necessary when independent product geometry is required. See [video segmentation and tracking findings](hybrid-analysis-study-2026-11-13.md). These experiments are not new renderer APIs or a production approval. + +## Interaction routing decision (2026-11-13) + +**All intended human–object interactions use reference-conditioned video generation by default.** This includes looking toward, pointing at, presenting, reaching for, touching, picking up, wearing and carrying an object. Generate the human, object, support surface and room together so gaze, gesture, orientation, scale, contact and lighting share one visual context. Treat the result as a candidate requiring review, not a promise that diffusion solves anatomy or preserves product details. + +The latest mask-composition exercise improved hair stability and removed measured hand/product overlap, but the presentation still failed: the person did not convincingly look toward the product, the gesture was unrelated to it, and the photographed headphones stood in an implausible pose. **Zero overlap is not a believable interaction. Do not manufacture a demonstration by moving an unrelated product cutout near a prerecorded gesture.** Do not keep iterating masks or placement on that route for this use case. + +Keep the existing composition framework around the generated shot: provider calls happen during preparation; retain references, prompts, job IDs, costs and original media; decode and bind masks/tracks to the accepted take; add editable typography, captions, prices, UI and suitable tracked screen content afterward. Screen-space cards stay outside subject holdouts. Independent product/portrait layouts, background swaps and code-rendered packshots remain valid when they do not imply interaction. A fully authored, synchronized 3D character/product scene is a separate explicit workflow, not a fallback inferred from a 2D avatar. + +Acceptance must inspect the whole gesture at normal and slow speed: eyes and head attend to the intended object, the open palm/index points toward its actual location, the product rests or is supported naturally, perspective and scale agree, contact does not slide or penetrate, and product identity remains faithful. Reject unnatural gaze, unsupported upright props, a gesture aimed elsewhere or a drifting product even when every frame decodes and every mask passes. Regenerate or change the shot; do not conceal the failure with a code overlay. + +Generated interaction is baked into the footage. Expose source selection, timing, crop, overall grade and code-overlay controls honestly. Changing gaze, pose, grip, product orientation or physical lighting requires a new take and invalidates dependent analysis. This is an authoring/host routing decision; it adds no implicit model service to the renderer. + +### Single-take result (2026-11-13): partial improvement, rejected for final use + +One [Kling 4.0 reference-image job on Replicate](https://replicate.com/kwaivgi/kling-v4.0) used a fictional presenter still, one official headphone view and an empty showroom reference. Requested five seconds at 720p; decoded output was 121 frames at 24 fps (5.0417 seconds), 1280×720. The published image-reference rate implies about $0.79 for the reported output duration; this is an estimate, not a verified billing-ledger charge. No second paid take was submitted. + +Sampled frames show her head/eyes attending to the headphones and an open palm presenting toward them before she returns attention to the camera. This is better coordinated than the unrelated-avatar/product composite. However, the model kept the headphones upright, matching the product reference pose, despite explicit instructions to lay them on their side. **The take fails the requested support/orientation criterion and is not approved as a product advert.** The observation is consistent with reference-pose bias; one trial does not prove that cause or that this provider is the best choice. Single-view product identity through a turn, pickup, multi-person interaction and exact brand fidelity remain unproven. + +For the next separately authorized take, first obtain or approve a physically plausible scene/pose reference showing the intended product orientation and a coherent presenter eyeline. Prefer an actual product photograph in that resting pose or a reviewed scene keyframe, with detail references alongside it. Do not repeat an upright packshot and assume a negative prompt will fix the support geometry. If a provider accepts both scene keyframes and detail references, verify their combined endpoint contract and numbering. The raw take must pass gaze, gesture, support and product-fidelity review before final overlays are approved. + +The trial is also rendered through the existing code renderer with editable screen-space typography. Those controls change only the overlay; the human/product interaction remains the original generated footage. Preparing masks or importing the clip does not turn a failed raw take into an accepted one. diff --git a/docs/hybrid-compositing-plan.md b/docs/hybrid-compositing-plan.md index 71dfdba..6d59bd4 100644 --- a/docs/hybrid-compositing-plan.md +++ b/docs/hybrid-compositing-plan.md @@ -1,5 +1,7 @@ # Reliable hybrid compositing and motion design +**Interaction policy, 2026-11-13:** generate intended human–object interaction as a reference-conditioned whole shot, including looking and pointing. Masking and non-overlap do not establish gaze, natural support, gesture or contact. Keep screen-space cards outside person holdouts. Unrelated avatar footage plus an independently placed product image is rejected for an interaction shot; the code compositor remains responsible for editable overlays and non-interacting layouts. This is a routing decision, not a new implemented renderer API. + Human foreground extension: [avatar lighting](avatar-lighting.md) records the representation-dependent routing, still-image findings and pending video acceptance. This is a design addition, not a claim of shipped portrait relighting. Status: implementation and acceptance plan, 2026-11-11. Implemented APIs are documented separately below; research gates remain explicit. It supersedes any inference that a successful render or a few attractive frames establish a usable hybrid clip. Existing primitives and their tested scope remain documented in [hybrid-scenes.md](hybrid-scenes.md). diff --git a/docs/hybrid-scenes.md b/docs/hybrid-scenes.md index 702d814..417700b 100644 --- a/docs/hybrid-scenes.md +++ b/docs/hybrid-scenes.md @@ -1,5 +1,7 @@ # Hybrid scenes: code inside footage +**Interaction policy (2026-11-13):** looking, pointing and physical handling use a reference-conditioned whole-shot generation route. See [the interaction decision](avatar-lighting.md#interaction-routing-decision-2026-11-13). Independent masks are not a substitute for coherent gaze, gesture, product support or contact. + Research update (2026-11-13): [video segmentation and tracking findings](hybrid-analysis-study-2026-11-13.md) and [reference-conditioned handling shots](avatar-lighting.md#reference-conditioned-handling-shots-2026-11-13) define the next experiments and the editability boundary of flattened footage. These do not claim new implemented renderer services. **Quality correction, 2026-11-11:** later review found erased fingers/heads, incorrect can placement and mismatched generated geometry in the example videos. Successful rendering and tracking do not establish whole-shot quality. See the [revised compositing and motion-design plan](hybrid-compositing-plan.md) for diagnoses, model/runtime research and proposed release gates. Those new features are planned, not implemented. diff --git a/skills/editableframes/references/hybrid-compositing-plan.md b/skills/editableframes/references/hybrid-compositing-plan.md index c77e5b9..0a97140 100644 --- a/skills/editableframes/references/hybrid-compositing-plan.md +++ b/skills/editableframes/references/hybrid-compositing-plan.md @@ -1,5 +1,7 @@ # Reliable hybrid compositing and motion design +**Interaction policy, 2026-11-13:** generate intended human–object interaction as a reference-conditioned whole shot, including looking and pointing. Masking and non-overlap do not establish gaze, natural support, gesture or contact. Keep screen-space cards outside person holdouts. Unrelated avatar footage plus an independently placed product image is rejected for an interaction shot; the code compositor remains responsible for editable overlays and non-interacting layouts. This is a routing decision, not a new implemented renderer API. + Status: proposed next work, 2026-11-11. This is a design and acceptance plan, not an implemented API. It supersedes any inference that a successful render or a few attractive frames establish a usable hybrid clip. Existing primitives and their tested scope remain documented in [hybrid guide](hybrid.md). Implementation update: the [prepared-media primitives](prepared-plates.md) now implement receipts, exact frame access, holdouts, corrections, cylinder/mesh replay and kinetic text. These mechanisms have synthetic regression coverage; the real-shot acceptance gates below still require full visual QA. Automatic geometry solving and production model selection remain research. From 81ef1879770ac45b03490fd9d3a790fd15f795ed Mon Sep 17 00:00:00 2001 From: Laurence Xavier <35849747+lxf82dev@users.noreply.github.com> Date: Fri, 13 Nov 2026 17:23:59 +0800 Subject: [PATCH 26/49] docs: define staged scene handoff for coupled interactions --- docs/avatar-lighting.md | 6 ++- docs/hybrid-compositing-plan.md | 2 + docs/hybrid-scenes.md | 2 + docs/interaction-staging-workflow.md | 42 +++++++++++++++++++ .../references/hybrid-compositing-plan.md | 2 + .../interaction-staging-workflow.md | 42 +++++++++++++++++++ 6 files changed, 94 insertions(+), 2 deletions(-) create mode 100644 docs/interaction-staging-workflow.md create mode 100644 skills/editableframes/references/interaction-staging-workflow.md diff --git a/docs/avatar-lighting.md b/docs/avatar-lighting.md index 2b334d5..0aa76f4 100644 --- a/docs/avatar-lighting.md +++ b/docs/avatar-lighting.md @@ -1,5 +1,7 @@ # Human foreground lighting +**Scene staging decision (2026-11-13):** object–object, living thing–object and living thing–living thing interactions default to **stage → approved snapshot + reference images → joint video generation → editable finishing**. Independent masks do not create a coupled performance. See [workflow, evidence and remaining integration](interaction-staging-workflow.md). The latest pickup improved, but the snapshot handoff and broader interaction categories remain untested. + Status: design and isolated still-image evaluation, not a shipped avatar relighting feature. Existing prepared-media primitives provide source-bound alpha and exact frame sampling; they do not recover a person's geometry or original illumination. Continuous speech, hands, multiple people, temporal stability and native preview/export parity still need video acceptance. ## Route by the foreground's representation @@ -91,9 +93,9 @@ Generated interaction is baked into the footage. Expose source selection, timing ### Single-take result (2026-11-13): partial improvement, rejected for final use -One [Kling 4.0 reference-image job on Replicate](https://replicate.com/kwaivgi/kling-v4.0) used a fictional presenter still, one official headphone view and an empty showroom reference. Requested five seconds at 720p; decoded output was 121 frames at 24 fps (5.0417 seconds), 1280×720. The published image-reference rate implies about $0.79 for the reported output duration; this is an estimate, not a verified billing-ledger charge. No second paid take was submitted. +One [Kling 4.0 reference-image job on Replicate](https://replicate.com/kwaivgi/kling-v4.0) used a fictional presenter still, one official headphone view and an empty showroom reference. Requested five seconds at 720p; decoded output was 121 frames at 24 fps (5.0417 seconds), 1280×720. The published image-reference rate implies about $0.79 for the reported output duration; this is an estimate, not a verified billing-ledger charge. No second paid take was submitted in that initial exercise. A later authorized video-edit take is recorded in [the staging workflow](interaction-staging-workflow.md#retained-experiments-and-conclusions). -Sampled frames show her head/eyes attending to the headphones and an open palm presenting toward them before she returns attention to the camera. This is better coordinated than the unrelated-avatar/product composite. However, the model kept the headphones upright, matching the product reference pose, despite explicit instructions to lay them on their side. **The take fails the requested support/orientation criterion and is not approved as a product advert.** The observation is consistent with reference-pose bias; one trial does not prove that cause or that this provider is the best choice. Single-view product identity through a turn, pickup, multi-person interaction and exact brand fidelity remain unproven. +Sampled frames show her head/eyes attending to the headphones and an open palm presenting toward them before she returns attention to the camera. This is better coordinated than the unrelated-avatar/product composite. However, the model kept the headphones upright, matching the product reference pose, despite explicit instructions to lay them on their side. **The take fails the requested support/orientation criterion and is not approved as a product advert.** The observation is consistent with reference-pose bias; one trial does not prove that cause or that this provider is the best choice. At that checkpoint pickup had not been tested. The later video edit demonstrates a plausible pickup-and-hold; identity through a turn, multi-person interaction and exact brand fidelity remain unproven. For the next separately authorized take, first obtain or approve a physically plausible scene/pose reference showing the intended product orientation and a coherent presenter eyeline. Prefer an actual product photograph in that resting pose or a reviewed scene keyframe, with detail references alongside it. Do not repeat an upright packshot and assume a negative prompt will fix the support geometry. If a provider accepts both scene keyframes and detail references, verify their combined endpoint contract and numbering. The raw take must pass gaze, gesture, support and product-fidelity review before final overlays are approved. diff --git a/docs/hybrid-compositing-plan.md b/docs/hybrid-compositing-plan.md index 6d59bd4..9aca3e9 100644 --- a/docs/hybrid-compositing-plan.md +++ b/docs/hybrid-compositing-plan.md @@ -1,5 +1,7 @@ # Reliable hybrid compositing and motion design +**Scene staging decision (2026-11-13):** object–object, living thing–object and living thing–living thing interactions default to **stage → approved snapshot + reference images → joint video generation → editable finishing**. Independent masks do not create a coupled performance. See [workflow, evidence and remaining integration](interaction-staging-workflow.md). The latest pickup improved, but the snapshot handoff and broader interaction categories remain untested. + **Interaction policy, 2026-11-13:** generate intended human–object interaction as a reference-conditioned whole shot, including looking and pointing. Masking and non-overlap do not establish gaze, natural support, gesture or contact. Keep screen-space cards outside person holdouts. Unrelated avatar footage plus an independently placed product image is rejected for an interaction shot; the code compositor remains responsible for editable overlays and non-interacting layouts. This is a routing decision, not a new implemented renderer API. Human foreground extension: [avatar lighting](avatar-lighting.md) records the representation-dependent routing, still-image findings and pending video acceptance. This is a design addition, not a claim of shipped portrait relighting. diff --git a/docs/hybrid-scenes.md b/docs/hybrid-scenes.md index 417700b..eff99e5 100644 --- a/docs/hybrid-scenes.md +++ b/docs/hybrid-scenes.md @@ -1,5 +1,7 @@ # Hybrid scenes: code inside footage +**Scene staging decision (2026-11-13):** object–object, living thing–object and living thing–living thing interactions default to **stage → approved snapshot + reference images → joint video generation → editable finishing**. Independent masks do not create a coupled performance. See [workflow, evidence and remaining integration](interaction-staging-workflow.md). The latest pickup improved, but the snapshot handoff and broader interaction categories remain untested. + **Interaction policy (2026-11-13):** looking, pointing and physical handling use a reference-conditioned whole-shot generation route. See [the interaction decision](avatar-lighting.md#interaction-routing-decision-2026-11-13). Independent masks are not a substitute for coherent gaze, gesture, product support or contact. Research update (2026-11-13): [video segmentation and tracking findings](hybrid-analysis-study-2026-11-13.md) and [reference-conditioned handling shots](avatar-lighting.md#reference-conditioned-handling-shots-2026-11-13) define the next experiments and the editability boundary of flattened footage. These do not claim new implemented renderer services. diff --git a/docs/interaction-staging-workflow.md b/docs/interaction-staging-workflow.md new file mode 100644 index 0000000..7d6e6bc --- /dev/null +++ b/docs/interaction-staging-workflow.md @@ -0,0 +1,42 @@ +# Stage the scene, then generate the interaction + +Decision and evidence checkpoint: 2026-11-13. This is the selected authoring workflow and remaining delivery plan, not a claim of a completed provider integration. + +## The boundary + +Independent compositing can position layers, preserve exact artwork and resolve reviewed visibility. It does not infer a shared physical performance. Masks and depth alone cannot make a hand grip an object, two people exchange it, an animal respond to a person, or two objects collide convincingly. Good edges and zero overlap do not establish gaze, support, contact, force or coordinated motion. + +For **object–object, living thing–object, and living thing–living thing interactions**, default to staging the intended scene in EditableFrames and generating the coupled action together. This includes coordinated attention and gestures as well as contact. The broader categories are a workflow decision inferred from the human/headphone exercise; animal, multi-person and object-collision shots have not yet been validated. Fully authored animation, rigging or physics can still solve an interaction when explicitly supplied and reviewed; this is a limitation of assembling independent plates, not a claim that code cannot animate interaction. + +## Author and agent workflow + +1. **Stage:** place subjects, products, support surfaces and background; set scale, orientation, camera, eyelines and initial lighting. Humans and agents edit the same saved scene. Use plausible resting poses and reachable objects. Blocking proxies describe placement, not final appearance or solved anatomy. +2. **Approve and freeze:** choose the source frame and shot camera, commit the intended scene revision, and capture a clean snapshot without selection outlines, gizmos or editor chrome. Save the editable scene alongside it. Re-check support, reach and framing before spending on generation. +3. **Package the scene set:** include that snapshot plus separate subject identity, product detail/multi-angle and background references as available. Label each reference's purpose and preserve their order. Record scene/source revision, frame/time base, camera, output dimensions, assets and hashes, reference rights/provenance, desired action beats and acceptance criteria. Retain the actual submitted bytes and prompt, not merely expiring URLs. +4. **Generate during preparation:** select a model such as Kling using the chosen endpoint's actual capabilities. Prefer a start-frame/keyframe input for composition and separate reference inputs for appearance when the endpoint supports both together. An ordinary reference image is a softer hint; do not label it a locked first frame. Verify combinations, reference numbering, duration and cost before submitting. If the endpoint cannot accept the scene set, choose a compatible route or disclose the limitation rather than silently dropping a reference. An accepted video can instead be the base for a video-edit request. +5. **Review the whole interaction:** inspect normal/slow playback and every contact transition for gaze, reachable grip, support/release, hand/limb anatomy, collisions, identity, product geometry/branding, shadows and reflections. Judge positional instruction following separately from overall appearance. A snapshot conditions the result; it does not constrain a solver or guarantee exact placement. +6. **Return to composition:** import an accepted take as a versioned footage asset, probe actual decoded frames/timestamps, then derive masks/tracks from those exact bytes where needed. Keep typography, prices, captions and suitable surface inserts independently editable. Screen-space UI does not inherit physical subject holdouts. Keep the staged scene so another layout can produce another snapshot/take. + +Generate the interacting subjects and shared support/room as one shot by default: it gives the model a common lighting and contact context. Foreground-only generation is a separately tested option when alpha, edge colors, contact shadows and background correspondence are actually available. It is not a general solution for changing a room after a pickup. + +## What exists and what remains + +The standalone Scene Studio example already exposes placement, camera/light controls, saved scene state and **Save reference PNG** from a frozen committed shot. It is an opt-in example, not proof of a universal editor/agent capture API or a native host integration. The scene-set manifest, automatic provider packaging, generation handoff, receipt binding and accepted-take import still need host integration and end-to-end tests. No implicit model call belongs in `render(clock)` and no mandatory vendor dependency is added to the core. + +Proposed acceptance for that handoff: agent and human paths capture the same committed revision/frame; active gesture drafts and helpers never leak; stale scene edits are detected before submission; submitted reference bytes/order match the receipt; failed/ambiguous jobs never silently duplicate spend or overwrite an accepted take; imported media uses decoded timing rather than provider billing metrics. These are delivery gates, not new CLI flags. + +## Retained experiments and conclusions + +The mask-based headphone presentation improved hair and measured overlap but still looked awkward: a product placed beside unrelated avatar motion did not establish convincing attention or support. + +The first reference-conditioned Kling take used separate presenter, product and room images. Attention improved, but the headphones stayed upright despite a side-resting instruction. The follow-up used **that accepted-looking video as the base plus the official single-view product photo**, not a newly staged scene snapshot. It produced a clearer headband grip, lift and supported two-hand hold; the user preferred it. The requested camera-left shift was not meaningfully achieved, and the weighing motion read mainly as pickup-and-hold. The upright start remained. Thus the pickup result supports joint generation; it does **not** complete the snapshot-plus-references test, establish exact product fidelity or validate other interaction categories. + +The follow-up decoded to 1280×720, 121 frames at 24 fps (5.0417 s). Its EditableFrames round trip retained the frame count, repeated a randomly sought frame identically in the tested browser, and preserved source pixels outside the title before encoding. Title/eyebrow/accent/visibility remained editable. Those are renderer-integrity checks, not proof of physical realism. Contact crops covered all frames and full-scene samples were inspected; no fresh independent reviewer approval is claimed. + +At the recorded provider rate, the successful video edit was estimated at about $0.95; the account ledger charge was not retrieved. One earlier upload-URL attempt failed validation and is retained separately. A direct original MP4 output URL, verified against the local source hash, resolved the transport issue. The provider returned a 10.084-second duration metric for a 5.0417-second file, consistent with input-plus-output billing; decoded timestamps must own the timeline. + +## Editability and evidence retention + +After generation, coupled action, pose, physical light and product appearance are baked. Expose only genuine controls: footage selection, timing where appropriate, crop, grade and separate code layers. A new pose, grip, placement or background geometry usually needs a new take. Regeneration invalidates dependent masks, tracks and acceptance; a matte does not recover independently editable 3D objects. + +Retain scene JSON/source binding, clean snapshot, all reference bytes/hashes, exact prompt and role mapping, endpoint/schema/pricing snapshot, request/job/terminal receipts, estimate versus actual billing when available, raw download/hash, decoded timing, derived-data revisions, final render and review verdicts including failures. Keep secrets, private paths and signed URLs out of public documentation. Record reused assets honestly. Future tests must cover each untested interaction category and the actual snapshot handoff before broad quality claims. diff --git a/skills/editableframes/references/hybrid-compositing-plan.md b/skills/editableframes/references/hybrid-compositing-plan.md index 0a97140..0cabc20 100644 --- a/skills/editableframes/references/hybrid-compositing-plan.md +++ b/skills/editableframes/references/hybrid-compositing-plan.md @@ -1,5 +1,7 @@ # Reliable hybrid compositing and motion design +**Scene staging decision (2026-11-13):** object–object, living thing–object and living thing–living thing interactions default to **stage → approved snapshot + reference images → joint video generation → editable finishing**. Independent masks do not create a coupled performance. See [workflow, evidence and remaining integration](interaction-staging-workflow.md). The latest pickup improved, but the snapshot handoff and broader interaction categories remain untested. + **Interaction policy, 2026-11-13:** generate intended human–object interaction as a reference-conditioned whole shot, including looking and pointing. Masking and non-overlap do not establish gaze, natural support, gesture or contact. Keep screen-space cards outside person holdouts. Unrelated avatar footage plus an independently placed product image is rejected for an interaction shot; the code compositor remains responsible for editable overlays and non-interacting layouts. This is a routing decision, not a new implemented renderer API. Status: proposed next work, 2026-11-11. This is a design and acceptance plan, not an implemented API. It supersedes any inference that a successful render or a few attractive frames establish a usable hybrid clip. Existing primitives and their tested scope remain documented in [hybrid guide](hybrid.md). diff --git a/skills/editableframes/references/interaction-staging-workflow.md b/skills/editableframes/references/interaction-staging-workflow.md new file mode 100644 index 0000000..7d6e6bc --- /dev/null +++ b/skills/editableframes/references/interaction-staging-workflow.md @@ -0,0 +1,42 @@ +# Stage the scene, then generate the interaction + +Decision and evidence checkpoint: 2026-11-13. This is the selected authoring workflow and remaining delivery plan, not a claim of a completed provider integration. + +## The boundary + +Independent compositing can position layers, preserve exact artwork and resolve reviewed visibility. It does not infer a shared physical performance. Masks and depth alone cannot make a hand grip an object, two people exchange it, an animal respond to a person, or two objects collide convincingly. Good edges and zero overlap do not establish gaze, support, contact, force or coordinated motion. + +For **object–object, living thing–object, and living thing–living thing interactions**, default to staging the intended scene in EditableFrames and generating the coupled action together. This includes coordinated attention and gestures as well as contact. The broader categories are a workflow decision inferred from the human/headphone exercise; animal, multi-person and object-collision shots have not yet been validated. Fully authored animation, rigging or physics can still solve an interaction when explicitly supplied and reviewed; this is a limitation of assembling independent plates, not a claim that code cannot animate interaction. + +## Author and agent workflow + +1. **Stage:** place subjects, products, support surfaces and background; set scale, orientation, camera, eyelines and initial lighting. Humans and agents edit the same saved scene. Use plausible resting poses and reachable objects. Blocking proxies describe placement, not final appearance or solved anatomy. +2. **Approve and freeze:** choose the source frame and shot camera, commit the intended scene revision, and capture a clean snapshot without selection outlines, gizmos or editor chrome. Save the editable scene alongside it. Re-check support, reach and framing before spending on generation. +3. **Package the scene set:** include that snapshot plus separate subject identity, product detail/multi-angle and background references as available. Label each reference's purpose and preserve their order. Record scene/source revision, frame/time base, camera, output dimensions, assets and hashes, reference rights/provenance, desired action beats and acceptance criteria. Retain the actual submitted bytes and prompt, not merely expiring URLs. +4. **Generate during preparation:** select a model such as Kling using the chosen endpoint's actual capabilities. Prefer a start-frame/keyframe input for composition and separate reference inputs for appearance when the endpoint supports both together. An ordinary reference image is a softer hint; do not label it a locked first frame. Verify combinations, reference numbering, duration and cost before submitting. If the endpoint cannot accept the scene set, choose a compatible route or disclose the limitation rather than silently dropping a reference. An accepted video can instead be the base for a video-edit request. +5. **Review the whole interaction:** inspect normal/slow playback and every contact transition for gaze, reachable grip, support/release, hand/limb anatomy, collisions, identity, product geometry/branding, shadows and reflections. Judge positional instruction following separately from overall appearance. A snapshot conditions the result; it does not constrain a solver or guarantee exact placement. +6. **Return to composition:** import an accepted take as a versioned footage asset, probe actual decoded frames/timestamps, then derive masks/tracks from those exact bytes where needed. Keep typography, prices, captions and suitable surface inserts independently editable. Screen-space UI does not inherit physical subject holdouts. Keep the staged scene so another layout can produce another snapshot/take. + +Generate the interacting subjects and shared support/room as one shot by default: it gives the model a common lighting and contact context. Foreground-only generation is a separately tested option when alpha, edge colors, contact shadows and background correspondence are actually available. It is not a general solution for changing a room after a pickup. + +## What exists and what remains + +The standalone Scene Studio example already exposes placement, camera/light controls, saved scene state and **Save reference PNG** from a frozen committed shot. It is an opt-in example, not proof of a universal editor/agent capture API or a native host integration. The scene-set manifest, automatic provider packaging, generation handoff, receipt binding and accepted-take import still need host integration and end-to-end tests. No implicit model call belongs in `render(clock)` and no mandatory vendor dependency is added to the core. + +Proposed acceptance for that handoff: agent and human paths capture the same committed revision/frame; active gesture drafts and helpers never leak; stale scene edits are detected before submission; submitted reference bytes/order match the receipt; failed/ambiguous jobs never silently duplicate spend or overwrite an accepted take; imported media uses decoded timing rather than provider billing metrics. These are delivery gates, not new CLI flags. + +## Retained experiments and conclusions + +The mask-based headphone presentation improved hair and measured overlap but still looked awkward: a product placed beside unrelated avatar motion did not establish convincing attention or support. + +The first reference-conditioned Kling take used separate presenter, product and room images. Attention improved, but the headphones stayed upright despite a side-resting instruction. The follow-up used **that accepted-looking video as the base plus the official single-view product photo**, not a newly staged scene snapshot. It produced a clearer headband grip, lift and supported two-hand hold; the user preferred it. The requested camera-left shift was not meaningfully achieved, and the weighing motion read mainly as pickup-and-hold. The upright start remained. Thus the pickup result supports joint generation; it does **not** complete the snapshot-plus-references test, establish exact product fidelity or validate other interaction categories. + +The follow-up decoded to 1280×720, 121 frames at 24 fps (5.0417 s). Its EditableFrames round trip retained the frame count, repeated a randomly sought frame identically in the tested browser, and preserved source pixels outside the title before encoding. Title/eyebrow/accent/visibility remained editable. Those are renderer-integrity checks, not proof of physical realism. Contact crops covered all frames and full-scene samples were inspected; no fresh independent reviewer approval is claimed. + +At the recorded provider rate, the successful video edit was estimated at about $0.95; the account ledger charge was not retrieved. One earlier upload-URL attempt failed validation and is retained separately. A direct original MP4 output URL, verified against the local source hash, resolved the transport issue. The provider returned a 10.084-second duration metric for a 5.0417-second file, consistent with input-plus-output billing; decoded timestamps must own the timeline. + +## Editability and evidence retention + +After generation, coupled action, pose, physical light and product appearance are baked. Expose only genuine controls: footage selection, timing where appropriate, crop, grade and separate code layers. A new pose, grip, placement or background geometry usually needs a new take. Regeneration invalidates dependent masks, tracks and acceptance; a matte does not recover independently editable 3D objects. + +Retain scene JSON/source binding, clean snapshot, all reference bytes/hashes, exact prompt and role mapping, endpoint/schema/pricing snapshot, request/job/terminal receipts, estimate versus actual billing when available, raw download/hash, decoded timing, derived-data revisions, final render and review verdicts including failures. Keep secrets, private paths and signed URLs out of public documentation. Record reused assets honestly. Future tests must cover each untested interaction category and the actual snapshot handoff before broad quality claims. From eeb211894c774c4639554b43fbb8726b631b1eb2 Mon Sep 17 00:00:00 2001 From: Laurence Xavier <35849747+lxf82dev@users.noreply.github.com> Date: Fri, 13 Nov 2026 19:33:23 +0800 Subject: [PATCH 27/49] docs: record full-clip masking, tracker and lighting acceptance results --- docs/hybrid-acceptance-round1-2026-11-13.md | 52 +++++++++++++++++++ docs/hybrid-compositing-plan.md | 2 + docs/hybrid-scenes.md | 2 + docs/interaction-staging-workflow.md | 2 + .../hybrid-acceptance-round1-2026-11-13.md | 52 +++++++++++++++++++ .../references/hybrid-compositing-plan.md | 2 + .../interaction-staging-workflow.md | 2 + 7 files changed, 114 insertions(+) create mode 100644 docs/hybrid-acceptance-round1-2026-11-13.md create mode 100644 skills/editableframes/references/hybrid-acceptance-round1-2026-11-13.md diff --git a/docs/hybrid-acceptance-round1-2026-11-13.md b/docs/hybrid-acceptance-round1-2026-11-13.md new file mode 100644 index 0000000..8206208 --- /dev/null +++ b/docs/hybrid-acceptance-round1-2026-11-13.md @@ -0,0 +1,52 @@ +# Hybrid acceptance round 1 — 2026-11-13 + +Status: local experiments, no new generated take, no independent reviewer approval, no native-host integration claim. Existing generated footage and cached local models were reused. Hosted generation spending in this round: $0. + +## Staged snapshot handoff + +A seller/product scene now renders through the current renderer-host with editable product horizontal/vertical position, scale, image-plane rotation and an approximate foreshortening control. The headphones lie camera-left on the table, within reach of the presenter's hand, against a detailed warm-lamp/cool-window background. Repeated frame-zero captures are byte-identical in the tested browser; changing horizontal placement changes the PNG. Source, assets, controls and captured PNG are hashed into a local manifest. + +This is a 2D reference composition, not solved 3D product orientation, contact or lighting. The snapshot plus separate product and presenter references has **not been submitted** to a model. The latest provider schema supports start-image plus references and explicitly numbers the start image before the references. The quoted 5-second 720p image-input trial is approximately $0.785 at $0.157/s; re-check pricing before submission. The previous video-edit pickup does not establish this round trip. + +The earlier local Scene Studio suite passed 19 checks, including clean capture during active drafts and identical capture-button/programmatic outputs. An offline packet prototype exercised eight integrity cases. These do not replace real provider receipts, ambiguous-job recovery or native integration tests. + +## Full-clip masking through a pickup + +The complete previously generated pickup was processed: 121 frames, 24 fps, 5.0417 seconds. Source SHA256: `3b9aaf790d8f639eda5005808e08977ae951b0de05f8418c6f73acf66512d6cf`. Analysis resolution was 640×360; this is not 1080p boundary acceptance. + +- SAM 2.1 Hiera Tiny on Apple Metal propagated separate person/product/gripping-hand prompts across every frame. Raw thresholded masks, no correction clicks or optional model postprocessing. Propagation plus saving took 136.67 s; steady-step median/p95 1.157/1.176 s; process peak RSS about 2.14 GB. These are preparation costs, not render FPS. +- RVM MobileNetV3 FP32 on CPU processed all 121 frames with continuous recurrent state, at 640×360 and downsample ratio 1. Wall time including saved foreground/alpha was 24.27 s. Some local workloads overlapped, so this is not an isolated hardware/model benchmark. RVM and SAM solve different problems. +- The comparison preserves the original table below y=277 and replaces the background above it with a bright yellow diagnostic field. Original contact and lighting remain baked. SAM binary edges visibly lose soft hair detail. RVM softens the hair but introduces background remnants below the arms; neither raw route is an automatic pass. +- A second candidate constrains RVM alpha with each frame's SAM person support: alpha is unchanged up to 3 pixels outside support, tapers to zero by 6 pixels, and the product is separately restored from its SAM mask. This reduces the observed spill. It can still clip hair missed by SAM and retains boundary defects; it is a heuristic requiring review, not ground-truth matting or physical depth. + +Both comparisons export all 121 frames and repeat frame 48 with maximum RGB code difference zero in the tested browser. These are renderer checks. Sampled full-frame images and contact sheets were inspected; no annotated hair/hand error, full normal/slow playback approval, identity guarantee or production-quality badge is claimed. Whole-clip processing is broader evidence than the previous short interval, but not completion of the static/pan/handheld/multi-person stress matrix. + +**Plan change:** keep semantic masks, foreground colour/alpha and support correction as separate, versioned preparation artifacts. Add whole-shot bright/dark edge checks and correction ranges. A successful segmentation job is insufficient for background-swap acceptance. + +## Tracking: a negative forward/backward result + +A new diagnostic reuses the synthetic stationary panel with independently moving surrounding texture. It runs the current tracker on the 49-frame clip forwards and on a losslessly re-encoded reversed clip, then compares corresponding returned quads. + +Worst corner error against the known stationary panel: **6.861 px**. Maximum forward/backward disagreement: **0 px**. For 25 frames, actual error exceeds 4 px while correlation exceeds 0.95 and forward/backward disagreement is below 1 px. At the worst frame the score is 0.956. The motion is symmetric, making this a deliberately revealing case where both directions share the same wrong solution. + +**Plan change:** forward/backward agreement is a diagnostic, never sufficient acceptance. Independent intended-surface boundaries, visibility and distributed target evidence are required; ambiguous/blank surfaces need correction or rejection. No production rejection algorithm was implemented here. The original missing S1/orbit footage remains unretested; this experiment does not establish its exact cause. + +## Lighting: continuous controls and a representation boundary + +A new 120-frame, 24 fps clip holds camera, geometry, exposure and authored scene frame fixed while continuously changing a practical lamp from warm to cool. The scene uses a scanned pastry, procedural cup/plate/lamp, and a photographed HDR panorama. It is a renderer diagnostic, not a real moving room or final advertisement. Lamp source colour, bulb emission and shade emission change together. + +Matched warm/cool rectangular image regions show mean absolute RGB changes of 0.22/255 on the pastry, 5.74 on the cup and 24.96 on the table reflection. The tested upper-left photographed backdrop is byte-identical (0 change). These ROIs include some surrounding pixels and measure response, not material accuracy. Repeat-frame pixels match; no page errors were recorded. + +**Plan change:** continuous editable colour/intensity is supported; named presets are starting values, not a finite lighting catalogue. Accept per-object light response separately from the bulb looking brighter. Light placement must serve the intended hero object; the weak pastry response is a failed stress target. A baked panorama, product photo or human video does not acquire physically correct new illumination merely because a 3D light was added. Keep that distinction explicit and test separate relighting routes for those representations. Ordinary-computer performance and mixed human/product emitter scenes remain open. + +## Remaining order and numbering + +1. Submit and inspect the actual staged snapshot plus references once a fresh spending cap is settled; then test object–object contact and two-person handoff separately. +2. Implement real handoff receipts, failure recovery, accepted-take import and source-bound analysis in the host. The local packet prototype is not that implementation. +3. Annotated full-resolution mask/alpha acceptance, disappearance/re-entry, multiple people and actual-device comparison. SAM 3 remains an access/runtime and comparison gate. +4. Independent-surface tracker rejection and repeatable real-footage visibility tests. +5. Stronger hero-object light response, mixed human/product emitters and additional actual computers. + +**Feature item 6 (camera solve): not tested here. Feature item 13 (generated worlds): research only, not tested here.** Authored Three.js cameras, photographed HDR backdrops and homography tracking prove neither feature. The separate journey table also has an item 6, “many versions from one take”; that is a different, partially exercised editable-content journey. H5, feature 6 and feature 13 remain deferred under the prior scope decision, not silently completed. + +Primary references: [Kling input and pricing documentation](https://replicate.com/kwaivgi/kling-v4.0), [SAM 2](https://github.com/facebookresearch/sam2), [Robust Video Matting](https://github.com/PeterL1n/RobustVideoMatting). Measurements above come from local retained experiment receipts, not those references. diff --git a/docs/hybrid-compositing-plan.md b/docs/hybrid-compositing-plan.md index 9aca3e9..4c02673 100644 --- a/docs/hybrid-compositing-plan.md +++ b/docs/hybrid-compositing-plan.md @@ -1,5 +1,7 @@ # Reliable hybrid compositing and motion design +**Local acceptance follow-up (2026-11-13):** [snapshot preparation, full-clip masks, tracker counterexample and continuous lighting](hybrid-acceptance-round1-2026-11-13.md). No new generated take yet; camera solve (feature 6) and generated worlds (feature 13) remain untested. + **Scene staging decision (2026-11-13):** object–object, living thing–object and living thing–living thing interactions default to **stage → approved snapshot + reference images → joint video generation → editable finishing**. Independent masks do not create a coupled performance. See [workflow, evidence and remaining integration](interaction-staging-workflow.md). The latest pickup improved, but the snapshot handoff and broader interaction categories remain untested. **Interaction policy, 2026-11-13:** generate intended human–object interaction as a reference-conditioned whole shot, including looking and pointing. Masking and non-overlap do not establish gaze, natural support, gesture or contact. Keep screen-space cards outside person holdouts. Unrelated avatar footage plus an independently placed product image is rejected for an interaction shot; the code compositor remains responsible for editable overlays and non-interacting layouts. This is a routing decision, not a new implemented renderer API. diff --git a/docs/hybrid-scenes.md b/docs/hybrid-scenes.md index eff99e5..c346e05 100644 --- a/docs/hybrid-scenes.md +++ b/docs/hybrid-scenes.md @@ -1,5 +1,7 @@ # Hybrid scenes: code inside footage +**Local acceptance follow-up (2026-11-13):** [snapshot preparation, full-clip masks, tracker counterexample and continuous lighting](hybrid-acceptance-round1-2026-11-13.md). No new generated take yet; camera solve (feature 6) and generated worlds (feature 13) remain untested. + **Scene staging decision (2026-11-13):** object–object, living thing–object and living thing–living thing interactions default to **stage → approved snapshot + reference images → joint video generation → editable finishing**. Independent masks do not create a coupled performance. See [workflow, evidence and remaining integration](interaction-staging-workflow.md). The latest pickup improved, but the snapshot handoff and broader interaction categories remain untested. **Interaction policy (2026-11-13):** looking, pointing and physical handling use a reference-conditioned whole-shot generation route. See [the interaction decision](avatar-lighting.md#interaction-routing-decision-2026-11-13). Independent masks are not a substitute for coherent gaze, gesture, product support or contact. diff --git a/docs/interaction-staging-workflow.md b/docs/interaction-staging-workflow.md index 7d6e6bc..07be35b 100644 --- a/docs/interaction-staging-workflow.md +++ b/docs/interaction-staging-workflow.md @@ -1,5 +1,7 @@ # Stage the scene, then generate the interaction +**Local acceptance follow-up (2026-11-13):** [snapshot preparation, full-clip masks, tracker counterexample and continuous lighting](hybrid-acceptance-round1-2026-11-13.md). No new generated take yet; camera solve (feature 6) and generated worlds (feature 13) remain untested. + Decision and evidence checkpoint: 2026-11-13. This is the selected authoring workflow and remaining delivery plan, not a claim of a completed provider integration. ## The boundary diff --git a/skills/editableframes/references/hybrid-acceptance-round1-2026-11-13.md b/skills/editableframes/references/hybrid-acceptance-round1-2026-11-13.md new file mode 100644 index 0000000..8206208 --- /dev/null +++ b/skills/editableframes/references/hybrid-acceptance-round1-2026-11-13.md @@ -0,0 +1,52 @@ +# Hybrid acceptance round 1 — 2026-11-13 + +Status: local experiments, no new generated take, no independent reviewer approval, no native-host integration claim. Existing generated footage and cached local models were reused. Hosted generation spending in this round: $0. + +## Staged snapshot handoff + +A seller/product scene now renders through the current renderer-host with editable product horizontal/vertical position, scale, image-plane rotation and an approximate foreshortening control. The headphones lie camera-left on the table, within reach of the presenter's hand, against a detailed warm-lamp/cool-window background. Repeated frame-zero captures are byte-identical in the tested browser; changing horizontal placement changes the PNG. Source, assets, controls and captured PNG are hashed into a local manifest. + +This is a 2D reference composition, not solved 3D product orientation, contact or lighting. The snapshot plus separate product and presenter references has **not been submitted** to a model. The latest provider schema supports start-image plus references and explicitly numbers the start image before the references. The quoted 5-second 720p image-input trial is approximately $0.785 at $0.157/s; re-check pricing before submission. The previous video-edit pickup does not establish this round trip. + +The earlier local Scene Studio suite passed 19 checks, including clean capture during active drafts and identical capture-button/programmatic outputs. An offline packet prototype exercised eight integrity cases. These do not replace real provider receipts, ambiguous-job recovery or native integration tests. + +## Full-clip masking through a pickup + +The complete previously generated pickup was processed: 121 frames, 24 fps, 5.0417 seconds. Source SHA256: `3b9aaf790d8f639eda5005808e08977ae951b0de05f8418c6f73acf66512d6cf`. Analysis resolution was 640×360; this is not 1080p boundary acceptance. + +- SAM 2.1 Hiera Tiny on Apple Metal propagated separate person/product/gripping-hand prompts across every frame. Raw thresholded masks, no correction clicks or optional model postprocessing. Propagation plus saving took 136.67 s; steady-step median/p95 1.157/1.176 s; process peak RSS about 2.14 GB. These are preparation costs, not render FPS. +- RVM MobileNetV3 FP32 on CPU processed all 121 frames with continuous recurrent state, at 640×360 and downsample ratio 1. Wall time including saved foreground/alpha was 24.27 s. Some local workloads overlapped, so this is not an isolated hardware/model benchmark. RVM and SAM solve different problems. +- The comparison preserves the original table below y=277 and replaces the background above it with a bright yellow diagnostic field. Original contact and lighting remain baked. SAM binary edges visibly lose soft hair detail. RVM softens the hair but introduces background remnants below the arms; neither raw route is an automatic pass. +- A second candidate constrains RVM alpha with each frame's SAM person support: alpha is unchanged up to 3 pixels outside support, tapers to zero by 6 pixels, and the product is separately restored from its SAM mask. This reduces the observed spill. It can still clip hair missed by SAM and retains boundary defects; it is a heuristic requiring review, not ground-truth matting or physical depth. + +Both comparisons export all 121 frames and repeat frame 48 with maximum RGB code difference zero in the tested browser. These are renderer checks. Sampled full-frame images and contact sheets were inspected; no annotated hair/hand error, full normal/slow playback approval, identity guarantee or production-quality badge is claimed. Whole-clip processing is broader evidence than the previous short interval, but not completion of the static/pan/handheld/multi-person stress matrix. + +**Plan change:** keep semantic masks, foreground colour/alpha and support correction as separate, versioned preparation artifacts. Add whole-shot bright/dark edge checks and correction ranges. A successful segmentation job is insufficient for background-swap acceptance. + +## Tracking: a negative forward/backward result + +A new diagnostic reuses the synthetic stationary panel with independently moving surrounding texture. It runs the current tracker on the 49-frame clip forwards and on a losslessly re-encoded reversed clip, then compares corresponding returned quads. + +Worst corner error against the known stationary panel: **6.861 px**. Maximum forward/backward disagreement: **0 px**. For 25 frames, actual error exceeds 4 px while correlation exceeds 0.95 and forward/backward disagreement is below 1 px. At the worst frame the score is 0.956. The motion is symmetric, making this a deliberately revealing case where both directions share the same wrong solution. + +**Plan change:** forward/backward agreement is a diagnostic, never sufficient acceptance. Independent intended-surface boundaries, visibility and distributed target evidence are required; ambiguous/blank surfaces need correction or rejection. No production rejection algorithm was implemented here. The original missing S1/orbit footage remains unretested; this experiment does not establish its exact cause. + +## Lighting: continuous controls and a representation boundary + +A new 120-frame, 24 fps clip holds camera, geometry, exposure and authored scene frame fixed while continuously changing a practical lamp from warm to cool. The scene uses a scanned pastry, procedural cup/plate/lamp, and a photographed HDR panorama. It is a renderer diagnostic, not a real moving room or final advertisement. Lamp source colour, bulb emission and shade emission change together. + +Matched warm/cool rectangular image regions show mean absolute RGB changes of 0.22/255 on the pastry, 5.74 on the cup and 24.96 on the table reflection. The tested upper-left photographed backdrop is byte-identical (0 change). These ROIs include some surrounding pixels and measure response, not material accuracy. Repeat-frame pixels match; no page errors were recorded. + +**Plan change:** continuous editable colour/intensity is supported; named presets are starting values, not a finite lighting catalogue. Accept per-object light response separately from the bulb looking brighter. Light placement must serve the intended hero object; the weak pastry response is a failed stress target. A baked panorama, product photo or human video does not acquire physically correct new illumination merely because a 3D light was added. Keep that distinction explicit and test separate relighting routes for those representations. Ordinary-computer performance and mixed human/product emitter scenes remain open. + +## Remaining order and numbering + +1. Submit and inspect the actual staged snapshot plus references once a fresh spending cap is settled; then test object–object contact and two-person handoff separately. +2. Implement real handoff receipts, failure recovery, accepted-take import and source-bound analysis in the host. The local packet prototype is not that implementation. +3. Annotated full-resolution mask/alpha acceptance, disappearance/re-entry, multiple people and actual-device comparison. SAM 3 remains an access/runtime and comparison gate. +4. Independent-surface tracker rejection and repeatable real-footage visibility tests. +5. Stronger hero-object light response, mixed human/product emitters and additional actual computers. + +**Feature item 6 (camera solve): not tested here. Feature item 13 (generated worlds): research only, not tested here.** Authored Three.js cameras, photographed HDR backdrops and homography tracking prove neither feature. The separate journey table also has an item 6, “many versions from one take”; that is a different, partially exercised editable-content journey. H5, feature 6 and feature 13 remain deferred under the prior scope decision, not silently completed. + +Primary references: [Kling input and pricing documentation](https://replicate.com/kwaivgi/kling-v4.0), [SAM 2](https://github.com/facebookresearch/sam2), [Robust Video Matting](https://github.com/PeterL1n/RobustVideoMatting). Measurements above come from local retained experiment receipts, not those references. diff --git a/skills/editableframes/references/hybrid-compositing-plan.md b/skills/editableframes/references/hybrid-compositing-plan.md index 0cabc20..84ef662 100644 --- a/skills/editableframes/references/hybrid-compositing-plan.md +++ b/skills/editableframes/references/hybrid-compositing-plan.md @@ -1,5 +1,7 @@ # Reliable hybrid compositing and motion design +**Local acceptance follow-up (2026-11-13):** [snapshot preparation, full-clip masks, tracker counterexample and continuous lighting](hybrid-acceptance-round1-2026-11-13.md). No new generated take yet; camera solve (feature 6) and generated worlds (feature 13) remain untested. + **Scene staging decision (2026-11-13):** object–object, living thing–object and living thing–living thing interactions default to **stage → approved snapshot + reference images → joint video generation → editable finishing**. Independent masks do not create a coupled performance. See [workflow, evidence and remaining integration](interaction-staging-workflow.md). The latest pickup improved, but the snapshot handoff and broader interaction categories remain untested. **Interaction policy, 2026-11-13:** generate intended human–object interaction as a reference-conditioned whole shot, including looking and pointing. Masking and non-overlap do not establish gaze, natural support, gesture or contact. Keep screen-space cards outside person holdouts. Unrelated avatar footage plus an independently placed product image is rejected for an interaction shot; the code compositor remains responsible for editable overlays and non-interacting layouts. This is a routing decision, not a new implemented renderer API. diff --git a/skills/editableframes/references/interaction-staging-workflow.md b/skills/editableframes/references/interaction-staging-workflow.md index 7d6e6bc..07be35b 100644 --- a/skills/editableframes/references/interaction-staging-workflow.md +++ b/skills/editableframes/references/interaction-staging-workflow.md @@ -1,5 +1,7 @@ # Stage the scene, then generate the interaction +**Local acceptance follow-up (2026-11-13):** [snapshot preparation, full-clip masks, tracker counterexample and continuous lighting](hybrid-acceptance-round1-2026-11-13.md). No new generated take yet; camera solve (feature 6) and generated worlds (feature 13) remain untested. + Decision and evidence checkpoint: 2026-11-13. This is the selected authoring workflow and remaining delivery plan, not a claim of a completed provider integration. ## The boundary From caa225665f91c48709713c09c1a8831c9cee76ac Mon Sep 17 00:00:00 2001 From: Laurence Xavier <35849747+lxf82dev@users.noreply.github.com> Date: Fri, 13 Nov 2026 19:56:37 +0800 Subject: [PATCH 28/49] docs: record staged pickup and completed two-person handoff --- docs/hybrid-compositing-plan.md | 6 ++- docs/hybrid-scenes.md | 6 ++- docs/interaction-staging-workflow.md | 10 +++-- docs/staged-generation-results-2026-11-13.md | 44 +++++++++++++++++++ .../references/hybrid-compositing-plan.md | 6 ++- .../interaction-staging-workflow.md | 10 +++-- .../staged-generation-results-2026-11-13.md | 44 +++++++++++++++++++ 7 files changed, 112 insertions(+), 14 deletions(-) create mode 100644 docs/staged-generation-results-2026-11-13.md create mode 100644 skills/editableframes/references/staged-generation-results-2026-11-13.md diff --git a/docs/hybrid-compositing-plan.md b/docs/hybrid-compositing-plan.md index 4c02673..dbbeb8f 100644 --- a/docs/hybrid-compositing-plan.md +++ b/docs/hybrid-compositing-plan.md @@ -1,8 +1,10 @@ # Reliable hybrid compositing and motion design -**Local acceptance follow-up (2026-11-13):** [snapshot preparation, full-clip masks, tracker counterexample and continuous lighting](hybrid-acceptance-round1-2026-11-13.md). No new generated take yet; camera solve (feature 6) and generated worlds (feature 13) remain untested. +**Generated trials completed (2026-11-13):** [staged camera-left pickup and completed two-person handoff](staged-generation-results-2026-11-13.md), both returned to editable finishing. One take per case; exact product fidelity and native integration remain open. Estimated total US$1.90 under the fresh US$2 cap; account ledger unverified. -**Scene staging decision (2026-11-13):** object–object, living thing–object and living thing–living thing interactions default to **stage → approved snapshot + reference images → joint video generation → editable finishing**. Independent masks do not create a coupled performance. See [workflow, evidence and remaining integration](interaction-staging-workflow.md). The latest pickup improved, but the snapshot handoff and broader interaction categories remain untested. +**Local acceptance follow-up (2026-11-13):** [snapshot preparation, full-clip masks, tracker counterexample and continuous lighting](hybrid-acceptance-round1-2026-11-13.md). That earlier local checkpoint preceded the generated trials now recorded separately; camera solve (feature 6) and generated worlds (feature 13) remain untested. + +**Scene staging decision (2026-11-13):** object–object, living thing–object and living thing–living thing interactions default to **stage → approved snapshot + reference images → joint video generation → editable finishing**. Independent masks do not create a coupled performance. See [workflow, evidence and remaining integration](interaction-staging-workflow.md). A staged-snapshot pickup and a two-person handoff now have local evidence; native integration, broader interactions and exact product fidelity remain open. **Interaction policy, 2026-11-13:** generate intended human–object interaction as a reference-conditioned whole shot, including looking and pointing. Masking and non-overlap do not establish gaze, natural support, gesture or contact. Keep screen-space cards outside person holdouts. Unrelated avatar footage plus an independently placed product image is rejected for an interaction shot; the code compositor remains responsible for editable overlays and non-interacting layouts. This is a routing decision, not a new implemented renderer API. diff --git a/docs/hybrid-scenes.md b/docs/hybrid-scenes.md index c346e05..d9d4143 100644 --- a/docs/hybrid-scenes.md +++ b/docs/hybrid-scenes.md @@ -1,8 +1,10 @@ # Hybrid scenes: code inside footage -**Local acceptance follow-up (2026-11-13):** [snapshot preparation, full-clip masks, tracker counterexample and continuous lighting](hybrid-acceptance-round1-2026-11-13.md). No new generated take yet; camera solve (feature 6) and generated worlds (feature 13) remain untested. +**Generated trials completed (2026-11-13):** [staged camera-left pickup and completed two-person handoff](staged-generation-results-2026-11-13.md), both returned to editable finishing. One take per case; exact product fidelity and native integration remain open. Estimated total US$1.90 under the fresh US$2 cap; account ledger unverified. -**Scene staging decision (2026-11-13):** object–object, living thing–object and living thing–living thing interactions default to **stage → approved snapshot + reference images → joint video generation → editable finishing**. Independent masks do not create a coupled performance. See [workflow, evidence and remaining integration](interaction-staging-workflow.md). The latest pickup improved, but the snapshot handoff and broader interaction categories remain untested. +**Local acceptance follow-up (2026-11-13):** [snapshot preparation, full-clip masks, tracker counterexample and continuous lighting](hybrid-acceptance-round1-2026-11-13.md). That earlier local checkpoint preceded the generated trials now recorded separately; camera solve (feature 6) and generated worlds (feature 13) remain untested. + +**Scene staging decision (2026-11-13):** object–object, living thing–object and living thing–living thing interactions default to **stage → approved snapshot + reference images → joint video generation → editable finishing**. Independent masks do not create a coupled performance. See [workflow, evidence and remaining integration](interaction-staging-workflow.md). A staged-snapshot pickup and a two-person handoff now have local evidence; native integration, broader interactions and exact product fidelity remain open. **Interaction policy (2026-11-13):** looking, pointing and physical handling use a reference-conditioned whole-shot generation route. See [the interaction decision](avatar-lighting.md#interaction-routing-decision-2026-11-13). Independent masks are not a substitute for coherent gaze, gesture, product support or contact. diff --git a/docs/interaction-staging-workflow.md b/docs/interaction-staging-workflow.md index 07be35b..8b4a328 100644 --- a/docs/interaction-staging-workflow.md +++ b/docs/interaction-staging-workflow.md @@ -1,6 +1,8 @@ # Stage the scene, then generate the interaction -**Local acceptance follow-up (2026-11-13):** [snapshot preparation, full-clip masks, tracker counterexample and continuous lighting](hybrid-acceptance-round1-2026-11-13.md). No new generated take yet; camera solve (feature 6) and generated worlds (feature 13) remain untested. +**Generated trials completed (2026-11-13):** [staged camera-left pickup and completed two-person handoff](staged-generation-results-2026-11-13.md), both returned to editable finishing. One take per case; exact product fidelity and native integration remain open. Estimated total US$1.90 under the fresh US$2 cap; account ledger unverified. + +**Local acceptance follow-up (2026-11-13):** [snapshot preparation, full-clip masks, tracker counterexample and continuous lighting](hybrid-acceptance-round1-2026-11-13.md). That earlier local checkpoint preceded the generated trials now recorded separately; camera solve (feature 6) and generated worlds (feature 13) remain untested. Decision and evidence checkpoint: 2026-11-13. This is the selected authoring workflow and remaining delivery plan, not a claim of a completed provider integration. @@ -8,7 +10,7 @@ Decision and evidence checkpoint: 2026-11-13. This is the selected authoring wor Independent compositing can position layers, preserve exact artwork and resolve reviewed visibility. It does not infer a shared physical performance. Masks and depth alone cannot make a hand grip an object, two people exchange it, an animal respond to a person, or two objects collide convincingly. Good edges and zero overlap do not establish gaze, support, contact, force or coordinated motion. -For **object–object, living thing–object, and living thing–living thing interactions**, default to staging the intended scene in EditableFrames and generating the coupled action together. This includes coordinated attention and gestures as well as contact. The broader categories are a workflow decision inferred from the human/headphone exercise; animal, multi-person and object-collision shots have not yet been validated. Fully authored animation, rigging or physics can still solve an interaction when explicitly supplied and reviewed; this is a limitation of assembling independent plates, not a claim that code cannot animate interaction. +For **object–object, living thing–object, and living thing–living thing interactions**, default to staging the intended scene in EditableFrames and generating the coupled action together. This includes coordinated attention and gestures as well as contact. The broader categories are a workflow decision inferred from the human/headphone exercise; a two-person transfer now has one local demonstration, while animal and object-collision shots remain untested and broader multi-person reliability remains unvalidated. Fully authored animation, rigging or physics can still solve an interaction when explicitly supplied and reviewed; this is a limitation of assembling independent plates, not a claim that code cannot animate interaction. ## Author and agent workflow @@ -27,7 +29,7 @@ The standalone Scene Studio example already exposes placement, camera/light cont Proposed acceptance for that handoff: agent and human paths capture the same committed revision/frame; active gesture drafts and helpers never leak; stale scene edits are detected before submission; submitted reference bytes/order match the receipt; failed/ambiguous jobs never silently duplicate spend or overwrite an accepted take; imported media uses decoded timing rather than provider billing metrics. These are delivery gates, not new CLI flags. -## Retained experiments and conclusions +## Earlier experiments and conclusions (before the staged trial) The mask-based headphone presentation improved hair and measured overlap but still looked awkward: a product placed beside unrelated avatar motion did not establish convincing attention or support. @@ -41,4 +43,4 @@ At the recorded provider rate, the successful video edit was estimated at about After generation, coupled action, pose, physical light and product appearance are baked. Expose only genuine controls: footage selection, timing where appropriate, crop, grade and separate code layers. A new pose, grip, placement or background geometry usually needs a new take. Regeneration invalidates dependent masks, tracks and acceptance; a matte does not recover independently editable 3D objects. -Retain scene JSON/source binding, clean snapshot, all reference bytes/hashes, exact prompt and role mapping, endpoint/schema/pricing snapshot, request/job/terminal receipts, estimate versus actual billing when available, raw download/hash, decoded timing, derived-data revisions, final render and review verdicts including failures. Keep secrets, private paths and signed URLs out of public documentation. Record reused assets honestly. Future tests must cover each untested interaction category and the actual snapshot handoff before broad quality claims. +Retain scene JSON/source binding, clean snapshot, all reference bytes/hashes, exact prompt and role mapping, endpoint/schema/pricing snapshot, request/job/terminal receipts, estimate versus actual billing when available, raw download/hash, decoded timing, derived-data revisions, final render and review verdicts including failures. Keep secrets, private paths and signed URLs out of public documentation. Record reused assets honestly. Future tests must cover each untested interaction category, repeat the snapshot handoff and validate native host integration before broad quality claims. diff --git a/docs/staged-generation-results-2026-11-13.md b/docs/staged-generation-results-2026-11-13.md new file mode 100644 index 0000000..eef6ab3 --- /dev/null +++ b/docs/staged-generation-results-2026-11-13.md @@ -0,0 +1,44 @@ +# Staged generation tests — 2026-11-13 + +Follow-up to the local acceptance report. The user authorized a fresh US$2 total generation cap. Two sequential tests use the same provider/model and retain all inputs, raw outputs and failed-quality observations. This is a local preparation/finishing workflow, not completed native provider integration or an independent reviewer approval. + +## Test A: authored snapshot → pickup + +The editable reference scene places the real product photograph on the camera-left table using exposed position, scale, image-plane rotation and approximate foreshortening controls. Its background and fictional presenter come from a retained image. This is a 2D blocking composition: it does not establish physical resting geometry, a camera solve or measured lighting. + +The captured 1280×720 snapshot was submitted as `start_image`; separate product-detail and presenter images followed in that order as `@image_2` and `@image_3`. Thus this trial really exercises first-frame plus separate references, unlike the previous video-edit trial. The exact prompt asks for look → grip → lift → supporting palm → gentle heft/hold in five seconds, with a fixed camera and the original starting position. + +Prediction `nj6k9wyeenrmt0d1tjwr4cqc8m`, `kwaivgi/kling-v4.0`, image-input route. Processing took 111.34 s. Decoded output: 1280×720, 121 frames, 24 fps, 5.041667 s; audio present. SHA256: `10276551f3efb9d2dfbc4831baf054173475c271ffb575f0d667366ffc056afb`. + +**Observed:** the camera-left resting start is retained. A product-and-table image patch matches at zero whole-pixel translation, normalized correlation 0.99398; mean absolute RGB differences are 3.91/255 over the frame and 3.85/255 over the product region. This measures opening-frame placement, not exact product shape or a physically constrained trajectory. The woman looks down, reaches, closes on the headband, rotates/lifts the single pair, brings the other hand below it, then shifts to a supported display. The requested heft reads mainly as pickup and hold. All 121 contact crops and 15 full-scene samples were inspected. No conspicuous duplicate product or gross hand-through-earcup event was found in that inspection; fine anatomy, text fidelity, exact geometry and normal/slow playback acceptance are not certified. + +The accepted-for-inspection take was imported into an EditableFrames renderer with separate title/eyebrow/accent/visibility controls. Export retains 121 frames at 24 fps. Repeat frame 48 has zero maximum RGB difference; source pixels outside typography are unchanged before encoding; a title-control edit changes 15,118 pixels; no page errors. Generated hands, product motion, physical light and room pixels remain baked. + +**Verdict: works with manual staging for this pickup.** This advances the local snapshot handoff from untested to one demonstrated case. It is not exact-object advertising approval, universal first-frame compliance, multi-angle validation or native host delivery. + +## Test B: two-person handoff + +The final decoded frame of Test A is the start image; product and presenter references remain separate. The second adult is specified in text, not supplied as an identity reference or pre-staged actor. The seven-second prompt requires entry → receiver grip/support → giver releases both hands → receiver alone holds. This is a living-thing–living-thing–object test, not an object–object collision test. + +Prediction `7dz5cxr6mdrmt0d1tjz9eahxg0`, same image-input route. Processing took 100.33 s. Output: 1280×720, 169 frames, 24 fps, 7.041667 s; audio present. SHA256: `99f2bd0be73114fbc4d92d3cbd20b8f2a7533efbbf8c869ab3574fe951c69423`. + +**Observed:** the man enters from camera-right and lowers himself beside the woman. She turns toward him and extends the single pair. Their hands share support around 3.5–4.7 s. At about 4.8–5.0 s she releases and withdraws her hands; by about 5.25 s her empty hands are on the table. The receiver alone holds and inspects the headphones through the end. All 169 contact crops and first/middle/last full-scene images were inspected. No gross duplication or disconnected limb was found in that inspection. Fine fingers, exact product surfaces/lettering and photometric consistency are not certified. Recipient identity consistency across other shots is untested. + +The opening-frame product-region patch has zero whole-pixel translation and correlation 0.9970; whole-frame RGB difference averages 3.32/255. These are opening-frame comparisons, not interaction fidelity scores. Editable typography is placed over the empty lower-left tabletop to avoid the second actor. Physical interaction remains baked in the generated footage. Export retains all 169 frames at 24 fps; repeat frame 48 and source pixels outside the lower-left typography region have zero maximum RGB difference before encoding. A control edit changes 15,803 pixels; no page errors. + +**Verdict: works with manual review for this transfer.** Completed release is now demonstrated once; it is not proof of repeatable multi-person choreography. The seven-second duration and different starting pose prevent treating this as a controlled comparison against the five-second pickup. + +## Budget and durable evidence + +Published image-input pricing was rechecked at $0.157/s for 720p. Five plus seven requested seconds estimated $1.884. Actual decoded durations total 12.083333 s, estimating **$1.8971** at the published rate (provider-rounded durations estimate $1.8972). Actual account billing was not retrieved. The round is closed to further submissions; the remaining estimate is below the minimum three-second image-input job. Each submission is guarded against retry after an ambiguous POST and linked to ordered input hashes and a job receipt. No third job is permitted in this round. Provider cost estimates are not a verified account ledger charge. + +## Plan implications + +- Preserve the distinction between `start_image` and an ordinary appearance reference. The observed placement benefit supports using an approved starting frame, without claiming an exact constraint or a controlled A/B model study. +- Freeze source/render binding, scene controls, frame/camera, snapshot and reference bytes/order before submission. Preserve the editable scene for another layout, and regenerate action when that layout changes. +- Acceptance must include the actual action beats. A good-looking pickup without heft, or two people holding without release, is not full instruction compliance. +- Source-bound masks/tracks must be regenerated for new take bytes. Existing masks from the earlier pickup cannot be attached to these new videos. +- Remaining: object–object contact, repeatability across seeds/takes, two identity-referenced subjects, multi-angle product fidelity, full-resolution edge annotations, native receipt/import/failure handling, stronger mixed human/product relighting and actual additional-computer benchmarks. +- Feature item 6 (camera solve) and feature item 13 (generated worlds) remain untested/deferred. Authored cameras, captured stills and generated videos are not evidence for either. + +Primary provider reference: [Kling inputs and pricing](https://replicate.com/kwaivgi/kling-v4.0). Visual findings and timings above are local experiment observations. diff --git a/skills/editableframes/references/hybrid-compositing-plan.md b/skills/editableframes/references/hybrid-compositing-plan.md index 84ef662..3831cca 100644 --- a/skills/editableframes/references/hybrid-compositing-plan.md +++ b/skills/editableframes/references/hybrid-compositing-plan.md @@ -1,8 +1,10 @@ # Reliable hybrid compositing and motion design -**Local acceptance follow-up (2026-11-13):** [snapshot preparation, full-clip masks, tracker counterexample and continuous lighting](hybrid-acceptance-round1-2026-11-13.md). No new generated take yet; camera solve (feature 6) and generated worlds (feature 13) remain untested. +**Generated trials completed (2026-11-13):** [staged camera-left pickup and completed two-person handoff](staged-generation-results-2026-11-13.md), both returned to editable finishing. One take per case; exact product fidelity and native integration remain open. Estimated total US$1.90 under the fresh US$2 cap; account ledger unverified. -**Scene staging decision (2026-11-13):** object–object, living thing–object and living thing–living thing interactions default to **stage → approved snapshot + reference images → joint video generation → editable finishing**. Independent masks do not create a coupled performance. See [workflow, evidence and remaining integration](interaction-staging-workflow.md). The latest pickup improved, but the snapshot handoff and broader interaction categories remain untested. +**Local acceptance follow-up (2026-11-13):** [snapshot preparation, full-clip masks, tracker counterexample and continuous lighting](hybrid-acceptance-round1-2026-11-13.md). That earlier local checkpoint preceded the generated trials now recorded separately; camera solve (feature 6) and generated worlds (feature 13) remain untested. + +**Scene staging decision (2026-11-13):** object–object, living thing–object and living thing–living thing interactions default to **stage → approved snapshot + reference images → joint video generation → editable finishing**. Independent masks do not create a coupled performance. See [workflow, evidence and remaining integration](interaction-staging-workflow.md). A staged-snapshot pickup and a two-person handoff now have local evidence; native integration, broader interactions and exact product fidelity remain open. **Interaction policy, 2026-11-13:** generate intended human–object interaction as a reference-conditioned whole shot, including looking and pointing. Masking and non-overlap do not establish gaze, natural support, gesture or contact. Keep screen-space cards outside person holdouts. Unrelated avatar footage plus an independently placed product image is rejected for an interaction shot; the code compositor remains responsible for editable overlays and non-interacting layouts. This is a routing decision, not a new implemented renderer API. diff --git a/skills/editableframes/references/interaction-staging-workflow.md b/skills/editableframes/references/interaction-staging-workflow.md index 07be35b..8b4a328 100644 --- a/skills/editableframes/references/interaction-staging-workflow.md +++ b/skills/editableframes/references/interaction-staging-workflow.md @@ -1,6 +1,8 @@ # Stage the scene, then generate the interaction -**Local acceptance follow-up (2026-11-13):** [snapshot preparation, full-clip masks, tracker counterexample and continuous lighting](hybrid-acceptance-round1-2026-11-13.md). No new generated take yet; camera solve (feature 6) and generated worlds (feature 13) remain untested. +**Generated trials completed (2026-11-13):** [staged camera-left pickup and completed two-person handoff](staged-generation-results-2026-11-13.md), both returned to editable finishing. One take per case; exact product fidelity and native integration remain open. Estimated total US$1.90 under the fresh US$2 cap; account ledger unverified. + +**Local acceptance follow-up (2026-11-13):** [snapshot preparation, full-clip masks, tracker counterexample and continuous lighting](hybrid-acceptance-round1-2026-11-13.md). That earlier local checkpoint preceded the generated trials now recorded separately; camera solve (feature 6) and generated worlds (feature 13) remain untested. Decision and evidence checkpoint: 2026-11-13. This is the selected authoring workflow and remaining delivery plan, not a claim of a completed provider integration. @@ -8,7 +10,7 @@ Decision and evidence checkpoint: 2026-11-13. This is the selected authoring wor Independent compositing can position layers, preserve exact artwork and resolve reviewed visibility. It does not infer a shared physical performance. Masks and depth alone cannot make a hand grip an object, two people exchange it, an animal respond to a person, or two objects collide convincingly. Good edges and zero overlap do not establish gaze, support, contact, force or coordinated motion. -For **object–object, living thing–object, and living thing–living thing interactions**, default to staging the intended scene in EditableFrames and generating the coupled action together. This includes coordinated attention and gestures as well as contact. The broader categories are a workflow decision inferred from the human/headphone exercise; animal, multi-person and object-collision shots have not yet been validated. Fully authored animation, rigging or physics can still solve an interaction when explicitly supplied and reviewed; this is a limitation of assembling independent plates, not a claim that code cannot animate interaction. +For **object–object, living thing–object, and living thing–living thing interactions**, default to staging the intended scene in EditableFrames and generating the coupled action together. This includes coordinated attention and gestures as well as contact. The broader categories are a workflow decision inferred from the human/headphone exercise; a two-person transfer now has one local demonstration, while animal and object-collision shots remain untested and broader multi-person reliability remains unvalidated. Fully authored animation, rigging or physics can still solve an interaction when explicitly supplied and reviewed; this is a limitation of assembling independent plates, not a claim that code cannot animate interaction. ## Author and agent workflow @@ -27,7 +29,7 @@ The standalone Scene Studio example already exposes placement, camera/light cont Proposed acceptance for that handoff: agent and human paths capture the same committed revision/frame; active gesture drafts and helpers never leak; stale scene edits are detected before submission; submitted reference bytes/order match the receipt; failed/ambiguous jobs never silently duplicate spend or overwrite an accepted take; imported media uses decoded timing rather than provider billing metrics. These are delivery gates, not new CLI flags. -## Retained experiments and conclusions +## Earlier experiments and conclusions (before the staged trial) The mask-based headphone presentation improved hair and measured overlap but still looked awkward: a product placed beside unrelated avatar motion did not establish convincing attention or support. @@ -41,4 +43,4 @@ At the recorded provider rate, the successful video edit was estimated at about After generation, coupled action, pose, physical light and product appearance are baked. Expose only genuine controls: footage selection, timing where appropriate, crop, grade and separate code layers. A new pose, grip, placement or background geometry usually needs a new take. Regeneration invalidates dependent masks, tracks and acceptance; a matte does not recover independently editable 3D objects. -Retain scene JSON/source binding, clean snapshot, all reference bytes/hashes, exact prompt and role mapping, endpoint/schema/pricing snapshot, request/job/terminal receipts, estimate versus actual billing when available, raw download/hash, decoded timing, derived-data revisions, final render and review verdicts including failures. Keep secrets, private paths and signed URLs out of public documentation. Record reused assets honestly. Future tests must cover each untested interaction category and the actual snapshot handoff before broad quality claims. +Retain scene JSON/source binding, clean snapshot, all reference bytes/hashes, exact prompt and role mapping, endpoint/schema/pricing snapshot, request/job/terminal receipts, estimate versus actual billing when available, raw download/hash, decoded timing, derived-data revisions, final render and review verdicts including failures. Keep secrets, private paths and signed URLs out of public documentation. Record reused assets honestly. Future tests must cover each untested interaction category, repeat the snapshot handoff and validate native host integration before broad quality claims. diff --git a/skills/editableframes/references/staged-generation-results-2026-11-13.md b/skills/editableframes/references/staged-generation-results-2026-11-13.md new file mode 100644 index 0000000..eef6ab3 --- /dev/null +++ b/skills/editableframes/references/staged-generation-results-2026-11-13.md @@ -0,0 +1,44 @@ +# Staged generation tests — 2026-11-13 + +Follow-up to the local acceptance report. The user authorized a fresh US$2 total generation cap. Two sequential tests use the same provider/model and retain all inputs, raw outputs and failed-quality observations. This is a local preparation/finishing workflow, not completed native provider integration or an independent reviewer approval. + +## Test A: authored snapshot → pickup + +The editable reference scene places the real product photograph on the camera-left table using exposed position, scale, image-plane rotation and approximate foreshortening controls. Its background and fictional presenter come from a retained image. This is a 2D blocking composition: it does not establish physical resting geometry, a camera solve or measured lighting. + +The captured 1280×720 snapshot was submitted as `start_image`; separate product-detail and presenter images followed in that order as `@image_2` and `@image_3`. Thus this trial really exercises first-frame plus separate references, unlike the previous video-edit trial. The exact prompt asks for look → grip → lift → supporting palm → gentle heft/hold in five seconds, with a fixed camera and the original starting position. + +Prediction `nj6k9wyeenrmt0d1tjwr4cqc8m`, `kwaivgi/kling-v4.0`, image-input route. Processing took 111.34 s. Decoded output: 1280×720, 121 frames, 24 fps, 5.041667 s; audio present. SHA256: `10276551f3efb9d2dfbc4831baf054173475c271ffb575f0d667366ffc056afb`. + +**Observed:** the camera-left resting start is retained. A product-and-table image patch matches at zero whole-pixel translation, normalized correlation 0.99398; mean absolute RGB differences are 3.91/255 over the frame and 3.85/255 over the product region. This measures opening-frame placement, not exact product shape or a physically constrained trajectory. The woman looks down, reaches, closes on the headband, rotates/lifts the single pair, brings the other hand below it, then shifts to a supported display. The requested heft reads mainly as pickup and hold. All 121 contact crops and 15 full-scene samples were inspected. No conspicuous duplicate product or gross hand-through-earcup event was found in that inspection; fine anatomy, text fidelity, exact geometry and normal/slow playback acceptance are not certified. + +The accepted-for-inspection take was imported into an EditableFrames renderer with separate title/eyebrow/accent/visibility controls. Export retains 121 frames at 24 fps. Repeat frame 48 has zero maximum RGB difference; source pixels outside typography are unchanged before encoding; a title-control edit changes 15,118 pixels; no page errors. Generated hands, product motion, physical light and room pixels remain baked. + +**Verdict: works with manual staging for this pickup.** This advances the local snapshot handoff from untested to one demonstrated case. It is not exact-object advertising approval, universal first-frame compliance, multi-angle validation or native host delivery. + +## Test B: two-person handoff + +The final decoded frame of Test A is the start image; product and presenter references remain separate. The second adult is specified in text, not supplied as an identity reference or pre-staged actor. The seven-second prompt requires entry → receiver grip/support → giver releases both hands → receiver alone holds. This is a living-thing–living-thing–object test, not an object–object collision test. + +Prediction `7dz5cxr6mdrmt0d1tjz9eahxg0`, same image-input route. Processing took 100.33 s. Output: 1280×720, 169 frames, 24 fps, 7.041667 s; audio present. SHA256: `99f2bd0be73114fbc4d92d3cbd20b8f2a7533efbbf8c869ab3574fe951c69423`. + +**Observed:** the man enters from camera-right and lowers himself beside the woman. She turns toward him and extends the single pair. Their hands share support around 3.5–4.7 s. At about 4.8–5.0 s she releases and withdraws her hands; by about 5.25 s her empty hands are on the table. The receiver alone holds and inspects the headphones through the end. All 169 contact crops and first/middle/last full-scene images were inspected. No gross duplication or disconnected limb was found in that inspection. Fine fingers, exact product surfaces/lettering and photometric consistency are not certified. Recipient identity consistency across other shots is untested. + +The opening-frame product-region patch has zero whole-pixel translation and correlation 0.9970; whole-frame RGB difference averages 3.32/255. These are opening-frame comparisons, not interaction fidelity scores. Editable typography is placed over the empty lower-left tabletop to avoid the second actor. Physical interaction remains baked in the generated footage. Export retains all 169 frames at 24 fps; repeat frame 48 and source pixels outside the lower-left typography region have zero maximum RGB difference before encoding. A control edit changes 15,803 pixels; no page errors. + +**Verdict: works with manual review for this transfer.** Completed release is now demonstrated once; it is not proof of repeatable multi-person choreography. The seven-second duration and different starting pose prevent treating this as a controlled comparison against the five-second pickup. + +## Budget and durable evidence + +Published image-input pricing was rechecked at $0.157/s for 720p. Five plus seven requested seconds estimated $1.884. Actual decoded durations total 12.083333 s, estimating **$1.8971** at the published rate (provider-rounded durations estimate $1.8972). Actual account billing was not retrieved. The round is closed to further submissions; the remaining estimate is below the minimum three-second image-input job. Each submission is guarded against retry after an ambiguous POST and linked to ordered input hashes and a job receipt. No third job is permitted in this round. Provider cost estimates are not a verified account ledger charge. + +## Plan implications + +- Preserve the distinction between `start_image` and an ordinary appearance reference. The observed placement benefit supports using an approved starting frame, without claiming an exact constraint or a controlled A/B model study. +- Freeze source/render binding, scene controls, frame/camera, snapshot and reference bytes/order before submission. Preserve the editable scene for another layout, and regenerate action when that layout changes. +- Acceptance must include the actual action beats. A good-looking pickup without heft, or two people holding without release, is not full instruction compliance. +- Source-bound masks/tracks must be regenerated for new take bytes. Existing masks from the earlier pickup cannot be attached to these new videos. +- Remaining: object–object contact, repeatability across seeds/takes, two identity-referenced subjects, multi-angle product fidelity, full-resolution edge annotations, native receipt/import/failure handling, stronger mixed human/product relighting and actual additional-computer benchmarks. +- Feature item 6 (camera solve) and feature item 13 (generated worlds) remain untested/deferred. Authored cameras, captured stills and generated videos are not evidence for either. + +Primary provider reference: [Kling inputs and pricing](https://replicate.com/kwaivgi/kling-v4.0). Visual findings and timings above are local experiment observations. From 33b3f505fbd60197509a7e083547452a9f99fb58 Mon Sep 17 00:00:00 2001 From: Laurence Xavier <35849747+lxf82dev@users.noreply.github.com> Date: Fri, 13 Nov 2026 21:23:50 +0800 Subject: [PATCH 29/49] docs: record accepted interactions and stylized story generation findings --- ...code-generated-story-results-2026-11-13.md | 56 +++++++++++++++++++ docs/hybrid-compositing-plan.md | 2 + docs/hybrid-scenes.md | 5 +- docs/interaction-staging-workflow.md | 2 + docs/staged-generation-results-2026-11-13.md | 2 + skills/editableframes/SKILL.md | 2 + ...code-generated-story-results-2026-11-13.md | 56 +++++++++++++++++++ .../references/hybrid-compositing-plan.md | 2 + skills/editableframes/references/hybrid.md | 2 + .../interaction-staging-workflow.md | 2 + .../staged-generation-results-2026-11-13.md | 2 + 11 files changed, 132 insertions(+), 1 deletion(-) create mode 100644 docs/code-generated-story-results-2026-11-13.md create mode 100644 skills/editableframes/references/code-generated-story-results-2026-11-13.md diff --git a/docs/code-generated-story-results-2026-11-13.md b/docs/code-generated-story-results-2026-11-13.md new file mode 100644 index 0000000..000d9ff --- /dev/null +++ b/docs/code-generated-story-results-2026-11-13.md @@ -0,0 +1,56 @@ +# Interaction acceptance and code-generated story films — 2026-11-13 + +## Decisions from the latest outputs + +The user accepts the visual direction of the full-pickup and two-person handoff outputs and prefers the Fable 5.2 story film as closer to the supplied fantasy-game references. These are **user visual acceptance and preference**, not independent certification of every frame, exact product fidelity, or a completed Fable review. The two model implementations are one creative exercise, with different refinement histories; they are not a general model benchmark. + +Keep two distinct production routes, selected by the required representation and editability: + +| Need | Selected route | What remains editable | Evidence / boundary | +|---|---|---|---| +| Realistic people handling a product or exchanging it | Stage the scene → approved start image plus identity/product references → jointly generate the interacting subjects and room → review → EditableFrames finishing | Staging before generation; accepted footage selection/timing/crop/grade and separate titles/captions afterward | Pickup and completed transfer now have user-accepted examples. Physical performance and product pixels are baked; repeatability and exact identity/branding remain open. | +| Stylized characters acting in an authored world | Code builds the set, rigs, action, cameras, lights and renderer; export directly | Authored geometry, rigs, animation and look in source; selected parameters via controls | Two 48-second fantasy RPG films rendered. Fable's direction is preferred, but its draft fails one seek check and requires refinement. Not generic automatic character animation. | +| Realistic interaction within an otherwise editable story | Use an approved authored shot/snapshot as generation input, then return the accepted clip to the edit | Code shots stay editable; generated sections have the same baked boundary as above | Proposed shot-level combination; this story exercise did not test such a round trip. Do not claim that model video preserves exact meshes or camera motion. | + +The earlier interaction rule applies to **independently assembled realistic plates**. It must not become a ban on code-authored character stories. A shared authored rig and choreography can represent an interaction; independent masks cannot invent it. Nor does stylization excuse intersecting hands, incoherent eyelines, or unsupported props. + +## What Fable actually used + +Both entries use **Three.js raster rendering in the current EditableFrames `defineRenderer` / `mountRenderer` contract**, exported locally through browser capture and FFmpeg. No diffusion-generated frames, external character asset pack, path tracer, NVIDIA-only runtime or paid generation call was used for these films. The difference is authored assets, staging and rendering choices, not a different foundational framework. + +| Area | Fable implementation observed in source | Why it fits the references better / remaining limitation | +|---|---|---| +| Character construction | Lofted heads and bodies, character-specific proportions, separate noses/ears/hair, articulated segmented limbs and five-finger hands. Canvas-painted face textures include lids, brows, pupils, mouth states and emissive eyes. | Narrower faces and controlled facial detail read closer to the reference game art. This is procedural geometry and a scene-specific rig, not a learned human reconstruction or a production facial rig. | +| Materials | Seeded, low-resolution stone, wood, cloth, leather and skin texture functions; nearest-neighbor magnification with mipmapped minification. Humanoids use Lambert materials. | Local wear, varied stone courses, planks and painted features provide more surface detail. Physically based materials alone do not guarantee a better stylized image; Astra used standard materials yet its asset forms were more primitive. | +| Acting | Two-bone arm IK, gaze targets, walk/sit/gesture poses, a deforming dragon spine and wings, speech-envelope-driven animation with limited facial states. | More purposeful action than small idle oscillations. IK positions joints; it does not verify grasp, reach, collisions or force. Speech-envelope animation is not phoneme-level lip sync. | +| Camera and sets | Fifteen shots rather than Astra's eight; a medieval lane and a furnished tavern; approach, reaction, over-table, detail and ensemble shots. | Greater spatial context, shot variety and first-person framing. The doorway transition and handoff detail still need refinement. | +| Lighting and finish | Local torches, ember, window/fill and chandelier lights; HDR beauty pass at twice the output dimensions, object-ID/depth contour pass, half-resolution bloom, tone mapping, grade, vignette and grain. | Local light and depth-aware contours make a coherent game-art look. The large bloom/highlights also obscure detail in parts of the draft; adding effects is not automatically a quality improvement. | +| Framework | Explicit frame clock and editable light/look/camera/title/subtitle properties, with separate local TTS/audio preparation. | Source remains authorable and selected controls redraw the scene. This does not make every performance or audio edit automatically available in a panel. | + +These are source-backed mechanisms and plausible contributors to the user preference, **not isolated causal tests**. No ablation has established which individual technique explains how much of the difference. The preferred direction is a reusable authoring approach, not a requirement to reproduce Fable's bugs or every shader. + +## Actual result and acceptance + +- **Astra:** 48.000 seconds, 720×1280, 24 fps, 1,152 decoded frames, voiced/subtitled. Three sampled repeat seeks matched exactly in the tested browser; a light-control edit changed the scene. Faces/hands remain puppet-like, material and architectural variety are limited, and jaw movement is approximate. +- **Fable 5.2:** authored the scene, soundtrack and 15-shot timeline, then hit its provider usage limit during visual refinement. The parent exported that saved source unchanged; hashes before/after confirm preservation. Both full video and original source are retained. The output is a **recovered unfinished draft**, not Fable's final approved delivery. +- **Recovered Fable export:** 48.000 seconds, 720×1280, 24 fps, 1,152 frames decoded without video errors. Light-control edit changed the render. A generic browser resource 404 was retained; its URL was not established, so it is not silently dismissed as a confirmed favicon request. +- **Seek defect:** frames 228 and 768 repeated exactly, but frame 960 changed 183,794 pixels; mean channel difference 7.128/255, maximum 238. The dragon's head direction visibly changes. The `better` shot reads the previous camera position for its gaze before setting the current camera, a likely cause from source inspection; a fix has not yet been verified. Successful sequential export does not pass random-access authoring. +- **Audio recovery:** initial decoded AAC peak was 1.372. The parent applied gain 0.5 at output while copying video unchanged; delivered peak measured 0.737. The original audio export is retained. This avoids the measured output overshoot but cannot undo distortion already present in the mix. +- **Visual limits:** rigid joints, sparse facial animation, awkward/oversized hand contact, strong light/bloom and the doorway transition. Fifteen shot stills and a 1 fps decoded sheet were inspected; there is no claim of normal-speed playback or exhaustive visual inspection of all 1,152 frames by the reviewer. + +The user prefers Fable's **visual direction**. Neither film reaches the reference's character finish; a general production-ready or deterministic story engine is not yet demonstrated. References supplied art direction; their screenshot pixels were not used as finished scene backgrounds. Preserve reference rights/provenance before redistributing any supplied images. + +## Story track: extend beyond the dungeon without constraining the core + +This is a new authored-story exercise, separate from **feature item 6 (camera solve)** and **feature item 13 (world reconstruction into splats/meshes)**. Code-generated geometry and known cameras do not validate either deferred feature. Also keep it distinct from the existing “many versions from one take” journey numbered 6. + +1. **ST1 — finish and stabilize this film.** Let Fable complete its own refinement when available. Correct the current-frame camera/gaze dependency and test random, repeated and reverse seeks across every shot and cut boundary; compare with sequential frames in the same renderer. Inspect normal/slow playback, all contact intervals, reach/support/release, camera-wall clipping and gaze. Repair highlight loss and audio gain; retain original versus corrected versions and explicit authorship. Verify each advertised control in both preview and export. No model call or wall-clock state inside frame rendering. +2. **ST2 — extract optional reusable authoring modules.** Separate character shape/face/rig, props and set dressing, action targets/contacts, shot/camera track, light track, material/contour/post look and dialogue/subtitle timing. Give selected controls stable IDs and source bindings; keep arbitrary source code and replacement renderers possible. Do not embed a mandatory fantasy vocabulary, actor taxonomy or model provider into the core. Existing film scripts are prototypes, not a shipped animation package. +3. **ST3 — test style transfer through code, not only palette changes.** Produce three additional short studies, for example a science-fiction repair shop, a sunny cel-shaded village and a clay/toy workshop. Use a common walk → dialogue → shared-prop action and camera brief while changing silhouettes, facial design, surface detail, set construction, light response and contour/post treatment. Retain the full editable sources and exact settings. Each style must pass its own whole-shot visual review; portability beyond the fantasy study is currently unproven. No new hosted spending is implied. +4. **ST4 — test practical reuse and host delivery.** Reuse an approved actor across shots and changes in framing, light, costume and dialogue; check identity, silhouettes and contact after edits. Regenerate local speech/alignment when dialogue changes rather than retaining stale audio. Bind source, assets and audio to project revisions and test save/reload, undo/redo and export parity in the host before claiming an integrated story workflow. Measure preview, capture time and peak memory on actual additional desktop/laptop machines; this Mac run establishes no performance floor for ordinary computers. + +Style is an open combination of authorable geometry, textures, rigs, cameras and lights, not a fixed list of “dungeon / office / cool” presets. Presets may be convenient starting points. Cross-style reuse and a useful agent authoring workflow must be earned by ST3/ST4, not inferred from parameter exposure alone. + +## Interaction work that remains + +The accepted pickup/handoff samples validate the selected staged joint-generation direction sufficiently to proceed with host implementation. Prioritize frozen scene-set capture, ordered reference roles/hashes, durable submission receipts, failed/ambiguous-job handling, actual decoded timing and accepted-take import; keep provider work outside rendering. Repeat the tests with both people identity-referenced and with difficult contact/occlusion before claiming broader reliability. Exact product geometry/print, multi-angle consistency, object–object collisions and animal interactions remain separate acceptance gates. The detailed [staged-generation report](staged-generation-results-2026-11-13.md) retains the observed action beats, estimates and limits. diff --git a/docs/hybrid-compositing-plan.md b/docs/hybrid-compositing-plan.md index dbbeb8f..e05709b 100644 --- a/docs/hybrid-compositing-plan.md +++ b/docs/hybrid-compositing-plan.md @@ -1,5 +1,7 @@ # Reliable hybrid compositing and motion design +**Latest decisions (2026-11-13):** the user accepts the full-pickup and two-person handoff examples and prefers Fable 5.2’s visual direction for the 48-second code-generated fantasy story. [Results, technical comparison and story track ST1–ST4](code-generated-story-results-2026-11-13.md). The Fable draft is unfinished and fails a random-seek check; cross-style reuse is a planned experiment. Realistic joint generation and explicitly authored stylized animation are separate routes. + **Generated trials completed (2026-11-13):** [staged camera-left pickup and completed two-person handoff](staged-generation-results-2026-11-13.md), both returned to editable finishing. One take per case; exact product fidelity and native integration remain open. Estimated total US$1.90 under the fresh US$2 cap; account ledger unverified. **Local acceptance follow-up (2026-11-13):** [snapshot preparation, full-clip masks, tracker counterexample and continuous lighting](hybrid-acceptance-round1-2026-11-13.md). That earlier local checkpoint preceded the generated trials now recorded separately; camera solve (feature 6) and generated worlds (feature 13) remain untested. diff --git a/docs/hybrid-scenes.md b/docs/hybrid-scenes.md index d9d4143..2bc42a6 100644 --- a/docs/hybrid-scenes.md +++ b/docs/hybrid-scenes.md @@ -1,12 +1,14 @@ # Hybrid scenes: code inside footage +**Latest decisions (2026-11-13):** the user accepts the full-pickup and two-person handoff examples and prefers Fable 5.2’s visual direction for the 48-second code-generated fantasy story. [Results, technical comparison and story track ST1–ST4](code-generated-story-results-2026-11-13.md). The Fable draft is unfinished and fails a random-seek check; cross-style reuse is a planned experiment. Realistic joint generation and explicitly authored stylized animation are separate routes. + **Generated trials completed (2026-11-13):** [staged camera-left pickup and completed two-person handoff](staged-generation-results-2026-11-13.md), both returned to editable finishing. One take per case; exact product fidelity and native integration remain open. Estimated total US$1.90 under the fresh US$2 cap; account ledger unverified. **Local acceptance follow-up (2026-11-13):** [snapshot preparation, full-clip masks, tracker counterexample and continuous lighting](hybrid-acceptance-round1-2026-11-13.md). That earlier local checkpoint preceded the generated trials now recorded separately; camera solve (feature 6) and generated worlds (feature 13) remain untested. **Scene staging decision (2026-11-13):** object–object, living thing–object and living thing–living thing interactions default to **stage → approved snapshot + reference images → joint video generation → editable finishing**. Independent masks do not create a coupled performance. See [workflow, evidence and remaining integration](interaction-staging-workflow.md). A staged-snapshot pickup and a two-person handoff now have local evidence; native integration, broader interactions and exact product fidelity remain open. -**Interaction policy (2026-11-13):** looking, pointing and physical handling use a reference-conditioned whole-shot generation route. See [the interaction decision](avatar-lighting.md#interaction-routing-decision-2026-11-13). Independent masks are not a substitute for coherent gaze, gesture, product support or contact. +**Interaction policy (2026-11-13):** realistic avatar/product looking, pointing and physical handling use a reference-conditioned whole-shot generation route. Explicitly authored stylized rigs are a separate route, with their own contact and seek acceptance. See [the interaction decision](avatar-lighting.md#interaction-routing-decision-2026-11-13). Independent masks are not a substitute for coherent gaze, gesture, product support or contact. Research update (2026-11-13): [video segmentation and tracking findings](hybrid-analysis-study-2026-11-13.md) and [reference-conditioned handling shots](avatar-lighting.md#reference-conditioned-handling-shots-2026-11-13) define the next experiments and the editability boundary of flattened footage. These do not claim new implemented renderer services. @@ -45,6 +47,7 @@ Each journey says what the author does, what EditableFrames does, and how far it | 6 | **Many versions from one take.** The same shot in twenty prices, five languages, three label colours. | One plate and its data, then control edits. | Re-renders each version from the same pinned inputs. If the plate is replaced, its old matte, depth and track are refused instead of being composited slightly wrong. | Integration test for the refusals; edits use the existing revision-checked history. | | 7 | **Fast motion.** Code elements that move quickly should smear like the footage does. | A shutter angle. | Renders several sub-frame samples per output frame and averages them. | Integration test: smear width and edge colour. | | 8 | **A moving camera.** The product stays put in a shot whose camera travels. | A camera path solved elsewhere. | Replays the path on a Three.js camera, with rotation interpolated correctly. | Unit tests only. Not yet tried on a real solve; solves of generated footage are approximate. | +| 9 | **An authored stylized story.** Characters move and speak in a code-built world. | Character/set assets or procedural source, rigs, shot/action/light tracks and prepared speech. | Renders authored geometry and sampled animation with exposed controls; no implicit model call. | Two 48-second local SDK films; Fable visual direction user-preferred, interrupted draft has a seek defect. [Story findings and next tests](code-generated-story-results-2026-11-13.md). No native story editor or cross-style portability claim. | The integration tests use a synthetic plate. [On generated footage](#on-generated-footage) says what a trial on plates from video models found. diff --git a/docs/interaction-staging-workflow.md b/docs/interaction-staging-workflow.md index 8b4a328..5b0e8f1 100644 --- a/docs/interaction-staging-workflow.md +++ b/docs/interaction-staging-workflow.md @@ -1,5 +1,7 @@ # Stage the scene, then generate the interaction +**Latest decisions (2026-11-13):** the user accepts the full-pickup and two-person handoff examples and prefers Fable 5.2’s visual direction for the 48-second code-generated fantasy story. [Results, technical comparison and story track ST1–ST4](code-generated-story-results-2026-11-13.md). The Fable draft is unfinished and fails a random-seek check; cross-style reuse is a planned experiment. Realistic joint generation and explicitly authored stylized animation are separate routes. + **Generated trials completed (2026-11-13):** [staged camera-left pickup and completed two-person handoff](staged-generation-results-2026-11-13.md), both returned to editable finishing. One take per case; exact product fidelity and native integration remain open. Estimated total US$1.90 under the fresh US$2 cap; account ledger unverified. **Local acceptance follow-up (2026-11-13):** [snapshot preparation, full-clip masks, tracker counterexample and continuous lighting](hybrid-acceptance-round1-2026-11-13.md). That earlier local checkpoint preceded the generated trials now recorded separately; camera solve (feature 6) and generated worlds (feature 13) remain untested. diff --git a/docs/staged-generation-results-2026-11-13.md b/docs/staged-generation-results-2026-11-13.md index eef6ab3..a93e190 100644 --- a/docs/staged-generation-results-2026-11-13.md +++ b/docs/staged-generation-results-2026-11-13.md @@ -1,5 +1,7 @@ # Staged generation tests — 2026-11-13 +**User visual acceptance (2026-11-13):** the user says the full-pickup and two-person handoff outputs look good. Treat these takes as accepted demonstrations of the staged joint-generation direction and proceed with the planned host workflow. This does not certify exact product fidelity, requested heft, repeatability, all-frame anatomy or native delivery, and is not a new independent Fable review. The original measurements below remain unchanged. [Combined conclusions and the separate authored-story experiment](code-generated-story-results-2026-11-13.md). + Follow-up to the local acceptance report. The user authorized a fresh US$2 total generation cap. Two sequential tests use the same provider/model and retain all inputs, raw outputs and failed-quality observations. This is a local preparation/finishing workflow, not completed native provider integration or an independent reviewer approval. ## Test A: authored snapshot → pickup diff --git a/skills/editableframes/SKILL.md b/skills/editableframes/SKILL.md index 130cbb9..e46b240 100644 --- a/skills/editableframes/SKILL.md +++ b/skills/editableframes/SKILL.md @@ -32,3 +32,5 @@ For final short clips, inspect every decoded frame, crossing crops and playback; ## Spatial objects For separately editable spatial objects expose one animatable vec3 with role position and explicit coordinateSpace/unit, plus one positive number with role scale. Use editableframes/manipulation (or editableframes/three-manipulation) and consume the same props in rendering. Publish working per-object manipulationCapabilities and measurement; roles alone cannot make a renderer draggable. Nonspatial lighting parameters need no invented transforms. Keep the 200-control budget; arbitrary renderer code and future libraries remain supported. Read docs/object-manipulation.md for source tick identity, first-key holding and gesture write policy. Preserve existing split-number tracks; migrate them explicitly rather than relabeling their type. + +For explicitly authored stylized character stories, read the [code-generated story findings and acceptance track](references/code-generated-story-results-2026-11-13.md). Rigs, choreography and looks remain replaceable source, not a fixed core scene grammar. The preferred fantasy draft is not production-ready: contact, current-frame gaze/camera evaluation, reverse/random seeks, audio timing and cross-style reuse still need acceptance. Realistic interactions assembled from independent plates retain the staged joint-generation route. diff --git a/skills/editableframes/references/code-generated-story-results-2026-11-13.md b/skills/editableframes/references/code-generated-story-results-2026-11-13.md new file mode 100644 index 0000000..000d9ff --- /dev/null +++ b/skills/editableframes/references/code-generated-story-results-2026-11-13.md @@ -0,0 +1,56 @@ +# Interaction acceptance and code-generated story films — 2026-11-13 + +## Decisions from the latest outputs + +The user accepts the visual direction of the full-pickup and two-person handoff outputs and prefers the Fable 5.2 story film as closer to the supplied fantasy-game references. These are **user visual acceptance and preference**, not independent certification of every frame, exact product fidelity, or a completed Fable review. The two model implementations are one creative exercise, with different refinement histories; they are not a general model benchmark. + +Keep two distinct production routes, selected by the required representation and editability: + +| Need | Selected route | What remains editable | Evidence / boundary | +|---|---|---|---| +| Realistic people handling a product or exchanging it | Stage the scene → approved start image plus identity/product references → jointly generate the interacting subjects and room → review → EditableFrames finishing | Staging before generation; accepted footage selection/timing/crop/grade and separate titles/captions afterward | Pickup and completed transfer now have user-accepted examples. Physical performance and product pixels are baked; repeatability and exact identity/branding remain open. | +| Stylized characters acting in an authored world | Code builds the set, rigs, action, cameras, lights and renderer; export directly | Authored geometry, rigs, animation and look in source; selected parameters via controls | Two 48-second fantasy RPG films rendered. Fable's direction is preferred, but its draft fails one seek check and requires refinement. Not generic automatic character animation. | +| Realistic interaction within an otherwise editable story | Use an approved authored shot/snapshot as generation input, then return the accepted clip to the edit | Code shots stay editable; generated sections have the same baked boundary as above | Proposed shot-level combination; this story exercise did not test such a round trip. Do not claim that model video preserves exact meshes or camera motion. | + +The earlier interaction rule applies to **independently assembled realistic plates**. It must not become a ban on code-authored character stories. A shared authored rig and choreography can represent an interaction; independent masks cannot invent it. Nor does stylization excuse intersecting hands, incoherent eyelines, or unsupported props. + +## What Fable actually used + +Both entries use **Three.js raster rendering in the current EditableFrames `defineRenderer` / `mountRenderer` contract**, exported locally through browser capture and FFmpeg. No diffusion-generated frames, external character asset pack, path tracer, NVIDIA-only runtime or paid generation call was used for these films. The difference is authored assets, staging and rendering choices, not a different foundational framework. + +| Area | Fable implementation observed in source | Why it fits the references better / remaining limitation | +|---|---|---| +| Character construction | Lofted heads and bodies, character-specific proportions, separate noses/ears/hair, articulated segmented limbs and five-finger hands. Canvas-painted face textures include lids, brows, pupils, mouth states and emissive eyes. | Narrower faces and controlled facial detail read closer to the reference game art. This is procedural geometry and a scene-specific rig, not a learned human reconstruction or a production facial rig. | +| Materials | Seeded, low-resolution stone, wood, cloth, leather and skin texture functions; nearest-neighbor magnification with mipmapped minification. Humanoids use Lambert materials. | Local wear, varied stone courses, planks and painted features provide more surface detail. Physically based materials alone do not guarantee a better stylized image; Astra used standard materials yet its asset forms were more primitive. | +| Acting | Two-bone arm IK, gaze targets, walk/sit/gesture poses, a deforming dragon spine and wings, speech-envelope-driven animation with limited facial states. | More purposeful action than small idle oscillations. IK positions joints; it does not verify grasp, reach, collisions or force. Speech-envelope animation is not phoneme-level lip sync. | +| Camera and sets | Fifteen shots rather than Astra's eight; a medieval lane and a furnished tavern; approach, reaction, over-table, detail and ensemble shots. | Greater spatial context, shot variety and first-person framing. The doorway transition and handoff detail still need refinement. | +| Lighting and finish | Local torches, ember, window/fill and chandelier lights; HDR beauty pass at twice the output dimensions, object-ID/depth contour pass, half-resolution bloom, tone mapping, grade, vignette and grain. | Local light and depth-aware contours make a coherent game-art look. The large bloom/highlights also obscure detail in parts of the draft; adding effects is not automatically a quality improvement. | +| Framework | Explicit frame clock and editable light/look/camera/title/subtitle properties, with separate local TTS/audio preparation. | Source remains authorable and selected controls redraw the scene. This does not make every performance or audio edit automatically available in a panel. | + +These are source-backed mechanisms and plausible contributors to the user preference, **not isolated causal tests**. No ablation has established which individual technique explains how much of the difference. The preferred direction is a reusable authoring approach, not a requirement to reproduce Fable's bugs or every shader. + +## Actual result and acceptance + +- **Astra:** 48.000 seconds, 720×1280, 24 fps, 1,152 decoded frames, voiced/subtitled. Three sampled repeat seeks matched exactly in the tested browser; a light-control edit changed the scene. Faces/hands remain puppet-like, material and architectural variety are limited, and jaw movement is approximate. +- **Fable 5.2:** authored the scene, soundtrack and 15-shot timeline, then hit its provider usage limit during visual refinement. The parent exported that saved source unchanged; hashes before/after confirm preservation. Both full video and original source are retained. The output is a **recovered unfinished draft**, not Fable's final approved delivery. +- **Recovered Fable export:** 48.000 seconds, 720×1280, 24 fps, 1,152 frames decoded without video errors. Light-control edit changed the render. A generic browser resource 404 was retained; its URL was not established, so it is not silently dismissed as a confirmed favicon request. +- **Seek defect:** frames 228 and 768 repeated exactly, but frame 960 changed 183,794 pixels; mean channel difference 7.128/255, maximum 238. The dragon's head direction visibly changes. The `better` shot reads the previous camera position for its gaze before setting the current camera, a likely cause from source inspection; a fix has not yet been verified. Successful sequential export does not pass random-access authoring. +- **Audio recovery:** initial decoded AAC peak was 1.372. The parent applied gain 0.5 at output while copying video unchanged; delivered peak measured 0.737. The original audio export is retained. This avoids the measured output overshoot but cannot undo distortion already present in the mix. +- **Visual limits:** rigid joints, sparse facial animation, awkward/oversized hand contact, strong light/bloom and the doorway transition. Fifteen shot stills and a 1 fps decoded sheet were inspected; there is no claim of normal-speed playback or exhaustive visual inspection of all 1,152 frames by the reviewer. + +The user prefers Fable's **visual direction**. Neither film reaches the reference's character finish; a general production-ready or deterministic story engine is not yet demonstrated. References supplied art direction; their screenshot pixels were not used as finished scene backgrounds. Preserve reference rights/provenance before redistributing any supplied images. + +## Story track: extend beyond the dungeon without constraining the core + +This is a new authored-story exercise, separate from **feature item 6 (camera solve)** and **feature item 13 (world reconstruction into splats/meshes)**. Code-generated geometry and known cameras do not validate either deferred feature. Also keep it distinct from the existing “many versions from one take” journey numbered 6. + +1. **ST1 — finish and stabilize this film.** Let Fable complete its own refinement when available. Correct the current-frame camera/gaze dependency and test random, repeated and reverse seeks across every shot and cut boundary; compare with sequential frames in the same renderer. Inspect normal/slow playback, all contact intervals, reach/support/release, camera-wall clipping and gaze. Repair highlight loss and audio gain; retain original versus corrected versions and explicit authorship. Verify each advertised control in both preview and export. No model call or wall-clock state inside frame rendering. +2. **ST2 — extract optional reusable authoring modules.** Separate character shape/face/rig, props and set dressing, action targets/contacts, shot/camera track, light track, material/contour/post look and dialogue/subtitle timing. Give selected controls stable IDs and source bindings; keep arbitrary source code and replacement renderers possible. Do not embed a mandatory fantasy vocabulary, actor taxonomy or model provider into the core. Existing film scripts are prototypes, not a shipped animation package. +3. **ST3 — test style transfer through code, not only palette changes.** Produce three additional short studies, for example a science-fiction repair shop, a sunny cel-shaded village and a clay/toy workshop. Use a common walk → dialogue → shared-prop action and camera brief while changing silhouettes, facial design, surface detail, set construction, light response and contour/post treatment. Retain the full editable sources and exact settings. Each style must pass its own whole-shot visual review; portability beyond the fantasy study is currently unproven. No new hosted spending is implied. +4. **ST4 — test practical reuse and host delivery.** Reuse an approved actor across shots and changes in framing, light, costume and dialogue; check identity, silhouettes and contact after edits. Regenerate local speech/alignment when dialogue changes rather than retaining stale audio. Bind source, assets and audio to project revisions and test save/reload, undo/redo and export parity in the host before claiming an integrated story workflow. Measure preview, capture time and peak memory on actual additional desktop/laptop machines; this Mac run establishes no performance floor for ordinary computers. + +Style is an open combination of authorable geometry, textures, rigs, cameras and lights, not a fixed list of “dungeon / office / cool” presets. Presets may be convenient starting points. Cross-style reuse and a useful agent authoring workflow must be earned by ST3/ST4, not inferred from parameter exposure alone. + +## Interaction work that remains + +The accepted pickup/handoff samples validate the selected staged joint-generation direction sufficiently to proceed with host implementation. Prioritize frozen scene-set capture, ordered reference roles/hashes, durable submission receipts, failed/ambiguous-job handling, actual decoded timing and accepted-take import; keep provider work outside rendering. Repeat the tests with both people identity-referenced and with difficult contact/occlusion before claiming broader reliability. Exact product geometry/print, multi-angle consistency, object–object collisions and animal interactions remain separate acceptance gates. The detailed [staged-generation report](staged-generation-results-2026-11-13.md) retains the observed action beats, estimates and limits. diff --git a/skills/editableframes/references/hybrid-compositing-plan.md b/skills/editableframes/references/hybrid-compositing-plan.md index 3831cca..952f674 100644 --- a/skills/editableframes/references/hybrid-compositing-plan.md +++ b/skills/editableframes/references/hybrid-compositing-plan.md @@ -1,5 +1,7 @@ # Reliable hybrid compositing and motion design +**Latest decisions (2026-11-13):** the user accepts the full-pickup and two-person handoff examples and prefers Fable 5.2’s visual direction for the 48-second code-generated fantasy story. [Results, technical comparison and story track ST1–ST4](code-generated-story-results-2026-11-13.md). The Fable draft is unfinished and fails a random-seek check; cross-style reuse is a planned experiment. Realistic joint generation and explicitly authored stylized animation are separate routes. + **Generated trials completed (2026-11-13):** [staged camera-left pickup and completed two-person handoff](staged-generation-results-2026-11-13.md), both returned to editable finishing. One take per case; exact product fidelity and native integration remain open. Estimated total US$1.90 under the fresh US$2 cap; account ledger unverified. **Local acceptance follow-up (2026-11-13):** [snapshot preparation, full-clip masks, tracker counterexample and continuous lighting](hybrid-acceptance-round1-2026-11-13.md). That earlier local checkpoint preceded the generated trials now recorded separately; camera solve (feature 6) and generated worlds (feature 13) remain untested. diff --git a/skills/editableframes/references/hybrid.md b/skills/editableframes/references/hybrid.md index 8688036..b180597 100644 --- a/skills/editableframes/references/hybrid.md +++ b/skills/editableframes/references/hybrid.md @@ -1,5 +1,7 @@ # Hybrid scenes: code inside footage +**Latest decisions (2026-11-13):** the user accepts the full-pickup and two-person handoff examples and prefers Fable 5.2’s visual direction for the 48-second code-generated fantasy story. [Results, technical comparison and story track ST1–ST4](code-generated-story-results-2026-11-13.md). The Fable draft is unfinished and fails a random-seek check; cross-style reuse is a planned experiment. Realistic joint generation and explicitly authored stylized animation are separate routes. + **Quality correction, 2026-11-11:** later review found erased fingers/heads, incorrect can placement and mismatched generated geometry in the example videos. Successful rendering and tracking do not establish whole-shot quality. See the [revised compositing and motion-design plan](hybrid-compositing-plan.md) for diagnoses, model/runtime research and proposed release gates. Those new features are planned, not implemented. A hybrid scene combines two kinds of picture in one shot: diff --git a/skills/editableframes/references/interaction-staging-workflow.md b/skills/editableframes/references/interaction-staging-workflow.md index 8b4a328..5b0e8f1 100644 --- a/skills/editableframes/references/interaction-staging-workflow.md +++ b/skills/editableframes/references/interaction-staging-workflow.md @@ -1,5 +1,7 @@ # Stage the scene, then generate the interaction +**Latest decisions (2026-11-13):** the user accepts the full-pickup and two-person handoff examples and prefers Fable 5.2’s visual direction for the 48-second code-generated fantasy story. [Results, technical comparison and story track ST1–ST4](code-generated-story-results-2026-11-13.md). The Fable draft is unfinished and fails a random-seek check; cross-style reuse is a planned experiment. Realistic joint generation and explicitly authored stylized animation are separate routes. + **Generated trials completed (2026-11-13):** [staged camera-left pickup and completed two-person handoff](staged-generation-results-2026-11-13.md), both returned to editable finishing. One take per case; exact product fidelity and native integration remain open. Estimated total US$1.90 under the fresh US$2 cap; account ledger unverified. **Local acceptance follow-up (2026-11-13):** [snapshot preparation, full-clip masks, tracker counterexample and continuous lighting](hybrid-acceptance-round1-2026-11-13.md). That earlier local checkpoint preceded the generated trials now recorded separately; camera solve (feature 6) and generated worlds (feature 13) remain untested. diff --git a/skills/editableframes/references/staged-generation-results-2026-11-13.md b/skills/editableframes/references/staged-generation-results-2026-11-13.md index eef6ab3..a93e190 100644 --- a/skills/editableframes/references/staged-generation-results-2026-11-13.md +++ b/skills/editableframes/references/staged-generation-results-2026-11-13.md @@ -1,5 +1,7 @@ # Staged generation tests — 2026-11-13 +**User visual acceptance (2026-11-13):** the user says the full-pickup and two-person handoff outputs look good. Treat these takes as accepted demonstrations of the staged joint-generation direction and proceed with the planned host workflow. This does not certify exact product fidelity, requested heft, repeatability, all-frame anatomy or native delivery, and is not a new independent Fable review. The original measurements below remain unchanged. [Combined conclusions and the separate authored-story experiment](code-generated-story-results-2026-11-13.md). + Follow-up to the local acceptance report. The user authorized a fresh US$2 total generation cap. Two sequential tests use the same provider/model and retain all inputs, raw outputs and failed-quality observations. This is a local preparation/finishing workflow, not completed native provider integration or an independent reviewer approval. ## Test A: authored snapshot → pickup From beef201392c5af6bd633f5211513d9ca3b3e2a21 Mon Sep 17 00:00:00 2001 From: Laurence Xavier <35849747+lxf82dev@users.noreply.github.com> Date: Fri, 13 Nov 2026 22:24:31 +0800 Subject: [PATCH 30/49] docs: map hybrid experiments and define shot-level video routes --- docs/hybrid-experiment-map.html | 7 ++ docs/hybrid-experiment-map.md | 167 +++++++++++++++++++++++++++ docs/hybrid-scenes.md | 14 +++ docs/media/hybrid-experiment-map.svg | 1 + 4 files changed, 189 insertions(+) create mode 100644 docs/hybrid-experiment-map.html create mode 100644 docs/hybrid-experiment-map.md create mode 100644 docs/media/hybrid-experiment-map.svg diff --git a/docs/hybrid-experiment-map.html b/docs/hybrid-experiment-map.html new file mode 100644 index 0000000..bc0a395 --- /dev/null +++ b/docs/hybrid-experiment-map.html @@ -0,0 +1,7 @@ +Video experiment map

How should we make this movie?

Build the stage. Make the action together. Combine the pieces. Pick the right tool for each shot.

Build with code

Like a toy theatre: keep the actors, lights and moves editable.

Make action together

Like filming a play: hands and props must share the same action.

Combine the pieces

Like a scrapbook: add words, cut-outs and backgrounds.

41 grouped trials · 8 areas

Counts group related attempts—not individual renders, equal-sized studies or a success rate. These include HTML scenes and the models that supplied their inputs.

● 12 Worked in this test● 21 Needs more work● 8 Missed the goal

“Worked” means only the stated check or user judgment passed. It does not mean ready for every video.

▱ Keep pictures in the right place 5 trialsA sticker must stay on its sign.

Clean synthetic tracker Worked in this test

A clean moving test card tracked very accurately.

Limit: Known-answer synthetic proof; not real-scene reliability.

Generated café, poster and phone Needs more work

Cards followed short moving clips, with manual corners and some drift.

Limit: Up to about 8 px café error despite high confidence; curved paper is not planar.

Real filmed box orbit Missed the goal

The sticker slid onto the next face of the box.

Limit: Blank surfaces and changing faces defeat this tracker.

Tracker confidence + reverse check Missed the goal

Forward and backward trackers agreed on the same wrong answer.

Limit: 6.861 px error with zero forward/backward disagreement; score correctness bug separately fixed.

Frame timing and colour export Worked in this test

Fixed repeated source frames and unwanted darkening.

Limit: Integer timestamp and colour-tag corrections; retained export checks.

▤ Put people in front of the right things 5 trialsA hand should hide what is behind it.

Original phone thumb + café head Missed the goal

Old overlays erased a thumb and covered hair.

Limit: Original outputs failed even when the rest of the video looked fine.

Repaired phone + café + native card Worked in this test

Reviewed masks kept the thumb, head and hair visible.

Limit: Works with manual tuning on retained shots; native café preview/export exercised.

Depth map with an added can Missed the goal

A hand cut through the extra can.

Limit: Depth tuning did not establish common scene geometry.

Wrap the original left can Worked in this test

Put the artwork on the existing can instead of adding another one.

Limit: Manual rigid-cylinder fit; the hand did not cross that original can.

Kinetic words and exact screen cards Worked in this test

Words enter, move and stay on their intended surface.

Limit: Retained titles/rows/wipes/spring/orbit/extrusion examples; broader style library not certified.

✂ Cut out hair, hands and products 5 trialsA cut-out edge needs more than scissors.

Avatar stills + bounded light matching Needs more work

Small colour changes preserve the original face.

Limit: Separate screenshots, not continuous speech; cannot create correct new directional shadows.

Local SAM 2 video + CPU fallback Needs more work

Followed people, hands and products through short clips.

Limit: Binary masks; preparation on one Mac, not live 24 fps or fine hair alpha.

Full pickup: SAM / RVM / guided alpha Needs more work

Processed the whole pickup and reduced some background spill.

Limit: 121 frames at 640×360; hair/edge errors remain, no annotated full-resolution pass.

Yellow-wall hair swap and repair Needs more work

Hair stopped disappearing as much after better preparation.

Limit: Improved source quality, prior-frame context and boundary repair; not all faults isolated.

Cut-out avatar pointing at headphones Missed the goal

The edges improved, but the person still did not convincingly present the object.

Limit: User rejected this route for interaction; zero overlap is not coherent gaze or contact.

☀ Make things belong in the light 7 trialsA lamp must light the object, not just glow.

Plate-based light guesses Needs more work

Sometimes found the useful side of the light; manual overrides mattered.

Limit: A bright surface or backlight can mislead the estimate.

Exact can on an empty generated stage Needs more work

Kept the product shape in code with an authored shadow.

Limit: Rendering worked; pasted-on lighting prompted the later lighting studies.

Local raster / WebGPU / Cycles Needs more work

All ran locally; corrected render tests were retained.

Limit: One Mac, unequal looks/tone maps and limited path-traced sequences; no best-computer claim.

DiffusionLight environment estimate Missed the goal

Invented lighting that did not fit the authored room.

Limit: Negative result for this scene, not a universal rejection of estimation.

IC-Light on exact artwork Missed the goal

Changed lettering and object detail.

Limit: Rejected for exact branded-object finishing; tests were stills, not a full relit video.

IC-Light on avatar stills / ratio hint Needs more work

A bounded hint kept original pixels; raw replacement changed facial detail.

Limit: Experimental still-image result; no temporal identity or light-direction acceptance.

One lamp changes warm → cool Needs more work

The cup and table responded, but the pastry barely did.

Limit: Baked photographed background stayed unchanged; per-object response must be checked.

◈ Try real and designed products 9 trialsCorrect shape matters as much as pretty light.

LUMA, SPRIG, CROWN & ROOT cans Needs more work

More detailed packaging helped; red design was preferred.

Limit: Lids, reflections, droplets, label seams and motion still needed refinement.

12 products × 6 lighting setups Needs more work

Expanded to PCs, phones, watches, cameras and lifestyle products.

Limit: 72 cases / 22 sequences; Fable found flat faces, decal shadows, weak metals and glass faults.

Oura / Garmin / Nothing photographs Needs more work

Recognisable products work as cut-outs and layouts.

Limit: Colour matching only: baked highlights and unseen sides cannot be relit or spun out.

Framework photo + grille repair Worked in this test

Improved small-detail downsampling for the layout.

Limit: Context photo only, not a relighting test or full temporal aliasing certification.

iPhone / Galaxy / MacBook 3D assets Needs more work

MacBook responded to moving lights after fixes.

Limit: iPhone/Galaxy assets rejected for hero shots; MacBook remains a limited screen carrier.

Two copies: spin, orbit and overlap Worked in this test

The nearer object drew in front in the tested crossing poses.

Limit: 35 poses; photo copies still have no real turn; mutual reflections/bounce untested.

Photos-to-3D product attempt Missed the goal

The generated model did not preserve the needed materials.

Limit: An importable mesh is not yet a faithful commercial product.

Glass, liquid and ice scenes Needs more work

Rendered scenes, but nested transparent parts could vanish.

Limit: Raster limitations; limited Cycles trials were not a matched-quality comparison.

Pastry, ceramic, plants, furniture, jewelry Needs more work

Broadened the material and scene tests.

Limit: Grounding, fabrics, jewelry detail and simple billboard steam remained weak.

↔ Make people show and hand over a product 5 trialsBodies must agree about the same action.

HeyGen Avatar IV + Atmee pointing Needs more work

Both made a presenter talk and gesture in a detailed room.

Limit: Requested gesture timing was not followed; these outputs were flattened video.

HeyGen walk, pickup and carry Needs more work

An explicit standing start gave the best framing.

Limit: Product detail drift and late speech remained.

Kling references + video-edit pickup Needs more work

Joint generation improved looking, gripping and holding.

Limit: The early upright position and camera-left instruction were not fully corrected.

Approved snapshot → full pickup Worked in this test

Camera-left placement and pickup looked good to the user.

Limit: One accepted example; heft is weak, exact geometry and lettering unproven.

Two-person handoff Worked in this test

Receiver supports it; giver lets go. The user likes the result.

Limit: One accepted example; second person lacked an identity reference.

♜ Build an animated story with code 2 trialsBuild the stage, actors and their moves.

Astra fantasy RPG film Needs more work

48 seconds of voiced, subtitled, editable 3D storytelling.

Limit: Three repeat seeks passed; faces and hands look more puppet-like than references.

Fable 5.2 fantasy RPG film Needs more work

User prefers its richer sets, proportions and cinematic direction.

Limit: 48-second recovered draft; usage limit interrupted refinement; one seek test fails.

↻ Keep the work editable and safe to repeat 3 trialsSave the recipe, not only the movie.

Clean staging snapshot + reference packet Worked in this test

Kept the chosen layout and reference order in a saved packet.

Limit: Local Scene Studio/packet checks; full native provider workflow still pending.

Generated clips → editable finishing Worked in this test

Titles, prices and other code layers remain changeable after generation.

Limit: Hands, product motion and room light inside the footage remain baked.

Clay/depth/normal/object-ID control passes Worked in this test

The authored scene can emit these inputs for another tool.

Limit: No successful hosted control-video restyling round trip established.

\ No newline at end of file diff --git a/docs/hybrid-experiment-map.md b/docs/hybrid-experiment-map.md new file mode 100644 index 0000000..c906575 --- /dev/null +++ b/docs/hybrid-experiment-map.md @@ -0,0 +1,167 @@ +# What we tried, and where code-generated video fits + +Checkpoint: 2026-11-13. [Interactive experiment map](hybrid-experiment-map.html) · [Static infographic](media/hybrid-experiment-map.svg). + +**41 grouped trial entries across 8 areas.** These are an inventory of related attempts, not 41 independent jobs, equal-sized experiments or a success-rate benchmark. They include the local browser/HTML scene studies and the model/preparation steps used by those compositions. Superseded failures stay visible beside later repairs. This is not a claim to enumerate every frame or revision. + +**Legend:** “Worked in this test” means the specifically stated check or user judgment succeeded; it does not mean production-ready. “Needs more work” has a useful partial result. “Missed the goal” records a failed use case, not a universal ban on a technology. Proposed work appears separately. + +## The debate: a strong direction, not an unlimited promise + +**The user’s forecast:** future LLMs may eventually author almost any game-look or fantasy video. We adopt this as a direction to explore, not a verified promise about Fable 5.5, Fable 6, release dates or permanent vendor leadership. One preferred film does not rank providers in general. + +**The strongest case for it.** Code can retain the world, cast, actions, cameras and lights as a reusable recipe. Once a rig or set works, the next scene can reuse it. Stylized art often tolerates simplified surfaces, and a game aesthetic fits real-time renderers naturally. Better authoring, better assets and better rendering tools can compound. Our two complete 48-second exports establish that this route already makes coherent short, voiced scenes; Fable’s richer assets and direction were preferred. + +**The strongest objection.** Writing valid code is not the same as directing believable acting. Anatomy, facial performance, contact, eyelines, cloth, sound, camera cuts, continuity and taste need work even when the program runs. Rendering time, memory and source-asset quality do not disappear with a smarter LLM. Fable’s unfinished draft still fails one random-seek check. We have neither a multi-episode test nor a benchmark on ordinary laptops. Cross-style portability is a hypothesis awaiting ST3, not a result. + +**The line is not cartoon versus real.** Code can render a realistic product if it has faithful geometry and materials. A fantasy battle can still be cheaper or better as a simulated or generated shot. The useful question is: *what must remain changeable or exact, and do we own the representation needed to change it?* + +## Choose a route for each shot—and sometimes each layer + +1. **Build with code** when we can author the shapes, rigs and motion and need repeatable edits: price, UI, product layout, a known camera, stylized characters, diagrams or an approved CAD model. Geometry being editable does not make an invented mesh accurate. Exact labels require correct artwork and a validated render. +2. **Make the action together** when independently composited people/objects cannot convincingly share gaze, grip, weight or support. Use a single choreographed rig/simulation, filmed performance, or jointly generated shot. Our chosen realistic-avatar route is approved staging → snapshot + references → joint generation → review. This is a workflow default from our trials, not a claim that realistic CG interaction is impossible. +3. **Combine independent pieces** when their relationship is mostly placement, visibility and colour: captions, titles, background swaps, a presenter beside a diagram, a pinned screen. Masks solve who hides whom; they do not create acting, contact, reflections or lighting geometry. +4. **Use genuine footage** when the shot claims a real event, testimony, actual gameplay or measured product behaviour. Code can clarify and annotate it. Synthetic footage may be a labelled illustration, not proof. + +An interaction group should share one performance. For example, the two people, their hands and the transferred product belong together. A separate price card can remain code outside that group. A generated clip is editable as a clip—trim, crop, grade, replace—but its internal fingers, product motion and room lighting are baked. Moving a product afterward without its hand requires regeneration or a separately validated reconstruction/rig. + +### Example: one 60-second advert can use several routes + +Illustrative edit, **not a tested deliverable**: + +| Time | Section | Route | Why | +|---|---|---|---| +| 0–5 s | Animated headline | Code | Exact words and motion. | +| 5–15 s | Product turns with specifications | Code + approved 3D asset | Repeatable angle and exact information; asset fidelity gate. | +| 15–30 s | Seller picks up and hands over product | Filmed or jointly generated action | Shared support, gaze and contact. Generated product accuracy must be reviewed. | +| 30–40 s | Interface / feature explanation | Code, with captured UI where necessary | Changeable callouts and correct screen content. | +| 40–55 s | Customer testimonial | Genuine authorised recording | Real testimony must remain real. | +| 55–60 s | Price and call to action | Code | Versions without regenerating the performance. | + +A fantasy episode can likewise mix authored dialogue with a difficult simulated/generated insert. That mixed story round trip has not been tested here. + +## What “unlimited lighting options” means + +The warm/cool/office labels are starting settings, not a closed menu. Direction, position, size, colour, intensity, environment, material and time can vary continuously. But a control only changes representations it reaches: a 3D light can light a mesh; it cannot recover the back of a photograph or remove baked shadows from footage. A new visible lamp needs illumination on nearby surfaces, appropriate shadows/reflections and consistent changes over time. Our lamp sweep exposed weak pastry response and an unchanged photographed background. Mixed human/product relighting is still an open gate. + +## Decisions and next experiments + +- Keep code-authored storytelling as a first-class, open authoring route. Build optional rig/action/set/look modules rather than a mandatory dungeon template or fixed genre list. +- Finish **ST1** before calling the Fable draft dependable: fix seek state, inspect acting/contact/cut boundaries, check audio and exposed controls in preview/export. Then extract reusable parts (**ST2**). +- For **ST3**, use the same walk → dialogue → shared-prop brief in a sci-fi workshop, cel-shaded village and toy/clay scene. Change shapes, faces, motion, sets and lighting as well as palette. A style counts only after whole-shot review and seek checks. +- For **ST4**, keep the same actor through scene/light/dialogue edits, test save/reload and host export, and measure additional real computers. Do not extrapolate one Mac into a minimum supported laptop specification. +- Keep the accepted realistic pickup/handoff route; implement durable scene-set capture, ordered references, job recovery and accepted-take import. Repeat with both people identity-referenced and difficult contact before claiming reliability. +- Keep feature **6 (camera solve)** and **13 (world reconstruction)** explicitly untested. Authored fantasy worlds establish neither. + +**Evidence and review status:** this synthesis uses retained renders, source inspection, measurements, user judgments and earlier Fable reviews. Those are different kinds of evidence. No new render, paid model call or fresh Fable review was performed for this map. Fable’s recorded provider limit prevented a new consultation at this checkpoint. Its earlier findings challenge rendering/material/interaction claims; they are not approval of this new debate or the unfinished story draft. + +## Video categories and the present evidence + +| Category | Likely route | What we know | Boundary | +|---|---|---|---| +| Fantasy / RPG / game-like stories | Build with code | Two 48-second fantasy drafts; user prefers Fable. | New styles, longer acting and reliable seeking remain unproven. | +| Sci-fi, cartoons, toy/clay and mascot stories | Build with code | Plausible next studies, not demonstrated styles. | Need new silhouettes, rigs, sets and movement—not only new colours. | +| Lessons, diagrams and animated explainers | Build + combine | Exact text, graphics and moving cards exercised. | A complete educational film and factual review are separate tests. | +| Product ads, assembly and digital showrooms | Build + combine | Product rendering, moving copies and layouts exercised. | Faithful CAD/materials and approved artwork matter; a photo has no hidden back. | +| Game trailers / architectural walkthroughs | Build or use captured footage | The scene/camera machinery is relevant; no dedicated acceptance. | A generated reenactment is not evidence of real gameplay or a real building. | +| People talking, demonstrating or handing over | Make the action together | Pickup and handoff accepted; standalone avatar tests have limits. | Film it or jointly generate it. Do not glue an unrelated gesture onto a product. | +| Hair, cloth, fluids, crowds and destruction | Choose per shot | Hair cut-out and simple glass/liquid studies only. | May need authored simulation, specialist assets or generated footage; cost matters. | +| News, interviews, testimonials and real events | Use genuine footage + code | This is an authenticity requirement, not an experiment result. | Preserve recorded evidence; a convincing synthetic performance cannot replace it. | + +## Inventory of studies already tried + +### Keep pictures in the right place + +A sticker must stay on its sign. + +- **Clean synthetic tracker — Worked in this test.** A clean moving test card tracked very accurately. **Limit:** Known-answer synthetic proof; not real-scene reliability. Evidence: [hybrid-scenes.md](hybrid-scenes.md). +- **Generated café, poster and phone — Needs more work.** Cards followed short moving clips, with manual corners and some drift. **Limit:** Up to about 8 px café error despite high confidence; curved paper is not planar. Evidence: [hybrid-scenes.md](hybrid-scenes.md). Context summary; the detailed trial remains in the retained study records. +- **Real filmed box orbit — Missed the goal.** The sticker slid onto the next face of the box. **Limit:** Blank surfaces and changing faces defeat this tracker. Evidence: [hybrid-scenes.md](hybrid-scenes.md). Context summary; the detailed trial remains in the retained study records. +- **Tracker confidence + reverse check — Missed the goal.** Forward and backward trackers agreed on the same wrong answer. **Limit:** 6.861 px error with zero forward/backward disagreement; score correctness bug separately fixed. Evidence: [hybrid-analysis-study-2026-11-13.md](hybrid-analysis-study-2026-11-13.md). +- **Frame timing and colour export — Worked in this test.** Fixed repeated source frames and unwanted darkening. **Limit:** Integer timestamp and colour-tag corrections; retained export checks. Evidence: [hybrid-scenes.md](hybrid-scenes.md). Context summary; the detailed trial remains in the retained study records. + +### Put people in front of the right things + +A hand should hide what is behind it. + +- **Original phone thumb + café head — Missed the goal.** Old overlays erased a thumb and covered hair. **Limit:** Original outputs failed even when the rest of the video looked fine. Evidence: [hybrid-compositing-plan.md](hybrid-compositing-plan.md). Context summary; the detailed trial remains in the retained study records. +- **Repaired phone + café + native card — Worked in this test.** Reviewed masks kept the thumb, head and hair visible. **Limit:** Works with manual tuning on retained shots; native café preview/export exercised. Evidence: [hybrid-compositing-plan.md](hybrid-compositing-plan.md). Context summary; the detailed trial remains in the retained study records. +- **Depth map with an added can — Missed the goal.** A hand cut through the extra can. **Limit:** Depth tuning did not establish common scene geometry. Evidence: [hybrid-scenes.md](hybrid-scenes.md). Context summary; the detailed trial remains in the retained study records. +- **Wrap the original left can — Worked in this test.** Put the artwork on the existing can instead of adding another one. **Limit:** Manual rigid-cylinder fit; the hand did not cross that original can. Evidence: [hybrid-compositing-plan.md](hybrid-compositing-plan.md). Context summary; the detailed trial remains in the retained study records. +- **Kinetic words and exact screen cards — Worked in this test.** Words enter, move and stay on their intended surface. **Limit:** Retained titles/rows/wipes/spring/orbit/extrusion examples; broader style library not certified. Evidence: [hybrid-compositing-plan.md](hybrid-compositing-plan.md). Context summary; the detailed trial remains in the retained study records. + +### Cut out hair, hands and products + +A cut-out edge needs more than scissors. + +- **Avatar stills + bounded light matching — Needs more work.** Small colour changes preserve the original face. **Limit:** Separate screenshots, not continuous speech; cannot create correct new directional shadows. Evidence: [avatar-lighting.md](avatar-lighting.md). +- **Local SAM 2 video + CPU fallback — Needs more work.** Followed people, hands and products through short clips. **Limit:** Binary masks; preparation on one Mac, not live 24 fps or fine hair alpha. Evidence: [hybrid-analysis-study-2026-11-13.md](hybrid-analysis-study-2026-11-13.md). +- **Full pickup: SAM / RVM / guided alpha — Needs more work.** Processed the whole pickup and reduced some background spill. **Limit:** 121 frames at 640×360; hair/edge errors remain, no annotated full-resolution pass. Evidence: [hybrid-acceptance-round1-2026-11-13.md](hybrid-acceptance-round1-2026-11-13.md). +- **Yellow-wall hair swap and repair — Needs more work.** Hair stopped disappearing as much after better preparation. **Limit:** Improved source quality, prior-frame context and boundary repair; not all faults isolated. Evidence: Retained local study: `mask-composition/retry/README.md` (not bundled here). +- **Cut-out avatar pointing at headphones — Missed the goal.** The edges improved, but the person still did not convincingly present the object. **Limit:** User rejected this route for interaction; zero overlap is not coherent gaze or contact. Evidence: [avatar-lighting.md](avatar-lighting.md). Context summary; the detailed trial remains in the retained study records. + +### Make things belong in the light + +A lamp must light the object, not just glow. + +- **Plate-based light guesses — Needs more work.** Sometimes found the useful side of the light; manual overrides mattered. **Limit:** A bright surface or backlight can mislead the estimate. Evidence: [hybrid-scenes.md](hybrid-scenes.md). Context summary; the detailed trial remains in the retained study records. +- **Exact can on an empty generated stage — Needs more work.** Kept the product shape in code with an authored shadow. **Limit:** Rendering worked; pasted-on lighting prompted the later lighting studies. Evidence: [hybrid-compositing-plan.md](hybrid-compositing-plan.md). Context summary; the detailed trial remains in the retained study records. +- **Local raster / WebGPU / Cycles — Needs more work.** All ran locally; corrected render tests were retained. **Limit:** One Mac, unequal looks/tone maps and limited path-traced sequences; no best-computer claim. Evidence: Retained local study: `review-resolution.txt` (not bundled here). +- **DiffusionLight environment estimate — Missed the goal.** Invented lighting that did not fit the authored room. **Limit:** Negative result for this scene, not a universal rejection of estimation. Evidence: Retained local study: `fable-review.txt` (not bundled here). +- **IC-Light on exact artwork — Missed the goal.** Changed lettering and object detail. **Limit:** Rejected for exact branded-object finishing; tests were stills, not a full relit video. Evidence: Retained local study: `fable-review.txt` (not bundled here). +- **IC-Light on avatar stills / ratio hint — Needs more work.** A bounded hint kept original pixels; raw replacement changed facial detail. **Limit:** Experimental still-image result; no temporal identity or light-direction acceptance. Evidence: [avatar-lighting.md](avatar-lighting.md). +- **One lamp changes warm → cool — Needs more work.** The cup and table responded, but the pastry barely did. **Limit:** Baked photographed background stayed unchanged; per-object response must be checked. Evidence: [hybrid-acceptance-round1-2026-11-13.md](hybrid-acceptance-round1-2026-11-13.md). + +### Try real and designed products + +Correct shape matters as much as pretty light. + +- **LUMA, SPRIG, CROWN & ROOT cans — Needs more work.** More detailed packaging helped; red design was preferred. **Limit:** Lids, reflections, droplets, label seams and motion still needed refinement. Evidence: Retained local study: `beverage-design/fable-design-review.txt` (not bundled here). +- **12 products × 6 lighting setups — Needs more work.** Expanded to PCs, phones, watches, cameras and lifestyle products. **Limit:** 72 cases / 22 sequences; Fable found flat faces, decal shadows, weak metals and glass faults. Evidence: Retained local study: `product-lab/fable-expanded-review.txt` (not bundled here). +- **Oura / Garmin / Nothing photographs — Needs more work.** Recognisable products work as cut-outs and layouts. **Limit:** Colour matching only: baked highlights and unseen sides cannot be relit or spun out. Evidence: [avatar-lighting.md](avatar-lighting.md). Context summary; the detailed trial remains in the retained study records. +- **Framework photo + grille repair — Worked in this test.** Improved small-detail downsampling for the layout. **Limit:** Context photo only, not a relighting test or full temporal aliasing certification. Evidence: [avatar-lighting.md](avatar-lighting.md). Context summary; the detailed trial remains in the retained study records. +- **iPhone / Galaxy / MacBook 3D assets — Needs more work.** MacBook responded to moving lights after fixes. **Limit:** iPhone/Galaxy assets rejected for hero shots; MacBook remains a limited screen carrier. Evidence: [avatar-lighting.md](avatar-lighting.md). Context summary; the detailed trial remains in the retained study records. +- **Two copies: spin, orbit and overlap — Worked in this test.** The nearer object drew in front in the tested crossing poses. **Limit:** 35 poses; photo copies still have no real turn; mutual reflections/bounce untested. Evidence: [avatar-lighting.md](avatar-lighting.md). Context summary; the detailed trial remains in the retained study records. +- **Photos-to-3D product attempt — Missed the goal.** The generated model did not preserve the needed materials. **Limit:** An importable mesh is not yet a faithful commercial product. Evidence: [hybrid-compositing-plan.md](hybrid-compositing-plan.md). Context summary; the detailed trial remains in the retained study records. +- **Glass, liquid and ice scenes — Needs more work.** Rendered scenes, but nested transparent parts could vanish. **Limit:** Raster limitations; limited Cycles trials were not a matched-quality comparison. Evidence: Retained local study: `scene-lab/README.txt` (not bundled here). +- **Pastry, ceramic, plants, furniture, jewelry — Needs more work.** Broadened the material and scene tests. **Limit:** Grounding, fabrics, jewelry detail and simple billboard steam remained weak. Evidence: Retained local study: `scene-lab/README.txt` (not bundled here). + +### Make people show and hand over a product + +Bodies must agree about the same action. + +- **HeyGen Avatar IV + Atmee pointing — Needs more work.** Both made a presenter talk and gesture in a detailed room. **Limit:** Requested gesture timing was not followed; these outputs were flattened video. Evidence: [avatar-lighting.md](avatar-lighting.md). Context summary; the detailed trial remains in the retained study records. +- **HeyGen walk, pickup and carry — Needs more work.** An explicit standing start gave the best framing. **Limit:** Product detail drift and late speech remained. Evidence: [avatar-lighting.md](avatar-lighting.md). Context summary; the detailed trial remains in the retained study records. +- **Kling references + video-edit pickup — Needs more work.** Joint generation improved looking, gripping and holding. **Limit:** The early upright position and camera-left instruction were not fully corrected. Evidence: [interaction-staging-workflow.md](interaction-staging-workflow.md). +- **Approved snapshot → full pickup — Worked in this test.** Camera-left placement and pickup looked good to the user. **Limit:** One accepted example; heft is weak, exact geometry and lettering unproven. Evidence: [staged-generation-results-2026-11-13.md](staged-generation-results-2026-11-13.md). +- **Two-person handoff — Worked in this test.** Receiver supports it; giver lets go. The user likes the result. **Limit:** One accepted example; second person lacked an identity reference. Evidence: [staged-generation-results-2026-11-13.md](staged-generation-results-2026-11-13.md). + +### Build an animated story with code + +Build the stage, actors and their moves. + +- **Astra fantasy RPG film — Needs more work.** 48 seconds of voiced, subtitled, editable 3D storytelling. **Limit:** Three repeat seeks passed; faces and hands look more puppet-like than references. Evidence: [code-generated-story-results-2026-11-13.md](code-generated-story-results-2026-11-13.md). +- **Fable 5.2 fantasy RPG film — Needs more work.** User prefers its richer sets, proportions and cinematic direction. **Limit:** 48-second recovered draft; usage limit interrupted refinement; one seek test fails. Evidence: [code-generated-story-results-2026-11-13.md](code-generated-story-results-2026-11-13.md). + +### Keep the work editable and safe to repeat + +Save the recipe, not only the movie. + +- **Clean staging snapshot + reference packet — Worked in this test.** Kept the chosen layout and reference order in a saved packet. **Limit:** Local Scene Studio/packet checks; full native provider workflow still pending. Evidence: [hybrid-acceptance-round1-2026-11-13.md](hybrid-acceptance-round1-2026-11-13.md). +- **Generated clips → editable finishing — Worked in this test.** Titles, prices and other code layers remain changeable after generation. **Limit:** Hands, product motion and room light inside the footage remain baked. Evidence: [staged-generation-results-2026-11-13.md](staged-generation-results-2026-11-13.md). +- **Clay/depth/normal/object-ID control passes — Worked in this test.** The authored scene can emit these inputs for another tool. **Limit:** No successful hosted control-video restyling round trip established. Evidence: [hybrid-scenes.md](hybrid-scenes.md). + +## Not yet established + +- **SAM 3 video:** Access/runtime gate; no accuracy comparison with SAM 2. +- **Camera solve · feature 6:** No accepted real 3D camera reconstruction. +- **Reconstructed worlds · feature 13:** No splat/mesh reconstruction test; a code-authored world is different. +- **Cloth/skin reskin + automatic contact:** No general deforming-surface or physical interaction solver. +- **More story styles:** Sci-fi, cel village and clay/toy styles are proposed, not tested. +- **Longer episodes and persistent cast:** No multi-episode identity/performance acceptance. +- **Ordinary-computer coverage:** No robust Windows/Linux/modest-laptop benchmark. +- **Native generation handoff:** Local packets exist; full capture/job/recovery/import flow remains to be delivered. +- **Complex interaction breadth:** Object collisions, animals, crowds and repeated two-person identity tests remain open. +- **Stronger human video relighting:** No complete mixed human/product emitter and temporal-identity pass. + +For the source-level Fable/Astra comparison and ST1–ST4 acceptance, see [the story report](code-generated-story-results-2026-11-13.md). For the accepted interaction takes and costs, see [the staged-generation report](staged-generation-results-2026-11-13.md). diff --git a/docs/hybrid-scenes.md b/docs/hybrid-scenes.md index 2bc42a6..78e3715 100644 --- a/docs/hybrid-scenes.md +++ b/docs/hybrid-scenes.md @@ -1,5 +1,19 @@ # Hybrid scenes: code inside footage +## Start here: what we tried, and which tool fits the shot + +[![Eight areas of video experiments: tracking, layers, masks, lighting, products, actors, stories and workflow. Build with code, make actions together, or combine pieces.](media/hybrid-experiment-map.svg)](hybrid-experiment-map.html) + +**[Open the interactive HTML map](hybrid-experiment-map.html)** · **[Read the full inventory and debate](hybrid-experiment-map.md)**. The HTML file opens locally in a browser; GitHub shows this static infographic and the Markdown evidence. No server or model call is needed. + +The map records **41 grouped trial entries in eight areas**, including failed attempts and later repairs. “Worked” means only the stated check or user judgment succeeded. It is not a production-readiness score. Ten remaining research/integration areas are listed separately. + +**Current position:** code-authored game-like storytelling is a promising, expandable route. Future LLM capability is a forecast; the preferred Fable fantasy draft is evidence of one short style, not every genre or a general provider ranking. Choose by the shot’s required accuracy, editability and shared action—not simply cartoon versus realistic. Exact graphics and authored worlds favour code; realistic handling trials favour staged joint generation; genuine testimony requires recorded evidence. Independent masks cannot create a shared performance. + +The HTML includes simple route illustrations, searchable trial cards, the strongest arguments on both sides, a category map and an illustrative mixed-route advert. This synthesis draws on existing Fable reviews; no fresh Fable endorsement was obtained during its recorded provider-limit window. + +--- + **Latest decisions (2026-11-13):** the user accepts the full-pickup and two-person handoff examples and prefers Fable 5.2’s visual direction for the 48-second code-generated fantasy story. [Results, technical comparison and story track ST1–ST4](code-generated-story-results-2026-11-13.md). The Fable draft is unfinished and fails a random-seek check; cross-style reuse is a planned experiment. Realistic joint generation and explicitly authored stylized animation are separate routes. **Generated trials completed (2026-11-13):** [staged camera-left pickup and completed two-person handoff](staged-generation-results-2026-11-13.md), both returned to editable finishing. One take per case; exact product fidelity and native integration remain open. Estimated total US$1.90 under the fresh US$2 cap; account ledger unverified. diff --git a/docs/media/hybrid-experiment-map.svg b/docs/media/hybrid-experiment-map.svg new file mode 100644 index 0000000..7a99973 --- /dev/null +++ b/docs/media/hybrid-experiment-map.svg @@ -0,0 +1 @@ +Our video experiment mapEight areas tested. Some checks worked, many still need work. Code builds editable scenes; joint action keeps bodies together; composition combines pieces. Choose per shot.Build a movie like a storybook41 grouped trials • 8 areas • findings, not a production scoreBUILD ITCode owns the stage and moves.MAKE ACTION TOGETHERHands and props share one act.COMBINE PIECESMasks, text and video fit together.Tracking: stay on the sign2 worked1 partial2 missedA sticker must stay on its sign.Layers: keep hands in front3 worked0 partial2 missedA hand should hide what is behind it.Masks: keep the hair0 worked4 partial1 missedA cut-out edge needs more than scissors.Lighting: match the room0 worked5 partial2 missedA lamp must light the object, not just glow.Products: shape and material2 worked6 partial1 missedCorrect shape matters as much as pretty light.Actors: share the same action2 worked3 partial0 missedBodies must agree about the same action.Stories: build a talking cast0 worked2 partial0 missedBuild the stage, actors and their moves.Workflow: save the recipe3 worked0 partial0 missedSave the recipe, not only the movie.Choose by the shot, not just the style.A realistic product can be code. A fantasy action can be generated.A mask fixes the edge. It cannot teach a hand to hold something.Worked = only the stated test passed. Partial = more work. Missed = failed this goal.Not yet proven: other story styles, long episodes, camera solve, reconstructed worlds. \ No newline at end of file From b4351d3b0ca32a63a9c457ccfa1234c782c968a1 Mon Sep 17 00:00:00 2001 From: Laurence Xavier <35849747+lxf82dev@users.noreply.github.com> Date: Sat, 14 Nov 2026 01:53:10 +0800 Subject: [PATCH 31/49] Support explicit Chromium selection and record verified hybrid subchecks --- bin/editableframe.mjs | 3 +- ...code-generated-story-results-2026-11-13.md | 2 + docs/hybrid-experiment-map.html | 4 +- docs/hybrid-experiment-map.md | 2 + docs/hybrid-gap-closure-2026-11-14.md | 40 +++++++++++++++++++ docs/hybrid-scenes.md | 6 ++- docs/renderer-contract.md | 7 ++++ scripts/browser.mjs | 14 +++++++ scripts/project.mjs | 2 +- scripts/render.mjs | 5 ++- ...code-generated-story-results-2026-11-13.md | 2 + .../hybrid-gap-closure-2026-11-14.md | 40 +++++++++++++++++++ skills/editableframes/references/hybrid.md | 29 +++++++++++++- skills/editableframes/references/renderer.md | 7 ++++ tests/browser-config.test.mjs | 22 ++++++++++ 15 files changed, 176 insertions(+), 9 deletions(-) create mode 100644 docs/hybrid-gap-closure-2026-11-14.md create mode 100644 scripts/browser.mjs create mode 100644 skills/editableframes/references/hybrid-gap-closure-2026-11-14.md create mode 100644 tests/browser-config.test.mjs diff --git a/bin/editableframe.mjs b/bin/editableframe.mjs index accf3f5..0b39644 100755 --- a/bin/editableframe.mjs +++ b/bin/editableframe.mjs @@ -1,4 +1,5 @@ #!/usr/bin/env node +import {chromiumOptions} from '../scripts/browser.mjs'; import fs from 'node:fs/promises';import path from 'node:path'; import {root,buildApps} from '../scripts/build.mjs';import {serve} from '../scripts/server.mjs';import {init,readProject,mutate,preview,rebind,importAsset} from '../scripts/project.mjs'; const [cmd,...args]=process.argv.slice(2),out=v=>console.log(JSON.stringify(v,null,2)); @@ -15,7 +16,7 @@ try{ else if(cmd==='render'){const {render}=await import('../scripts/render.mjs');const option=name=>{const i=args.indexOf(name);return i<0?undefined:args[i+1]};const controller=new AbortController();process.once('SIGINT',()=>controller.abort());out(await render(args[0],args[1],{frames:option('--frames')?Number(option('--frames')):args[2]&&!args[2].startsWith('--')?Number(args[2]):undefined,fps:option('--fps'),format:option('--format'),background:option('--background'),pass:option('--pass'),motionBlur:option('--motion-blur')?{angle:Number(option('--motion-blur')),samples:option('--samples')?Number(option('--samples')):8}:undefined,signal:controller.signal,onProgress:p=>{if(p.phase!=='frames'||p.frame%24===0)console.error(JSON.stringify(p))}}))} else if(cmd==='assets'){const {run}=await import('../scripts/assets.mjs');await run(args)} else if(cmd==='install-skill'){const {install}=await import('../scripts/install-skill.mjs');out(await install(args[0],args[1]))} - else if(cmd==='doctor'){const {run,ffmpeg,ffprobe}=await import('../scripts/process.mjs');const {chromium}=await import('playwright');const checks={};for(const [name,command]of [['ffmpeg',ffmpeg()],['ffprobe',ffprobe()]]){try{checks[name]=(await run(command,['-version'])).toString().split('\n')[0]}catch(e){checks[name]='MISSING: '+e.message}}try{await fs.access(chromium.executablePath());checks.browser='installed'}catch{checks.browser='MISSING: run npx playwright install chromium'}out({node:process.version,version:'0.1.0-beta.1',platform:process.platform,checks,ready:Object.values(checks).every(x=>!x.startsWith('MISSING')),trust:'Local trusted source; not an untrusted-code sandbox',distribution:'source-checkout',npmPublished:false})} + else if(cmd==='doctor'){const {run,ffmpeg,ffprobe}=await import('../scripts/process.mjs');const {chromium}=await import('playwright');const checks={};for(const [name,command]of [['ffmpeg',ffmpeg()],['ffprobe',ffprobe()]]){try{checks[name]=(await run(command,['-version'])).toString().split('\n')[0]}catch(e){checks[name]='MISSING: '+e.message}}try{const options=chromiumOptions();await fs.access(options.executablePath??chromium.executablePath());checks.browser=options.executablePath?'configured executable exists (launch checked during render)':'Playwright Chromium exists (launch checked during render)'}catch(e){checks.browser='MISSING: '+e.message+'; install Playwright Chromium or set EDITABLEFRAMES_CHROMIUM_EXECUTABLE to an existing compatible browser'}out({node:process.version,version:'0.1.0-beta.1',platform:process.platform,checks,ready:Object.values(checks).every(x=>!x.startsWith('MISSING')),trust:'Local trusted source; not an untrusted-code sandbox',distribution:'source-checkout',npmPublished:false})} else if(!cmd||cmd==='help'||cmd==='--help')console.log(`EditableFrames 0.1.0-beta.1\n\n init DIR [--media|--renderer|--hybrid] Create an editable clip (media and hybrid demos need FFmpeg)\n rebind DIR [--reset] Accept edited source; archive prior project\n inspect DIR JSON controls + current file revision\n apply DIR proposal.json Revision-checked atomic edit\n undo DIR | redo DIR Saved edit history\n preview DIR [PORT] Preview trusted code on loopback\n render DIR OUTPUT [--frames N] [--fps 30000/1001] [--format png]\n [--pass clay|depth|normal|id|matte] [--motion-blur ANGLE [--samples N]]\n .mp4 = opaque; .mov = alpha ProRes4444\n asset-add DIR ID FILE Pin local media; rebind then swap a port\n [--role alpha|matte|depth|normals|track|camera|environment|analysis|surface|coverage|foreground --of PLATE_ID [--subject ID]]\n [--depth inverse|linear --near N --far F] Data derived from a plate\n studio [PORT] Open all bundled studies and device library\n assets list|verify|pack|install-pack [FILE]\n install-skill codex|claude|grok|generic TARGET\n doctor Show environment requirements\n\nCustom clip modules are executable JavaScript. Use trusted projects.\nNo model, account, cloud service, or Stitchable installation required.`); else throw Error('Unknown command. Run editableframes help'); }catch(e){console.error(e.message);process.exitCode=1} diff --git a/docs/code-generated-story-results-2026-11-13.md b/docs/code-generated-story-results-2026-11-13.md index 000d9ff..edf1668 100644 --- a/docs/code-generated-story-results-2026-11-13.md +++ b/docs/code-generated-story-results-2026-11-13.md @@ -1,5 +1,7 @@ # Interaction acceptance and code-generated story films — 2026-11-13 +> **2026-11-14 follow-up:** the original Fable worker resumed, repaired camera/gaze state dependence and completed the film. Independent checks reproduce 1,152 frames, 228 new seek samples and all 12 controls; a three-frame CLI edit/undo specimen also passes. Earlier unfinished-draft failures below are historical. Acting/contact, native integration and style reuse remain open. See [current evidence](hybrid-gap-closure-2026-11-14.md). + ## Decisions from the latest outputs The user accepts the visual direction of the full-pickup and two-person handoff outputs and prefers the Fable 5.2 story film as closer to the supplied fantasy-game references. These are **user visual acceptance and preference**, not independent certification of every frame, exact product fidelity, or a completed Fable review. The two model implementations are one creative exercise, with different refinement histories; they are not a general model benchmark. diff --git a/docs/hybrid-experiment-map.html b/docs/hybrid-experiment-map.html index bc0a395..8b2451b 100644 --- a/docs/hybrid-experiment-map.html +++ b/docs/hybrid-experiment-map.html @@ -1,7 +1,7 @@ -Video experiment map

How should we make this movie?

Build the stage. Make the action together. Combine the pieces. Pick the right tool for each shot.

Build with code

Like a toy theatre: keep the actors, lights and moves editable.

Make action together

Like filming a play: hands and props must share the same action.

Combine the pieces

Like a scrapbook: add words, cut-outs and backgrounds.

41 grouped trials · 8 areas

Counts group related attempts—not individual renders, equal-sized studies or a success rate. These include HTML scenes and the models that supplied their inputs.

● 12 Worked in this test● 21 Needs more work● 8 Missed the goal

“Worked” means only the stated check or user judgment passed. It does not mean ready for every video.

▱ Keep pictures in the right place 5 trialsA sticker must stay on its sign.

Clean synthetic tracker Worked in this test

A clean moving test card tracked very accurately.

Limit: Known-answer synthetic proof; not real-scene reliability.

Generated café, poster and phone Needs more work

Cards followed short moving clips, with manual corners and some drift.

Limit: Up to about 8 px café error despite high confidence; curved paper is not planar.

Real filmed box orbit Missed the goal

The sticker slid onto the next face of the box.

Limit: Blank surfaces and changing faces defeat this tracker.

Tracker confidence + reverse check Missed the goal

Forward and backward trackers agreed on the same wrong answer.

Limit: 6.861 px error with zero forward/backward disagreement; score correctness bug separately fixed.

Frame timing and colour export Worked in this test

Fixed repeated source frames and unwanted darkening.

Limit: Integer timestamp and colour-tag corrections; retained export checks.

▤ Put people in front of the right things 5 trialsA hand should hide what is behind it.

Original phone thumb + café head Missed the goal

Old overlays erased a thumb and covered hair.

Limit: Original outputs failed even when the rest of the video looked fine.

Repaired phone + café + native card Worked in this test

Reviewed masks kept the thumb, head and hair visible.

Limit: Works with manual tuning on retained shots; native café preview/export exercised.

Depth map with an added can Missed the goal

A hand cut through the extra can.

Limit: Depth tuning did not establish common scene geometry.

Wrap the original left can Worked in this test

Put the artwork on the existing can instead of adding another one.

Limit: Manual rigid-cylinder fit; the hand did not cross that original can.

Kinetic words and exact screen cards Worked in this test

Words enter, move and stay on their intended surface.

Limit: Retained titles/rows/wipes/spring/orbit/extrusion examples; broader style library not certified.

✂ Cut out hair, hands and products 5 trialsA cut-out edge needs more than scissors.

Avatar stills + bounded light matching Needs more work

Small colour changes preserve the original face.

Limit: Separate screenshots, not continuous speech; cannot create correct new directional shadows.

Local SAM 2 video + CPU fallback Needs more work

Followed people, hands and products through short clips.

Limit: Binary masks; preparation on one Mac, not live 24 fps or fine hair alpha.

Full pickup: SAM / RVM / guided alpha Needs more work

Processed the whole pickup and reduced some background spill.

Limit: 121 frames at 640×360; hair/edge errors remain, no annotated full-resolution pass.

Yellow-wall hair swap and repair Needs more work

Hair stopped disappearing as much after better preparation.

Limit: Improved source quality, prior-frame context and boundary repair; not all faults isolated.

Cut-out avatar pointing at headphones Missed the goal

The edges improved, but the person still did not convincingly present the object.

Limit: User rejected this route for interaction; zero overlap is not coherent gaze or contact.

☀ Make things belong in the light 7 trialsA lamp must light the object, not just glow.

Plate-based light guesses Needs more work

Sometimes found the useful side of the light; manual overrides mattered.

Limit: A bright surface or backlight can mislead the estimate.

Exact can on an empty generated stage Needs more work

Kept the product shape in code with an authored shadow.

Limit: Rendering worked; pasted-on lighting prompted the later lighting studies.

Local raster / WebGPU / Cycles Needs more work

All ran locally; corrected render tests were retained.

Limit: One Mac, unequal looks/tone maps and limited path-traced sequences; no best-computer claim.

DiffusionLight environment estimate Missed the goal

Invented lighting that did not fit the authored room.

Limit: Negative result for this scene, not a universal rejection of estimation.

IC-Light on exact artwork Missed the goal

Changed lettering and object detail.

Limit: Rejected for exact branded-object finishing; tests were stills, not a full relit video.

IC-Light on avatar stills / ratio hint Needs more work

A bounded hint kept original pixels; raw replacement changed facial detail.

Limit: Experimental still-image result; no temporal identity or light-direction acceptance.

One lamp changes warm → cool Needs more work

The cup and table responded, but the pastry barely did.

Limit: Baked photographed background stayed unchanged; per-object response must be checked.

◈ Try real and designed products 9 trialsCorrect shape matters as much as pretty light.

LUMA, SPRIG, CROWN & ROOT cans Needs more work

More detailed packaging helped; red design was preferred.

Limit: Lids, reflections, droplets, label seams and motion still needed refinement.

12 products × 6 lighting setups Needs more work

Expanded to PCs, phones, watches, cameras and lifestyle products.

Limit: 72 cases / 22 sequences; Fable found flat faces, decal shadows, weak metals and glass faults.

Oura / Garmin / Nothing photographs Needs more work

Recognisable products work as cut-outs and layouts.

Limit: Colour matching only: baked highlights and unseen sides cannot be relit or spun out.

Framework photo + grille repair Worked in this test

Improved small-detail downsampling for the layout.

Limit: Context photo only, not a relighting test or full temporal aliasing certification.

iPhone / Galaxy / MacBook 3D assets Needs more work

MacBook responded to moving lights after fixes.

Limit: iPhone/Galaxy assets rejected for hero shots; MacBook remains a limited screen carrier.

Two copies: spin, orbit and overlap Worked in this test

The nearer object drew in front in the tested crossing poses.

Limit: 35 poses; photo copies still have no real turn; mutual reflections/bounce untested.

Photos-to-3D product attempt Missed the goal

The generated model did not preserve the needed materials.

Limit: An importable mesh is not yet a faithful commercial product.

Glass, liquid and ice scenes Needs more work

Rendered scenes, but nested transparent parts could vanish.

Limit: Raster limitations; limited Cycles trials were not a matched-quality comparison.

Pastry, ceramic, plants, furniture, jewelry Needs more work

Broadened the material and scene tests.

Limit: Grounding, fabrics, jewelry detail and simple billboard steam remained weak.

↔ Make people show and hand over a product 5 trialsBodies must agree about the same action.

HeyGen Avatar IV + Atmee pointing Needs more work

Both made a presenter talk and gesture in a detailed room.

Limit: Requested gesture timing was not followed; these outputs were flattened video.

HeyGen walk, pickup and carry Needs more work

An explicit standing start gave the best framing.

Limit: Product detail drift and late speech remained.

Kling references + video-edit pickup Needs more work

Joint generation improved looking, gripping and holding.

Limit: The early upright position and camera-left instruction were not fully corrected.

Approved snapshot → full pickup Worked in this test

Camera-left placement and pickup looked good to the user.

Limit: One accepted example; heft is weak, exact geometry and lettering unproven.

Two-person handoff Worked in this test

Receiver supports it; giver lets go. The user likes the result.

Limit: One accepted example; second person lacked an identity reference.

♜ Build an animated story with code 2 trialsBuild the stage, actors and their moves.

Astra fantasy RPG film Needs more work

48 seconds of voiced, subtitled, editable 3D storytelling.

Limit: Three repeat seeks passed; faces and hands look more puppet-like than references.

Fable 5.2 fantasy RPG film Needs more work

User prefers its richer sets, proportions and cinematic direction.

Limit: 48-second recovered draft; usage limit interrupted refinement; one seek test fails.

↻ Keep the work editable and safe to repeat 3 trialsSave the recipe, not only the movie.

Clean staging snapshot + reference packet Worked in this test

Kept the chosen layout and reference order in a saved packet.

Limit: Local Scene Studio/packet checks; full native provider workflow still pending.

Generated clips → editable finishing Worked in this test

Titles, prices and other code layers remain changeable after generation.

Limit: Hands, product motion and room light inside the footage remain baked.

Clay/depth/normal/object-ID control passes Worked in this test

The authored scene can emit these inputs for another tool.

Limit: No successful hosted control-video restyling round trip established.

\ No newline at end of file +show("closure"); \ No newline at end of file diff --git a/docs/hybrid-experiment-map.md b/docs/hybrid-experiment-map.md index c906575..698f384 100644 --- a/docs/hybrid-experiment-map.md +++ b/docs/hybrid-experiment-map.md @@ -1,5 +1,7 @@ # What we tried, and where code-generated video fits +> **2026-11-14 follow-up:** the original Fable worker resumed, repaired camera/gaze state dependence and completed the film. Independent checks reproduce 1,152 frames, 228 new seek samples and all 12 controls; a three-frame CLI edit/undo specimen also passes. Earlier unfinished-draft failures below are historical. Acting/contact, native integration and style reuse remain open. See [current evidence](hybrid-gap-closure-2026-11-14.md). + Checkpoint: 2026-11-13. [Interactive experiment map](hybrid-experiment-map.html) · [Static infographic](media/hybrid-experiment-map.svg). **41 grouped trial entries across 8 areas.** These are an inventory of related attempts, not 41 independent jobs, equal-sized experiments or a success-rate benchmark. They include the local browser/HTML scene studies and the model/preparation steps used by those compositions. Superseded failures stay visible beside later repairs. This is not a claim to enumerate every frame or revision. diff --git a/docs/hybrid-gap-closure-2026-11-14.md b/docs/hybrid-gap-closure-2026-11-14.md new file mode 100644 index 0000000..65e3712 --- /dev/null +++ b/docs/hybrid-gap-closure-2026-11-14.md @@ -0,0 +1,40 @@ +# Hybrid gap closure — 2026-11-14 checkpoint + +This is an active research checkpoint. The [experiment dashboard](hybrid-experiment-map.html) now has a Gap closure tab with scoped subchecks, attempts and retained artifact descriptions. No whole work item is declared finished. No new hosted-model calls were made in this round. + +| Work item | New measured evidence | What remains | +|---|---|---| +| ST1: dependable authored story | Resumed original Fable film completed. Coordinator reproduced all 1,152 sequential frame hashes, 228 new shuffled/reverse/cut-adjacent checks and all 12 exposed control changes/restorations. | Acting, physical contact, face finish, soundtrack listening, native app integration and other hardware. | +| ST1: CLI delivery specimen | Three source frames (228, 696, 960) exported through the current CLI. Exposure edit changes all three; stale proposal rejected; undo restores pixels exactly. | This is three sampled frames, not full-film audio export or desktop acceptance. | +| TRACK1: misleading confidence | Target-interior texture diagnostic flags all 49 frames of the retained synthetic wrong-track case. Six new regressions and 13 existing plate tests pass. | Geometry is unchanged: worst error 6.861 px at correlation 0.956. Wrong textured planes can evade this warning. Original real-footage failures remain unavailable. | +| FLOW1: recoverable generation | Network-free local prototype passes 11 crash/concurrency/input/output fault tests using retained real pickup and handoff media. | Native transport/UI, actual provider reconciliation and atomic managed-asset import. No claim of provider idempotency or prevented real charges. | +| ST2–3: reusable cast / contrasting styles | New Fable worker read source/APIs, then hit provider usage limit before creating a new style artifact. | Resume when available. Quota failure is not a failed visual method and provides no style-quality evidence. | +| LIGHT1: moving product illumination | Separate Opus study assigned current corrected assets and matched before/after acceptance. | Await delivered evidence and independent verification; do not count a running task as success. | + +## Story: the earlier failed draft is historical + +The original Fable worker resumed and fixed two shot routines that read camera position before setting the current frame's camera. Its final film remains 48 seconds, 720×1280, 24 fps. The earlier recovered draft and failed seek result are retained; they are superseded for current runtime acceptance, not erased. + +The coordinator performed a fresh full sequential pass, additional seek samples, and one change/restoration per declared control. No page or resource errors appeared in that pass. These are same-machine, same-browser comparisons. They do not prove pixel identity on another GPU/browser or high-quality acting. The source still uses painted facial detail, rigid body segments, approximate lip-sync, stock speech and system fonts. Audio level/timing measurements are not a listening review. + +The CLI specimen exposed a missing managed Chromium installation even though another compatible Chromium existed. An explicit `EDITABLEFRAMES_CHROMIUM_EXECUTABLE` option now selects an existing absolute executable path, with no automatic download or silent fallback. Rendering verifies launch and records the browser version plus whether an override was configured. `doctor` checks file presence; it does not claim launch compatibility. A runtime-source change intentionally requires project rebind under the existing binding contract. The CLI specimen passed after explicit rebind. All 136 SDK unit tests pass, including configuration validation and distribution documentation consistency. + +## Tracking: a useful warning is not a repaired track + +The diagnostic samples the selected quad's interior, excluding its surrounding template margin, and checks spatially distributed two-axis texture. It identifies blank targets, a single edge, concentrated detail and out-of-frame support. Its thresholds are heuristic, not calibrated accuracy probabilities. The result reports `accuracy_verified: false`; even distributed texture does not approve identity or visibility. + +The comparison video shows the same wrong geometry before and after, with an added review warning. Do not interpret the warning as a correct replacement surface, an automatic hide/reject decision, a new tracker, or a visual-native-UI feature. Independent surface identity, occlusion recovery and boundary accuracy remain research gates. + +## Generation workflow: tested contract before host integration + +The local prototype freezes scene revision, action, provider/model and ordered reference hashes. It persists an attempt marker before any external transport would begin. A forced process exit at that point reopens as ambiguous; automatic retry is refused. Explicit provider-ID reconciliation can resume the record. Two concurrent owners cannot both start the same row. + +Changed reference order/bytes, changed endpoint/action and stale revisions are rejected. Decoding is separate from visual acceptance. Corrupt or failed replacements preserve the last accepted take across restart; a modified output cannot be accepted. Variable-rate media requires an explicit conform step. + +The retained pickup decodes to **121 frames / 5.041667 s**, and the handoff to **169 frames / 7.041667 s**, both 1280×720 at 24 fps. Requested five/seven-second durations must not replace measured timing. + +Limits: this local SQLite prototype assumes one transport owner has stopped before recovery. Its local approval field is not an authorization boundary. Mutable file paths need atomic managed-asset import. No actual provider timeout, credit reconciliation, authenticated desktop integration or new paid request was exercised. + +## Remaining gates + +Hair/contact whole-clip evidence, mixed human/product directional lighting, nested transparent materials, real additional computers, SAM 3 access/runtime, camera solve (feature 6), and reconstructed worlds (feature 13) remain open. Authored fantasy scenes do not complete camera solve or world reconstruction. Neither a completed worker nor passing integrity tests establishes visual production readiness. diff --git a/docs/hybrid-scenes.md b/docs/hybrid-scenes.md index 78e3715..2e6adbf 100644 --- a/docs/hybrid-scenes.md +++ b/docs/hybrid-scenes.md @@ -14,7 +14,9 @@ The HTML includes simple route illustrations, searchable trial cards, the strong --- -**Latest decisions (2026-11-13):** the user accepts the full-pickup and two-person handoff examples and prefers Fable 5.2’s visual direction for the 48-second code-generated fantasy story. [Results, technical comparison and story track ST1–ST4](code-generated-story-results-2026-11-13.md). The Fable draft is unfinished and fails a random-seek check; cross-style reuse is a planned experiment. Realistic joint generation and explicitly authored stylized animation are separate routes. +**Gap closure checkpoint (2026-11-14):** [Verified subchecks, retained failures and remaining gates](hybrid-gap-closure-2026-11-14.md). The completed Fable film now passes independent seeking/control checks and a three-frame CLI edit/undo specimen. Target-texture warnings and a local recovery prototype add safeguards; tracking geometry, native integration and visual acting remain open. + +**Latest decisions (2026-11-13):** the user accepts the full-pickup and two-person handoff examples and prefers Fable 5.2’s visual direction for the 48-second code-generated fantasy story. [Results, technical comparison and story track ST1–ST4](code-generated-story-results-2026-11-13.md). At that checkpoint the Fable draft was unfinished and failed a random-seek check. The resumed film now passes the scoped runtime checks above; cross-style reuse remains a planned experiment. Realistic joint generation and explicitly authored stylized animation are separate routes. **Generated trials completed (2026-11-13):** [staged camera-left pickup and completed two-person handoff](staged-generation-results-2026-11-13.md), both returned to editable finishing. One take per case; exact product fidelity and native integration remain open. Estimated total US$1.90 under the fresh US$2 cap; account ledger unverified. @@ -61,7 +63,7 @@ Each journey says what the author does, what EditableFrames does, and how far it | 6 | **Many versions from one take.** The same shot in twenty prices, five languages, three label colours. | One plate and its data, then control edits. | Re-renders each version from the same pinned inputs. If the plate is replaced, its old matte, depth and track are refused instead of being composited slightly wrong. | Integration test for the refusals; edits use the existing revision-checked history. | | 7 | **Fast motion.** Code elements that move quickly should smear like the footage does. | A shutter angle. | Renders several sub-frame samples per output frame and averages them. | Integration test: smear width and edge colour. | | 8 | **A moving camera.** The product stays put in a shot whose camera travels. | A camera path solved elsewhere. | Replays the path on a Three.js camera, with rotation interpolated correctly. | Unit tests only. Not yet tried on a real solve; solves of generated footage are approximate. | -| 9 | **An authored stylized story.** Characters move and speak in a code-built world. | Character/set assets or procedural source, rigs, shot/action/light tracks and prepared speech. | Renders authored geometry and sampled animation with exposed controls; no implicit model call. | Two 48-second local SDK films; Fable visual direction user-preferred, interrupted draft has a seek defect. [Story findings and next tests](code-generated-story-results-2026-11-13.md). No native story editor or cross-style portability claim. | +| 9 | **An authored stylized story.** Characters move and speak in a code-built world. | Character/set assets or procedural source, rigs, shot/action/light tracks and prepared speech. | Renders authored geometry and sampled animation with exposed controls; no implicit model call. | Two 48-second local SDK films; Fable visual direction user-preferred; resumed film passes same-machine sequential/seek/control checks and a three-frame CLI specimen. [Story findings and next tests](code-generated-story-results-2026-11-13.md). No native story editor or cross-style portability claim. | The integration tests use a synthetic plate. [On generated footage](#on-generated-footage) says what a trial on plates from video models found. diff --git a/docs/renderer-contract.md b/docs/renderer-contract.md index daa2185..994ae92 100644 --- a/docs/renderer-contract.md +++ b/docs/renderer-contract.md @@ -72,6 +72,13 @@ SVG and WebGL descendants. PNG and ProRes preserve alpha; MP4 flattens over the requested background. `window.editableframes.captureTarget` describes the capture selector for browser harnesses. `png()` remains the legacy Canvas-only shortcut. This is trusted local browser execution, not isolation from malicious authored code. +The CLI normally uses Playwright's managed Chromium. To use an already installed, +compatible Chromium explicitly, set `EDITABLEFRAMES_CHROMIUM_EXECUTABLE` to its +absolute executable path. `doctor` checks that configured file; `render` verifies +it can actually launch. This opt-in does not download a browser or silently fall +back. Record the browser version with visual evidence; cross-version pixel +identity is not promised. + For WebGL, retain the rendered drawing buffer for capture (for example, `preserveDrawingBuffer: true`) and await required GPU work. Cross-browser/GPU/font pixel identity is not promised. diff --git a/scripts/browser.mjs b/scripts/browser.mjs new file mode 100644 index 0000000..ce08b0c --- /dev/null +++ b/scripts/browser.mjs @@ -0,0 +1,14 @@ +import path from 'node:path'; +import {statSync} from 'node:fs'; + +// Explicit opt-in to a locally managed Chromium; never download or silently +// substitute a different browser when the Playwright-managed one is missing. +export function chromiumOptions(env = process.env) { + const executablePath = env.EDITABLEFRAMES_CHROMIUM_EXECUTABLE; + if (!executablePath) return {}; + if (!path.isAbsolute(executablePath)) throw Error('EDITABLEFRAMES_CHROMIUM_EXECUTABLE must be an absolute path'); + let file; + try { file = statSync(executablePath); } catch { throw Error('EDITABLEFRAMES_CHROMIUM_EXECUTABLE does not name an existing file'); } + if (!file.isFile()) throw Error('EDITABLEFRAMES_CHROMIUM_EXECUTABLE must name a browser executable file'); + return {executablePath}; +} diff --git a/scripts/project.mjs b/scripts/project.mjs index 71a5078..477b500 100644 --- a/scripts/project.mjs +++ b/scripts/project.mjs @@ -9,7 +9,7 @@ export async function definition(dir){ dir=await fs.realpath(dir);const file=path.join(dir,'clip.mjs'); const bundled=await build({entryPoints:[file],bundle:true,format:'esm',platform:'browser',write:false,minify:true,nodePaths:[path.join(root,'node_modules')],plugins:[publicPackagePlugin()]}); const assets=await readAssets(dir);const assetIdentity=Object.fromEntries(Object.entries(assets).map(([id,{file,...rest}])=>[id,rest])); - const runtimeFiles=['packages/core/rotation.mjs','packages/core/spatial-session.mjs','packages/three/spatial-math.mjs','packages/three/spatial-editor.mjs','packages/core/key-timing.mjs','packages/core/manipulation.mjs','packages/three/manipulation.mjs','packages/core/index.mjs','packages/core/animation.mjs','packages/core/host.mjs','packages/core/renderer.mjs','packages/core/controls.mjs','packages/core/objects.mjs','packages/core/interaction.mjs','packages/core/definition.mjs','packages/runtime/renderer-host.mjs','packages/runtime/renderer-compositor.mjs','packages/runtime/editor.mjs','packages/runtime/compositor.mjs','packages/media/ports.mjs','packages/media/browser.mjs','packages/media/audio-plan.mjs','packages/media/playback.mjs','scripts/render.mjs','scripts/audio.mjs','package-lock.json']; + const runtimeFiles=['packages/core/rotation.mjs','packages/core/spatial-session.mjs','packages/three/spatial-math.mjs','packages/three/spatial-editor.mjs','packages/core/key-timing.mjs','packages/core/manipulation.mjs','packages/three/manipulation.mjs','packages/core/index.mjs','packages/core/animation.mjs','packages/core/host.mjs','packages/core/renderer.mjs','packages/core/controls.mjs','packages/core/objects.mjs','packages/core/interaction.mjs','packages/core/definition.mjs','packages/runtime/renderer-host.mjs','packages/runtime/renderer-compositor.mjs','packages/runtime/editor.mjs','packages/runtime/compositor.mjs','packages/media/ports.mjs','packages/media/browser.mjs','packages/media/audio-plan.mjs','packages/media/playback.mjs','scripts/render.mjs','scripts/browser.mjs','scripts/audio.mjs','package-lock.json']; const runtimeIdentity=Object.fromEntries(await Promise.all(runtimeFiles.map(async file=>[file,hash(await fs.readFile(path.join(root,file)))]))); const binding=hash(Buffer.concat([Buffer.from(bundled.outputFiles[0].contents),Buffer.from(JSON.stringify(runtimeIdentity)),Buffer.from(JSON.stringify(assetIdentity))])); const normalized=normalizeClipModule(await import('data:text/javascript;base64,'+Buffer.from(bundled.outputFiles[0].contents).toString('base64'))); diff --git a/scripts/render.mjs b/scripts/render.mjs index ee14bb4..4116400 100644 --- a/scripts/render.mjs +++ b/scripts/render.mjs @@ -1,3 +1,4 @@ +import {chromiumOptions} from './browser.mjs'; import fs from 'node:fs/promises';import path from 'node:path';import {randomUUID} from 'node:crypto';import {chromium} from 'playwright'; import {preview,readProject} from './project.mjs';import {mixAudio} from './audio.mjs';import {run,ffmpeg,ffprobe} from './process.mjs';import {HZ} from '../packages/core/index.mjs';import {shutterSamples,validateShutter} from '../packages/plate/motion-blur.mjs'; export function frameRate(value={num:24,den:1}){ @@ -22,7 +23,7 @@ export async function render(dir,output,{fps,frames,format,background='#101922', const abort=()=>browser?.close().catch(()=>{});signal?.addEventListener('abort',abort,{once:true}); try{ onProgress({phase:'media',progress:0});host=await preview(dir,{port:0,editable:false,signal,snapshot:d}); - browser=await chromium.launch({headless:true,args:['--enable-webgl',process.platform==='darwin'?'--use-angle=metal':'--use-angle=swiftshader']}); + browser=await chromium.launch({...chromiumOptions(),headless:true,args:['--enable-webgl',process.platform==='darwin'?'--use-angle=metal':'--use-angle=swiftshader']}); const page=await browser.newPage();page.on('pageerror',e=>errors.push(e.message));await page.goto(host.url);await page.waitForFunction(()=>window.editableframe?.ready,{},{timeout:30000}); const frameDir=path.join(temp,'frames'),sampleDir=path.join(temp,'samples');await fs.mkdir(frameDir);if(shutter)await fs.mkdir(sampleDir); for(let frame=0;frames.codec_type==='video')||audio.tracks&&!info.streams.some(s=>s.codec_type==='audio'))throw Error('Encoded media failed stream validation'); } signal?.throwIfAborted(); - const receipt={version:1,engine:'editableframe',binding:d.binding,projectRevision:d.revision,fps:rate,frames:count,duration:actualDuration,format,alpha:format!=='mp4',pass,motionBlur:shutter,runtime:d.runtimeIdentity,browser:browser.version(),ffmpeg:(await run(ffmpeg(),['-version'])).toString().split('\n')[0],platform:process.platform,background:format==='mp4'?background:null,audio:audio.tracks>0,audioTracks:audio.tracks,assets:Object.fromEntries(Object.entries(d.assets).map(([id,a])=>[id,a.sha256]))}; + const receipt={configuredBrowser:Boolean(process.env.EDITABLEFRAMES_CHROMIUM_EXECUTABLE),version:1,engine:'editableframe',binding:d.binding,projectRevision:d.revision,fps:rate,frames:count,duration:actualDuration,format,alpha:format!=='mp4',pass,motionBlur:shutter,runtime:d.runtimeIdentity,browser:browser.version(),ffmpeg:(await run(ffmpeg(),['-version'])).toString().split('\n')[0],platform:process.platform,background:format==='mp4'?background:null,audio:audio.tracks>0,audioTracks:audio.tracks,assets:Object.fromEntries(Object.entries(d.assets).map(([id,a])=>[id,a.sha256]))}; // Reserve the receipt path, and publish a complete file without overwriting another writer. const receiptFile=output+'.json',fd=await fs.open(receiptFile,'wx');let published=false; try{await fd.writeFile(JSON.stringify(receipt,null,2));await fd.sync();if(format==='png'){await absent(output);await fs.rename(result,output)}else await fs.link(result,output);published=true}finally{await fd.close();if(!published)await fs.rm(receiptFile,{force:true})} diff --git a/skills/editableframes/references/code-generated-story-results-2026-11-13.md b/skills/editableframes/references/code-generated-story-results-2026-11-13.md index 000d9ff..edf1668 100644 --- a/skills/editableframes/references/code-generated-story-results-2026-11-13.md +++ b/skills/editableframes/references/code-generated-story-results-2026-11-13.md @@ -1,5 +1,7 @@ # Interaction acceptance and code-generated story films — 2026-11-13 +> **2026-11-14 follow-up:** the original Fable worker resumed, repaired camera/gaze state dependence and completed the film. Independent checks reproduce 1,152 frames, 228 new seek samples and all 12 controls; a three-frame CLI edit/undo specimen also passes. Earlier unfinished-draft failures below are historical. Acting/contact, native integration and style reuse remain open. See [current evidence](hybrid-gap-closure-2026-11-14.md). + ## Decisions from the latest outputs The user accepts the visual direction of the full-pickup and two-person handoff outputs and prefers the Fable 5.2 story film as closer to the supplied fantasy-game references. These are **user visual acceptance and preference**, not independent certification of every frame, exact product fidelity, or a completed Fable review. The two model implementations are one creative exercise, with different refinement histories; they are not a general model benchmark. diff --git a/skills/editableframes/references/hybrid-gap-closure-2026-11-14.md b/skills/editableframes/references/hybrid-gap-closure-2026-11-14.md new file mode 100644 index 0000000..65e3712 --- /dev/null +++ b/skills/editableframes/references/hybrid-gap-closure-2026-11-14.md @@ -0,0 +1,40 @@ +# Hybrid gap closure — 2026-11-14 checkpoint + +This is an active research checkpoint. The [experiment dashboard](hybrid-experiment-map.html) now has a Gap closure tab with scoped subchecks, attempts and retained artifact descriptions. No whole work item is declared finished. No new hosted-model calls were made in this round. + +| Work item | New measured evidence | What remains | +|---|---|---| +| ST1: dependable authored story | Resumed original Fable film completed. Coordinator reproduced all 1,152 sequential frame hashes, 228 new shuffled/reverse/cut-adjacent checks and all 12 exposed control changes/restorations. | Acting, physical contact, face finish, soundtrack listening, native app integration and other hardware. | +| ST1: CLI delivery specimen | Three source frames (228, 696, 960) exported through the current CLI. Exposure edit changes all three; stale proposal rejected; undo restores pixels exactly. | This is three sampled frames, not full-film audio export or desktop acceptance. | +| TRACK1: misleading confidence | Target-interior texture diagnostic flags all 49 frames of the retained synthetic wrong-track case. Six new regressions and 13 existing plate tests pass. | Geometry is unchanged: worst error 6.861 px at correlation 0.956. Wrong textured planes can evade this warning. Original real-footage failures remain unavailable. | +| FLOW1: recoverable generation | Network-free local prototype passes 11 crash/concurrency/input/output fault tests using retained real pickup and handoff media. | Native transport/UI, actual provider reconciliation and atomic managed-asset import. No claim of provider idempotency or prevented real charges. | +| ST2–3: reusable cast / contrasting styles | New Fable worker read source/APIs, then hit provider usage limit before creating a new style artifact. | Resume when available. Quota failure is not a failed visual method and provides no style-quality evidence. | +| LIGHT1: moving product illumination | Separate Opus study assigned current corrected assets and matched before/after acceptance. | Await delivered evidence and independent verification; do not count a running task as success. | + +## Story: the earlier failed draft is historical + +The original Fable worker resumed and fixed two shot routines that read camera position before setting the current frame's camera. Its final film remains 48 seconds, 720×1280, 24 fps. The earlier recovered draft and failed seek result are retained; they are superseded for current runtime acceptance, not erased. + +The coordinator performed a fresh full sequential pass, additional seek samples, and one change/restoration per declared control. No page or resource errors appeared in that pass. These are same-machine, same-browser comparisons. They do not prove pixel identity on another GPU/browser or high-quality acting. The source still uses painted facial detail, rigid body segments, approximate lip-sync, stock speech and system fonts. Audio level/timing measurements are not a listening review. + +The CLI specimen exposed a missing managed Chromium installation even though another compatible Chromium existed. An explicit `EDITABLEFRAMES_CHROMIUM_EXECUTABLE` option now selects an existing absolute executable path, with no automatic download or silent fallback. Rendering verifies launch and records the browser version plus whether an override was configured. `doctor` checks file presence; it does not claim launch compatibility. A runtime-source change intentionally requires project rebind under the existing binding contract. The CLI specimen passed after explicit rebind. All 136 SDK unit tests pass, including configuration validation and distribution documentation consistency. + +## Tracking: a useful warning is not a repaired track + +The diagnostic samples the selected quad's interior, excluding its surrounding template margin, and checks spatially distributed two-axis texture. It identifies blank targets, a single edge, concentrated detail and out-of-frame support. Its thresholds are heuristic, not calibrated accuracy probabilities. The result reports `accuracy_verified: false`; even distributed texture does not approve identity or visibility. + +The comparison video shows the same wrong geometry before and after, with an added review warning. Do not interpret the warning as a correct replacement surface, an automatic hide/reject decision, a new tracker, or a visual-native-UI feature. Independent surface identity, occlusion recovery and boundary accuracy remain research gates. + +## Generation workflow: tested contract before host integration + +The local prototype freezes scene revision, action, provider/model and ordered reference hashes. It persists an attempt marker before any external transport would begin. A forced process exit at that point reopens as ambiguous; automatic retry is refused. Explicit provider-ID reconciliation can resume the record. Two concurrent owners cannot both start the same row. + +Changed reference order/bytes, changed endpoint/action and stale revisions are rejected. Decoding is separate from visual acceptance. Corrupt or failed replacements preserve the last accepted take across restart; a modified output cannot be accepted. Variable-rate media requires an explicit conform step. + +The retained pickup decodes to **121 frames / 5.041667 s**, and the handoff to **169 frames / 7.041667 s**, both 1280×720 at 24 fps. Requested five/seven-second durations must not replace measured timing. + +Limits: this local SQLite prototype assumes one transport owner has stopped before recovery. Its local approval field is not an authorization boundary. Mutable file paths need atomic managed-asset import. No actual provider timeout, credit reconciliation, authenticated desktop integration or new paid request was exercised. + +## Remaining gates + +Hair/contact whole-clip evidence, mixed human/product directional lighting, nested transparent materials, real additional computers, SAM 3 access/runtime, camera solve (feature 6), and reconstructed worlds (feature 13) remain open. Authored fantasy scenes do not complete camera solve or world reconstruction. Neither a completed worker nor passing integrity tests establishes visual production readiness. diff --git a/skills/editableframes/references/hybrid.md b/skills/editableframes/references/hybrid.md index b180597..96463d5 100644 --- a/skills/editableframes/references/hybrid.md +++ b/skills/editableframes/references/hybrid.md @@ -1,6 +1,32 @@ # Hybrid scenes: code inside footage -**Latest decisions (2026-11-13):** the user accepts the full-pickup and two-person handoff examples and prefers Fable 5.2’s visual direction for the 48-second code-generated fantasy story. [Results, technical comparison and story track ST1–ST4](code-generated-story-results-2026-11-13.md). The Fable draft is unfinished and fails a random-seek check; cross-style reuse is a planned experiment. Realistic joint generation and explicitly authored stylized animation are separate routes. +## Start here: what we tried, and which tool fits the shot + +[![Eight areas of video experiments: tracking, layers, masks, lighting, products, actors, stories and workflow. Build with code, make actions together, or combine pieces.](media/hybrid-experiment-map.svg)](hybrid-experiment-map.html) + +**[Open the interactive HTML map](hybrid-experiment-map.html)** · **[Read the full inventory and debate](hybrid-experiment-map.md)**. The HTML file opens locally in a browser; GitHub shows this static infographic and the Markdown evidence. No server or model call is needed. + +The map records **41 grouped trial entries in eight areas**, including failed attempts and later repairs. “Worked” means only the stated check or user judgment succeeded. It is not a production-readiness score. Ten remaining research/integration areas are listed separately. + +**Current position:** code-authored game-like storytelling is a promising, expandable route. Future LLM capability is a forecast; the preferred Fable fantasy draft is evidence of one short style, not every genre or a general provider ranking. Choose by the shot’s required accuracy, editability and shared action—not simply cartoon versus realistic. Exact graphics and authored worlds favour code; realistic handling trials favour staged joint generation; genuine testimony requires recorded evidence. Independent masks cannot create a shared performance. + +The HTML includes simple route illustrations, searchable trial cards, the strongest arguments on both sides, a category map and an illustrative mixed-route advert. This synthesis draws on existing Fable reviews; no fresh Fable endorsement was obtained during its recorded provider-limit window. + +--- + +**Gap closure checkpoint (2026-11-14):** [Verified subchecks, retained failures and remaining gates](hybrid-gap-closure-2026-11-14.md). The completed Fable film now passes independent seeking/control checks and a three-frame CLI edit/undo specimen. Target-texture warnings and a local recovery prototype add safeguards; tracking geometry, native integration and visual acting remain open. + +**Latest decisions (2026-11-13):** the user accepts the full-pickup and two-person handoff examples and prefers Fable 5.2’s visual direction for the 48-second code-generated fantasy story. [Results, technical comparison and story track ST1–ST4](code-generated-story-results-2026-11-13.md). At that checkpoint the Fable draft was unfinished and failed a random-seek check. The resumed film now passes the scoped runtime checks above; cross-style reuse remains a planned experiment. Realistic joint generation and explicitly authored stylized animation are separate routes. + +**Generated trials completed (2026-11-13):** [staged camera-left pickup and completed two-person handoff](staged-generation-results-2026-11-13.md), both returned to editable finishing. One take per case; exact product fidelity and native integration remain open. Estimated total US$1.90 under the fresh US$2 cap; account ledger unverified. + +**Local acceptance follow-up (2026-11-13):** [snapshot preparation, full-clip masks, tracker counterexample and continuous lighting](hybrid-acceptance-round1-2026-11-13.md). That earlier local checkpoint preceded the generated trials now recorded separately; camera solve (feature 6) and generated worlds (feature 13) remain untested. + +**Scene staging decision (2026-11-13):** object–object, living thing–object and living thing–living thing interactions default to **stage → approved snapshot + reference images → joint video generation → editable finishing**. Independent masks do not create a coupled performance. See [workflow, evidence and remaining integration](interaction-staging-workflow.md). A staged-snapshot pickup and a two-person handoff now have local evidence; native integration, broader interactions and exact product fidelity remain open. + +**Interaction policy (2026-11-13):** realistic avatar/product looking, pointing and physical handling use a reference-conditioned whole-shot generation route. Explicitly authored stylized rigs are a separate route, with their own contact and seek acceptance. See [the interaction decision](avatar-lighting.md#interaction-routing-decision-2026-11-13). Independent masks are not a substitute for coherent gaze, gesture, product support or contact. + +Research update (2026-11-13): [video segmentation and tracking findings](hybrid-analysis-study-2026-11-13.md) and [reference-conditioned handling shots](avatar-lighting.md#reference-conditioned-handling-shots-2026-11-13) define the next experiments and the editability boundary of flattened footage. These do not claim new implemented renderer services. **Quality correction, 2026-11-11:** later review found erased fingers/heads, incorrect can placement and mismatched generated geometry in the example videos. Successful rendering and tracking do not establish whole-shot quality. See the [revised compositing and motion-design plan](hybrid-compositing-plan.md) for diagnoses, model/runtime research and proposed release gates. Those new features are planned, not implemented. @@ -33,6 +59,7 @@ Each journey says what the author does, what EditableFrames does, and how far it | 6 | **Many versions from one take.** The same shot in twenty prices, five languages, three label colours. | One plate and its data, then control edits. | Re-renders each version from the same pinned inputs. If the plate is replaced, its old matte, depth and track are refused instead of being composited slightly wrong. | Integration test for the refusals; edits use the existing revision-checked history. | | 7 | **Fast motion.** Code elements that move quickly should smear like the footage does. | A shutter angle. | Renders several sub-frame samples per output frame and averages them. | Integration test: smear width and edge colour. | | 8 | **A moving camera.** The product stays put in a shot whose camera travels. | A camera path solved elsewhere. | Replays the path on a Three.js camera, with rotation interpolated correctly. | Unit tests only. Not yet tried on a real solve; solves of generated footage are approximate. | +| 9 | **An authored stylized story.** Characters move and speak in a code-built world. | Character/set assets or procedural source, rigs, shot/action/light tracks and prepared speech. | Renders authored geometry and sampled animation with exposed controls; no implicit model call. | Two 48-second local SDK films; Fable visual direction user-preferred; resumed film passes same-machine sequential/seek/control checks and a three-frame CLI specimen. [Story findings and next tests](code-generated-story-results-2026-11-13.md). No native story editor or cross-style portability claim. | The integration tests use a synthetic plate. [On generated footage](#on-generated-footage) says what a trial on plates from video models found. diff --git a/skills/editableframes/references/renderer.md b/skills/editableframes/references/renderer.md index daa2185..994ae92 100644 --- a/skills/editableframes/references/renderer.md +++ b/skills/editableframes/references/renderer.md @@ -72,6 +72,13 @@ SVG and WebGL descendants. PNG and ProRes preserve alpha; MP4 flattens over the requested background. `window.editableframes.captureTarget` describes the capture selector for browser harnesses. `png()` remains the legacy Canvas-only shortcut. This is trusted local browser execution, not isolation from malicious authored code. +The CLI normally uses Playwright's managed Chromium. To use an already installed, +compatible Chromium explicitly, set `EDITABLEFRAMES_CHROMIUM_EXECUTABLE` to its +absolute executable path. `doctor` checks that configured file; `render` verifies +it can actually launch. This opt-in does not download a browser or silently fall +back. Record the browser version with visual evidence; cross-version pixel +identity is not promised. + For WebGL, retain the rendered drawing buffer for capture (for example, `preserveDrawingBuffer: true`) and await required GPU work. Cross-browser/GPU/font pixel identity is not promised. diff --git a/tests/browser-config.test.mjs b/tests/browser-config.test.mjs new file mode 100644 index 0000000..0aefe40 --- /dev/null +++ b/tests/browser-config.test.mjs @@ -0,0 +1,22 @@ +import {test} from 'node:test'; +import assert from 'node:assert/strict'; +import fs from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; +import {chromiumOptions} from '../scripts/browser.mjs'; + +test('managed browser is the default and no path is guessed',()=>{ + assert.deepEqual(chromiumOptions({}),{}); + assert.deepEqual(chromiumOptions({EDITABLEFRAMES_CHROMIUM_EXECUTABLE:''}),{}); +}); +test('configured browser preserves an existing absolute path including spaces',()=>{ + const dir=fs.mkdtempSync(path.join(os.tmpdir(),'ef-browser-')); + try {const file=path.join(dir,'Browser With Spaces');fs.writeFileSync(file,'fixture only');assert.deepEqual(chromiumOptions({EDITABLEFRAMES_CHROMIUM_EXECUTABLE:file}),{executablePath:file});} + finally {fs.rmSync(dir,{recursive:true,force:true});} +}); +test('bad explicit configuration is rejected rather than silently falling back',()=>{ + assert.throws(()=>chromiumOptions({EDITABLEFRAMES_CHROMIUM_EXECUTABLE:'relative/chrome'}),/absolute/); + const dir=fs.mkdtempSync(path.join(os.tmpdir(),'ef-browser-')); + try {assert.throws(()=>chromiumOptions({EDITABLEFRAMES_CHROMIUM_EXECUTABLE:dir}),/file/);assert.throws(()=>chromiumOptions({EDITABLEFRAMES_CHROMIUM_EXECUTABLE:path.join(dir,'missing')}),/existing/);} + finally {fs.rmSync(dir,{recursive:true,force:true});} +}); From 5452f3e259617170a7c2dadce74de7b5599c55bf Mon Sep 17 00:00:00 2001 From: Laurence Xavier <35849747+lxf82dev@users.noreply.github.com> Date: Sat, 14 Nov 2026 01:55:53 +0800 Subject: [PATCH 32/49] Record interrupted lighting study and retained baseline evidence --- docs/hybrid-experiment-map.html | 2 +- docs/hybrid-gap-closure-2026-11-14.md | 2 +- .../editableframes/references/hybrid-gap-closure-2026-11-14.md | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/docs/hybrid-experiment-map.html b/docs/hybrid-experiment-map.html index 8b2451b..eb7daf2 100644 --- a/docs/hybrid-experiment-map.html +++ b/docs/hybrid-experiment-map.html @@ -1,4 +1,4 @@ -Video experiment map

How should we make this movie?

Build the stage. Make the action together. Combine the pieces. Pick the right tool for each shot.

Build with code

Like a toy theatre: keep the actors, lights and moves editable.

Make action together

Like filming a play: hands and props must share the same action.

Combine the pieces

Like a scrapbook: add words, cut-outs and backgrounds.

Closing the gaps · 2026-11-14

9 tested subchecks resolved · 0/11 whole work items closed · $0 new hosted calls

Open a row to see what changed, what still fails, and the artifacts. A green subcheck only covers its stated test. This is an active checkpoint, not completion of the research programme.

Checkpoint report and limitations

ST1 · Make the preferred story dependable Improved; gap remainsCoordinator verification of resumed Fable result

Acceptance: Random/reverse seeks across every shot and cut match sequential reference in the same renderer; audio and all exposed controls checked; contact and framing improved.

Current limit: Painted faces, rigid joints, contact staging, local fonts and stock voices remain. No audio listening review or full native desktop source/audio/history acceptance.

What changed: All1152 sequential frames reproduced,228 new seeks and all12 controls passed. CLI samples now also pass revision-checked edits, stale rejection and byte-identical undo. These close runtime subchecks on this Mac; visual performance and native integration remain open.

  • ✓ Sequential frame reproduction — 1152/1152 hashes match saved worker render.
  • ✓ New shuffled and reverse seeks — 228/228 including cut-adjacent samples; no errors.
  • ✓ Every exposed control — 12/12 visibly change pixels and restore defaults exactly.
  • ✓ CLI edits and undo — Frames228,696,960 change with exposure; stale edit refused; undo byte-identical. Three-frame specimen only.
  • ◐ Acting, contact and native app — Visual limitations retained; no listening review or full native app acceptance.
Attempts and artifacts (3 attempts · 7 artifacts)
Resumed original Fable film

Fixed camera-before-gaze ordering in two shots and rendered a fresh full export.

Result: Worker completed48 seconds and fixed two camera-before-gaze reads; initial60 seek checks passed. Coordinator verification below subsequently reproduced and extended this evidence.

Verify independently; preserve earlier failed recovery as historical evidence.

Coordinator reproduction

Fresh sequential pass, new cut-boundary/shuffled/reverse picks and independent edit per declared control using saved bundle.

Result: All runtime checks pass; no resource or page errors. Same Mac/browser only.

Keep visual quality and broader-device/host acceptance open.

CLI specimen through current SDK

Import unmodified scene, sample three shots, edit exposure, reject stale revision, undo and render again.

Result: Passed. Added explicit Chromium executable selection after missing managed browser; explicit source rebind accepted runtime update.136 SDK tests pass.

Full film/audio/native app integration and other devices remain separate.

Completed Fable film — New 48-second export; visual and runtime acceptance are separate. Retained local evidence; not bundled.

Fable QA record — Worker-produced format, seek, control and audio measurements. Retained local evidence; not bundled.

Shot contact sheet — One frame per shot from the delivered MP4. Retained local evidence; not bundled.

Coordinator verification — 1152 sequential hashes, 228 repeat checks, all12 control edits. Retained local evidence; not bundled.

CLI edit/undo evidence — Three actual CLI-rendered frames; no full film/native acceptance claim. Retained local evidence; not bundled.

Exposure control: before — Original source and default lighting. Retained local evidence; not bundled.

Exposure control: after — Same frame after declared control edit. Retained local evidence; not bundled.

ST2-3 · Reuse the cast beyond the dungeon Needs a resourceFable 5.2

Acceptance: At least two genuinely different short styles with reused rigs, a shared-prop action and evidence of editable changes.

Current limit: Fable began reading APIs, then provider rate limit stopped it before any new scene artifact. Reported reset 02:20 Asia/Singapore Nov14. No quality conclusion.

Attempts and artifacts (1 attempts · 0 artifacts)
Fable worker launch

Read completed source and inspected APIs.

Result: Provider rate-limit termination; no new style source found.

Await provider availability; do not count this as a failed visual method.

LIGHT1 · Make products respond properly to moving lights WorkingOpus 5.5

Acceptance: Matched before/after clips, face/reflection gradients, shadow/decal checks, screen treatment and repeatability; inspect current v6 before repeating old fixes.

Current limit: Earlier flat-face, weak-material and lighting-response findings; latest corrections must be audited.

Attempts and artifacts (0 attempts · 0 artifacts)

No new attempt has been completed in this round. Earlier evidence is retained in the original map.

TRACK1 · Expose and contain tracking failures Improved; gap remainsCoordinator

Acceptance: Retained wrong-face and false-confidence counterexamples reproduced; a useful quality/review mechanism rejects or flags failures without claiming correctness from round-trip agreement.

Current limit: Worst corner drift remains6.861px at correlation0.956. Diagnostics cannot identify a textured wrong plane or recover vanished targets; original filmed failure clips remain unavailable.

What changed: Implemented per-frame target-interior texture diagnostics and honest confidence semantics in the analysis tool. All49 frames of the retained wrong-track case are flagged for review. Existing alignment is deliberately unchanged.

  • ✓ Detect low-support target — 49/49 counterexample frames flagged;6 new regressions pass.
  • ◐ Correct the wrong alignment — Not fixed.6.861px worst drift remains; this safeguard is not a new tracker.
Attempts and artifacts (1 attempts · 2 artifacts)
Target observability guard

Fixed-scale 4x4 two-axis gradient support inside the selected quad; exclude surrounding template margin.

Result: Blank, single-edge, localized and out-of-frame evidence flagged; distributed texture recognized without accuracy approval.13 existing and6 new tests pass.

Independent boundaries/identity and real-footage visibility acceptance remain open.

Before/after warning diagnostic — The same wrong track, now explicitly flagged. No geometry-fix claim. Retained local evidence; not bundled.

Tracker measurements — 49-frame retained counterexample and diagnostic output. Retained local evidence; not bundled.

FLOW1 · Turn scene packets into a recoverable workflow Improved; gap remainsCoordinator

Acceptance: Local persisted job/receipt/import checks cover restart, failed/ambiguous work, reference order and actual decoded timing; no new paid submissions.

Current limit: Prototype only: native UI/transport, actual provider reconciliation and atomic managed-asset import still need implementation.

What changed: A local durable-job prototype passes11 fault checks using retained real pickup and handoff outputs. Crash recovery refuses silent resubmission; failed replacements preserve the accepted take. No network request or provider integration.

  • ✓ Crash and concurrent-submit safety — Killed after durable submission marker; restart becomes ambiguous; second owner and automatic retry refused.
  • ✓ Ordered inputs and stale edits — Reference reordering, changed bytes, changed endpoint/action and stale revision refused.
  • ✓ Keep accepted video when replacement fails — Bad output and failed replacement preserve prior accepted take across restart.
  • ✓ Actual decoded timing — Pickup121 frames /5.0417s; handoff169 frames /7.0417s; both24fps. Variable cadence refused.
  • ◐ Native/provider integration — Network-free prototype; no live provider timeout, billing or app integration acceptance.
Attempts and artifacts (1 attempts · 3 artifacts)
Persistent local generation receipt

SQLite WAL/FULL, frozen ordered scene packet, submission marker before transport, explicit job-ID reconciliation and reviewed take selection.

Result: 11/11 tests passed, including forced subprocess exit, two concurrent owners, corrupt replacement, modified source/output and variable cadence.

Move validated contract into native job/asset ownership; test actual provider reconciliation before shipping.

Fault-test results — Measured timing from both retained generated videos. Retained local evidence; not bundled.

Prototype source — No network, credentials or native UI. Retained local evidence; not bundled.

Reproduction tests — Retains real failure assertions; no paid submissions. Retained local evidence; not bundled.

MASK1 · Finish the hair and contact evidence QueuedNext round

Acceptance: Whole retained clips reviewed on difficult replacement backgrounds; retain failure frames and compare methods honestly.

Current limit: Improved hair does not prove all temporal edges or body-object interaction.

Attempts and artifacts (0 attempts · 0 artifacts)

No new attempt has been completed in this round. Earlier evidence is retained in the original map.

GLASS1 · Resolve or bound transparent materials QueuedNext round

Acceptance: A matched scene comparison isolates nested transparency limits and gives a reproducible supported route.

Current limit: Prior glass/liquid/ice results incomplete; compute cost is unverified.

Attempts and artifacts (0 attempts · 0 artifacts)

No new attempt has been completed in this round. Earlier evidence is retained in the original map.

HUMAN1 · Light humans and products together QueuedNext round

Acceptance: Continuous changes preserve identity and agree across subjects/background; show limits of bounded colour matching.

Current limit: No full temporal/directional avatar relighting acceptance.

Attempts and artifacts (0 attempts · 0 artifacts)

No new attempt has been completed in this round. Earlier evidence is retained in the original map.

MACHINE1 · Check other ordinary computers Needs a resourceExternal resource

Acceptance: Run the same reproducible benchmark on actual additional hardware.

Current limit: One Mac cannot prove Windows/Linux/modest-laptop performance.

Attempts and artifacts (0 attempts · 0 artifacts)

No new attempt has been completed in this round. Earlier evidence is retained in the original map.

SAM3 · Compare SAM 3 video Needs a resourceAccess/runtime resource

Acceptance: An actually runnable licensed model and accepted access, followed by matched-video comparison.

Current limit: Previous gated access/runtime constraints; no new download/spend assumed.

Attempts and artifacts (0 attempts · 0 artifacts)

No new attempt has been completed in this round. Earlier evidence is retained in the original map.

RECON · Camera solve and reconstructed worlds QueuedLater research

Acceptance: Real-camera and reconstructed-world acceptance separately; authored scenes do not count.

Current limit: Feature 6 and 13 still untested; initial round prioritizes existing failures.

Attempts and artifacts (0 attempts · 0 artifacts)

No new attempt has been completed in this round. Earlier evidence is retained in the original map.

41 grouped trials · 8 areas

Counts group related attempts—not individual renders, equal-sized studies or a success rate. These include HTML scenes and the models that supplied their inputs.

● 12 Worked in this test● 21 Needs more work● 8 Missed the goal

“Worked” means only the stated check or user judgment passed. It does not mean ready for every video.

▱ Keep pictures in the right place 5 trialsA sticker must stay on its sign.

Clean synthetic tracker Worked in this test

A clean moving test card tracked very accurately.

Limit: Known-answer synthetic proof; not real-scene reliability.

Generated café, poster and phone Needs more work

Cards followed short moving clips, with manual corners and some drift.

Limit: Up to about 8 px café error despite high confidence; curved paper is not planar.

Real filmed box orbit Missed the goal

The sticker slid onto the next face of the box.

Limit: Blank surfaces and changing faces defeat this tracker.

Tracker confidence + reverse check Missed the goal

Forward and backward trackers agreed on the same wrong answer.

Limit: 6.861 px error with zero forward/backward disagreement; score correctness bug separately fixed.

Frame timing and colour export Worked in this test

Fixed repeated source frames and unwanted darkening.

Limit: Integer timestamp and colour-tag corrections; retained export checks.

▤ Put people in front of the right things 5 trialsA hand should hide what is behind it.

Original phone thumb + café head Missed the goal

Old overlays erased a thumb and covered hair.

Limit: Original outputs failed even when the rest of the video looked fine.

Repaired phone + café + native card Worked in this test

Reviewed masks kept the thumb, head and hair visible.

Limit: Works with manual tuning on retained shots; native café preview/export exercised.

Depth map with an added can Missed the goal

A hand cut through the extra can.

Limit: Depth tuning did not establish common scene geometry.

Wrap the original left can Worked in this test

Put the artwork on the existing can instead of adding another one.

Limit: Manual rigid-cylinder fit; the hand did not cross that original can.

Kinetic words and exact screen cards Worked in this test

Words enter, move and stay on their intended surface.

Limit: Retained titles/rows/wipes/spring/orbit/extrusion examples; broader style library not certified.

✂ Cut out hair, hands and products 5 trialsA cut-out edge needs more than scissors.

Avatar stills + bounded light matching Needs more work

Small colour changes preserve the original face.

Limit: Separate screenshots, not continuous speech; cannot create correct new directional shadows.

Local SAM 2 video + CPU fallback Needs more work

Followed people, hands and products through short clips.

Limit: Binary masks; preparation on one Mac, not live 24 fps or fine hair alpha.

Full pickup: SAM / RVM / guided alpha Needs more work

Processed the whole pickup and reduced some background spill.

Limit: 121 frames at 640×360; hair/edge errors remain, no annotated full-resolution pass.

Yellow-wall hair swap and repair Needs more work

Hair stopped disappearing as much after better preparation.

Limit: Improved source quality, prior-frame context and boundary repair; not all faults isolated.

Cut-out avatar pointing at headphones Missed the goal

The edges improved, but the person still did not convincingly present the object.

Limit: User rejected this route for interaction; zero overlap is not coherent gaze or contact.

☀ Make things belong in the light 7 trialsA lamp must light the object, not just glow.

Plate-based light guesses Needs more work

Sometimes found the useful side of the light; manual overrides mattered.

Limit: A bright surface or backlight can mislead the estimate.

Exact can on an empty generated stage Needs more work

Kept the product shape in code with an authored shadow.

Limit: Rendering worked; pasted-on lighting prompted the later lighting studies.

Local raster / WebGPU / Cycles Needs more work

All ran locally; corrected render tests were retained.

Limit: One Mac, unequal looks/tone maps and limited path-traced sequences; no best-computer claim.

DiffusionLight environment estimate Missed the goal

Invented lighting that did not fit the authored room.

Limit: Negative result for this scene, not a universal rejection of estimation.

IC-Light on exact artwork Missed the goal

Changed lettering and object detail.

Limit: Rejected for exact branded-object finishing; tests were stills, not a full relit video.

IC-Light on avatar stills / ratio hint Needs more work

A bounded hint kept original pixels; raw replacement changed facial detail.

Limit: Experimental still-image result; no temporal identity or light-direction acceptance.

One lamp changes warm → cool Needs more work

The cup and table responded, but the pastry barely did.

Limit: Baked photographed background stayed unchanged; per-object response must be checked.

◈ Try real and designed products 9 trialsCorrect shape matters as much as pretty light.

LUMA, SPRIG, CROWN & ROOT cans Needs more work

More detailed packaging helped; red design was preferred.

Limit: Lids, reflections, droplets, label seams and motion still needed refinement.

12 products × 6 lighting setups Needs more work

Expanded to PCs, phones, watches, cameras and lifestyle products.

Limit: 72 cases / 22 sequences; Fable found flat faces, decal shadows, weak metals and glass faults.

Oura / Garmin / Nothing photographs Needs more work

Recognisable products work as cut-outs and layouts.

Limit: Colour matching only: baked highlights and unseen sides cannot be relit or spun out.

Framework photo + grille repair Worked in this test

Improved small-detail downsampling for the layout.

Limit: Context photo only, not a relighting test or full temporal aliasing certification.

iPhone / Galaxy / MacBook 3D assets Needs more work

MacBook responded to moving lights after fixes.

Limit: iPhone/Galaxy assets rejected for hero shots; MacBook remains a limited screen carrier.

Two copies: spin, orbit and overlap Worked in this test

The nearer object drew in front in the tested crossing poses.

Limit: 35 poses; photo copies still have no real turn; mutual reflections/bounce untested.

Photos-to-3D product attempt Missed the goal

The generated model did not preserve the needed materials.

Limit: An importable mesh is not yet a faithful commercial product.

Glass, liquid and ice scenes Needs more work

Rendered scenes, but nested transparent parts could vanish.

Limit: Raster limitations; limited Cycles trials were not a matched-quality comparison.

Pastry, ceramic, plants, furniture, jewelry Needs more work

Broadened the material and scene tests.

Limit: Grounding, fabrics, jewelry detail and simple billboard steam remained weak.

↔ Make people show and hand over a product 5 trialsBodies must agree about the same action.

HeyGen Avatar IV + Atmee pointing Needs more work

Both made a presenter talk and gesture in a detailed room.

Limit: Requested gesture timing was not followed; these outputs were flattened video.

HeyGen walk, pickup and carry Needs more work

An explicit standing start gave the best framing.

Limit: Product detail drift and late speech remained.

Kling references + video-edit pickup Needs more work

Joint generation improved looking, gripping and holding.

Limit: The early upright position and camera-left instruction were not fully corrected.

Approved snapshot → full pickup Worked in this test

Camera-left placement and pickup looked good to the user.

Limit: One accepted example; heft is weak, exact geometry and lettering unproven.

Two-person handoff Worked in this test

Receiver supports it; giver lets go. The user likes the result.

Limit: One accepted example; second person lacked an identity reference.

♜ Build an animated story with code 2 trialsBuild the stage, actors and their moves.

Astra fantasy RPG film Needs more work

48 seconds of voiced, subtitled, editable 3D storytelling.

Limit: Three repeat seeks passed; faces and hands look more puppet-like than references.

Fable 5.2 fantasy RPG film Needs more work

User prefers its richer sets, proportions and cinematic direction.

Limit: 48-second recovered draft; usage limit interrupted refinement; one seek test fails.

↻ Keep the work editable and safe to repeat 3 trialsSave the recipe, not only the movie.

Clean staging snapshot + reference packet Worked in this test

Kept the chosen layout and reference order in a saved packet.

Limit: Local Scene Studio/packet checks; full native provider workflow still pending.

Generated clips → editable finishing Worked in this test

Titles, prices and other code layers remain changeable after generation.

Limit: Hands, product motion and room light inside the footage remain baked.

Clay/depth/normal/object-ID control passes Worked in this test

The authored scene can emit these inputs for another tool.

Limit: No successful hosted control-video restyling round trip established.