decision-racing / index.html
lysandre's picture
lysandre HF Staff
Full project: llama.cpp backend, community buckets, README and AGENTS.md
98276bf verified
Raw History Blame Contribute Delete
45.2 kB
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Decision Racing</title>
<link rel="icon" href="data:,">
<style>
:root { --panel: rgba(18, 18, 22, .9); --text: #f1f1f3; --muted: #a3a3ad; --border: rgba(255, 255, 255, .12); }
* { box-sizing: border-box; }
[hidden] { display: none !important; } /* the menu and panels set their own display */
html, body { margin: 0; height: 100%; overflow: hidden; background: #9ec9f0; color: var(--text);
font: 13px/1.4 system-ui, sans-serif; }
canvas { display: block; }
button { background: #2a2a31; color: var(--text); border: 1px solid var(--border); border-radius: 8px; padding: 5px 10px;
font: inherit; cursor: pointer; margin: 6px 2px 0; }
button:disabled { opacity: .4; cursor: default; }
.label { font-size: 10px; text-transform: uppercase; letter-spacing: .05em; color: var(--muted); margin-top: 8px; }
/* Per-duck panels, stacked left and right */
.column { position: fixed; top: 14px; display: flex; flex-direction: column; gap: 8px; max-height: calc(100vh - 28px); overflow-y: auto; }
#column-left { left: 14px; } #column-right { right: 14px; }
.panel { flex: none; width: 250px; background: var(--panel); border: 1px solid var(--border); border-radius: 12px; padding: 12px; }
.compact .view, .compact .view-label, .compact .picked { display: none; } /* more than two ducks */
.who { display: flex; align-items: center; gap: 8px; font-weight: 650; font-size: 14px; }
.who img { width: 26px; height: 26px; border-radius: 6px; object-fit: cover; background: #fff; }
.who span { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.stats { display: grid; grid-template-columns: 1fr 1fr; gap: 2px 10px; margin: 8px 0; color: var(--muted);
font-variant-numeric: tabular-nums; }
.stats b { color: var(--text); font-weight: 600; }
.controls { display: flex; gap: 10px; align-items: flex-end; }
.gauge { width: 120px; height: 68px; }
.throttle { display: flex; gap: 4px; align-items: flex-end; height: 56px; }
.throttle div { width: 16px; display: flex; flex-direction: column; justify-content: flex-end; align-items: center;
height: 100%; font-size: 10px; color: var(--muted); }
.throttle i { display: block; width: 100%; background: rgba(74, 222, 128, .4); border-radius: 3px 3px 0 0; min-height: 2px; }
.throttle .top i { background: #4ade80; } .throttle .top { color: var(--text); font-weight: 700; }
.step { display: flex; flex-direction: column; align-items: center; gap: 4px; margin-left: auto; font-size: 10px;
color: var(--muted); font-variant-numeric: tabular-nums; text-align: center; }
.step i { width: 14px; height: 14px; border-radius: 50%; background: var(--step); opacity: .35; animation: inference .9s ease-out; }
@keyframes inference { 0% { opacity: 1; transform: scale(1.6); box-shadow: 0 0 0 0 var(--step); }
60% { opacity: 1; } 100% { opacity: .35; transform: scale(1); box-shadow: 0 0 0 12px transparent; } }
.picked { display: grid; grid-template-columns: 1fr 1fr; gap: 8px; margin-top: 6px; color: var(--muted); font-size: 12px; }
.picked b { color: var(--text); }
.view { margin-top: 8px; width: 100%; aspect-ratio: 8 / 5; border-radius: 6px; background: #000; object-fit: cover; }
.error { color: #ff8a8a; font-size: 12px; }
/* Top bar, finish banner */
#top { position: fixed; top: 14px; left: 50%; transform: translateX(-50%); text-align: center; background: var(--panel);
border: 1px solid var(--border); border-radius: 12px; padding: 8px 14px; max-width: calc(100vw - 560px); }
#top h1 { font-size: 15px; margin: 0; }
#status { color: var(--muted); font-variant-numeric: tabular-nums; }
#progress { height: 6px; margin-top: 6px; background: #2a2a31; border-radius: 3px; overflow: hidden; }
#progress div { height: 100%; width: 0; background: #4ade80; transition: width .3s; }
#banner { position: fixed; top: 112px; left: 50%; transform: translate(-50%, -12px); opacity: 0; pointer-events: none;
background: var(--panel); border: 1px solid var(--border); border-radius: 12px; padding: 10px 18px;
font-size: 17px; font-weight: 650; transition: opacity .3s, transform .3s; white-space: nowrap; }
#banner.show { opacity: 1; transform: translate(-50%, 0); }
#credit { position: fixed; right: 12px; bottom: 8px; font-size: 11px; color: rgba(0, 0, 0, .55); }
#credit a { color: inherit; }
/* Menu */
#menu { position: fixed; inset: 0; display: grid; place-items: center; background: rgba(10, 10, 14, .55); }
#menu > div { background: #18181c; border: 1px solid var(--border); border-radius: 14px; padding: 20px; width: min(420px, 92vw);
max-height: 92vh; overflow: auto; }
#menu h2 { margin: 0 0 4px; font-size: 18px; }
#runs { max-height: 300px; overflow: auto; border: 1px solid var(--border); border-radius: 8px; margin-top: 6px; }
#runs label { display: flex; gap: 8px; align-items: center; padding: 7px 9px; border-bottom: 1px solid var(--border); cursor: pointer; }
#runs label:last-child { border-bottom: 0; }
#runs .source { padding: 6px 9px 4px; font-size: 11px; text-transform: uppercase; letter-spacing: .05em; color: var(--muted);
background: rgba(255, 255, 255, .04); border-bottom: 1px solid var(--border); }
#runs small { color: var(--muted); }
#record input { width: 100%; margin-top: 4px; padding: 7px 9px; border-radius: 8px; border: 1px solid var(--border);
background: #0f0f12; color: var(--text); font: inherit; }
@media (max-width: 900px) { .panel { width: 200px; } #top { max-width: calc(100vw - 460px); } }
</style>
<script type="importmap">
{ "imports": { "three": "https://cdn.jsdelivr.net/npm/three@0.170.0/build/three.module.js",
"three/addons/": "https://cdn.jsdelivr.net/npm/three@0.170.0/examples/jsm/" } }
</script>
</head>
<body>
<div class="column" id="column-left"></div>
<div class="column" id="column-right"></div>
<div id="top">
<h1>Decision Racing</h1>
<div id="status">Pick models to watch</div>
<div id="progress" hidden><div></div></div>
<button id="menu-btn">Menu</button><button id="camera-btn">Overview</button><button id="replay-btn" disabled>Replay</button>
</div>
<div id="banner"></div>
<div id="credit">Racers: <a href="https://github.com/pollen-robotics/microduck_rl">Microduck</a> by Pollen Robotics (Apache-2.0)</div>
<div id="menu">
<div>
<h2>Decision Racing</h2>
<div style="color: var(--muted)">Each Microduck is driven by a model through <code>/v1/systemone</code> (<code>transformers serve</code>, or llama.cpp
through an adapter): it sees the view behind it and answers two <code>score</code> questions, steering and throttle.
Pick the runs to race.</div>
<div id="runs"><span style="display: block; padding: 7px 9px; color: var(--muted)">Loading runs…</span></div>
<button id="watch-btn" disabled style="width: 100%; padding: 8px;">Race them</button>
<form id="record" hidden>
<div class="label" style="margin-top: 16px;">Record a new run</div>
<input name="model" required placeholder="a vision-language model, e.g. Qwen/Qwen3.5-9B">
<button type="submit" style="width: 100%; padding: 8px;">Run it</button>
</form>
</div>
</div>
<script type="module">
import * as THREE from "three";
import { GLTFLoader } from "three/addons/loaders/GLTFLoader.js";
import { DecalGeometry } from "three/addons/geometries/DecalGeometry.js";
// ---------- Settings: fixed, so every model's run is comparable ----------
const LAPS = 1, DECISION_SECONDS = 0.3, TIME_LIMIT = 120; // seconds of race time before a run gives up
// Runs live in buckets (runs/index.json plus one file per run); ?buckets=alice/decision-racing adds someone's.
// Locally, race.py also serves (and records into) runs/.
const ON_SPACE = location.hostname.endsWith(".hf.space");
const params = new URLSearchParams(location.search);
const SOURCES = [...new Set([...(ON_SPACE ? [] : ["local"]), "lysandre/decision-racing", ...(params.get("buckets") ?? "").split(",").filter(Boolean)])];
const sourceUrl = (source) => (source === "local" ? "runs/" : `https://huggingface.co/buckets/${source}/resolve/runs/`);
// A run is referenced as "<source>/<file name>", e.g. "lysandre/decision-racing/Qwen--Qwen3.5-9B".
const runUrl = (ref) => `${sourceUrl(ref.slice(0, ref.lastIndexOf("/")))}${ref.slice(ref.lastIndexOf("/") + 1)}.json`;
const runName = (run) => (run.label ? `${run.model} · ${run.label}` : run.model); // e.g. "Qwen/Qwen3.5-9B · llama.cpp Q4_K_M"
// ---------- Track ----------
const WIDTH = 14, N = 700, STEP = 1 / 60;
const CONTROL = [[0, 0], [90, 0], [135, 12], [150, 50], [128, 82], [88, 84], [66, 104], [78, 138], [52, 166], [6, 160],
[-28, 132], [-40, 92], [-20, 62], [-42, 32], [-30, 6]];
const curve = new THREE.CatmullRomCurve3(CONTROL.map(([x, z]) => new THREE.Vector3(x, 0, z)), true, "centripetal");
const centers = curve.getSpacedPoints(N).slice(0, N);
const forwards = centers.map((_, i) => curve.getTangentAt(i / N));
const rights = forwards.map((f) => new THREE.Vector3(-f.z, 0, f.x));
const $ = (id) => document.getElementById(id);
const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setPixelRatio(Math.min(devicePixelRatio, 2));
document.body.prepend(renderer.domElement);
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x9ec9f0);
scene.fog = new THREE.Fog(0x9ec9f0, 180, 520);
scene.add(new THREE.HemisphereLight(0xdfefff, 0x4c6b3a, 1.6));
const sun = new THREE.DirectionalLight(0xffffff, 1.6);
sun.position.set(80, 120, -40);
scene.add(sun);
// ---------- Island ----------
// An irregular ellipse around the track: grass on top, a sandy beach, then low-poly sea out to the horizon.
const trackMin = new THREE.Vector3(Infinity, 0, Infinity), trackMax = new THREE.Vector3(-Infinity, 0, -Infinity);
centers.forEach((c) => { trackMin.min(c); trackMax.max(c); });
const islandCenter = trackMin.clone().add(trackMax).multiplyScalar(0.5);
let islandA = (trackMax.x - trackMin.x) / 2 + 30, islandB = (trackMax.z - trackMin.z) / 2 + 30;
const reach = Math.max(...centers.map((c) => Math.hypot((c.x - islandCenter.x) / islandA, (c.z - islandCenter.z) / islandB)));
islandA *= Math.max(1, reach / 0.8); islandB *= Math.max(1, reach / 0.8); // the coast wobbles by up to 10%: keep the track inside
const coast = (angle) => 1 + 0.06 * Math.sin(3 * angle + 1) + 0.04 * Math.sin(7 * angle + 2);
// 1 at the coastline, below 1 inland.
const islandLevel = (x, z) => {
const dx = (x - islandCenter.x) / islandA, dz = (z - islandCenter.z) / islandB;
return Math.hypot(dx, dz) / coast(Math.atan2(dz, dx));
};
function islandShape(scale) {
const points = [];
for (let i = 0; i < 160; i++) {
const angle = (i / 160) * Math.PI * 2, r = coast(angle) * scale;
points.push(new THREE.Vector2(islandCenter.x + Math.cos(angle) * islandA * r, -(islandCenter.z + Math.sin(angle) * islandB * r)));
}
return new THREE.Shape(points);
}
for (const [scale, y, color] of [[1.08, -0.06, 0xe3cf9a], [1.0, 0, 0x4f8f3c]]) { // beach (above the highest wave crest), then grass
const land = new THREE.Mesh(new THREE.ShapeGeometry(islandShape(scale)), new THREE.MeshLambertMaterial({ color }));
land.rotation.x = -Math.PI / 2; // shape y becomes -z, hence the negated z above
land.position.y = y;
scene.add(land);
}
const SEA = 120; // segments per side of the animated sea
const sea = new THREE.Mesh(new THREE.PlaneGeometry(1400, 1400, SEA, SEA),
new THREE.MeshPhongMaterial({ color: 0x2f86c4, specular: 0x9fd8ff, shininess: 60, flatShading: true }));
sea.rotation.x = -Math.PI / 2;
sea.position.set(islandCenter.x, -0.6, islandCenter.z);
scene.add(sea);
const seaBase = sea.geometry.attributes.position.array.slice();
function animateSea(time) {
const position = sea.geometry.attributes.position;
for (let i = 0; i < position.count; i++) {
const x = seaBase[3 * i], y = seaBase[3 * i + 1];
position.array[3 * i + 2] = 0.3 * Math.sin(x * 0.05 + time * 1.3) + 0.2 * Math.sin(y * 0.07 - time * 1.1);
}
position.needsUpdate = true;
}
const farSea = new THREE.Mesh(new THREE.PlaneGeometry(6000, 6000), new THREE.MeshLambertMaterial({ color: 0x2f86c4 }));
farSea.rotation.x = -Math.PI / 2;
farSea.position.set(islandCenter.x, -1.6, islandCenter.z); // below the deepest wave trough
scene.add(farSea);
function ribbon(inner, outer, y, colorAt) {
const positions = [], colors = [], index = [];
for (let i = 0; i <= N; i++) {
const c = centers[i % N], r = rights[i % N], color = new THREE.Color(colorAt(i % N));
for (const offset of [inner, outer]) {
positions.push(c.x + r.x * offset, y, c.z + r.z * offset);
colors.push(color.r, color.g, color.b);
}
if (i < N) index.push(2 * i, 2 * i + 1, 2 * i + 2, 2 * i + 1, 2 * i + 3, 2 * i + 2);
}
const geometry = new THREE.BufferGeometry();
geometry.setAttribute("position", new THREE.Float32BufferAttribute(positions, 3));
geometry.setAttribute("color", new THREE.Float32BufferAttribute(colors, 3));
geometry.setIndex(index);
geometry.computeVertexNormals();
scene.add(new THREE.Mesh(geometry, new THREE.MeshLambertMaterial({ vertexColors: true, side: THREE.DoubleSide })));
}
ribbon(-WIDTH / 2, WIDTH / 2, 0.06, () => 0x3b3b40);
for (const side of [-1, 1]) {
ribbon(side * (WIDTH / 2 - 0.6), side * (WIDTH / 2 - 0.25), 0.1, () => 0xf4f4f4);
ribbon(side * WIDTH / 2, side * (WIDTH / 2 + 1.4), 0.06, (i) => (Math.floor(i / 3) % 2 ? 0xd7262b : 0xf4f4f4));
}
// Checkered start line at sample 0.
const checker = document.createElement("canvas");
checker.width = 140; checker.height = 20;
const ctx = checker.getContext("2d");
for (let x = 0; x < 14; x++) for (let y = 0; y < 2; y++) { ctx.fillStyle = (x + y) % 2 ? "#111" : "#fff"; ctx.fillRect(x * 10, y * 10, 10, 10); }
const line = new THREE.Mesh(new THREE.PlaneGeometry(WIDTH, 2), new THREE.MeshBasicMaterial({ map: new THREE.CanvasTexture(checker) }));
line.rotation.set(-Math.PI / 2, 0, Math.atan2(forwards[0].x, forwards[0].z));
line.position.copy(centers[0]).setY(0.12);
scene.add(line);
// Trees, kept clear of the track.
const trunk = new THREE.CylinderGeometry(0.4, 0.5, 3), crown = new THREE.ConeGeometry(2.6, 7, 8);
const trunkMat = new THREE.MeshLambertMaterial({ color: 0x6b4a2b }), crownMat = new THREE.MeshLambertMaterial({ color: 0x2f6b2a });
let seed = 7;
const rand = () => (seed = (seed * 16807) % 2147483647) / 2147483647;
for (let placed = 0, tries = 0; placed < 160 && tries < 5000; tries++) {
const p = new THREE.Vector3(-120 + rand() * 340, 0, -90 + rand() * 330);
if (islandLevel(p.x, p.z) > 0.93) continue; // on land, off the beach
if (Math.min(...centers.map((c) => c.distanceToSquared(p))) < (WIDTH / 2 + 9) ** 2) continue;
const tree = new THREE.Group();
const t = new THREE.Mesh(trunk, trunkMat); t.position.y = 1.5;
const c = new THREE.Mesh(crown, crownMat); c.position.y = 6;
tree.add(t, c); tree.position.copy(p); tree.scale.setScalar(0.8 + rand() * 0.6);
scene.add(tree);
placed++;
}
// ---------- Racers ----------
// The org's (or user's) Hub avatar, as a promise of its URL (or null).
const logos = {};
const logoUrl = (model) => (logos[model.split("/")[0]] ??= (async (org) => {
for (const kind of ["organizations", "users"]) {
const response = await fetch(`https://huggingface.co/api/${kind}/${org}/avatar`).catch(() => null);
if (response?.ok) return (await response.json()).avatarUrl;
}
return null;
})(model.split("/")[0]));
const COLORS = [0xff6b4a, 0x4a8dff, 0x4ade80, 0xfacc15, 0xc084fc, 0xf472b6, 0x22d3ee, 0xfb923c];
const hex = (color) => `#${color.toString(16).padStart(6, "0")}`;
// Racers are Pollen Robotics' Microduck (assets/microduck.glb, built by make_duck.py), scaled up to car size.
const DUCK_SCALE = 12, HIP_HEIGHT = 0.102; // hip pivot height in the model, in meters (see make_duck.py)
const duckTemplate = new Promise((resolve) =>
new GLTFLoader().load("assets/microduck.glb", (gltf) => {
// The CAD meshes carry no normals: flat shading lights them per face, which suits the robot's hard edges.
gltf.scene.traverse((part) => { if (part.isMesh) part.material.flatShading = true; });
headTattoo = tattooGeometry(gltf.scene);
resolve(gltf.scene);
}, undefined, () => resolve(null)));
// Floating name tag: the model ID (e.g. "Qwen/Qwen3.5-9B"), edged in the racer's color. The org logo is on the head.
function nameTag(model, color) {
const canvas = document.createElement("canvas"), ctx = canvas.getContext("2d"), name = model;
const H = 96, pad = 18, font = "600 50px system-ui, sans-serif";
ctx.font = font;
canvas.width = Math.ceil(ctx.measureText(name).width) + 3 * pad;
canvas.height = H;
const texture = new THREE.CanvasTexture(canvas);
texture.colorSpace = THREE.SRGBColorSpace;
const draw = () => {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.beginPath();
ctx.roundRect(3, 3, canvas.width - 6, H - 6, 18);
ctx.fillStyle = "rgba(18, 18, 22, .88)";
ctx.fill();
ctx.lineWidth = 6;
ctx.strokeStyle = hex(color);
ctx.stroke();
ctx.font = font;
ctx.fillStyle = "#f1f1f3";
ctx.textBaseline = "middle";
ctx.fillText(name, 1.5 * pad, H / 2 + 2);
texture.needsUpdate = true;
};
draw();
const tag = new THREE.Sprite(new THREE.SpriteMaterial({ map: texture }));
tag.scale.set((canvas.width / H) * 1.4, 1.4, 1);
return tag;
}
// Shape of the logo "tattoo": a decal on the back of the head, projected from where the cameras look (behind and
// about 40 degrees above), so it reads in the follow view and in the models' camera images.
let headTattoo = null;
function tattooGeometry(duck) {
duck.updateMatrixWorld(true);
const head = [];
duck.traverse((part) => { if (part.isMesh && !/leg_/.test(part.parent?.name ?? "")) head.push(part); });
const ray = new THREE.Raycaster(), down = new THREE.Vector3(0, -1, 0);
let top = null;
for (let z = -0.08; z <= 0.08; z += 0.005) {
ray.set(new THREE.Vector3(0, 1, z), down);
const hit = ray.intersectObjects(head, false)[0];
if (hit && (!top || hit.point.y > top.point.y)) top = hit;
}
if (!top) return null;
const elevation = 0.7, view = new THREE.Vector3(0, -Math.sin(elevation), Math.cos(elevation)); // looking forward and down
ray.set(new THREE.Vector3(0, top.point.y - 0.024, top.point.z).addScaledVector(view, -1), view); // mid back of the head
const hit = ray.intersectObjects(head, false)[0] ?? top;
// The projector's depth axis points back at the camera; its "up" points up the head, so the logo reads upright.
return new DecalGeometry(hit.object, hit.point, new THREE.Euler(elevation - Math.PI, 0, Math.PI), new THREE.Vector3(0.085, 0.085, 0.05));
}
function carMesh(color, model) {
const racer = new THREE.Group(), body = new THREE.Group(); // the racer turns; the body inside it waddles
racer.add(body);
racer.userData.body = body;
const ring = new THREE.Mesh(new THREE.RingGeometry(1.4, 2.0, 40), new THREE.MeshBasicMaterial({ color, side: THREE.DoubleSide }));
ring.rotation.x = -Math.PI / 2;
ring.position.y = 0.13;
racer.add(ring);
duckTemplate.then((duck) => {
if (!duck) return;
const copy = duck.clone();
copy.scale.setScalar(DUCK_SCALE);
body.add(copy);
racer.userData.legs = [copy.getObjectByName("leg_left"), copy.getObjectByName("leg_right")].filter(Boolean);
if (headTattoo) logoUrl(model).then((url) => {
if (!url) return;
const texture = new THREE.TextureLoader().load(url);
texture.colorSpace = THREE.SRGBColorSpace;
copy.add(new THREE.Mesh(headTattoo, new THREE.MeshBasicMaterial({
map: texture, transparent: true, polygonOffset: true, polygonOffsetFactor: -4, depthWrite: false }))); // logos with transparent backgrounds
});
});
const tag = nameTag(model, color);
tag.position.y = 4.6;
racer.add(tag);
scene.add(racer);
return racer;
}
// ---------- Simulation ----------
const nearest = (car, window = 40) => {
let best = car.index, bestD = Infinity;
const range = window ? [...Array(2 * window + 1).keys()].map((k) => (car.index + k - window + N) % N) : [...Array(N).keys()];
for (const i of range) {
const dx = car.x - centers[i].x, dz = car.z - centers[i].z, d = dx * dx + dz * dz;
if (d < bestD) { bestD = d; best = i; }
}
return best;
};
const headingAt = (i) => Math.atan2(forwards[i].x, forwards[i].z);
function newCar() { // on the grid, just before the line
const i = N - 10;
return { x: centers[i].x, z: centers[i].z, heading: headingAt(i), speed: 0, index: i, progress: -10,
steer: 0, throttle: 0, offTrack: 0, resets: 0, wasOff: false, lapTimes: [], finished: null };
}
function step(car, time) {
const lateral = (car.x - centers[car.index].x) * rights[car.index].x + (car.z - centers[car.index].z) * rights[car.index].z;
const off = Math.abs(lateral) > WIDTH / 2 + 0.5;
if (off && !car.wasOff) car.offTrack++;
car.wasOff = off;
const accel = car.throttle >= 0 ? car.throttle * 14 : car.throttle * 28;
const drag = 0.007 + (off ? 0.06 : 0);
car.speed = Math.max(0, car.speed + (accel - drag * car.speed * car.speed) * STEP);
const angle = (car.steer * 0.55) / (1 + car.speed / 30);
car.heading -= (car.speed / 2.8) * Math.tan(angle) * STEP; // positive steer turns right
car.x += Math.sin(car.heading) * car.speed * STEP;
car.z += Math.cos(car.heading) * car.speed * STEP;
const index = nearest(car);
let delta = index - car.index;
if (delta > N / 2) delta -= N;
if (delta < -N / 2) delta += N;
car.index = index;
car.progress += delta;
if (Math.abs(lateral) > WIDTH / 2 + 14) { // far off: put it back on the track, stopped
car.index = nearest(car, 0);
Object.assign(car, { x: centers[car.index].x, z: centers[car.index].z, heading: headingAt(car.index), speed: 4 });
car.resets++;
}
const lap = Math.floor(car.progress / N);
while (car.lapTimes.length < lap && car.lapTimes.length < LAPS) car.lapTimes.push(time);
if (car.lapTimes.length >= LAPS && car.finished === null) car.finished = time;
}
// ---------- What each model sees ----------
const VIEW_W = 256, VIEW_H = 160;
// Rendered by the main renderer into an off-screen target: a second WebGL context sharing the scene is unreliable.
const viewTarget = new THREE.WebGLRenderTarget(VIEW_W, VIEW_H);
viewTarget.texture.colorSpace = THREE.SRGBColorSpace;
const viewCamera = new THREE.PerspectiveCamera(75, VIEW_W / VIEW_H, 1, 400);
const viewCanvas = document.createElement("canvas");
viewCanvas.width = VIEW_W; viewCanvas.height = VIEW_H;
const viewContext = viewCanvas.getContext("2d"), viewPixels = new Uint8Array(VIEW_W * VIEW_H * 4);
const viewImage = viewContext.createImageData(VIEW_W, VIEW_H);
// `dt` advances the walk cycle: real seconds times playback speed (0 for camera captures).
function pose(mesh, state, dt = 0) {
mesh.position.set(state.x, 0, state.z);
mesh.rotation.y = state.heading;
// Walk: legs swing in turn, the body sways and dips. Faster with speed, capped at 8 steps a second.
// A finished racer keeps its last speed in the frames but stands still at the line.
const speed = state.finished == null ? state.speed : 0;
const steps = Math.min(8, speed / 2), effort = Math.min(1, speed / 6);
const phase = (mesh.userData.phase = (mesh.userData.phase ?? 0) + dt * steps * Math.PI), swing = Math.sin(phase);
const angle = swing * 0.7 * effort;
mesh.userData.legs?.forEach((leg, i) => { leg.rotation.x = i ? -angle : angle; });
mesh.userData.body.rotation.z = swing * 0.1 * effort;
// A swung leg reaches less far down: drop the body by that much so a foot stays on the ground.
mesh.userData.body.position.y = -(1 - Math.cos(angle)) * HIP_HEIGHT * DUCK_SCALE;
}
function chaseCamera(camera, state, back, up, ahead) {
const fx = Math.sin(state.heading), fz = Math.cos(state.heading);
camera.position.set(state.x - fx * back, up, state.z - fz * back);
camera.lookAt(state.x + fx * ahead, 0.5, state.z + fz * ahead);
}
function capture(car, mesh) {
pose(mesh, car);
chaseCamera(viewCamera, car, 9, 6, 14); // high enough to see the road over the duck's head
renderer.setRenderTarget(viewTarget);
renderer.render(scene, viewCamera);
renderer.readRenderTargetPixels(viewTarget, 0, 0, VIEW_W, VIEW_H, viewPixels);
renderer.setRenderTarget(null);
for (let y = 0; y < VIEW_H; y++) { // WebGL rows start at the bottom
viewImage.data.set(viewPixels.subarray((VIEW_H - 1 - y) * VIEW_W * 4, (VIEW_H - y) * VIEW_W * 4), y * VIEW_W * 4);
}
viewContext.putImageData(viewImage, 0, 0);
return viewCanvas.toDataURL("image/jpeg", 0.75);
}
// ---------- Decisions ----------
const STEER = ["hard left", "left", "straight", "right", "hard right"];
const THROTTLE = ["brake", "coast", "accelerate", "full throttle"], THROTTLE_VALUE = [-1, 0, 0.6, 1];
// One inference step: two score questions about the camera image. The probability-weighted scores become the controls.
async function decide(model, car, image) {
const body = {
model,
state: `You are driving a race car on a circuit. The image shows the view from behind your car. ` +
`Stay on the grey road between the red-and-white kerbs and drive fast. Speed: ${Math.round(car.speed * 3.6)} km/h.`,
images: [image],
questions: {
steer: { type: "score", instructions: "How should you steer to follow the road?", criteria: STEER },
throttle: { type: "score", instructions: "How much throttle should you apply?", criteria: THROTTLE },
},
};
try {
const response = await fetch("/api/systemone", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) });
const data = await response.json();
if (!response.ok) throw new Error(typeof data.detail === "string" ? data.detail : JSON.stringify(data.detail));
const { steer, throttle } = data.answers;
const t = throttle.score, low = Math.floor(Math.min(t, 2.999));
return { image, steer, throttle,
controls: { steer: (steer.score - 2) / 2, throttle: THROTTLE_VALUE[low] + (THROTTLE_VALUE[low + 1] - THROTTLE_VALUE[low]) * (t - low) } };
} catch (error) {
return { image, error: error.message, controls: { steer: 0, throttle: 0 } };
}
}
// ---------- Race state ----------
let race = null, meshes = []; // race: { models, done }
const frames = [], chunks = []; // frames[i].cars[slot]; chunks[k] = { frame, latency, decisions[slot] }, one per decision step
let playhead = 0, mode = "replay", chunkPointer = 0;
const snapshot = (car, time) => ({ time, car: { x: car.x, z: car.z, heading: car.heading, speed: car.speed, progress: car.progress,
offTrack: car.offTrack, resets: car.resets, finished: car.finished } });
// Record a model's run (locally, through race.py): physics pauses while the model decides, so the whole run is
// computed first, then replayed at real speed and saved as runs/<org>--<model>.json.
async function record(model) {
const car = newCar(), steps = Math.round(DECISION_SECONDS / STEP);
race = { models: [model], done: false, started: performance.now(), car, latency: 0 };
startScene(race.models);
mode = "computing";
$("progress").hidden = false;
const run = { model, frames: [snapshot(car, 0)], chunks: [] };
let time = 0;
while (!race.done) {
const started = performance.now(), decision = await decide(model, car, capture(car, meshes[0]));
race.latency = performance.now() - started;
Object.assign(car, decision.controls);
run.chunks.push({ frame: run.frames.length - 1, latency: race.latency, decision });
race.steps = run.chunks.length;
for (let s = 0; s < steps && !race.done; s++) {
time += STEP;
step(car, time);
run.frames.push(snapshot(car, time));
race.done = car.finished !== null || time > TIME_LIMIT;
}
// Show the latest decision while computing.
frames.length = chunks.length = 0;
frames.push({ time: 0, cars: [run.frames[0].car] });
chunks.push({ frame: 0, latency: race.latency, decisions: [decision] });
}
$("progress").hidden = true;
const saved = await fetch("/api/runs", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(run) });
location.search = `?runs=${encodeURIComponent(`local/${(await saved.json()).name}`)}`; // watch it
}
// Load runs and put every duck on the track together, each replaying its own run (they can't collide).
async function watch(refs) {
const runs = await Promise.all(refs.map(async (ref) => {
const response = await fetch(runUrl(ref));
if (!response.ok) throw new Error(`no run ${ref}`);
return response.json();
}));
const at = (list, i) => list[Math.min(i, list.length - 1)]; // a finished duck waits at the line
const longest = runs.reduce((a, b) => (b.chunks.length > a.chunks.length ? b : a));
const models = runs.map(runName);
race = { models, done: true, setups: runs.map((run) => `${runName(run)}\n${run.setup.backend} on ${run.setup.machine}`) };
for (let i = 0; i < Math.max(...runs.map((run) => run.frames.length)); i++) {
frames.push({ time: i * STEP, cars: runs.map((run) => at(run.frames, i).car) });
}
longest.chunks.forEach((chunk, k) => chunks.push({ frame: chunk.frame, latency: Math.max(...runs.map((run) => at(run.chunks, k).latency)),
decisions: runs.map((run) => at(run.chunks, k).decision) }));
startScene(models);
startReplay();
}
function startScene(models) {
meshes = models.map((model, slot) => carMesh(COLORS[slot % COLORS.length], model));
document.body.classList.toggle("compact", models.length > 2);
models.forEach((_, slot) => setupPanel(slot));
$("menu").hidden = true;
}
// ---------- HUD ----------
function arc(cx, cy, r0, r1, a0, a1) {
const p = (r, a) => `${cx + r * Math.cos(a)},${cy - r * Math.sin(a)}`;
return `M${p(r1, a0)} A${r1},${r1} 0 0 1 ${p(r1, a1)} L${p(r0, a1)} A${r0},${r0} 0 0 0 ${p(r0, a0)} Z`;
}
const average = (values) => values.reduce((a, b) => a + b, 0) / values.length;
const formatTime = (t) => (t == null ? "—" : `${Math.floor(t / 60)}:${(t % 60).toFixed(2).padStart(5, "0")}`);
function setupPanel(slot) {
const model = race.models[slot], panel = document.createElement("div");
panel.className = "panel";
panel.id = `panel-${slot}`;
panel.style.borderTop = `3px solid ${hex(COLORS[slot % COLORS.length])}`;
panel.innerHTML = `<div class="who"><img alt="" style="visibility: hidden">
<span title="${race.setups?.[slot] ?? model}">${model}</span></div><div class="stats"></div><div class="decision"></div>
<div class="label view-label">What the model sees</div><img class="view" alt="">`;
$(slot % 2 ? "column-right" : "column-left").append(panel);
logoUrl(model).then((url) => { if (url) Object.assign(panel.querySelector(".who img"), { src: url, style: "" }); });
}
function renderStats(slot, frame) {
const car = frame.cars[slot], stats = $(`panel-${slot}`).querySelector(".stats");
const html = `<span><b>${car.finished == null ? Math.round(car.speed * 3.6) : 0}</b> km/h</span><span>Finish <b>${formatTime(car.finished)}</b></span>
<span>Off track <b>${car.offTrack}</b></span><span>Resets <b>${car.resets}</b></span>`;
if (stats.dataset.html !== html) { stats.innerHTML = html; stats.dataset.html = html; } // repaint only on change
}
// Re-rendered once per decision, so the step indicator's CSS animation pulses on every inference step.
function renderDecision(slot, decision, step, latency) {
const panel = $(`panel-${slot}`);
if (decision?.image) panel.querySelector(".view").src = decision.image;
if (decision?.error) { panel.querySelector(".decision").innerHTML = `<div class="error">${decision.error}</div>`; return; }
if (!decision?.steer) return;
const n = STEER.length, color = hex(COLORS[slot % COLORS.length]);
const paths = STEER.map((_, i) => {
const a0 = Math.PI - (i * Math.PI) / n, a1 = Math.PI - ((i + 1) * Math.PI) / n, p = decision.steer.probabilities[String(i)];
return `<path d="${arc(60, 62, 30, 56, a0, a1)}" fill="${color}" fill-opacity="${0.12 + 0.88 * p}" stroke="#18181c" stroke-width="1.5"/>`;
}).join("");
const needle = Math.PI - ((decision.steer.score + 0.5) * Math.PI) / n;
const top = (probabilities) => +Object.entries(probabilities).reduce((a, b) => (b[1] > a[1] ? b : a))[0];
const topSteer = top(decision.steer.probabilities), topThrottle = top(decision.throttle.probabilities);
const outline = `<path d="${arc(60, 62, 30, 56, Math.PI - (topSteer * Math.PI) / n, Math.PI - ((topSteer + 1) * Math.PI) / n)}"
fill="none" stroke="#fff" stroke-width="2"/>`;
const throttle = THROTTLE.map((label, i) => `<div class="${i === topThrottle ? "top" : ""}" title="${label}">
<i style="height:${Math.round(decision.throttle.probabilities[String(i)] * 100)}%"></i>${"BCAF"[i]}</div>`).join("");
const pct = (probabilities, i) => Math.round(probabilities[String(i)] * 100) + "%";
panel.querySelector(".decision").innerHTML = `<div class="label">Steering · throttle</div><div class="controls">
<svg class="gauge" viewBox="0 0 120 68">${paths}${outline}
<line x1="60" y1="62" x2="${60 + 52 * Math.cos(needle)}" y2="${62 - 52 * Math.sin(needle)}" stroke="#fff" stroke-width="2.5" stroke-linecap="round"/>
<circle cx="60" cy="62" r="4" fill="#fff"/></svg><div class="throttle">${throttle}</div>
<div class="step" style="--step: ${color}" title="A new inference step: the model answered both questions"><i></i>step ${step}<br>${(latency / 1000).toFixed(1)} s</div></div>
<div class="picked"><span>Steer <b>${STEER[topSteer]}</b> ${pct(decision.steer.probabilities, topSteer)}</span>
<span>Throttle <b>${THROTTLE[topThrottle]}</b> ${pct(decision.throttle.probabilities, topThrottle)}</span></div>`;
}
// Medals over finishers and a banner as each one crosses the line.
const MEDALS = ["🏆", "🥈", "🥉"];
const ordinal = (n) => n + (["th", "st", "nd", "rd"][(n % 100 - 20) % 10] || ["th", "st", "nd", "rd"][n % 100] || "th");
const badgeTextures = {};
function badgeTexture(rank) { // trophy and medals for the podium, then "4th", "5th"...
if (!badgeTextures[rank]) {
const canvas = document.createElement("canvas"), ctx = canvas.getContext("2d");
canvas.width = canvas.height = 128;
ctx.textAlign = "center"; ctx.textBaseline = "middle";
if (rank <= 3) {
ctx.font = "100px system-ui, sans-serif";
ctx.fillText(MEDALS[rank - 1], 64, 70);
} else {
ctx.beginPath(); ctx.arc(64, 64, 56, 0, Math.PI * 2);
ctx.fillStyle = "rgba(18, 18, 22, .9)"; ctx.fill();
ctx.lineWidth = 6; ctx.strokeStyle = "#a3a3ad"; ctx.stroke();
ctx.font = "700 44px system-ui, sans-serif"; ctx.fillStyle = "#f1f1f3";
ctx.fillText(ordinal(rank), 64, 68);
}
badgeTextures[rank] = new THREE.CanvasTexture(canvas);
badgeTextures[rank].colorSpace = THREE.SRGBColorSpace;
}
return badgeTextures[rank];
}
function setBadge(racer, rank) {
if (!racer.userData.badge) {
racer.userData.badge = new THREE.Sprite(new THREE.SpriteMaterial());
racer.userData.badge.scale.set(2.4, 2.4, 1);
racer.userData.badge.position.y = 6.8;
racer.add(racer.userData.badge);
}
const badge = racer.userData.badge;
badge.visible = rank > 0;
if (rank && badge.userData.rank !== rank) {
badge.material.map = badgeTexture(rank);
badge.material.needsUpdate = true;
badge.userData.rank = rank;
}
}
let bannerTimer = null;
function showBanner(text) {
$("banner").textContent = text;
$("banner").classList.add("show");
clearTimeout(bannerTimer);
bannerTimer = setTimeout(() => $("banner").classList.remove("show"), 4000);
}
// ---------- Camera ----------
const camera = new THREE.PerspectiveCamera(55, 1, 1, 1500);
let overview = false;
const spotlight = new THREE.SpotLight(0xfff1c4, 0, 0, 0.32, 0.6, 0); // on the winner
scene.add(spotlight, spotlight.target);
const cameraFocus = new THREE.Vector3(55, 0, 80); // smoothed look-at point
// Smoothed follow camera: offsets of the camera and its focus from the leading duck.
const cameraRig = { offset: new THREE.Vector3(0, 30, 30), focusOffset: new THREE.Vector3(), direction: new THREE.Vector3(0, 0, 1), leader: null };
const probe = new THREE.PerspectiveCamera(); // test camera for framing
// The follow shot: just ahead of the winning duck, looking back at it and the pack behind it, so it's big in the
// foreground while every other duck stays in the picture. Backs off only as far as needed to fit the farthest duck.
function leaderShot(lead, cars) {
const others = cars.filter((c) => c !== lead);
const forward = new THREE.Vector3(Math.sin(lead.heading), 0, Math.cos(lead.heading));
const pack = others.length ? new THREE.Vector3(average(others.map((c) => c.x)), 0, average(others.map((c) => c.z))) : null;
// Away from the pack (and a bit along the leader's heading, which steadies it when the pack is close).
const away = forward.clone().multiplyScalar(10);
if (pack) away.add(new THREE.Vector3(lead.x - pack.x, 0, lead.z - pack.z));
away.normalize();
cameraRig.direction.lerp(away, 0.05).normalize(); // turn gently
const leader = new THREE.Vector3(lead.x, 2, lead.z);
const focus = pack ? leader.clone().lerp(new THREE.Vector3(pack.x, 1, pack.z), 0.2) : leader;
probe.fov = camera.fov; probe.aspect = camera.aspect; probe.updateProjectionMatrix();
let position;
for (let distance = 14; distance < 400; distance *= 1.1) {
position = leader.clone().addScaledVector(cameraRig.direction, distance).setY(7 + distance * 0.75); // steep, over the trees
probe.position.copy(position); probe.lookAt(focus); probe.updateMatrixWorld();
const fits = cars.every((c) => [0, 6.5].every((y) => { // the whole duck, from its ring to its medal
const p = new THREE.Vector3(c.x, y, c.z).project(probe);
return p.z < 1 && Math.abs(p.x) < 0.58 && p.y > -0.85 && p.y < 0.8; // inside the view, clear of the side panels
}));
if (fits) break;
}
return { position, focus };
}
$("camera-btn").onclick = () => { overview = !overview; $("camera-btn").textContent = overview ? "Follow" : "Overview"; };
function startReplay() {
mode = "replay"; playhead = 0; chunkPointer = 0; lastPanel = null; lastStatsFrame = -1;
$("replay-btn").disabled = false;
}
$("replay-btn").onclick = startReplay;
function resize() { renderer.setSize(innerWidth, innerHeight); camera.aspect = innerWidth / innerHeight; camera.updateProjectionMatrix(); }
addEventListener("resize", resize);
resize();
camera.position.set(55, 260, -60);
camera.lookAt(55, 0, 80);
// ---------- Playback ----------
let lastTick = performance.now(), lastPanel = null, lastStatsFrame = -1;
const finishSeen = [];
renderer.setAnimationLoop(() => {
const now = performance.now(), elapsed = (now - lastTick) / 1000;
lastTick = now;
if (race && frames.length) {
if (mode === "replay") playhead = Math.min(frames.length - 1, playhead + elapsed / STEP);
const frame = frames[Math.floor(playhead)];
frame.cars.forEach((car, i) => pose(meshes[i], car, mode === "replay" ? elapsed : 0));
// Finish order in this frame: a medal over each finisher and a banner as they cross.
const order = frame.cars.map((c, i) => [c.finished, i]).filter(([t]) => t != null).sort((a, b) => a[0] - b[0]).map(([, i]) => i);
frame.cars.forEach((car, i) => {
const rank = order.indexOf(i) + 1; // 0 while still racing
setBadge(meshes[i], rank);
if (rank && !finishSeen[i]) showBanner(`${MEDALS[rank - 1] ?? ""} ${race.models[i]} finishes ${ordinal(rank)} · ${formatTime(car.finished)}`);
finishSeen[i] = rank > 0;
});
while (chunkPointer + 1 < chunks.length && chunks[chunkPointer + 1].frame <= playhead) chunkPointer++;
while (chunkPointer > 0 && chunks[chunkPointer].frame > playhead) chunkPointer--;
const chunk = chunks[chunkPointer];
if (chunk && chunk !== lastPanel) {
const stepNumber = mode === "computing" ? race.steps : chunkPointer + 1;
race.models.forEach((_, slot) => renderDecision(slot, chunk.decisions[slot], stepNumber, chunk.latency));
lastPanel = chunk;
}
if (Math.floor(playhead) !== lastStatsFrame) { race.models.forEach((_, slot) => renderStats(slot, frame)); lastStatsFrame = Math.floor(playhead); }
if (mode === "computing") {
const done = Math.min(1, Math.max(0, race.car.progress) / (N * LAPS));
const spent = (now - race.started) / 1000, eta = done > 0.02 ? spent / done - spent : null;
$("progress").firstElementChild.style.width = `${(done * 100).toFixed(1)}%`;
$("status").textContent = `Computing ${race.models[0]} · ${Math.round(done * 100)}% · step ${race.steps ?? 0} · ` +
`${(race.latency / 1000).toFixed(1)} s each` + (eta !== null ? ` · about ${formatTime(eta).replace(/\.\d+$/, "")} left` : "");
} else if (playhead >= frames.length - 1) {
const winner = order[0];
$("status").textContent = winner === undefined ? "Time limit reached"
: `Finished · ${race.models[winner]} ${race.models.length > 1 ? "wins" : "finishes"} in ${formatTime(frame.cars[winner].finished)}`;
} else {
$("status").textContent = `Race time ${formatTime(frame.time)}`;
}
// The duck that's winning: the first finisher, else the one furthest along. The spotlight is on it once it wins.
const ease = (rate) => 1 - Math.exp(-rate * elapsed);
const running = frame.cars.filter((c) => c.finished == null);
const lead = order.length ? frame.cars[order[0]] : running.reduce((a, b) => (b.progress > a.progress ? b : a));
spotlight.intensity += ((order.length ? 6 : 0) - spotlight.intensity) * ease(3);
spotlight.position.set(lead.x, 24, lead.z);
spotlight.target.position.set(lead.x, 0, lead.z);
if (overview) {
camera.position.lerp(new THREE.Vector3(55, 260, -60), 0.05);
camera.lookAt(55, 0, 80);
} else {
// Smooth the framing relative to the leader, not in world space: the camera moves with the duck exactly
// (no lagging behind a fast leader) and only eases changes of angle and zoom.
const shot = leaderShot(lead, frame.cars), anchor = new THREE.Vector3(lead.x, 0, lead.z);
const leadSlot = frame.cars.indexOf(lead); // by slot: every frame has its own car objects
if (cameraRig.leader !== leadSlot) { // a new leader: carry the current view over instead of jumping
cameraRig.offset.copy(camera.position).sub(anchor);
cameraRig.focusOffset.copy(cameraFocus).sub(anchor);
cameraRig.leader = leadSlot;
}
cameraRig.offset.lerp(shot.position.clone().sub(anchor), ease(1.6));
cameraRig.focusOffset.lerp(shot.focus.clone().sub(anchor), ease(2));
camera.position.copy(anchor).add(cameraRig.offset);
cameraFocus.copy(anchor).add(cameraRig.focusOffset);
camera.lookAt(cameraFocus);
}
}
animateSea(now / 1000);
renderer.render(scene, camera);
});
// ---------- Menu ----------
// ?runs=<ref>,<ref> races saved runs together; ?record=<model> records a new run (locally).
const keepBuckets = () => (params.get("buckets") ? `buckets=${encodeURIComponent(params.get("buckets"))}` : "");
$("menu-btn").onclick = () => { location.search = keepBuckets(); };
$("record").hidden = ON_SPACE; // recording needs a local model server
$("record").onsubmit = (event) => {
event.preventDefault();
location.search = `?record=${encodeURIComponent($("record").model.value.trim())}`;
};
Promise.all(SOURCES.map((source) => fetch(`${sourceUrl(source)}index.json`, { cache: "no-store" })
.then((r) => (r.ok ? r.json() : { runs: [] })).catch(() => ({ runs: [] }))
.then(({ runs }) => [source, runs ?? []]))).then((sources) => {
$("runs").innerHTML = sources.filter(([, runs]) => runs.length).map(([source, runs]) =>
`<div class="source">${source === "local" ? "Your runs" : source}</div>` + runs.map((run) =>
`<label title="${run.setup.backend} on ${run.setup.machine}"><input type="checkbox" value="${source}/${run.file.replace(/\.json$/, "")}">
<span>${run.model}${run.label ? ` <small>${run.label}</small>` : ""}</span></label>`).join("")).join("")
|| `<span style="display: block; padding: 7px 9px; color: var(--muted)">No runs yet</span>`;
$("runs").onchange = () => { $("watch-btn").disabled = !$("runs").querySelector("input:checked"); };
});
$("watch-btn").onclick = () => {
const refs = [...$("runs").querySelectorAll("input:checked")].map((box) => box.value);
location.search = [`runs=${encodeURIComponent(refs.join(","))}`, keepBuckets()].filter(Boolean).join("&");
};
if (params.get("runs")) watch(params.get("runs").split(",")).catch((error) => { $("status").textContent = error.message; });
else if (params.get("record") && !ON_SPACE) record(params.get("record"));
</script>
</body>
</html>