SCENEGOD/scenegod/web/render.js
type-two 128e24a7cb [deploy] digalot.fyi hosting: prefix-agnostic frontend, ship-check hardening, docker+nginx kit
- web: all URLs relative (imports ./web/..., fetches assets/...) so the app
  serves at / locally and under /scenegod/ behind nginx; esc() on dock
  innerHTML interpolations (ship-check XSS class)
- server: capped_body on every POST (scenes 5MB, frames 25MB, meta/director
  256KB-1MB), render begin sanity (fps<=60, dims<=4096, frame idx<=20000)
- deploy/: Dockerfile (slim+ffmpeg), compose (project 'scenegod' — avoids
  the shared-'deploy'-project orphan trap with meshgod), nginx location
  (suite basic-auth), deploy.sh (rsync model, meshgod-style)
- live: digalot.fyi/scenegod/ -> 401 unauthed, app healthy on dealgod_default

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-21 02:43:26 +10:00

81 lines
3.8 KiB
JavaScript

// render.js — draft + final video capture (Lane C, PLAN §4.3 / C-server §C5).
// Talks to Stage/Timeline through their public APIs only. No three.js import.
//
// draftRecord(stage, timeline) -> Promise<Blob> quick webm via MediaRecorder
// finalRender(stage, timeline, opts) -> Promise<url> deterministic PNG->ffmpeg mp4
const sleep = ms => new Promise(r => setTimeout(r, ms));
// --- draft: record the live canvas while the timeline plays, once through ----
export function draftRecord(stage, timeline, { fps = 30, mimeType = 'video/webm' } = {}) {
const stream = stage.renderer.domElement.captureStream(fps);
const rec = new MediaRecorder(stream, MediaRecorder.isTypeSupported(mimeType) ? { mimeType } : {});
const chunks = [];
rec.ondataavailable = e => e.data.size && chunks.push(e.data);
return new Promise((resolve, reject) => {
rec.onstop = () => resolve(new Blob(chunks, { type: rec.mimeType || 'video/webm' }));
rec.onerror = reject;
rec.start();
timeline.seek(0);
timeline.play();
const stop = timeline.onTick(t => {
if (t >= timeline.duration) { timeline.pause(); rec.stop(); if (typeof stop === 'function') stop(); }
});
});
}
// --- final: step frame-by-frame (deterministic), upload PNGs, ffmpeg encode ---
export async function finalRender(stage, timeline, opts = {}) {
const { fps = 30, width = 1920, height = 1080, name = 'scene', audio = [], onProgress } = opts;
const canvas = stage.renderer.domElement;
const prev = { w: canvas.width, h: canvas.height, dpr: stage.renderer.getPixelRatio() };
stage.renderer.setPixelRatio(1);
stage.renderer.setSize(width, height, false); // false = don't touch CSS size
try {
const total = Math.max(1, Math.round(timeline.duration * fps));
const { renderId } = await postJSON('render/begin', { name, fps, width, height });
const inflight = new Set();
for (let f = 0; f < total; f++) {
timeline.step(f); // seek(f/fps)+evaluate — never wall-clock
if (stage.syncVideos) await stage.syncVideos(timeline.time); // M6 video plates: seek + wait 'seeked'; no-op until Lane A lands it
stage.renderActiveCamera(null); // draw active cam (or director cam) to main canvas
const blob = await new Promise(res => canvas.toBlob(res, 'image/png'));
while (inflight.size >= 4) await Promise.race(inflight); // backpressure: <=4 in flight
const p = fetch(`render/${renderId}/frame/${f}`, { method: 'POST', body: blob })
.then(r => { if (!r.ok) throw new Error(`frame ${f}: ${r.status}`); })
.finally(() => inflight.delete(p));
inflight.add(p);
onProgress?.(f + 1, total);
}
await Promise.all(inflight);
await postJSON(`render/${renderId}/end`, { audio }); // scene audio[] muxed by ffmpeg
let st;
do { await sleep(500); st = await (await fetch(`render/${renderId}/status`)).json(); }
while (st.state === 'queued' || st.state === 'encoding');
if (st.state !== 'done') throw new Error('encode failed: ' + (st.log || st.state));
return `render/${renderId}/out.mp4`;
} finally {
stage.renderer.setPixelRatio(prev.dpr);
stage.renderer.setSize(prev.w, prev.h, false);
}
}
// trigger a browser download of a blob or url (draft webm / final mp4)
export function download(blobOrUrl, filename) {
const a = document.createElement('a');
a.href = typeof blobOrUrl === 'string' ? blobOrUrl : URL.createObjectURL(blobOrUrl);
a.download = filename;
a.click();
if (typeof blobOrUrl !== 'string') setTimeout(() => URL.revokeObjectURL(a.href), 1000);
}
async function postJSON(url, body) {
const r = await fetch(url, { method: 'POST', headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body) });
if (!r.ok) throw new Error(`${url}: ${r.status}`);
return r.json();
}