const sceneRoutes={}, localScenes=["pstudio","show3d"], defaultDataset="pstudio", expectedSamples=2, datasetNames={pstudio:"PStudio",show3d:"Show3D"}; function fillScenes(dataset) { document.getElementById("dataset-select").value = dataset; dom.sceneSelect.replaceChildren(); for (const sample of state.collection.filter(value => value.dataset === dataset)) { const option = document.createElement("option"); option.value = sample.id; option.textContent = sample.label; option.title = sample.label; dom.sceneSelect.appendChild(option); } } document.getElementById("dataset-select").addEventListener("change", event => { fillScenes(event.target.value); void loadSelectedScene(); }); // (c) Meta Platforms, Inc. and affiliates. Confidential and proprietary. const MODES = ["raw", "chain", "map"]; const MODE_INDEX = Object.freeze({raw: 0, chain: 1, map: 2}); const MILLIMETRES_PER_METRE = 1000; const RADIUS_UNITS_PER_METRE = 10000; const SEEK_BIAS_SECONDS = 1e-5; const dom = { chunkSelect: document.getElementById("chunk-select"), errorMessage: document.getElementById("error-message"), errorOverlay: document.getElementById("error-overlay"), frameOutput: document.getElementById("frame-output"), identity: document.getElementById("identity"), inputStatus: document.getElementById("input-status"), loading: document.getElementById("loading"), loadingDetail: document.getElementById("loading-detail"), loadingProgress: document.getElementById("loading-progress"), loadingTitle: document.getElementById("loading-title"), playButton: document.getElementById("play-button"), playIcon: document.getElementById("play-icon"), playLabel: document.getElementById("play-label"), provenanceDetails: document.getElementById("provenance-details"), provenanceSummary: document.getElementById("provenance-summary"), reportDetails: document.getElementById("report-details"), resetCamera: document.getElementById("reset-camera"), retryButton: document.getElementById("retry-button"), sceneSelect: document.getElementById("scene-select"), selfTestStatus: document.getElementById("self-test-status"), sourceVideo: document.getElementById("source-video"), timeline: document.getElementById("timeline"), videoFrame: document.getElementById("video-frame"), windowDetails: document.getElementById("window-details"), }; const state = { abortController: null, assets: null, camera: null, chunkEnd: 1, chunkStart: 0, frame: 0, generation: 0, renderers: [], scene: null, scenes: [], }; function invariant(condition, message) { if (!condition) { throw new Error(message); } } function finiteNumber(value, name) { invariant(Number.isFinite(value), `${name} must be finite`); return Number(value); } function integer(value, name, minimum = 0) { invariant(Number.isInteger(value) && value >= minimum, `${name} must be an integer >= ${minimum}`); return value; } function json(value) { return JSON.stringify(value, null, 2); } function packedAsset(name) { window.__TOOLBOX_PACKED__ ??= JSON.parse(document.getElementById("inline-assets").textContent); const packed = window.__TOOLBOX_PACKED__; invariant(packed[name], `Missing embedded asset ${name}`); return packed[name]; } function assetBytes(name) { return Uint8Array.from(packedAsset(name).data); } function assetUrl(name) { const asset = packedAsset(name); const bytes = assetBytes(name); const chunks = []; for (let start = 0; start < bytes.length; start += 32768) { chunks.push(String.fromCharCode(...bytes.subarray(start, start + 32768))); } return `data:${asset.type};base64,${btoa(chunks.join(""))}`; } function setLoading(title, detail, fraction = 0) { dom.loading.classList.remove("done"); dom.loadingTitle.textContent = title; dom.loadingDetail.textContent = detail; dom.loadingProgress.style.width = `${Math.max(4, Math.min(100, fraction * 100))}%`; } function finishLoading() { dom.loadingProgress.style.width = "100%"; dom.loading.classList.add("done"); } function errorText(error) { if (error instanceof Error) { return error.stack || error.message; } return String(error); } function showError(error) { pause(); dom.errorMessage.textContent = errorText(error); dom.errorOverlay.hidden = false; dom.retryButton.focus(); console.error(error); } function hideError() { dom.errorOverlay.hidden = true; } function copyUint8(view, offset, count, label) { invariant(offset + count <= view.byteLength, `${label}: truncated uint8 field`); return new Uint8Array(view.buffer, view.byteOffset + offset, count).slice(); } function readUint16LE(view, offset, count, scale, label) { invariant(offset + count * 2 <= view.byteLength, `${label}: truncated uint16 field`); const result = scale === 1 ? new Uint16Array(count) : new Float32Array(count); for (let index = 0; index < count; index += 1) { result[index] = view.getUint16(offset + index * 2, true) * scale; } return result; } function readInt16LE(view, offset, count, scale, label) { invariant(offset + count * 2 <= view.byteLength, `${label}: truncated int16 field`); const result = new Float32Array(count); for (let index = 0; index < count; index += 1) { result[index] = view.getInt16(offset + index * 2, true) * scale; } return result; } function decodeStatic(buffer, count, deathModes, label) { count = integer(count, `${label}.count`); deathModes = integer(deathModes, `${label}.deathModes`, 1); const expected = count * (14 + deathModes * 2); invariant(buffer.byteLength === expected, `${label}: expected ${expected} decoded bytes, got ${buffer.byteLength}`); const view = new DataView(buffer); let offset = 0; const positions = readInt16LE(view, offset, count * 3, 1 / MILLIMETRES_PER_METRE, `${label}.positions`); offset += count * 3 * 2; const birth = readUint16LE(view, offset, count, 1, `${label}.birth`); offset += count * 2; const radius = readUint16LE(view, offset, count, 1 / RADIUS_UNITS_PER_METRE, `${label}.radius`); offset += count * 2; const death = []; for (let mode = 0; mode < deathModes; mode += 1) { death.push(readUint16LE(view, offset, count, 1, `${label}.death[${mode}]`)); offset += count * 2; } const colors = copyUint8(view, offset, count * 3, `${label}.colors`); offset += count * 3; const originWindow = copyUint8(view, offset, count, `${label}.originWindow`); offset += count; invariant(offset === buffer.byteLength, `${label}: unconsumed bytes`); return {birth, colors, count, death, originWindow, positions, radius}; } function expectedTrackBytes(windows, includeStart) { let positionBytes = 0; let radiusBytes = 0; let byteBytes = 0; for (const [index, window] of windows.entries()) { const n = integer(window.n, `windows[${index}].n`); const length = integer(window.L, `windows[${index}].L`); positionBytes += length * n * 3 * 2; radiusBytes += n * 2; byteBytes += length * Math.ceil(n / 8) + n * 3 + (includeStart ? n : 0); } return {byteBytes, positionBytes, radiusBytes, total: positionBytes + radiusBytes + byteBytes}; } function decodeDeltaPositions(view, offset, n, length, label) { const values = length * n * 3; invariant(offset + values * 2 <= view.byteLength, `${label}: truncated position stream`); const previous = new Int32Array(n * 3); const positions = new Float32Array(values); let cursor = offset; for (let frame = 0; frame < length; frame += 1) { const frameOffset = frame * n * 3; for (let value = 0; value < n * 3; value += 1) { previous[value] += view.getInt16(cursor, true); positions[frameOffset + value] = previous[value] / MILLIMETRES_PER_METRE; cursor += 2; } } return positions; } function decodeTrackWindows(buffer, metadata, includeStart, label) { invariant(Array.isArray(metadata), `${label}: windows metadata must be an array`); const sizes = expectedTrackBytes(metadata, includeStart); invariant(buffer.byteLength === sizes.total, `${label}: expected ${sizes.total} decoded bytes, got ${buffer.byteLength}`); const view = new DataView(buffer); let positionOffset = 0; let radiusOffset = sizes.positionBytes; let byteOffset = sizes.positionBytes + sizes.radiusBytes; const windows = []; for (const [index, source] of metadata.entries()) { const n = source.n; const length = source.L; const bytesPerFrame = Math.ceil(n / 8); const positions = decodeDeltaPositions(view, positionOffset, n, length, `${label}[${index}].positions`); positionOffset += length * n * 3 * 2; const radius = readUint16LE(view, radiusOffset, n, 1 / RADIUS_UNITS_PER_METRE, `${label}[${index}].radius`); radiusOffset += n * 2; const visibility = copyUint8(view, byteOffset, length * bytesPerFrame, `${label}[${index}].visibility`); byteOffset += length * bytesPerFrame; const colors = copyUint8(view, byteOffset, n * 3, `${label}[${index}].colors`); byteOffset += n * 3; let liveStart = null; if (includeStart) { liveStart = copyUint8(view, byteOffset, n, `${label}[${index}].start`); byteOffset += n; } windows.push({ bytesPerFrame, colors, length, liveStart, n, end: source.end, ownEnd: source.own_end, positions, radius, start: source.start, visibility, }); } invariant(positionOffset === sizes.positionBytes, `${label}: position layout mismatch`); invariant(radiusOffset === sizes.positionBytes + sizes.radiusBytes, `${label}: radius layout mismatch`); invariant(byteOffset === buffer.byteLength, `${label}: byte layout mismatch`); return windows; } function visibilityBit(window, localFrame, point) { const offset = localFrame * window.bytesPerFrame + (point >> 3); return (window.visibility[offset] & (1 << (point & 7))) !== 0; } function crossfadeLayers(windows, frame, currentIndex) { const current = windows[currentIndex]; const local = frame - current.start; invariant(local >= 0 && local < current.length, `frame ${frame} is outside current window ${currentIndex}`); const layers = [{alpha: 1, index: currentIndex, local, window: current}]; if (currentIndex === 0) { return layers; } const previous = windows[currentIndex - 1]; const overlap = previous.end - current.start; const previousLocal = frame - previous.start; if (overlap <= 0 || local >= overlap || previousLocal < 0 || previousLocal >= previous.length) { return layers; } const laterAlpha = (local + 1) / (overlap + 1); return [ {alpha: 1 - laterAlpha, index: currentIndex - 1, local: previousLocal, window: previous}, {...layers[0], alpha: laterAlpha}, ]; } function multipartName(id, kind, part) { return part === 0 ? `${id}.${kind}.wasm` : `${id}.${kind}.p${part}.wasm`; } async function fetchPart(name, signal) { signal?.throwIfAborted(); return assetBytes(name); } async function gunzipMultipart(id, kind, parts, signal, onPart) { parts = integer(parts, `${kind}.parts`, 1); invariant(typeof DecompressionStream === "function", "This browser does not support DecompressionStream('gzip')"); const buffers = await Promise.all(Array.from({length: parts}, async (_, part) => { const name = multipartName(id, kind, part); const bytes = await fetchPart(name, signal); onPart(name, bytes.byteLength); return bytes; })); const compressedLength = buffers.reduce((total, bytes) => total + bytes.byteLength, 0); const compressed = new Uint8Array(compressedLength); let offset = 0; for (const bytes of buffers) { compressed.set(bytes, offset); offset += bytes.byteLength; } invariant(compressed.length >= 2 && compressed[0] === 0x1f && compressed[1] === 0x8b, `${id}.${kind}: payload is not the required gzip stream`); try { const stream = new Blob([compressed]).stream().pipeThrough(new DecompressionStream("gzip")); return await new Response(stream).arrayBuffer(); } catch (error) { throw new Error(`${id}.${kind}: gzip decompression failed: ${errorText(error)}`); } } function validateScene(scene) { invariant(scene && typeof scene === "object", "scenes.json entries must be objects"); invariant(typeof scene.id === "string" && scene.id.length > 0, "scene.id must be non-empty"); integer(scene.frames, `${scene.id}.frames`, 1); finiteNumber(scene.fps, `${scene.id}.fps`); invariant(scene.fps > 0, `${scene.id}.fps must be positive`); invariant(typeof scene.video === "string" && scene.video.length > 0, `${scene.id}.video must be non-empty`); invariant(scene.static && scene.dyn && scene.stable, `${scene.id}: static/dyn/stable metadata is required`); invariant(scene.stage2_overlap === true, `${scene.id}: schema-3 stage2 overlap must be enabled`); integer(scene.static.count, `${scene.id}.static.count`); integer(scene.static.parts, `${scene.id}.static.parts`, 1); integer(scene.dyn.parts, `${scene.id}.dyn.parts`, 1); integer(scene.stable.count, `${scene.id}.stable.count`); integer(scene.stable.parts, `${scene.id}.stable.parts`, 1); integer(scene.stable.live_parts, `${scene.id}.stable.live_parts`, 1); invariant(Array.isArray(scene.windows) && scene.windows.length > 0, `${scene.id}.windows must be non-empty`); invariant(scene.windows.length <= 256, `${scene.id}: uint8 origin-window wire field supports at most 256 windows`); invariant(Array.isArray(scene.dyn.windows) && scene.dyn.windows.length === scene.windows.length, `${scene.id}: dynamic windows mismatch`); invariant(Array.isArray(scene.stable.windows) && scene.stable.windows.length === scene.windows.length, `${scene.id}: stable live windows mismatch`); for (const mode of MODES) { const entry = scene.modes?.[mode]; invariant(entry && Array.isArray(entry.scale), `${scene.id}.${mode}: scale array is required`); invariant(entry.scale.length === scene.windows.length, `${scene.id}.${mode}: scale/window count mismatch`); for (const [index, scale] of entry.scale.entries()) { invariant(Number.isFinite(scale) && scale > 0, `${scene.id}.${mode}.scale[${index}] must be positive`); if (mode === "raw") { invariant(scale === 1, `${scene.id}.raw.scale[${index}] must be exactly unit scale`); } } } const global = scene.modes?.global; invariant(global && Array.isArray(global.scale), `${scene.id}.global: scale array is required`); invariant(global.scale.length === scene.windows.length, `${scene.id}.global: scale/window count mismatch`); for (const [index, scale] of global.scale.entries()) { invariant(Number.isFinite(scale) && scale > 0, `${scene.id}.global.scale[${index}] must be positive`); } const covered = new Int16Array(scene.frames); covered.fill(-1); for (const [index, metadata] of scene.dyn.windows.entries()) { integer(metadata.start, `${scene.id}.dyn.windows[${index}].start`); integer(metadata.own_end, `${scene.id}.dyn.windows[${index}].own_end`, 1); integer(metadata.end, `${scene.id}.dyn.windows[${index}].end`, 1); invariant(metadata.start < metadata.own_end && metadata.own_end <= metadata.end && metadata.end <= scene.frames, `${scene.id}.dyn.windows[${index}]: invalid owned/predicted range`); invariant(metadata.L === metadata.end - metadata.start, `${scene.id}.dyn.windows[${index}]: L must equal end-start`); invariant(scene.windows[index].start === metadata.start, `${scene.id}.windows[${index}]: origin start mismatch`); if (index > 0) { const previous = scene.dyn.windows[index - 1]; invariant(previous.own_end === metadata.start, `${scene.id}: adjacent owned ranges do not meet at C${index}`); invariant(previous.end > metadata.start, `${scene.id}: C${index - 1}/C${index} have no prediction overlap`); const declared = scene.provenance?.config?.overlap; if (Number.isInteger(declared)) { invariant(previous.end - metadata.start === declared, `${scene.id}: C${index - 1}/C${index} overlap differs from config`); } } for (let frame = metadata.start; frame < metadata.own_end; frame += 1) { invariant(covered[frame] === -1, `${scene.id}: owned ranges overlap at frame ${frame}`); covered[frame] = index; } const live = scene.stable.windows[index]; invariant(live.start === metadata.start && live.own_end === metadata.own_end && live.end === metadata.end && live.L === metadata.L, `${scene.id}.stable.windows[${index}]: predicted range mismatch`); } for (let frame = 0; frame < scene.frames; frame += 1) { invariant(covered[frame] >= 0, `${scene.id}: no owned window for frame ${frame}`); } const plan = scene.provenance?.window_plan; if (Array.isArray(plan)) { invariant(plan.length === scene.windows.length, `${scene.id}: provenance window plan count mismatch`); for (const [index, window] of plan.entries()) { const dynamic = scene.dyn.windows[index]; invariant(window.start === dynamic.start && window.own_end === dynamic.own_end && window.end === dynamic.end, `${scene.id}: provenance window range mismatch at C${index}`); invariant(Array.isArray(window.slots) && window.slots.length > 0, `${scene.id}: provenance slots missing at C${index}`); } } invariant(Array.isArray(scene.target) && scene.target.length === 3, `${scene.id}.target must have three values`); finiteNumber(scene.extent, `${scene.id}.extent`); finiteNumber(scene.fov, `${scene.id}.fov`); return covered; } function transformAboutCenter(x, y, z, center, scale, output, offset) { output[offset] = center[0] + scale * (x - center[0]); output[offset + 1] = center[1] + scale * (y - center[1]); output[offset + 2] = center[2] + scale * (z - center[2]); } class GeometryBuilder { constructor(capacity) { this.alpha = new Float32Array(capacity); this.positions = new Float32Array(capacity * 3); this.radius = new Float32Array(capacity); this.colors = new Uint8Array(capacity * 3); this.count = 0; this.staticCount = 0; this.liveCount = 0; this.fading = false; } reset() { this.count = 0; this.staticCount = 0; this.liveCount = 0; this.fading = false; } add(x, y, z, radius, colors, colorOffset, alpha = 1) { const point = this.count; const offset = point * 3; invariant(point < this.radius.length, "frame geometry exceeded decoded point capacity"); this.positions[offset] = x; this.positions[offset + 1] = y; this.positions[offset + 2] = z; this.radius[point] = radius; this.alpha[point] = alpha; this.colors[offset] = colors[colorOffset]; this.colors[offset + 1] = colors[colorOffset + 1]; this.colors[offset + 2] = colors[colorOffset + 2]; this.count += 1; } value() { return { alpha: this.alpha.subarray(0, this.count), colors: this.colors.subarray(0, this.count * 3), count: this.count, fading: this.fading, liveCount: this.liveCount, positions: this.positions.subarray(0, this.count * 3), radius: this.radius.subarray(0, this.count), staticCount: this.staticCount, }; } } class SceneAssets { constructor(scene, frameWindow, staticBuffer, dynamicBuffer, stableBuffer, liveBuffer) { this.scene = scene; this.frameWindow = frameWindow; this.static = decodeStatic(staticBuffer, scene.static.count, MODES.length, `${scene.id}.static`); this.dynamic = decodeTrackWindows(dynamicBuffer, scene.dyn.windows, false, `${scene.id}.dyn`); this.stable = decodeStatic(stableBuffer, scene.stable.count, 1, `${scene.id}.stable`); this.live = decodeTrackWindows(liveBuffer, scene.stable.windows, true, `${scene.id}.live`); this.modeStatic = this.precomputeModeStatic(); this.validateDecodedMembership(); const crossfadeCapacity = windows => Math.max(...windows.map((window, index) => window.n + (index > 0 && windows[index - 1].end > window.start ? windows[index - 1].n : 0)), 0); const maximumDynamic = crossfadeCapacity(this.dynamic); const maximumLive = crossfadeCapacity(this.live); this.builders = { raw: new GeometryBuilder(this.static.count + maximumDynamic), chain: new GeometryBuilder(this.static.count + maximumDynamic), map: new GeometryBuilder(this.static.count + maximumDynamic), stable: new GeometryBuilder(this.stable.count + maximumLive), }; this.cache = new Map(); } validateDecodedMembership() { for (let point = 0; point < this.static.count; point += 1) { invariant(this.static.originWindow[point] < this.scene.windows.length, `${this.scene.id}.static: origin window out of range at point ${point}`); } for (const [index, window] of this.live.entries()) { for (let point = 0; point < window.n; point += 1) { invariant(window.liveStart[point] < window.length, `${this.scene.id}.live[${index}]: point start outside owned window`); } } } precomputeModeStatic() { const result = {}; for (const mode of MODES) { const positions = new Float32Array(this.static.positions.length); const radius = new Float32Array(this.static.radius.length); const scales = this.scene.modes[mode].scale; for (let point = 0; point < this.static.count; point += 1) { const offset = point * 3; const window = this.static.originWindow[point]; const center = this.scene.windows[window].centre; const scale = scales[window]; transformAboutCenter( this.static.positions[offset], this.static.positions[offset + 1], this.static.positions[offset + 2], center, scale, positions, offset, ); radius[point] = this.static.radius[point] * scale; } result[mode] = {positions, radius}; } return result; } geometry(mode, frame) { const cached = this.cache.get(mode); if (cached?.frame === frame) { return cached.geometry; } const geometry = mode === "stable" ? this.stableGeometry(frame) : this.modeGeometry(mode, frame); this.cache.set(mode, {frame, geometry}); return geometry; } modeGeometry(mode, frame) { const builder = this.builders[mode]; builder.reset(); const modeIndex = MODE_INDEX[mode]; const transformed = this.modeStatic[mode]; for (let point = 0; point < this.static.count; point += 1) { if (this.static.birth[point] <= frame && frame < this.static.death[modeIndex][point]) { const offset = point * 3; builder.add( transformed.positions[offset], transformed.positions[offset + 1], transformed.positions[offset + 2], transformed.radius[point], this.static.colors, offset, ); } } builder.staticCount = builder.count; const layers = crossfadeLayers(this.dynamic, frame, this.frameWindow[frame]); builder.fading = layers.length > 1; for (const layer of layers) { const {alpha, index: windowIndex, local, window} = layer; const center = this.scene.windows[windowIndex].centre; const scale = this.scene.modes[mode].scale[windowIndex]; const frameOffset = local * window.n * 3; for (let point = 0; point < window.n; point += 1) { if (!visibilityBit(window, local, point)) { continue; } const offset = frameOffset + point * 3; const colorOffset = point * 3; const output = builder.count * 3; invariant(builder.count < builder.radius.length, "frame geometry exceeded decoded point capacity"); transformAboutCenter( window.positions[offset], window.positions[offset + 1], window.positions[offset + 2], center, scale, builder.positions, output, ); builder.radius[builder.count] = window.radius[point] * scale; builder.alpha[builder.count] = alpha; builder.colors[output] = window.colors[colorOffset]; builder.colors[output + 1] = window.colors[colorOffset + 1]; builder.colors[output + 2] = window.colors[colorOffset + 2]; builder.count += 1; } } builder.liveCount = builder.count - builder.staticCount; return builder.value(); } stableGeometry(frame) { const builder = this.builders.stable; builder.reset(); for (let point = 0; point < this.stable.count; point += 1) { if (this.stable.birth[point] <= frame && frame < this.stable.death[0][point]) { const offset = point * 3; builder.add( this.stable.positions[offset], this.stable.positions[offset + 1], this.stable.positions[offset + 2], this.stable.radius[point], this.stable.colors, offset, ); } } builder.staticCount = builder.count; const layers = crossfadeLayers(this.live, frame, this.frameWindow[frame]); builder.fading = layers.length > 1; for (const {alpha, local, window} of layers) { const frameOffset = local * window.n * 3; for (let point = 0; point < window.n; point += 1) { if (local < window.liveStart[point] || !visibilityBit(window, local, point)) { continue; } const offset = frameOffset + point * 3; builder.add( window.positions[offset], window.positions[offset + 1], window.positions[offset + 2], window.radius[point], window.colors, point * 3, alpha, ); } } builder.liveCount = builder.count - builder.staticCount; return builder.value(); } } async function loadSceneAssets(scene, frameWindow, signal) { const totalParts = scene.static.parts + scene.dyn.parts + scene.stable.parts + scene.stable.live_parts; let completedParts = 0; let compressedBytes = 0; const onPart = (name, bytes) => { completedParts += 1; compressedBytes += bytes; setLoading( "Loading embedded model points", `${completedParts}/${totalParts} parts · ${(compressedBytes / 1e6).toFixed(1)} MB · ${name}`, 0.08 + 0.7 * completedParts / totalParts, ); }; const [staticBuffer, dynamicBuffer, stableBuffer, liveBuffer] = await Promise.all([ gunzipMultipart(scene.id, "static", scene.static.parts, signal, onPart), gunzipMultipart(scene.id, "dyn", scene.dyn.parts, signal, onPart), gunzipMultipart(scene.id, "stable", scene.stable.parts, signal, onPart), gunzipMultipart(scene.id, "live", scene.stable.live_parts, signal, onPart), ]); setLoading("Decoding little-endian streams", "Validating lengths, visibility bits, deltas, and membership…", 0.84); await new Promise(resolve => setTimeout(resolve, 0)); return new SceneAssets(scene, frameWindow, staticBuffer, dynamicBuffer, stableBuffer, liveBuffer); } function vectorLength(x, y, z) { return Math.hypot(x, y, z); } function normalize3(x, y, z) { const length = vectorLength(x, y, z) || 1; return [x / length, y / length, z / length]; } function lookAt(eye, center, up) { const z = normalize3(eye[0] - center[0], eye[1] - center[1], eye[2] - center[2]); const x = normalize3( up[1] * z[2] - up[2] * z[1], up[2] * z[0] - up[0] * z[2], up[0] * z[1] - up[1] * z[0], ); const y = [ z[1] * x[2] - z[2] * x[1], z[2] * x[0] - z[0] * x[2], z[0] * x[1] - z[1] * x[0], ]; return new Float32Array([ x[0], y[0], z[0], 0, x[1], y[1], z[1], 0, x[2], y[2], z[2], 0, -(x[0] * eye[0] + x[1] * eye[1] + x[2] * eye[2]), -(y[0] * eye[0] + y[1] * eye[1] + y[2] * eye[2]), -(z[0] * eye[0] + z[1] * eye[1] + z[2] * eye[2]), 1, ]); } function perspective(verticalFovRadians, aspect, near, far) { const focal = 1 / Math.tan(verticalFovRadians / 2); const range = 1 / (near - far); return new Float32Array([ focal / aspect, 0, 0, 0, 0, focal, 0, 0, 0, 0, (far + near) * range, -1, 0, 0, 2 * far * near * range, 0, ]); } class OrbitCamera { constructor(onChange) { this.onChange = onChange; this.target = [0, 0, 1]; this.extent = 1; this.distance = 3; this.yaw = 0; this.pitch = 0; } reset(scene, notify = true) { this.target = scene.target.map(Number); this.extent = Math.max(Number(scene.extent) || 1, 0.05); this.distance = Math.max(this.extent * (Number(scene.orbit_distance_factor) || 2.8), 0.25); this.yaw = Number(scene.orbit_yaw) || 0; this.pitch = Number(scene.orbit_pitch) || 0; if (notify) { this.onChange(); } } orbit(deltaX, deltaY) { this.yaw -= deltaX * 0.006; this.pitch = Math.max(-1.42, Math.min(1.42, this.pitch + deltaY * 0.006)); this.onChange(); } zoom(delta) { this.distance = Math.max(this.extent * 0.08, Math.min(this.extent * 80, this.distance * Math.exp(delta * 0.001))); this.onChange(); } view() { const cosPitch = Math.cos(this.pitch); const eye = [ this.target[0] + Math.sin(this.yaw) * cosPitch * this.distance, this.target[1] + Math.sin(this.pitch) * this.distance, this.target[2] - Math.cos(this.yaw) * cosPitch * this.distance, ]; // Packed coordinates are OpenCV RDF, so negative world Y is visually up. return lookAt(eye, this.target, [0, -1, 0]); } } const VERTEX_SHADER = ` attribute vec3 aPosition; attribute float aRadius; attribute vec3 aColor; attribute float aAlpha; uniform mat4 uProjection; uniform mat4 uView; uniform float uFocalPixels; uniform float uMaxPointSize; uniform float uMinPointSize; varying vec3 vColor; varying float vAlpha; void main() { vec4 camera = uView * vec4(aPosition, 1.0); gl_Position = uProjection * camera; float depth = max(-camera.z, 0.0001); gl_PointSize = clamp(2.0 * aRadius * uFocalPixels / depth, uMinPointSize, uMaxPointSize); vColor = aColor; vAlpha = aAlpha; }`; const FRAGMENT_SHADER = ` precision mediump float; varying vec3 vColor; varying float vAlpha; void main() { vec2 delta = gl_PointCoord - vec2(0.5); if (dot(delta, delta) > 0.25) discard; gl_FragColor = vec4(vColor, vAlpha); }`; function compileShader(gl, kind, source) { const shader = gl.createShader(kind); invariant(shader, "WebGL could not allocate a shader"); gl.shaderSource(shader, source); gl.compileShader(shader); if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) { const message = gl.getShaderInfoLog(shader); gl.deleteShader(shader); throw new Error(`WebGL shader compilation failed: ${message}`); } return shader; } function createProgram(gl) { const vertex = compileShader(gl, gl.VERTEX_SHADER, VERTEX_SHADER); const fragment = compileShader(gl, gl.FRAGMENT_SHADER, FRAGMENT_SHADER); const program = gl.createProgram(); invariant(program, "WebGL could not allocate a program"); gl.attachShader(program, vertex); gl.attachShader(program, fragment); gl.linkProgram(program); gl.deleteShader(vertex); gl.deleteShader(fragment); if (!gl.getProgramParameter(program, gl.LINK_STATUS)) { const message = gl.getProgramInfoLog(program); gl.deleteProgram(program); throw new Error(`WebGL program linking failed: ${message}`); } return program; } function pointDrawPasses(geometry) { if (!geometry.fading) { return geometry.count > 0 ? [{blending: false, count: geometry.count, depthWrite: true, first: 0}] : []; } const passes = []; if (geometry.staticCount > 0) { passes.push({blending: false, count: geometry.staticCount, depthWrite: true, first: 0}); } const fadingCount = geometry.count - geometry.staticCount; if (fadingCount > 0) { passes.push({blending: true, count: fadingCount, depthWrite: false, first: geometry.staticCount}); } return passes; } class PointRenderer { constructor(panel, camera, onCameraChange) { this.panel = panel; this.mode = panel.dataset.mode; this.canvas = panel.querySelector("canvas"); this.status = panel.querySelector('[data-role="status"]'); this.scale = panel.querySelector('[data-role="scale"]'); this.camera = camera; this.onCameraChange = onCameraChange; this.gl = this.canvas.getContext("webgl", {alpha: false, antialias: true, preserveDrawingBuffer: true}); invariant(this.gl, `WebGL is unavailable for ${this.mode}`); this.program = createProgram(this.gl); this.locations = this.getLocations(); this.buffers = { alpha: this.gl.createBuffer(), colors: this.gl.createBuffer(), positions: this.gl.createBuffer(), radius: this.gl.createBuffer(), }; invariant(this.buffers.alpha && this.buffers.colors && this.buffers.positions && this.buffers.radius, "WebGL could not allocate point buffers"); this.maxPointSize = Math.min(64, this.gl.getParameter(this.gl.ALIASED_POINT_SIZE_RANGE)[1]); this.installInteraction(); this.canvas.addEventListener("webglcontextlost", event => { event.preventDefault(); showError(new Error(`${this.mode}: WebGL context lost`)); }); new ResizeObserver(() => this.onCameraChange()).observe(this.canvas); } getLocations() { const gl = this.gl; const locations = { alpha: gl.getAttribLocation(this.program, "aAlpha"), color: gl.getAttribLocation(this.program, "aColor"), focalPixels: gl.getUniformLocation(this.program, "uFocalPixels"), maxPointSize: gl.getUniformLocation(this.program, "uMaxPointSize"), minPointSize: gl.getUniformLocation(this.program, "uMinPointSize"), position: gl.getAttribLocation(this.program, "aPosition"), projection: gl.getUniformLocation(this.program, "uProjection"), radius: gl.getAttribLocation(this.program, "aRadius"), view: gl.getUniformLocation(this.program, "uView"), }; invariant(locations.position >= 0 && locations.radius >= 0 && locations.color >= 0 && locations.alpha >= 0, "WebGL attribute lookup failed"); invariant(locations.projection && locations.view && locations.focalPixels && locations.maxPointSize && locations.minPointSize, "WebGL uniform lookup failed"); return locations; } installInteraction() { let previous = null; this.canvas.addEventListener("pointerdown", event => { previous = [event.clientX, event.clientY]; this.canvas.setPointerCapture(event.pointerId); }); this.canvas.addEventListener("pointermove", event => { if (!previous || !this.canvas.hasPointerCapture(event.pointerId)) { return; } const next = [event.clientX, event.clientY]; this.camera.orbit(next[0] - previous[0], next[1] - previous[1]); previous = next; }); this.canvas.addEventListener("pointerup", event => { if (this.canvas.hasPointerCapture(event.pointerId)) { this.canvas.releasePointerCapture(event.pointerId); } previous = null; }); this.canvas.addEventListener("wheel", event => { event.preventDefault(); this.camera.zoom(event.deltaY); }, {passive: false}); this.canvas.addEventListener("dblclick", () => { if (state.scene) { state.scopeKey=null;this.camera.reset(state.scene); } }); this.canvas.addEventListener("keydown", event => { const orbit = { ArrowDown: [0, 16], ArrowLeft: [-16, 0], ArrowRight: [16, 0], ArrowUp: [0, -16], }[event.key]; if (orbit) { event.preventDefault(); this.camera.orbit(orbit[0], orbit[1]); } else if (event.key === "+" || event.key === "=") { event.preventDefault(); this.camera.zoom(-140); } else if (event.key === "-" || event.key === "_") { event.preventDefault(); this.camera.zoom(140); } else if (event.key === "Home" && state.scene) { event.preventDefault(); state.scopeKey=null;this.camera.reset(state.scene); } }); } resize() { const ratio = Math.min(window.devicePixelRatio || 1, 2); const width = Math.max(1, Math.round(this.canvas.clientWidth * ratio)); const height = Math.max(1, Math.round(this.canvas.clientHeight * ratio)); if (this.canvas.width !== width || this.canvas.height !== height) { this.canvas.width = width; this.canvas.height = height; } return [width, height]; } bindFloatBuffer(buffer, location, values, components) { const gl = this.gl; gl.bindBuffer(gl.ARRAY_BUFFER, buffer); gl.bufferData(gl.ARRAY_BUFFER, values, gl.DYNAMIC_DRAW); gl.enableVertexAttribArray(location); gl.vertexAttribPointer(location, components, gl.FLOAT, false, 0, 0); } draw(geometry, scene) { const gl = this.gl; const [width, height] = this.resize(); gl.viewport(0, 0, width, height); gl.clearColor(0, 0, 0, 1); gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT); gl.enable(gl.DEPTH_TEST); gl.useProgram(this.program); this.bindFloatBuffer(this.buffers.alpha, this.locations.alpha, geometry.alpha, 1); this.bindFloatBuffer(this.buffers.positions, this.locations.position, geometry.positions, 3); this.bindFloatBuffer(this.buffers.radius, this.locations.radius, geometry.radius, 1); gl.bindBuffer(gl.ARRAY_BUFFER, this.buffers.colors); gl.bufferData(gl.ARRAY_BUFFER, geometry.colors, gl.DYNAMIC_DRAW); gl.enableVertexAttribArray(this.locations.color); gl.vertexAttribPointer(this.locations.color, 3, gl.UNSIGNED_BYTE, true, 0, 0); const fov = scene.fov * Math.PI / 180; const far = Math.max(100, this.camera.distance + this.camera.extent * 40); gl.uniformMatrix4fv(this.locations.view, false, this.camera.view()); gl.uniformMatrix4fv(this.locations.projection, false, perspective(fov, width / height, 0.005, far)); gl.uniform1f(this.locations.focalPixels, height / (2 * Math.tan(fov / 2))); gl.uniform1f(this.locations.maxPointSize, this.maxPointSize); gl.uniform1f(this.locations.minPointSize, scene.min_point_size || 1.25); for (const pass of pointDrawPasses(geometry)) { if (pass.blending) { gl.enable(gl.BLEND); gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA); } else { gl.disable(gl.BLEND); } gl.depthMask(pass.depthWrite); gl.drawArrays(gl.POINTS, pass.first, pass.count); } gl.depthMask(true); gl.disable(gl.BLEND); this.status.textContent = `${geometry.staticCount.toLocaleString()} static · ${geometry.liveCount.toLocaleString()} live`; } } function currentWindowIndex(frame = state.frame) { return state.assets ? state.assets.frameWindow[frame] : 0; } function playbackFrame(time) { if (!state.scene) { return 0; } return Math.max(0, Math.min(state.scene.frames - 1, Math.floor(time * state.scene.fps + 1e-4))); } function seekTimeForFrame(frame, fps) { // MP4 PTS quantization can round the nominal frame/fps boundary upward. // Move just inside the requested frame without ever crossing a quarter-frame. return frame / fps + Math.min(SEEK_BIAS_SECONDS, 0.25 / fps); } function updateFrameUi() { dom.timeline.value = String(state.frame); dom.frameOutput.textContent = `${state.frame} / ${Math.max(0, state.chunkEnd - 1)}`; } function setFrame(frame, seekVideo = true) { if (!state.scene) { return; } frame = Math.round(Number(frame)); frame = Math.max(state.chunkStart, Math.min(state.chunkEnd - 1, frame)); const changed = frame !== state.frame; state.frame = frame; updateFrameUi(); if (seekVideo) { const target = seekTimeForFrame(frame, state.scene.fps); // A sub-frame tolerance can leave the paused source image on frame N while // every 3D panel has already rendered N+1 at an owned-window boundary. if ( playbackFrame(dom.sourceVideo.currentTime) !== frame || Math.abs(dom.sourceVideo.currentTime - target) > 1e-6 ) { dom.sourceVideo.currentTime = target; } } if (changed || seekVideo) { renderCurrentFrame(); } } function setPlaybackUi(playing) { dom.playIcon.textContent = playing ? "Ⅱ" : "▶"; dom.playLabel.textContent = playing ? "Pause" : "Play"; dom.playButton.setAttribute("aria-label", playing ? "Pause" : "Play"); } function pause() { if (!dom.sourceVideo.paused) { dom.sourceVideo.pause(); } setPlaybackUi(false); } async function play() { invariant(state.scene, "No scene is loaded"); if (state.frame >= state.chunkEnd - 1) { setFrame(state.chunkStart); } try { await dom.sourceVideo.play(); setPlaybackUi(true); } catch (error) { showError(new Error(`Source video playback failed: ${errorText(error)}`)); } } function syncFromVideo(mediaTime = dom.sourceVideo.currentTime) { if (!state.scene || dom.sourceVideo.seeking) { return; } const frame = playbackFrame(mediaTime); if (frame >= state.chunkEnd) { pause(); setFrame(state.chunkEnd - 1); return; } if (frame < state.chunkStart) { setFrame(state.chunkStart); return; } if (frame !== state.frame) { setFrame(frame, false); } } function scheduleVideoFrames() { let callbackId = 0; const tick = () => { callbackId = 0; syncFromVideo(); if (!dom.sourceVideo.paused && !dom.sourceVideo.ended) { callbackId = setTimeout(tick, 16); } }; dom.sourceVideo.addEventListener("play", () => { if (!callbackId) callbackId = setTimeout(tick, 0); }); dom.sourceVideo.addEventListener("pause", () => { clearTimeout(callbackId); callbackId = 0; syncFromVideo(); copyInput(); }); dom.sourceVideo.addEventListener("seeked", () => { syncFromVideo(); copyInput(); }); } function populateChunks(scene) { dom.chunkSelect.replaceChildren(); const all = document.createElement("option"); all.value = "all"; all.textContent = `All · [0, ${scene.frames})`; dom.chunkSelect.appendChild(all); for (const [index, window] of scene.dyn.windows.entries()) { const option = document.createElement("option"); option.value = String(index); option.textContent = `C${index} · [${window.start}, ${window.own_end}) · ${window.L} frames`; dom.chunkSelect.appendChild(option); } dom.chunkSelect.value = "all"; state.chunkStart = 0; state.chunkEnd = scene.frames; dom.timeline.min = "0"; dom.timeline.max = String(scene.frames - 1); } function selectChunk() { pause(); if (!state.scene) { return; } if (dom.chunkSelect.value === "all") { state.chunkStart = 0; state.chunkEnd = state.scene.frames; } else { const index = Number(dom.chunkSelect.value); const window = state.scene.dyn.windows[index]; invariant(window, `Unknown chunk ${dom.chunkSelect.value}`); state.chunkStart = window.start; state.chunkEnd = window.own_end; } dom.timeline.min = String(state.chunkStart); dom.timeline.max = String(state.chunkEnd - 1); setFrame(state.chunkStart); } function provenanceSource(provenance) { return provenance?.source || provenance?.continuous_scene?.manifest?.source || {}; } function checkpointFields(provenance) { const checkpoint = provenance?.checkpoint; const checkpointObject = checkpoint && typeof checkpoint === "object" ? checkpoint : {}; const artifacts = provenance?.assembly_artifacts || {}; const firstArtifact = artifacts.raw || artifacts.stable || {}; return { architecture: provenance?.checkpoint_architecture || checkpointObject.architecture, sha256: provenance?.checkpoint_sha256 || checkpointObject.sha256 || provenance?.checkpoint_provenance?.sha256 || provenance?.assembly_manifest?.checkpoint_sha256 || firstArtifact.checkpoint_sha256, source: provenance?.checkpoint_source || checkpointObject.config_source || provenance?.checkpoint_provenance?.config_source, uri: (typeof checkpoint === "string" ? checkpoint : checkpointObject.uri) || provenance?.assembly_manifest?.checkpoint_uri || firstArtifact.checkpoint_uri, }; } function addSummary(label, value, options = {}) { const wrapper = document.createElement("div"); if (options.wide) { wrapper.classList.add("wide"); } if (options.missing) { wrapper.classList.add("missing"); } const term = document.createElement("dt"); term.textContent = label; const description = document.createElement("dd"); description.textContent = String(value); wrapper.append(term, description); dom.provenanceSummary.appendChild(wrapper); } function videoReady(scene, generation) { return new Promise((resolve, reject) => { const cleanup = () => { dom.sourceVideo.removeEventListener("loadeddata", loaded); dom.sourceVideo.removeEventListener("error", failed); }; const loaded = () => { cleanup(); if (generation !== state.generation) { resolve(); return; } const expected = (scene.frames - 1) / scene.fps; invariant(Number.isFinite(dom.sourceVideo.duration) && dom.sourceVideo.duration + 1 / scene.fps >= expected, `${scene.video}: duration ${dom.sourceVideo.duration} does not cover ${scene.frames} frames at ${scene.fps} FPS`); resolve(); }; const failed = () => { cleanup(); reject(new Error(`${scene.video}: browser failed to decode the embedded video`)); }; dom.sourceVideo.addEventListener("loadeddata", loaded); dom.sourceVideo.addEventListener("error", failed); dom.sourceVideo.src = assetUrl(scene.video); dom.sourceVideo.load(); }); } function enableControls(enabled) { dom.playButton.disabled = !enabled; dom.chunkSelect.disabled = !enabled; dom.timeline.disabled = !enabled; dom.resetCamera.disabled = !enabled; } function createRenderers() { state.camera ??= new OrbitCamera(renderCurrentFrame); state.renderers = Array.from(document.querySelectorAll(".point-panel")).map(panel => { if (!panel.pointRenderer) { panel.pointRenderer = new PointRenderer(panel, state.camera, renderCurrentFrame); } return panel.pointRenderer; }); } class WireWriter { constructor(byteLength) { this.buffer = new ArrayBuffer(byteLength); this.view = new DataView(this.buffer); this.offset = 0; } i16(...values) { for (const value of values) { this.view.setInt16(this.offset, value, true); this.offset += 2; } return this; } u16(...values) { for (const value of values) { this.view.setUint16(this.offset, value, true); this.offset += 2; } return this; } u8(...values) { for (const value of values) { this.view.setUint8(this.offset, value); this.offset += 1; } return this; } finish() { invariant(this.offset === this.buffer.byteLength, `wire fixture wrote ${this.offset}/${this.buffer.byteLength} bytes`); return this.buffer; } } function close(actual, expected, name) { invariant(Math.abs(actual - expected) <= 1e-6, `${name}: expected ${expected}, got ${actual}`); } function runWireSelfTest() { let checks = 0; const check = (condition, message) => { invariant(condition, `wire self-test: ${message}`); checks += 1; }; const staticWire = new WireWriter(20) .i16(1000, 0, 2000) .u16(1, 5000, 4, 2, 4) .u8(1, 2, 3, 0) .finish(); const fixed = decodeStatic(staticWire, 1, 3, "selftest.static"); close(fixed.positions[0], 1, "static x"); checks += 1; close(fixed.radius[0], 0.5, "static radius"); checks += 1; check(fixed.birth[0] === 1 && fixed.death[1][0] === 2 && fixed.originWindow[0] === 0, "static fields"); check(!(fixed.birth[0] <= 0 && 0 < fixed.death[0][0]), "birth is inclusive"); check(fixed.birth[0] <= 1 && 1 < fixed.death[0][0], "point visible at birth"); check(!(fixed.birth[0] <= 4 && 4 < fixed.death[0][0]), "death is exclusive"); const dynamicWire = new WireWriter(36) .i16(1000, 0, 1000, 1000, 0, 1500, 1005, 0, 0, 1000, 0, 0) .u16(2500, 3750) .u8(3, 2, 4, 5, 6, 13, 14, 15) .finish(); const dynamic = decodeTrackWindows(dynamicWire, [{start: 1, own_end: 3, end: 3, n: 2, L: 2}], false, "selftest.dyn")[0]; close(dynamic.positions[6], 2.005, "dynamic delta reconstruction"); checks += 1; close(dynamic.positions[9], 2, "dynamic second-track delta"); checks += 1; check(visibilityBit(dynamic, 0, 0) && visibilityBit(dynamic, 0, 1), "visibility frame zero"); check(!visibilityBit(dynamic, 1, 0) && visibilityBit(dynamic, 1, 1), "little-endian visibility bits"); const liveWire = new WireWriter(20) .i16(1000, 0, 1000, 1000, 0, 0) .u16(2500) .u8(1, 1, 10, 11, 12, 1) .finish(); const live = decodeTrackWindows(liveWire, [{start: 1, own_end: 3, end: 3, n: 1, L: 2}], true, "selftest.live")[0]; check(live.liveStart[0] === 1 && visibilityBit(live, 1, 0), "stable live onset and visibility"); const transformed = new Float32Array(3); transformAboutCenter(3, 4, 5, [1, 2, 3], 2, transformed, 0); check(transformed[0] === 5 && transformed[1] === 6 && transformed[2] === 7, "scale about origin-window camera centre"); const blendWindows = [ {end: 8, length: 8, start: 0}, {end: 9, length: 7, start: 2}, ]; const firstBlend = crossfadeLayers(blendWindows, 2, 1); close(firstBlend[0].alpha, 6 / 7, "first shared earlier alpha"); checks += 1; close(firstBlend[1].alpha, 1 / 7, "first shared later alpha"); checks += 1; const lastBlend = crossfadeLayers(blendWindows, 7, 1); close(lastBlend[0].alpha, 1 / 7, "last shared earlier alpha"); checks += 1; close(lastBlend[1].alpha, 6 / 7, "last shared later alpha"); checks += 1; check(crossfadeLayers(blendWindows, 8, 1).length === 1, "previous window hidden after overlap"); const alphaGeometry = new GeometryBuilder(1); alphaGeometry.add(0, 0, 1, 0.01, new Uint8Array([1, 2, 3]), 0, 1 / 7); close(alphaGeometry.value().alpha[0], 1 / 7, "geometry carries cross-fade alpha"); checks += 1; const passes = pointDrawPasses({count: 5, fading: true, staticCount: 3}); check(passes.length === 2, "cross-fade renders static and dynamic in separate passes"); check(passes[0].first === 0 && passes[0].count === 3 && passes[0].depthWrite, "static pass writes depth"); check(passes[1].first === 3 && passes[1].count === 2 && passes[1].blending && !passes[1].depthWrite, "fading pass blends without writing depth"); const nonIntegerFps = 30.00834652150149; const biasedSeek = seekTimeForFrame(41, nonIntegerFps); check( biasedSeek > 41 / nonIntegerFps && Math.floor(biasedSeek * nonIntegerFps) === 41, "seek bias stays inside a non-integer-FPS frame", ); return {checks, ok: true}; } window.__INFD4RT_VIEWER_SELF_TEST__ = runWireSelfTest; dom.playButton.addEventListener("click", () => { if (dom.sourceVideo.paused) { void play(); } else { pause(); } }); dom.resetCamera.addEventListener("click", () => { if (state.scene) { state.scopeKey=null;state.camera.reset(state.scene); } }); dom.timeline.addEventListener("input", () => { pause(); setFrame(Number(dom.timeline.value)); }); dom.chunkSelect.addEventListener("change", selectChunk); dom.sceneSelect.addEventListener("change", () => void loadSelectedScene()); dom.retryButton.addEventListener("click", () => void bootstrap().catch(showError)); dom.sourceVideo.addEventListener("pause", () => setPlaybackUi(false)); dom.sourceVideo.addEventListener("play", () => setPlaybackUi(true)); dom.sourceVideo.addEventListener("seeking", () => { if (state.scene) { const frame = playbackFrame(dom.sourceVideo.currentTime); if (frame >= state.chunkStart && frame < state.chunkEnd) { state.frame = frame; updateFrameUi(); renderCurrentFrame(); } } }); dom.sourceVideo.addEventListener("ended", pause); window.addEventListener("unhandledrejection", event => showError(event.reason)); window.addEventListener("error", event => { if (event.error) { showError(event.error); } }); function queryGeometry(data, gt) { const positions = gt ? data.q_gt3d : data.q_pred3d; const valid = gt ? data.q_gtvalid : data.q_predvalid; const builder = new GeometryBuilder(positions.length); for (let query = 0; query < positions.length; query += 1) { if (!data.keep[query] || state.frame < data.q_t_src[query] || !valid[query][state.frame]) continue; const xyz = positions[query][state.frame]; if (!xyz.every(Number.isFinite)) continue; const color = gt ? [30, 255, 70] : data.q_colors[query]; builder.add(...xyz, gt ? 0.0035 : 0.0025, color, 0); } builder.liveCount = builder.count; return builder.value(); } function drawQueryLayer(renderer, geometry, overlay) { const gl = renderer.gl; if (overlay) { gl.disable(gl.DEPTH_TEST); const pixelRatio = Math.min(window.devicePixelRatio || 1, 2); const minimum = state.scene.gt_min_point_size || (state.scene.gt_marker_radius_m ? 1.25 : ["pstudio", "adt"].includes(state.currentSample.dataset) ? 6 * pixelRatio : 1.25); gl.uniform1f(renderer.locations.minPointSize, Math.min(minimum, renderer.maxPointSize)); } renderer.bindFloatBuffer(renderer.buffers.alpha, renderer.locations.alpha, geometry.alpha, 1); renderer.bindFloatBuffer(renderer.buffers.positions, renderer.locations.position, geometry.positions, 3); renderer.bindFloatBuffer(renderer.buffers.radius, renderer.locations.radius, geometry.radius, 1); gl.bindBuffer(gl.ARRAY_BUFFER, renderer.buffers.colors); gl.bufferData(gl.ARRAY_BUFFER, geometry.colors, gl.DYNAMIC_DRAW); gl.vertexAttribPointer(renderer.locations.color, 3, gl.UNSIGNED_BYTE, true, 0, 0); gl.depthMask(!overlay); gl.drawArrays(gl.POINTS, 0, geometry.count); gl.uniform1f(renderer.locations.minPointSize, 1.25); gl.depthMask(true); gl.enable(gl.DEPTH_TEST); } document.getElementById("show-gt").addEventListener("change", renderCurrentFrame); window.__TOOLBOX_REVIEW__ = {setFrame, renderCurrentFrame, state}; async function readPackedJson(name) { const bytes=assetBytes(name); let value; if(bytes[0]===0x1f&&bytes[1]===0x8b){ const stream=new Blob([bytes]).stream().pipeThrough(new DecompressionStream("gzip")); value=await new Response(stream).json(); }else value=JSON.parse(new TextDecoder("utf-8",{fatal:true}).decode(bytes)); return value.position_codec?await decodeTrackBlob(value):value; } function requestedScene() { return new URLSearchParams(location.hash.slice(1)).get("scene") || new URLSearchParams(location.search).get("scene"); } window.addEventListener("hashchange", () => { const requested = requestedScene(); if (state.collection?.some(sample => sample.id === requested) && dom.sceneSelect.value !== requested) { fillScenes(state.collection.find(sample => sample.id === requested).dataset); dom.sceneSelect.value = requested; void loadSelectedScene(); } }); function validateNativeScene(scene) { const counts = scene.available_view_counts || [1,2,3,4,5,6,7,8,9,10]; invariant(Number.isInteger(scene.frames) && scene.frames > 0 && scene.states.length > 0, "Expected nonempty matched predictions"); invariant(scene.query_times.length === scene.query_count, "Query timeline length mismatch"); invariant(scene.gt.positions.length === scene.query_count, "Ground-truth query count mismatch"); const pairs = new Set(); const modes = new Set(); scene.states.forEach(entry => { const camera = entry.camera || "on"; const model = entry.model || "default"; const pair = model + ":" + camera + ":" + entry.views; invariant(["on","off"].includes(camera) && counts.includes(entry.views) && !pairs.has(pair), "Invalid or duplicate prediction state"); pairs.add(pair);modes.add(model+":"+camera); invariant(entry.positions.length === scene.query_count, "Prediction query count mismatch"); entry.positions.forEach(points => invariant(points.length === scene.frames, "Prediction frame count mismatch")); }); modes.forEach(mode => counts.forEach(views => invariant(pairs.has(mode+":"+views), "Missing matched prediction state"))); } function chosenLayers() { const primary = {views:Number(document.getElementById("primary-view").value),camera:document.getElementById("primary-camera").value,model:document.getElementById("primary-model").value}; const comparison = {views:Number(document.getElementById("comparison-view").value),camera:document.getElementById("comparison-camera").value,model:document.getElementById("comparison-model").value}; return comparison.views && (comparison.views !== primary.views || comparison.camera !== primary.camera || comparison.model !== primary.model) ? [primary,comparison] : [primary]; } function predictionState(layer) { const result = state.scene.states.find(value => value.views === layer.views && (value.camera || "on") === layer.camera && (value.model || "default") === layer.model); invariant(result, "The selected camera mode and view count are unavailable"); const score=currentScope().scores[layer.model+'_'+layer.camera]; return {...result,aj:score.aj,apd:score.apd,mean_error_cm:score.epe}; } function layerLabel(layer) { const model = state.scene.model_labels?.[layer.model]; return (model ? model + " · " : "") + "camera " + layer.camera.toUpperCase() + " · " + layer.views + "v"; } function configurePredictionSelectors(scene) { const counts = scene.available_view_counts || [1,2,3,4,5,6,7,8,9,10]; const modes = [...new Set(scene.states.map(value => value.camera || "on"))]; const models = [...new Set(scene.states.map(value => value.model || "default"))]; const paired=document.getElementById("paired-camera"); paired.parentElement.hidden=!scene.match_teacher_inputs; document.getElementById("primary-camera").parentElement.hidden=!!scene.match_teacher_inputs; document.getElementById("comparison-camera").parentElement.hidden=!!scene.match_teacher_inputs; for(const option of paired.options)option.disabled=!modes.includes(option.value); for (const id of ["primary-model","comparison-model"]) { const select=document.getElementById(id);select.replaceChildren(); models.forEach(model=>{const option=document.createElement("option");option.value=model;option.textContent=scene.model_labels?.[model]||"SCALE4D";select.appendChild(option);}); select.parentElement.hidden=models.length===1; } for (const id of ["primary-view","comparison-view"]) { const select = document.getElementById(id); for (const option of select.options) option.disabled = Number(option.value) !== 0 && !counts.includes(Number(option.value)); if (select.selectedOptions[0]?.disabled) select.value = String(counts[0]); } for (const id of ["primary-camera","comparison-camera"]) { const select = document.getElementById(id); for (const option of select.options) option.disabled = !modes.includes(option.value); if (!modes.includes(select.value)) select.value = modes[0]; } if (scene.default_comparison) { const value = scene.default_comparison; document.getElementById("primary-view").value = String(value.views); document.getElementById("comparison-view").value = String(value.views); document.getElementById("primary-camera").value = value.primary_camera; document.getElementById("comparison-camera").value = value.comparison_camera; document.getElementById("primary-model").value = value.primary_model || models[0]; document.getElementById("comparison-model").value = value.comparison_model || models[0]; if(scene.match_teacher_inputs){ paired.value=modes.includes(state.pairedCamera)?state.pairedCamera:value.primary_camera; document.getElementById("primary-camera").value=paired.value; document.getElementById("comparison-camera").value=paired.value; } } document.getElementById("dense-context").disabled = !scene.states.some(value => value.dense); if (scene.default_display) { document.getElementById("dense-context").checked = scene.default_display.context; document.getElementById("history-select").value = String(scene.default_display.history); } document.getElementById("gt-visible-only").checked = !!scene.default_display?.visible_gt; document.getElementById("query-density").value = String(scene.default_display?.query_budget || 0); } function chosenViews() { return chosenLayers().map(layer => layer.views); } function displayedQueryIds() { const ids=currentScope().ids; const budget=Number(document.getElementById("query-density").value); const count=budget>0?Math.min(budget,ids.length):ids.length; return Array.from({length:count},(_,i)=>ids[Math.floor(i*ids.length/count)]); } function frameGeometry(layer, gt=false, history=0, index=0) { const sample = state.scene; const prediction = gt ? sample.gt : predictionState(layer); const positions = prediction.positions; const valid = prediction.valid; const dense = !gt && document.getElementById("dense-context").checked ? prediction.dense : null; const builder = new GeometryBuilder(sample.query_count*(history+1)+(dense?dense.positions.length:0)); const selected = chosenViews(); const rgb = document.getElementById("rgb-colors").checked && !gt && selected.length === 1; const shade = gt ? [30,255,70] : index === 0 ? [65,197,255] : [255,156,93]; for(let frame=Math.max(0,state.frame-history); frame<=state.frame; frame++) { for(const query of displayedQueryIds()) { if(frame0; return builder.value(); } function combineGeometry(layers) { const count=layers.reduce((n,layer)=>n+layer.count,0); const builder=new GeometryBuilder(count); for(const layer of layers) { for(let point=0;pointlayer.views),history=Number(document.getElementById("history-select").value); const showGt=document.getElementById("show-gt").checked; const layers=selected.map((layer,index)=>frameGeometry(layer,false,history,index)); const renderer=state.renderers[0]; renderer.draw(combineGeometry(layers),state.scene); const gt=frameGeometry(0,true,0); if(showGt)drawQueryLayer(renderer,gt,true); renderer.gl.flush(); const primary=predictionState(selected[0]); const comparison=selected.length>1?predictionState(selected[1]):null; document.getElementById("model-title").textContent="SCALE4D · "+selected.map(layerLabel).join(" vs "); renderer.status.textContent=selected.map((layer,i)=>layerLabel(layer)+": "+layers[i].count+" points").join(" · ")+" · "+(showGt?gt.count:0)+" GT"; renderer.scale.textContent=(state.scene.position_source==="xyz"?"Native metric XYZ":"Native UV/depth coordinates")+" · no alignment · "+currentScope().ids.length+" scoped scored queries"; const displayed = displayedQueryIds(); if (displayed.length < state.scene.query_count) renderer.scale.textContent += " · "+displayed.length+" fixed queries displayed"; if (document.getElementById("gt-visible-only").checked) renderer.scale.textContent += " · displaying GT-visible queries"; document.getElementById("selected-example").textContent=datasetNames[state.scene.dataset]+" · "+state.scene.label+ " · cyan "+layerLabel(selected[0])+" AJ "+primary.aj.toFixed(2)+"% · scoped error "+primary.mean_error_cm.toFixed(2)+" cm"+ (comparison?" · orange "+layerLabel(selected[1])+" AJ "+comparison.aj.toFixed(2)+"% · scoped error "+comparison.mean_error_cm.toFixed(2)+" cm":"")+ " · "+(selected.length>1&&selected[0].model!==selected[1].model?"separate EMA checkpoints; matched frame and queries":"same checkpoint, frame, and queries"); dom.videoFrame.textContent=String(state.frame); window.__TOOLBOX_FRAME_REPORT__=[{frame:state.frame,views,cameras:selected.map(layer=>layer.camera),models:selected.map(layer=>layer.model),counts:layers.map(x=>x.count),gt:showGt?gt.count:0,displayed_query_ids:displayed,position_source:state.scene.position_source}]; copyInput(); } function projectedPoint(xyz,camera) { const transform=state.scene.relative_cameras[camera][state.frame]; const point=[0,0,0]; for(let row=0;row<3;row++)point[row]=transform[row][3]+transform[row][0]*xyz[0]+transform[row][1]*xyz[1]+transform[row][2]*xyz[2]; if(!point.every(Number.isFinite)||point[2]<=0)return null; const k=state.scene.intrinsics[camera][state.frame]; const homogeneous=k.map(row=>row[0]*point[0]+row[1]*point[1]+row[2]*point[2]); return [homogeneous[0]/homogeneous[2]/state.scene.image_width,homogeneous[1]/homogeneous[2]/state.scene.image_height]; } function copyInput() { const video=dom.sourceVideo;if(!state.scene)return; if(video.readyState<2||video.seeking||playbackFrame(video.currentTime)!==state.frame||video.currentSrc!==assetUrl(state.scene.video)){ const canvas=document.getElementById("single-input"); canvas.getContext("2d").clearRect(0,0,canvas.width,canvas.height); dom.inputStatus.textContent="Loading RGB frame "+state.frame; window.__TOOLBOX_RGB_FRAME__=null; return; } const camera=Number(document.getElementById("display-camera").value),grid=state.scene.video_grid; const canvas=document.getElementById("single-input"),stage=canvas.parentElement.getBoundingClientRect(),ratio=Math.min(window.devicePixelRatio||1,2); canvas.width=Math.max(1,Math.round(stage.width*ratio));canvas.height=Math.max(1,Math.round(stage.height*ratio)); const context=canvas.getContext("2d"),scale=Math.min(canvas.width/grid.cell_width,canvas.height/grid.cell_height); const width=grid.cell_width*scale,height=grid.cell_height*scale,x=(canvas.width-width)/2,y=(canvas.height-height)/2; context.fillStyle="#000";context.fillRect(0,0,canvas.width,canvas.height); context.drawImage(video,(camera%grid.columns)*grid.cell_width,Math.floor(camera/grid.columns)*grid.cell_height,grid.cell_width,grid.cell_height,x,y,width,height); const selected=chosenLayers(); const arrays=selected.map((layer,index)=>{const prediction=predictionState(layer);return {positions:prediction.positions,valid:prediction.valid,color:index?"#ff9c5d":"#41c5ff"};}); if(document.getElementById("show-gt").checked)arrays.push({positions:state.scene.gt.positions,valid:state.scene.gt.valid,color:"#1eff46",radius:state.scene.gt_pixel_radius||2.0}); for(const layer of arrays) { context.fillStyle=layer.color; for(const query of displayedQueryIds()) { if(state.frame1||uv[1]>1)continue; context.beginPath();context.arc(x+uv[0]*width,y+uv[1]*height,(layer.radius||2.0)*ratio,0,Math.PI*2);context.fill(); } } dom.inputStatus.textContent="Camera "+state.scene.camera_ids[camera]+" · display only"; window.__TOOLBOX_RGB_FRAME__={scene:state.scene.id,frame:state.frame,video_frame:playbackFrame(video.currentTime)}; } function waitForRgbFrame(generation) { return new Promise((resolve,reject)=>{ let timeout; const cleanup=()=>{ clearTimeout(timeout); for(const event of ["seeked","loadeddata","error"])dom.sourceVideo.removeEventListener(event,check); }; const check=()=>{ if(generation!==state.generation){cleanup();resolve();return;} if(dom.sourceVideo.error){cleanup();reject(new Error("Could not decode the selected RGB frame"));return;} copyInput(); if(window.__TOOLBOX_RGB_FRAME__){cleanup();resolve();} }; for(const event of ["seeked","loadeddata","error"])dom.sourceVideo.addEventListener(event,check); timeout=setTimeout(()=>{cleanup();reject(new Error("Selected RGB frame did not become ready"));},15000); check(); }); } async function loadSelectedScene() { const selected=state.collection.find(sample=>sample.id===dom.sceneSelect.value); invariant(selected,"Unknown candidate"); const generation=++state.generation; pause();enableControls(false);hideError();window.__TOOLBOX_READY__=false; try { setLoading("Loading candidate","Reading the matched SCALE4D predictions",.1); const scene=await readPackedJson(selected.data); if(generation!==state.generation)return; validateNativeScene(scene); state.scene=scene;state.currentSample=selected; configurePredictionSelectors(scene); state.assets={frameWindow:new Int16Array(scene.frames)}; state.camera.reset(scene,false); state.frame=0;populateChunks(scene); const camera=document.getElementById("display-camera");camera.replaceChildren(); scene.camera_ids.forEach((id,index)=>{const option=document.createElement("option");option.value=String(index);option.textContent="Camera "+id+(index===0?" (target)":"");camera.appendChild(option);}); camera.value=String(scene.default_display_camera ?? 1); updateProvenance(scene); await videoReady(scene,generation); if(generation!==state.generation)return; setFrame(scene.default_frame||30); await waitForRgbFrame(generation); if(generation!==state.generation)return; enableControls(true);finishLoading();window.__TOOLBOX_READY__=true; }catch(error){if(generation===state.generation)showError(error);} } function updateProvenance(scene) { dom.provenanceSummary.replaceChildren(); addSummary("Model",scene.model_description || "SCALE4D · frozen 140k checkpoint"); addSummary("Input counts",(scene.available_view_counts||[1,2,3,4,5,6,7,8,9,10]).join(", ")+" input views; target camera fixed"); addSummary("Conditioning",scene.comparison_description || (scene.states.some(value=>value.camera==="off")?"ON and OFF use identical images, queries, camera order, and frozen checkpoint. Only camera conditioning changes.":"Camera conditioning ON")); addSummary("Coordinates",scene.position_source==="xyz"?"Native metric XYZ tracks used by the distillation evaluator; target-camera coordinates":"Exactly the UV-and-predicted-depth lifting used in Figure 11; native metric target-camera coordinates"); addSummary("Geometry",scene.query_count+" complete scored query trajectories in native metric coordinates."); if(scene.states.some(value=>value.dense))addSummary("Context","The additional source-frame-zero pixel-grid predictions provide scene context. Scores above use the original benchmark queries."); if(scene.default_display?.visible_gt)addSummary("Display filter","GT-visible queries shows both teachers on queries with visible ground truth at each frame. Turn it off to display all predictions. Scores use the complete scored clip."); addSummary("Query density","Lower densities use fixed, evenly spaced query IDs shared by both teachers and GT. Sampling uses query order, independent of prediction errors. All queries remain available; scores use the full clip."); addSummary("Display camera","The reference reference camera can be outside the chosen model input subset. It is used only to display projections."); addSummary("Selection",scene.selection); addSummary("Reference","Adapted from the supplied Pixelcloud viewer; its older checkpoint data is replaced."); dom.windowDetails.textContent=JSON.stringify(scene.benchmark_scores,null,2); dom.reportDetails.textContent=JSON.stringify(scene.states.map(x=>({input_views:x.views,camera_conditioning:x.camera||"on",aj_percent:x.aj,apd_percent:x.apd,mean_error_cm:x.mean_error_cm})),null,2); dom.provenanceDetails.textContent=JSON.stringify(scene.checkpoint_provenance||{model:"SCALE4D",checkpoint_iteration:scene.checkpoint_iteration||140000,frames:scene.frames,position_source:scene.position_source,query_count:scene.query_count},null,2); } async function bootstrap() { try { enableControls(false);hideError(); const result=runWireSelfTest();window.__VIEWER_SELF_TEST_RESULT__=result; dom.selfTestStatus.textContent="renderer self-test passed · "+result.checks+" checks";dom.selfTestStatus.classList.add("passed"); createRenderers(); state.collection=await readPackedJson("scenes.json"); invariant(state.collection.length>0,"Expected sample scenes"); const datasets=[...new Set(state.collection.map(item=>item.dataset))]; const datasetSelect=document.getElementById("dataset-select");datasetSelect.replaceChildren(); datasets.forEach(dataset=>{const option=document.createElement("option");option.value=dataset;datasetNames[dataset]=state.collection.find(item=>item.dataset===dataset).dataset_label||datasetNames[dataset]||dataset;option.textContent=datasetNames[dataset];datasetSelect.appendChild(option);}); fillScenes(datasets[0]); const requested=requestedScene();const chosen=state.collection.find(x=>x.id===requested); if(chosen)fillScenes(chosen.dataset); dom.sceneSelect.value=chosen?.id||state.collection[0].id; await loadSelectedScene(); }catch(error){showError(error);} } ["primary-view","comparison-view","primary-model","comparison-model","primary-camera","comparison-camera","display-camera","rgb-colors","history-select","dense-context","gt-visible-only","query-density"].forEach(id=>document.getElementById(id).addEventListener("change",renderCurrentFrame)); document.getElementById("paired-camera").addEventListener("change",event=>{ state.pairedCamera=event.target.value; document.getElementById("primary-camera").value=event.target.value; document.getElementById("comparison-camera").value=event.target.value; renderCurrentFrame(); }); window.__TOOLBOX_REVIEW__={setFrame,renderCurrentFrame,state}; scheduleVideoFrames(); bootstrap().catch(showError); function currentScope() { const key = document.getElementById('point-scope').value || 'object'; return {key, ...state.scene.scopes[key]}; } function metricScopeLabel() { return currentScope().key === 'all' ? 'full-clip error' : currentScope().label.toLowerCase() + ' error'; } function updateScopeCamera() { const scope = currentScope(); const key = state.scene.id + ':' + scope.key; if (state.scopeKey !== key) { state.camera.reset({...state.scene, target: scope.view.targets[state.frame], extent: scope.view.extent}, false); state.scopeKey = key; } state.camera.target = scope.view.targets[state.frame].map(Number); } function renderCurrentFrame() { if (!state.scene || !state.renderers.length) return; const four = document.getElementById('comparison-layout').value === 'four'; document.body.classList.toggle('four-way', four); for (const id of ['paired-camera','primary-model','comparison-model','primary-view','comparison-view']) { document.getElementById(id).parentElement.hidden = four; } const rgbLabel=document.getElementById('rgb-colors').closest('label'); if(rgbLabel) rgbLabel.hidden=four; updateScopeCamera(); renderOverlayFrame(); if (!four) return; document.getElementById('rgb-colors').checked=false; const history = Number(document.getElementById('history-select').value); const gt = frameGeometry(0, true, 0); const showGt = document.getElementById('show-gt').checked; const scope = currentScope(); const pairs = [ {model:'b2_ema',camera:'off',views:3}, {model:'b3_ema',camera:'off',views:3}, {model:'b2_ema',camera:'on',views:3}, {model:'b3_ema',camera:'on',views:3}, ]; const reports = []; for (let index = 0; index < pairs.length; index++) { const layer = pairs[index], renderer = state.renderers[index]; const geometry = frameGeometry(layer, false, history, layer.model === 'b3_ema' ? 0 : 1); renderer.draw(geometry, state.scene); if (showGt) drawQueryLayer(renderer, gt, true); renderer.gl.flush(); const score = predictionState(layer); renderer.panel.querySelector('h2').textContent = layer.camera.toUpperCase() + ' · ' + (layer.model === 'b3_ema' ? 'B3' : 'B2') + ' · ' + score.mean_error_cm.toFixed(2) + ' cm'; renderer.status.textContent = ''; renderer.scale.textContent = scope.label + ' · shared GT and view · ' + geometry.count + ' predictions / ' + gt.count + ' GT'; reports.push({frame:state.frame,model:layer.model,camera:layer.camera,views:3,query_ids:displayedQueryIds(),prediction_count:geometry.count,gt_count:gt.count,mean_error_cm:score.mean_error_cm}); } document.getElementById('selected-example').textContent = state.scene.label + ' · ' + scope.label + ' · '+scope.ids.length+' scoped scored queries · saved EMA 65k · 3 views · cyan B3 · orange B2 · green GT · all four panels share the same frame, GT queries and view'; window.__TOOLBOX_FRAME_REPORT__ = reports; window.__QUAD_REVIEW__ = {scope:scope.key,scored_queries:scope.ids.length,displayed_queries:displayedQueryIds().length,shared_target:state.camera.target.slice(),reports}; } document.getElementById('comparison-layout').addEventListener('change', renderCurrentFrame); document.getElementById('point-scope').addEventListener('change', () => { state.scopeKey = null; renderCurrentFrame(); }); async function decodeTrackBlob(scene) { const codec=scene.position_codec; if(!codec)return scene; if(codec.version!==1||codec.scale!==10000)throw new Error('Unsupported coordinate codec'); const stream=new Blob([assetBytes(codec.asset)]).stream().pipeThrough(new DecompressionStream('gzip')); const bytes=new Uint8Array(await new Response(stream).arrayBuffer()); const integers=[]; let cursor=0; function signed(){ let value=0,shift=0,byte; do{ if(cursor>=bytes.length||shift>35)throw new Error('Malformed coordinate stream'); byte=bytes[cursor++];value+=(byte&127)*2**shift;shift+=7; }while(byte&128); return value%2?-(value+1)/2:value/2; } for(let layer=0;layer>>0; } track.push(xyz); } positions.push(track); } if(hash.toString(16).padStart(8,'0')!==codec.checksums[layer])throw new Error('Coordinate checksum mismatch'); result.positions=positions;integers.push(quantized); } if(cursor!==bytes.length)throw new Error('Unexpected coordinate bytes'); scene.coordinate_codec_verified=true; return scene; }