Spaces:
Running on Zero

Flow4RT / viewer /viewer.js
github-actions[bot]
Sync from GitHub main@8597c25
12e4f34
Raw History Blame Contribute Delete
18.7 kB
/* Flow4RT 4D viewer of one prediction, adapted from the project page's viewer.
*
* visualize.py embeds the data as F4RT.add({...}) calls before this script: the scene description
* (kind "meta"), the dense tracks ("track") and the point maps in chunks of frames ("recon").
* Arrays are int16/uint8, byte-shuffled and gzipped; positions are normalised to the scene radius.
*/
(function () {
'use strict';
const RADIUS_CLIP = 2.5; // positions are quantised to [-2.5, 2.5] scene radii
const FPS = 12;
const LOOP_PAUSE = 1000; // ms to hold the last frame before looping back
const TRACK_FADE = 0.6; // how far tracking-mode points are washed out towards white
const TRAIL_WIDTH = 2.5; // px
// ------------------------------------------------------------------ decoding
async function inflate(b64, Type) {
const bin = atob(b64);
const bytes = new Uint8Array(bin.length);
for (let i = 0; i < bin.length; i++) bytes[i] = bin.charCodeAt(i);
const stream = new Blob([bytes]).stream().pipeThrough(new DecompressionStream('gzip'));
const buf = new Uint8Array(await new Response(stream).arrayBuffer());
const k = Type.BYTES_PER_ELEMENT;
if (k === 1) return new Type(buf.buffer);
const n = buf.length / k, out = new Uint8Array(buf.length);
for (let b = 0; b < k; b++) {
const off = b * n;
for (let i = 0; i < n; i++) out[i * k + b] = buf[off + i];
}
return new Type(out.buffer);
}
async function decode(parts) {
const meta = parts.find(p => p.kind === 'meta'), T = meta.T;
// Point maps: the chunks concatenated in frame order, so that frames 0..t are one draw range.
const chunks = parts.filter(p => p.kind === 'recon').sort((a, b) => a.first - b.first);
const counts = chunks.flatMap(c => c.counts), offsets = [0];
counts.forEach(c => offsets.push(offsets[offsets.length - 1] + c));
const n = offsets[T];
const recon = { counts, offsets, pos: new Int16Array(n * 3), col: new Uint8Array(n * 3), conf: new Uint8Array(n) };
for (const c of chunks) {
const o = offsets[c.first];
recon.pos.set(await inflate(c.pos, Int16Array), o * 3);
recon.col.set(await inflate(c.col, Uint8Array), o * 3);
recon.conf.set(await inflate(c.conf, Uint8Array), o);
}
// Dense tracks: frame-to-frame deltas, summed up (int16 wrap is exact).
const tp = parts.find(p => p.kind === 'track'), N = tp.n;
const delta = await inflate(tp.pos, Int16Array); // (T, 3, N)
const frames = new Int16Array(T * N * 3), cur = new Int16Array(N * 3);
for (let t = 0; t < T; t++) {
for (let c = 0; c < 3; c++) {
const base = (t * 3 + c) * N;
for (let i = 0; i < N; i++) cur[i * 3 + c] += delta[base + i];
}
frames.set(cur, t * N * 3);
}
const track = { n: N, frames, col: await inflate(tp.col, Uint8Array), conf: await inflate(tp.conf, Uint8Array) };
const trails = {};
for (const [name, s] of Object.entries(meta.trails)) {
const q = await inflate(s.pos, Int16Array); // (T, Q, 3)
const f = new Float32Array(q.length);
for (let i = 0; i < q.length; i++) f[i] = q[i] / 32767 * RADIUS_CLIP;
trails[name] = { traj: f, Q: s.colors.length, colors: s.colors, uv: s.uv };
}
return { meta, recon, track, trails };
}
// ------------------------------------------------------------------ helpers
let DISC = null;
function disc() {
if (DISC) return DISC;
const c = document.createElement('canvas');
c.width = c.height = 64;
const g = c.getContext('2d');
g.beginPath(); g.arc(32, 32, 30, 0, Math.PI * 2); g.fillStyle = '#fff'; g.fill();
// Nearest filtering without mipmaps: minified mip levels would blend the
// disc's transparent-black surround into small points and darken them.
DISC = new THREE.CanvasTexture(c);
DISC.generateMipmaps = false;
DISC.minFilter = DISC.magFilter = THREE.NearestFilter;
return DISC;
}
// Disc point sprites that drop points below the confidence percentile `u.thr` and are washed
// out towards the white background by `u.fade` in [0, 1].
function cloudMaterial(u) {
const mat = new THREE.PointsMaterial({ size: 0.01, vertexColors: true, map: disc(), alphaTest: 0.5, sizeAttenuation: true });
mat.onBeforeCompile = s => {
s.uniforms.fade = u.fade;
s.uniforms.thr = u.thr;
s.vertexShader = 'attribute float confq;\nuniform float thr;\n' + s.vertexShader.replace('#include <project_vertex>',
'#include <project_vertex>\n\tif (confq < thr) gl_Position = vec4(0.0, 0.0, 2.0, 1.0);');
s.fragmentShader = 'uniform float fade;\n' + s.fragmentShader.replace('#include <color_fragment>',
'#include <color_fragment>\n\tdiffuseColor.rgb = mix(diffuseColor.rgb, vec3(1.0), fade);');
};
mat.customProgramCacheKey = () => 'cloud';
return mat;
}
function cloud(pos, col, conf, mat) {
const g = new THREE.BufferGeometry();
g.setAttribute('position', pos);
g.setAttribute('color', new THREE.BufferAttribute(col, 3, true));
g.setAttribute('confq', new THREE.BufferAttribute(conf, 1));
const p = new THREE.Points(g, mat);
p.frustumCulled = false;
return p;
}
// The trajectory style of the paper figures: each curve widens and fades in from its old end,
// relative to the frame shown now. Every segment carries its frame index; `now` is set per frame.
const FADE_FLOOR = 0.12, FADE_GAMMA = 1.6, TAPER = 0.35;
function taperAndFade(g, m, T, Q) {
const ti = new Float32Array((T - 1) * Q);
for (let t = 0; t < T - 1; t++) ti.fill(t, t * Q, (t + 1) * Q);
g.setAttribute('instanceT', new THREE.InstancedBufferAttribute(ti, 1));
m.userData.now = { value: T - 1 };
m.onBeforeCompile = s => {
s.uniforms.now = m.userData.now;
s.vertexShader = s.vertexShader
.replace('attribute vec3 instanceColorStart;',
'attribute vec3 instanceColorStart;\nattribute float instanceT;\nuniform float now;\nvarying float vFade;')
.replace('void main() {',
'void main() {\n\tfloat ff = clamp((instanceT + 1.0) / max(now, 1.0), 0.0, 1.0);\n' +
`\tvFade = ${FADE_FLOOR.toFixed(3)} + ${(1 - FADE_FLOOR).toFixed(3)} * pow(ff, ${FADE_GAMMA.toFixed(2)});\n` +
`\tfloat taper = ${TAPER.toFixed(3)} + ${(1 - TAPER).toFixed(3)} * ff;`)
.replace('offset *= linewidth;', 'offset *= linewidth * taper;');
s.fragmentShader = 'varying float vFade;\n' + s.fragmentShader
.replace('#include <color_fragment>', '#include <color_fragment>\n\talpha *= vFade;');
};
m.customProgramCacheKey = () => 'trail-fade';
}
// Fat line segments, time-major so that `instanceCount = t * Q` reveals every trajectory up to
// frame t, and the heads of the trajectories as dots.
function trailObject(tr, T) {
const { traj, Q, colors } = tr;
const pos = new Float32Array((T - 1) * Q * 6), col = new Float32Array((T - 1) * Q * 6);
for (let t = 0; t < T - 1; t++) {
for (let q = 0; q < Q; q++) {
const s = (t * Q + q) * 6, a = (t * Q + q) * 3, b = ((t + 1) * Q + q) * 3;
pos.set(traj.subarray(a, a + 3), s); pos.set(traj.subarray(b, b + 3), s + 3);
const c = colors[q].map(v => v / 255);
col.set(c, s); col.set(c, s + 3);
}
}
const g = new THREE.LineSegmentsGeometry();
g.setPositions(pos); g.setColors(col);
const m = new THREE.LineMaterial({ linewidth: TRAIL_WIDTH, vertexColors: true, depthTest: false, transparent: true });
taperAndFade(g, m, T, Q);
const line = new THREE.LineSegments2(g, m);
line.renderOrder = 6;
line.frustumCulled = false;
const hg = new THREE.BufferGeometry();
const headPos = new THREE.BufferAttribute(new Float32Array(Q * 3), 3);
hg.setAttribute('position', headPos);
hg.setAttribute('color', new THREE.BufferAttribute(new Float32Array(colors.flat().map(v => v / 255)), 3));
const heads = new THREE.Points(hg, new THREE.PointsMaterial({ size: 6, sizeAttenuation: false,
vertexColors: true, map: disc(), alphaTest: 0.5, depthTest: false }));
heads.renderOrder = 7; heads.frustumCulled = false;
const group = new THREE.Group();
group.add(line, heads);
return {
group, line,
update(t) {
line.geometry.instanceCount = t * Q;
m.userData.now.value = t; // fade relative to this frame
headPos.array.set(traj.subarray(t * Q * 3, (t + 1) * Q * 3));
headPos.needsUpdate = true;
},
};
}
// Camera frustums as thin lines: apex to the four image corners, and the image rectangle.
function frustumObject(f) {
const idx = [0, 1, 0, 2, 0, 3, 0, 4, 1, 2, 2, 3, 3, 4, 4, 1];
const g = new THREE.BufferGeometry();
g.setAttribute('position', new THREE.Float32BufferAttribute(idx.flatMap(i => f[i]), 3));
return new THREE.LineSegments(g);
}
// ------------------------------------------------------------------ app
const ICON_PLAY = '<svg viewBox="0 0 16 16"><path fill="currentColor" d="M4.5 2.3v11.4c0 .5.5.8.9.5l8.6-5.7a.6.6 0 0 0 0-1L5.4 1.8c-.4-.3-.9 0-.9.5z"/></svg>';
const ICON_PAUSE = '<svg viewBox="0 0 16 16"><rect x="3.2" y="2" width="3.4" height="12" rx="1" fill="currentColor"/><rect x="9.4" y="2" width="3.4" height="12" rx="1" fill="currentColor"/></svg>';
async function main() {
const $ = sel => document.querySelector(sel);
const box = $('.canvas-box'), overlay = $('.overlay');
if (typeof DecompressionStream === 'undefined') {
overlay.textContent = 'This browser lacks DecompressionStream; please use a recent Chrome, Firefox, Safari or Edge.';
return;
}
// The web demo opens the viewer as viewer.html?download: a button that saves this page, a self-contained file.
const download = $('.download');
download.hidden = !new URLSearchParams(location.search).has('download');
if (!window.F4RT.parts.length) { // a viewer without data (write_empty_viewer): a blank canvas with a note
document.body.classList.add('no-data');
overlay.textContent = window.F4RT.empty || 'No data';
$('.playbtn').innerHTML = ICON_PLAY;
return;
}
const { meta, recon, track, trails } = await decode(window.F4RT.parts);
download.href = location.pathname; // only now: the button of the empty viewer stays a dead, greyed label
download.download = decodeURIComponent(location.pathname.split('/').pop());
const T = meta.T;
const opt = id => $('#opt-' + id);
// Initial state from the URL, e.g. viewer.html?mode=recon&t=20&accum=1
const params = new URLSearchParams(location.search);
for (const [k, v] of params) if (opt(k) && opt(k).type === 'checkbox') opt(k).checked = v !== '0';
const state = { mode: params.get('mode') === 'recon' ? 'recon' : 'track', t: 0, playing: true };
if (params.has('t')) { state.t = Math.max(0, Math.min(T - 1, +params.get('t'))); state.playing = false; }
// preserveDrawingBuffer so that the canvas can be saved as an image or screenshotted.
const renderer = new THREE.WebGLRenderer({ canvas: $('canvas.gl'), antialias: true, preserveDrawingBuffer: true });
renderer.setClearColor(0xffffff, 1);
renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 2));
const camera = new THREE.PerspectiveCamera(36, 1.6, 0.01, 100);
const controls = new THREE.OrbitControls(camera, renderer.domElement);
controls.enableDamping = true;
controls.dampingFactor = 0.12;
controls.rotateSpeed = 0.7;
controls.zoomSpeed = 0.8;
let dirty = true;
controls.addEventListener('change', () => { dirty = true; });
// ---- scene
const scene = new THREE.Scene();
const group = new THREE.Group();
group.scale.setScalar(RADIUS_CLIP); // int16 normalised -> scene units
scene.add(group);
const u = { fade: { value: 0 }, thr: { value: 0 } };
const mat = cloudMaterial(u);
const reconPts = cloud(new THREE.BufferAttribute(recon.pos, 3, true), recon.col, recon.conf, mat);
const trackPos = new THREE.BufferAttribute(new Int16Array(track.n * 3), 3, true);
trackPos.setUsage(THREE.DynamicDrawUsage);
const trackPts = cloud(trackPos, track.col, track.conf, mat);
group.add(reconPts, trackPts);
const trailObjs = {};
for (const [name, tr] of Object.entries(trails)) {
if (!tr.Q) continue;
trailObjs[name] = trailObject(tr, T);
scene.add(trailObjs[name].group);
}
const frustums = meta.frustums.map(frustumObject);
const past = new THREE.LineBasicMaterial({ color: 0x9aa3ad }), current = new THREE.LineBasicMaterial({ color: 0xea7814 });
frustums.forEach(f => scene.add(f));
// ---- controls
const slider = $('.timeline input'), playBtn = $('.playbtn'), tlabel = $('.tlabel');
slider.max = T - 1;
$('.scene-sub').textContent = `${T} frames · ${meta.w}×${meta.h}`;
const markMode = () => document.querySelectorAll('.seg-mode button').forEach(b => b.classList.toggle('on', b.dataset.v === state.mode));
document.querySelectorAll('.seg-mode button').forEach(b => {
b.onclick = () => { state.mode = b.dataset.v; markMode(); update(); };
});
markMode();
['trails', 'current', 'accum', 'cams'].forEach(id => { opt(id).onchange = update; });
opt('moving').onchange = () => { drawQueries(); update(); };
const confVal = $('#opt-conf + .val');
opt('conf').oninput = () => { u.thr.value = +opt('conf').value; confVal.textContent = opt('conf').value + '%'; dirty = true; };
opt('conf').oninput();
opt('size').oninput = () => { mat.size = meta.pointSize * opt('size').value; dirty = true; };
opt('size').oninput();
$('.reset').onclick = resetCamera;
slider.oninput = () => { state.t = +slider.value; state.playing = false; syncPlay(); update(); };
playBtn.onclick = () => { state.playing = !state.playing; syncPlay(); };
function syncPlay() {
playBtn.innerHTML = state.playing ? ICON_PAUSE : ICON_PLAY;
playBtn.setAttribute('aria-label', state.playing ? 'Pause' : 'Play');
}
syncPlay();
function resetCamera() {
camera.position.set(...meta.cam.pos);
controls.target.set(...meta.cam.target);
controls.update();
dirty = true;
}
function trailSet() { return opt('moving').checked ? 'moving' : 'all'; }
function drawQueries() {
const img = $('.frame0 img'), cv = $('.frame0 canvas');
const draw = () => {
const r = img.getBoundingClientRect(), dpr = window.devicePixelRatio || 1;
cv.width = r.width * dpr; cv.height = r.height * dpr;
const g = cv.getContext('2d');
g.scale(dpr, dpr);
const tr = trails[trailSet()];
tr.uv.forEach(([x, y], i) => {
const [R, G, B] = tr.colors[i];
g.beginPath(); g.arc(x * r.width, y * r.height, 2.4, 0, 7); g.fillStyle = '#222'; g.fill();
g.beginPath(); g.arc(x * r.width, y * r.height, 1.6, 0, 7); g.fillStyle = `rgb(${R},${G},${B})`; g.fill();
});
};
if (img.complete && img.naturalWidth) draw(); else img.onload = draw;
}
$('.frame0 img').src = meta.frames[meta.anchor];
drawQueries();
function update() {
const t = state.t, trackMode = state.mode === 'track';
const accum = !trackMode && opt('accum').checked;
// Options stay in place and are greyed out when they do not apply.
const avail = (id, on) => { opt(id).disabled = !on; opt(id).parentElement.classList.toggle('off', !on); };
['trails', 'moving', 'current'].forEach(id => avail(id, trackMode));
avail('accum', !trackMode);
u.fade.value = trackMode ? TRACK_FADE : 0; // so the trajectories stand out
trackPts.visible = trackMode;
if (trackMode) {
trackPos.array.set(track.frames.subarray(t * track.n * 3, (t + 1) * track.n * 3));
trackPos.needsUpdate = true;
}
reconPts.visible = !trackMode || opt('current').checked;
const first = accum ? 0 : t;
reconPts.geometry.setDrawRange(recon.offsets[first], recon.offsets[t + 1] - recon.offsets[first]);
for (const [name, o] of Object.entries(trailObjs)) {
o.group.visible = trackMode && opt('trails').checked && name === trailSet();
o.update(t);
}
frustums.forEach((f, i) => {
f.visible = opt('cams').checked && (i === t || (accum && i < t));
f.material = i === t ? current : past;
});
slider.value = t;
tlabel.textContent = `${t + 1} / ${T}`;
$('.framet img').src = meta.frames[t];
$('.framet figcaption').textContent = `Frame ${t + 1}`;
dirty = true;
}
function resize() {
const w = box.clientWidth, h = box.clientHeight;
renderer.setSize(w, h, false);
camera.aspect = w / h;
camera.updateProjectionMatrix();
const pr = renderer.getPixelRatio();
Object.values(trailObjs).forEach(o => o.line.material.resolution.set(w * pr, h * pr));
dirty = true;
}
new ResizeObserver(resize).observe(box);
resize();
resetCamera();
update();
overlay.style.display = 'none';
let last = performance.now(), acc = 0;
function frame(now) {
requestAnimationFrame(frame);
const dt = Math.min(now - last, 100); last = now;
if (state.playing) {
acc += dt;
if (acc >= 1000 / FPS + (state.t === T - 1 ? LOOP_PAUSE : 0)) {
acc = 0;
state.t = (state.t + 1) % T;
update();
}
}
if (controls.update()) dirty = true;
if (!dirty) return;
dirty = false;
renderer.render(scene, camera);
}
requestAnimationFrame(frame);
}
// ------------------------------------------------------------------ sliders
// The filled part of every slider's track is a gradient up to --p, so --p follows the value,
// whether the user moves the thumb or the script sets it.
const value = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value');
document.querySelectorAll('input[type=range]').forEach(el => {
const paint = () => {
const lo = +el.min || 0, hi = +el.max;
el.style.setProperty('--p', (hi > lo ? 100 * (value.get.call(el) - lo) / (hi - lo) : 0) + '%');
};
Object.defineProperty(el, 'value', {
get() { return value.get.call(this); },
set(v) { value.set.call(this, v); paint(); },
});
el.addEventListener('input', paint);
new MutationObserver(paint).observe(el, { attributes: true, attributeFilter: ['min', 'max'] });
paint();
});
main().catch(e => {
document.querySelector('.overlay').textContent = 'Could not load the data: ' + e.message;
throw e;
});
})();