Prompt specification
Build or customize the Three.js 3D scene "Toy garage race preparation" inside the active workspace.
Engineering Constraints:
1. Runtime & Orbit: Use Three.js r160 with OrbitControls (damping enabled) and ACESFilmicToneMapping.
2. Frame Timing: Drive all motion strictly with clock.getDelta() so animation speed is FPS-independent.
3. Viewport Hygiene: Handle window resize cleanly, cap DPR at Math.min(window.devicePixelRatio, 2), and dispose geometries/materials/renderer on unmount.
Scene Metadata:
Scene: Toy garage race preparation
Category: Games & Play · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/toy-garage-race-preparation-x0399
Scene Description Prompt:
Set up two stylized wind-up toy cars with equal winding inputs for a comparison race. Three.js from cdnjs, one HTML file.
Working Three.js Starter (toy-garage-race-preparation-x0399):
```html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Wind-Up Workshop — Equal Input Race</title>
<style>
:root {
--ink: #18313b;
--muted: #6d8087;
--paper: #fffdf7;
--coral: #ff715c;
--teal: #13a89d;
--yellow: #f5c752;
--line: rgba(24, 49, 59, 0.12);
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
color: var(--ink);
background: #dce9e2;
}
button {
font: inherit;
}
#stage {
position: fixed;
inset: 0;
}
#stage canvas {
display: block;
width: 100%;
height: 100%;
touch-action: none;
}
.ui {
position: fixed;
z-index: 5;
pointer-events: none;
}
.interactive {
pointer-events: auto;
}
.brand {
top: 24px;
left: 26px;
display: flex;
align-items: center;
gap: 13px;
text-shadow: 0 1px 0 rgba(255, 255, 255, 0.55);
}
.brand-mark {
display: grid;
place-items: center;
width: 48px;
height: 48px;
border-radius: 16px;
color: #fff;
background: var(--ink);
box-shadow: 0 8px 22px rgba(24, 49, 59, 0.2);
font-size: 24px;
font-weight: 950;
transform: rotate(-4deg);
}
.brand strong {
display: block;
font-size: 17px;
font-weight: 900;
letter-spacing: 0.08em;
}
.brand span {
display: block;
margin-top: 2px;
color: var(--muted);
font-size: 12px;
font-weight: 650;
}
.control-panel {
top: 24px;
right: 24px;
width: 326px;
padding: 18px;
border: 1px solid rgba(255, 255, 255, 0.72);
border-radius: 24px;
background: rgba(255, 253, 247, 0.88);
box-shadow:
0 22px 60px rgba(28, 62, 67, 0.16),
inset 0 1px 0 rgba(255, 255, 255, 0.85);
backdrop-filter: blur(18px);
-webkit-backdrop-filter: blur(18px);
}
.panel-heading {
display: flex;
align-items: center;
justify-content: space-between;
gap: 10px;
margin-bottom: 17px;
}
.panel-heading strong {
font-size: 13px;
font-weight: 900;
letter-spacing: 0.11em;
}
.lock-badge {
display: inline-flex;
align-items: center;
gap: 5px;
padding: 6px 9px;
border-radius: 999px;
color: #167d75;
background: rgba(19, 168, 157, 0.12);
font-size: 9px;
font-weight: 900;
letter-spacing: 0.1em;
}
.car-row {
padding: 12px;
border: 1px solid var(--line);
border-radius: 16px;
background: rgba(255, 255, 255, 0.54);
}
.car-row + .car-row {
margin-top: 9px;
}
.car-row-head {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 9px;
}
.car-name {
display: flex;
align-items: center;
gap: 8px;
font-size: 12px;
font-weight: 850;
}
.car-dot {
width: 10px;
height: 10px;
border-radius: 50%;
background: var(--coral);
box-shadow: 0 0 0 4px rgba(255, 113, 92, 0.13);
}
.car-dot.teal {
background: var(--teal);
box-shadow: 0 0 0 4px rgba(19, 168, 157, 0.13);
}
.turn-value {
color: var(--muted);
font-size: 11px;
font-weight: 750;
}
.pips {
display: grid;
grid-template-columns: repeat(10, 1fr);
gap: 4px;
}
.pip {
height: 7px;
border-radius: 99px;
background: rgba(24, 49, 59, 0.09);
transition: background 180ms ease, transform 180ms ease;
}
.row-a .pip.on {
background: var(--coral);
transform: scaleY(1.12);
}
.row-b .pip.on {
background: var(--teal);
transform: scaleY(1.12);
}
.fairness-note {
display: flex;
align-items: center;
gap: 8px;
margin: 13px 2px;
color: var(--muted);
font-size: 10px;
font-weight: 650;
line-height: 1.35;
}
.fairness-note b {
color: var(--teal);
font-size: 13px;
}
.wind-button,
.action-button,
.camera-button {
border: 0;
cursor: pointer;
transition:
transform 140ms ease,
box-shadow 140ms ease,
opacity 140ms ease,
background 140ms ease;
}
.wind-button:hover:not(:disabled),
.action-button:hover:not(:disabled),
.camera-button:hover {
transform: translateY(-1px);
}
.wind-button:active:not(:disabled),
.action-button:active:not(:disabled),
.camera-button:active {
transform: translateY(1px);
}
button:disabled {
cursor: not-allowed;
opacity: 0.48;
}
.wind-button {
display: grid;
grid-template-columns: 35px 1fr;
grid-template-rows: auto auto;
column-gap: 10px;
width: 100%;
padding: 12px 14px;
border-radius: 16px;
color: white;
text-align: left;
background: var(--ink);
box-shadow: 0 9px 20px rgba(24, 49, 59, 0.18);
}
.wind-icon {
grid-row: 1 / 3;
display: grid;
place-items: center;
width: 35px;
height: 35px;
border-radius: 11px;
color: var(--ink);
background: var(--yellow);
font-size: 24px;
font-weight: 900;
}
.wind-button strong {
align-self: end;
font-size: 12px;
letter-spacing: 0.08em;
}
.wind-button small {
align-self: start;
margin-top: 2px;
color: rgba(255, 255, 255, 0.64);
font-size: 10px;
}
.button-row {
display: grid;
grid-template-columns: 1fr 1.25fr;
gap: 8px;
margin-top: 9px;
}
.action-button {
min-height: 40px;
padding: 9px 11px;
border-radius: 13px;
font-size: 11px;
font-weight: 850;
}
.action-button.secondary {
color: var(--ink);
background: rgba(24, 49, 59, 0.08);
}
.action-button.start {
color: white;
background: var(--teal);
box-shadow: 0 7px 17px rgba(19, 168, 157, 0.22);
}
.reset-button {
width: 100%;
margin-top: 8px;
padding: 9px;
border: 0;
border-radius: 12px;
color: var(--muted);
background: transparent;
cursor: pointer;
font-size: 10px;
font-weight: 750;
}
.reset-button:hover:not(:disabled) {
color: var(--ink);
background: rgba(24, 49, 59, 0.05);
}
.race-banner {
top: 27px;
left: 50%;
display: flex;
align-items: center;
gap: 10px;
padding: 10px 16px;
border: 1px solid rgba(255, 255, 255, 0.65);
border-radius: 999px;
background: rgba(255, 253, 247, 0.76);
box-shadow: 0 10px 30px rgba(24, 49, 59, 0.09);
backdrop-filter: blur(12px);
transform: translateX(-50%);
white-space: nowrap;
}
.race-banner::before {
content: "";
width: 8px;
height: 8px;
border-radius: 50%;
background: var(--yellow);
box-shadow: 0 0 0 4px rgba(245, 199, 82, 0.22);
}
.race-banner strong {
font-size: 10px;
font-weight: 900;
letter-spacing: 0.11em;
}
.leaderboard {
bottom: 26px;
left: 50%;
min-width: 300px;
padding: 12px 18px;
border: 1px solid rgba(255, 255, 255, 0.7);
border-radius: 16px;
background: rgba(255, 253, 247, 0.84);
box-shadow: 0 12px 35px rgba(24, 49, 59, 0.11);
backdrop-filter: blur(12px);
text-align: center;
transform: translateX(-50%);
}
.leader-labels {
display: flex;
align-items: center;
justify-content: space-between;
gap: 25px;
font-size: 11px;
font-weight: 900;
}
.leader-labels .a {
color: var(--coral);
}
.leader-labels .b {
color: var(--teal);
}
.leader-center {
color: var(--muted);
font-size: 9px;
font-weight: 850;
letter-spacing: 0.08em;
}
.leader-track {
position: relative;
height: 5px;
margin-top: 9px;
overflow: hidden;
border-radius: 99px;
background: rgba(24, 49, 59, 0.08);
}
.leader-track::after {
content: "";
position: absolute;
top: -2px;
bottom: -2px;
left: 50%;
width: 1px;
background: rgba(24, 49, 59, 0.35);
}
.leader-fill-a,
.leader-fill-b {
position: absolute;
top: 0;
bottom: 0;
width: 0;
transition: width 80ms linear;
}
.leader-fill-a {
left: 0;
border-radius: 99px 0 0 99px;
background: var(--coral);
}
.leader-fill-b {
right: 0;
border-radius: 0 99px 99px 0;
background: var(--teal);
}
.camera-controls {
right: 24px;
bottom: 24px;
display: flex;
gap: 6px;
padding: 6px;
border: 1px solid rgba(255, 255, 255, 0.68);
border-radius: 15px;
background: rgba(255, 253, 247, 0.82);
box-shadow: 0 12px 30px rgba(24, 49, 59, 0.1);
backdrop-filter: blur(12px);
}
.camera-button {
padding: 9px 11px;
border-radius: 10px;
color: var(--muted);
background: transparent;
font-size: 9px;
font-weight: 850;
letter-spacing: 0.05em;
}
.camera-button.active {
color: white;
background: var(--ink);
}
.camera-hint {
bottom: 28px;
left: 26px;
color: rgba(24, 49, 59, 0.58);
font-size: 10px;
font-weight: 700;
letter-spacing: 0.02em;
}
.countdown {
top: 50%;
left: 50%;
display: grid;
place-items: center;
width: 145px;
height: 145px;
border: 5px solid rgba(255, 255, 255, 0.8);
border-radius: 50%;
color: white;
background: rgba(24, 49, 59, 0.84);
box-shadow: 0 20px 60px rgba(24, 49, 59, 0.26);
opacity: 0;
transform: translate(-50%, -50%) scale(0.75);
transition:
opacity 150ms ease,
transform 180ms cubic-bezier(0.2, 1.6, 0.4, 1);
font-size: 64px;
font-weight: 950;
}
.countdown.show {
opacity: 1;
transform: translate(-50%, -50%) scale(1);
}
.toast {
top: 90px;
left: 50%;
padding: 10px 15px;
border-radius: 999px;
color: white;
background: rgba(24, 49, 59, 0.9);
box-shadow: 0 10px 30px rgba(24, 49, 59, 0.15);
opacity: 0;
transform: translate(-50%, -8px);
transition:
opacity 160ms ease,
transform 160ms ease;
font-size: 10px;
font-weight: 850;
letter-spacing: 0.07em;
}
.toast.show {
opacity: 1;
transform: translate(-50%, 0);
}
@media (max-width: 760px) {
.brand {
top: 14px;
left: 14px;
}
.brand-mark {
width: 40px;
height: 40px;
border-radius: 13px;
font-size: 20px;
}
.brand strong {
font-size: 13px;
}
.brand span {
font-size: 10px;
}
.control-panel {
top: auto;
right: 12px;
bottom: 12px;
left: 12px;
width: auto;
padding: 13px;
border-radius: 19px;
}
.panel-heading {
margin-bottom: 9px;
}
.car-row {
padding: 8px 10px;
}
.fairness-note {
margin: 8px 2px;
}
.wind-button {
padding: 8px 12px;
}
.leaderboard {
top: 72px;
bottom: auto;
min-width: 260px;
padding: 9px 14px;
}
.camera-controls {
top: 16px;
right: 12px;
bottom: auto;
}
.camera-button {
padding: 8px;
font-size: 8px;
}
.camera-hint {
display: none;
}
.race-banner {
top: 20px;
}
.race-banner strong {
font-size: 8px;
}
}
@media (max-height: 720px) and (min-width: 761px) {
.control-panel {
top: 12px;
right: 12px;
transform: scale(0.9);
transform-origin: top right;
}
.leaderboard {
bottom: 14px;
}
}
</style>
</head>
<body>
<div id="stage"></div>
<header class="brand ui">
<div class="brand-mark">W</div>
<div>
<strong>WIND-UP WORKSHOP</strong>
<span>Equal-input comparison race</span>
</div>
</header>
<div class="race-banner ui">
<strong id="raceStatus">READY · EQUAL WIND</strong>
</div>
<section class="control-panel ui interactive" aria-label="Race controls">
<div class="panel-heading">
<strong>WINDING BENCH</strong>
<span class="lock-badge">◆ FAIRNESS LOCK</span>
</div>
<div class="car-row row-a">
<div class="car-row-head">
<span class="car-name">
<span class="car-dot"></span>
CAR A · SUNSET
</span>
<span class="turn-value" id="turnsA">6 turns</span>
</div>
<div class="pips" id="pipsA"></div>
</div>
<div class="car-row row-b">
<div class="car-row-head">
<span class="car-name">
<span class="car-dot teal"></span>
CAR B · TIDEPOOL
</span>
<span class="turn-value" id="turnsB">6 turns</span>
</div>
<div class="pips" id="pipsB"></div>
</div>
<div class="fairness-note">
<b>◆</b>
<span>Every winding input is applied to both springs at exactly the same time.</span>
</div>
<button class="wind-button" id="windButton" type="button">
<span class="wind-icon">↻</span>
<strong>WIND BOTH</strong>
<small>+1 equal turn to A and B</small>
</button>
<div class="button-row">
<button class="action-button secondary" id="presetButton" type="button">
LOAD 6 TURNS
</button>
<button class="action-button start" id="startButton" type="button">
START RACE
</button>
</div>
<button class="reset-button" id="resetButton" type="button">
Reset cars to the starting line
</button>
</section>
<div class="leaderboard ui" aria-live="polite">
<div class="leader-labels">
<span class="a" id="leaderA">A · 0%</span>
<span class="leader-center" id="leaderCenter">IDENTICAL INPUT</span>
<span class="b" id="leaderB">0% · B</span>
</div>
<div class="leader-track">
<div class="leader-fill-a" id="fillA"></div>
<div class="leader-fill-b" id="fillB"></div>
</div>
</div>
<div class="camera-controls ui interactive" aria-label="Camera presets">
<button class="camera-button active" data-camera="track" type="button">TRACKSIDE</button>
<button class="camera-button" data-camera="follow" type="button">FOLLOW</button>
<button class="camera-button" data-camera="top" type="button">OVERHEAD</button>
</div>
<div class="camera-hint ui">Drag to orbit · Scroll to zoom</div>
<div class="countdown ui" id="countdown">3</div>
<div class="toast ui" id="toast"></div>
<script type="module">
import * as THREE from "https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
// -------------------------------------------------------------------------
// Scene
// -------------------------------------------------------------------------
const stage = document.getElementById("stage");
const scene = new THREE.Scene();
scene.background = new THREE.Color(0xdce9e2);
scene.fog = new THREE.Fog(0xdce9e2, 48, 100);
const camera = new THREE.PerspectiveCamera(
42,
window.innerWidth / window.innerHeight,
0.1,
160
);
const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.08;
stage.appendChild(renderer.domElement);
const hemi = new THREE.HemisphereLight(0xf7fff8, 0x78918a, 2.2);
scene.add(hemi);
const sun = new THREE.DirectionalLight(0xfff1d3, 3.1);
sun.position.set(-16, 30, 19);
sun.castShadow = true;
sun.shadow.mapSize.set(2048, 2048);
sun.shadow.camera.left = -40;
sun.shadow.camera.right = 40;
sun.shadow.camera.top = 30;
sun.shadow.camera.bottom = -30;
sun.shadow.camera.near = 1;
sun.shadow.camera.far = 90;
sun.shadow.bias = -0.00035;
scene.add(sun);
const fill = new THREE.DirectionalLight(0xb8eeff, 0.7);
fill.position.set(20, 12, -20);
scene.add(fill);
const palette = {
ink: 0x18313b,
cream: 0xfff8e8,
road: 0xf4edda,
coral: 0xff715c,
coralDark: 0xc84438,
teal: 0x13a89d,
tealDark: 0x08746d,
yellow: 0xf5c752,
rubber: 0x243139,
glass: 0x8bc9d5,
wood: 0xa96f46,
leaf: 0x67ad7d
};
function material(color, options = {}) {
return new THREE.MeshStandardMaterial({
color,
roughness: 0.72,
metalness: 0.03,
...options
});
}
function addBox(parent, size, position, mat, shadow = true) {
const mesh = new THREE.Mesh(
new THREE.BoxGeometry(size[0], size[1], size[2]),
mat
);
mesh.position.set(position[0], position[1], position[2]);
mesh.castShadow = shadow;
mesh.receiveShadow = true;
parent.add(mesh);
return mesh;
}
function addCylinder(parent, radius, height, position, mat, segments = 16) {
const mesh = new THREE.Mesh(
new THREE.CylinderGeometry(radius, radius, height, segments),
mat
);
mesh.position.set(position[0], position[1], position[2]);
mesh.castShadow = true;
mesh.receiveShadow = true;
parent.add(mesh);
return mesh;
}
function cylinderBetween(a, b, radius, mat, parent = scene) {
const direction = new THREE.Vector3().subVectors(b, a);
const length = direction.length();
const mesh = new THREE.Mesh(
new THREE.CylinderGeometry(radius, radius, length, 8),
mat
);
mesh.position.copy(a).add(b).multiplyScalar(0.5);
mesh.quaternion.setFromUnitVectors(
new THREE.Vector3(0, 1, 0),
direction.normalize()
);
mesh.castShadow = true;
parent.add(mesh);
return mesh;
}
function roundedRectPath(ctx, x, y, width, height, radius) {
const r = Math.min(radius, width / 2, height / 2);
ctx.beginPath();
ctx.moveTo(x + r, y);
ctx.arcTo(x + width, y, x + width, y + height, r);
ctx.arcTo(x + width, y + height, x, y + height, r);
ctx.arcTo(x, y + height, x, y, r);
ctx.arcTo(x, y, x + width, y, r);
ctx.closePath();
}
function textSprite(text, background = "#18313b", foreground = "#ffffff") {
const canvas = document.createElement("canvas");
canvas.width = 512;
canvas.height = 160;
const ctx = canvas.getContext("2d");
roundedRectPath(ctx, 8, 8, 496, 144, 35);
ctx.fillStyle = background;
ctx.fill();
ctx.fillStyle = foreground;
ctx.font = "900 58px system-ui, sans-serif";
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.fillText(text, 256, 84);
const texture = new THREE.CanvasTexture(canvas);
texture.colorSpace = THREE.SRGBColorSpace;
const sprite = new THREE.Sprite(
new THREE.SpriteMaterial({
map: texture,
transparent: true,
depthWrite: false
})
);
sprite.scale.set(3.9, 1.22, 1);
sprite.userData.canvas = canvas;
sprite.userData.context = ctx;
sprite.userData.texture = texture;
return sprite;
}
// -------------------------------------------------------------------------
// Track and scenery
// -------------------------------------------------------------------------
const START_X = -26;
const FINISH_X = 26;
const MAX_TURNS = 10;
const ground = new THREE.Mesh(
new THREE.PlaneGeometry(130, 90),
material(0xd7e5dc)
);
ground.rotation.x = -Math.PI / 2;
ground.position.y = -0.07;
ground.receiveShadow = true;
scene.add(ground);
addBox(
scene,
[64, 0.28, 11.4],
[0, 0.08, 0],
material(palette.road)
);
const centerDashMat = material(palette.yellow, { roughness: 0.85 });
for (let x = -29; x <= 29; x += 3.2) {
addBox(scene, [1.45, 0.035, 0.12], [x, 0.25, 0], centerDashMat, false);
}
const railMat = material(0xffffff, { roughness: 0.62 });
for (const z of [-5.62, 5.62]) {
addBox(scene, [63, 0.27, 0.18], [0, 0.52, z], railMat);
for (let x = -30; x <= 30; x += 5) {
addBox(scene, [0.17, 0.7, 0.17], [x, 0.43, z], railMat);
}
}
// Checkerboard start and finish bands.
function checkerBand(x, useInk = false) {
for (let row = 0; row < 2; row++) {
for (let column = 0; column < 10; column++) {
const dark = (row + column) % 2 === 0;
const color = useInk
? dark
? palette.ink
: 0xffffff
: dark
? palette.ink
: 0xffffff;
addBox(
scene,
[0.62, 0.045, 0.62],
[x + row * 0.62, 0.285, -2.79 + column * 0.62],
material(color, { roughness: 0.9 }),
false
);
}
}
}
checkerBand(START_X - 0.62);
checkerBand(FINISH_X - 0.62);
function makeArch(x, label, color) {
const postMat = material(palette.ink);
addBox(scene, [0.28, 4.15, 0.28], [x, 2.05, -5.7], postMat);
addBox(scene, [0.28, 4.15, 0.28], [x, 2.05, 5.7], postMat);
addBox(scene, [0.32, 0.32, 11.75], [x, 4.08, 0], postMat);
const sign = textSprite(label, `#${color.toString(16).padStart(6, "0")}`);
sign.position.set(x, 4.08, 0);
sign.scale.set(3.4, 1.06, 1);
scene.add(sign);
}
makeArch(START_X, "START", 0xff715c);
makeArch(FINISH_X, "FINISH", 0x13a89d);
// Toy-like trees and shrubs.
let seed = 42;
function random() {
seed = (seed * 16807) % 2147483647;
return (seed - 1) / 2147483646;
}
const trunkMat = material(palette.wood);
const leafMats = [
material(0x65ad7c),
material(0x78ba82),
material(0x4d9872)
];
function tree(x, z, scale = 1) {
const group = new THREE.Group();
group.position.set(x, 0, z);
group.scale.setScalar(scale);
addCylinder(group, 0.22, 1.7, [0, 0.85, 0], trunkMat, 10);
const crown = new THREE.Mesh(
new THREE.IcosahedronGeometry(1.2, 1),
leafMats[Math.floor(random() * leafMats.length)]
);
crown.position.y = 2.15;
crown.scale.set(1, 1.12, 0.94);
crown.castShadow = true;
crown.receiveShadow = true;
group.add(crown);
scene.add(group);
}
for (let i = 0; i < 18; i++) {
const x = -37 + random() * 74;
const side = random() > 0.5 ? 1 : -1;
const z = side * (8.2 + random() * 9);
tree(x, z, 0.72 + random() * 0.75);
}
// Low toy blocks around the track.
const blockColors = [palette.coral, palette.teal, palette.yellow, 0x7a8fd1];
for (let i = 0; i < 18; i++) {
const x = -34 + random() * 68;
const z = (random() > 0.5 ? 1 : -1) * (7.2 + random() * 2.3);
const size = 0.5 + random() * 0.7;
addBox(
scene,
[size, size, size],
[x, size / 2, z],
material(blockColors[Math.floor(random() * blockColors.length)])
);
}
// Decorative bunting.
const buntingX = -17;
const wireMat = material(palette.ink);
cylinderBetween(
new THREE.Vector3(buntingX, 0, -5.6),
new THREE.Vector3(buntingX, 4.5, -5.6),
0.09,
wireMat
);
cylinderBetween(
new THREE.Vector3(buntingX, 0, 5.6),
new THREE.Vector3(buntingX, 4.5, 5.6),
0.09,
wireMat
);
cylinderBetween(
new THREE.Vector3(buntingX, 4.5, -5.6),
new THREE.Vector3(buntingX, 4.5, 5.6),
0.035,
wireMat
);
const flagColors = [palette.coral, palette.yellow, palette.teal, 0x6688d8];
for (let i = 0; i < 10; i++) {
const geometry = new THREE.BufferGeometry();
geometry.setAttribute(
"position",
new THREE.Float32BufferAttribute(
[-0.3, 0, 0, 0.3, 0, 0, 0, -0.58, 0],
3
)
);
geometry.computeVertexNormals();
const flag = new THREE.Mesh(
geometry,
material(flagColors[i % flagColors.length], { side: THREE.DoubleSide })
);
flag.position.set(buntingX, 4.48, -4.5 + i);
flag.castShadow = true;
scene.add(flag);
}
// -------------------------------------------------------------------------
// Toy cars
// -------------------------------------------------------------------------
function createCounterSprite(letter, color) {
const canvas = document.createElement("canvas");
canvas.width = 320;
canvas.height = 112;
const ctx = canvas.getContext("2d");
const texture = new THREE.CanvasTexture(canvas);
texture.colorSpace = THREE.SRGBColorSpace;
const sprite = new THREE.Sprite(
new THREE.SpriteMaterial({
map: texture,
transparent: true,
depthTest: false,
depthWrite: false
})
);
sprite.scale.set(2.35, 0.82, 1);
sprite.renderOrder = 20;
sprite.userData = {
canvas,
ctx,
texture,
letter,
color: `#${color.toString(16).padStart(6, "0")}`
};
return sprite;
}
function updateCounter(sprite, turns) {
const { canvas, ctx, texture, letter, color } = sprite.userData;
ctx.clearRect(0, 0, canvas.width, canvas.height);
roundedRectPath(ctx, 8, 8, 304, 96, 27);
ctx.fillStyle = "rgba(24, 49, 59, 0.92)";
ctx.fill();
ctx.fillStyle = color;
ctx.beginPath();
ctx.arc(47, 56, 23, 0, Math.PI * 2);
ctx.fill();
ctx.fillStyle = "#ffffff";
ctx.font = "900 30px system-ui, sans-serif";
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.fillText(letter, 47, 58);
ctx.textAlign = "left";
ctx.font = "850 25px system-ui, sans-serif";
ctx.fillText(`${Math.max(0, turns).toFixed(1)} TURNS`, 83, 57);
texture.needsUpdate = true;
}
function createToyCar(letter, color, darkColor, laneZ) {
const group = new THREE.Group();
group.position.set(START_X, 0, laneZ);
const bodyMat = material(color);
const darkBodyMat = material(darkColor);
const bumperMat = material(0xf8f2dc, { metalness: 0.18, roughness: 0.4 });
const glassMat = material(palette.glass, {
transparent: true,
opacity: 0.72,
roughness: 0.22,
metalness: 0.08
});
const wheelMat = material(palette.rubber, { roughness: 0.9 });
const hubMat = material(0xf7e8bd, { metalness: 0.25, roughness: 0.42 });
const keyMat = material(0xe6bd55, { metalness: 0.48, roughness: 0.34 });
addBox(group, [2.85, 0.5, 1.62], [0, 0.73, 0], bodyMat);
addBox(group, [1.3, 0.27, 1.48], [0.83, 1.06, 0], bodyMat);
addBox(group, [1.28, 0.67, 1.31], [-0.38, 1.31, 0], glassMat);
addBox(group, [1.48, 0.16, 1.5], [-0.43, 1.69, 0], bodyMat);
addBox(group, [0.15, 0.75, 1.5], [-0.99, 1.32, 0], darkBodyMat);
addBox(group, [0.16, 0.74, 0.16], [-0.38, 1.31, 0.69], bodyMat);
addBox(group, [0.16, 0.74, 0.16], [-0.38, 1.31, -0.69], bodyMat);
addBox(group, [0.18, 0.22, 1.72], [1.48, 0.72, 0], bumperMat);
addBox(group, [0.18, 0.22, 1.72], [-1.48, 0.72, 0], bumperMat);
const headlightMat = material(0xfff1a5, {
emissive: 0xf7c75e,
emissiveIntensity: 0.45
});
addBox(group, [0.13, 0.24, 0.35], [1.48, 1.01, 0.48], headlightMat);
addBox(group, [0.13, 0.24, 0.35], [1.48, 1.01, -0.48], headlightMat);
const tailLightMat = material(0xe94b45, {
emissive: 0x8e1d19,
emissiveIntensity: 0.25
});
addBox(group, [0.12, 0.2, 0.3], [-1.49, 1.0, 0.48], tailLightMat);
addBox(group, [0.12, 0.2, 0.3], [-1.49, 1.0, -0.48], tailLightMat);
const wheels = [];
for (const x of [-0.9, 0.9]) {
for (const z of [-0.86, 0.86]) {
const wheel = new THREE.Group();
wheel.position.set(x, 0.43, z);
const tire = new THREE.Mesh(
new THREE.CylinderGeometry(0.43, 0.43, 0.3, 20),
wheelMat
);
tire.rotation.x = Math.PI / 2;
tire.castShadow = true;
wheel.add(tire);
const hub = new THREE.Mesh(
new THREE.CylinderGeometry(0.18, 0.18, 0.32, 16),
hubMat
);
hub.rotation.x = Math.PI / 2;
hub.castShadow = true;
wheel.add(hub);
group.add(wheel);
wheels.push(wheel);
}
}
// Wind-up key: pivot rotates around the car's longitudinal axis.
const keyPivot = new THREE.Group();
keyPivot.position.set(-1.45, 1.02, 0);
group.add(keyPivot);
const keyStem = new THREE.Mesh(
new THREE.CylinderGeometry(0.075, 0.075, 0.68, 12),
keyMat
);
keyStem.rotation.z = Math.PI / 2;
keyStem.position.x = -0.34;
keyStem.castShadow = true;
keyPivot.add(keyStem);
const keyLoop = new THREE.Mesh(
new THREE.TorusGeometry(0.28, 0.075, 10, 24),
keyMat
);
keyLoop.rotation.y = Math.PI / 2;
keyLoop.position.x = -0.78;
keyLoop.castShadow = true;
keyPivot.add(keyLoop);
const keyBar = addBox(
keyPivot,
[0.1, 0.48, 0.1],
[-0.78, 0, 0],
keyMat
);
keyBar.castShadow = true;
const counter = createCounterSprite(letter, color);
counter.position.set(-0.1, 2.32, 0);
group.add(counter);
group.userData = {
wheels,
keyPivot,
counter,
laneZ,
keyVelocity: 0,
keyTarget: 0
};
scene.add(group);
return group;
}
const carA = createToyCar("A", palette.coral, palette.coralDark, 2.55);
const carB = createToyCar("B", palette.teal, palette.tealDark, -2.55);
const cars = [carA, carB];
// -------------------------------------------------------------------------
// UI and race state
// -------------------------------------------------------------------------
const windButton = document.getElementById("windButton");
const presetButton = document.getElementById("presetButton");
const startButton = document.getElementById("startButton");
const resetButton = document.getElementById("resetButton");
const countdownElement = document.getElementById("countdown");
const raceStatus = document.getElementById("raceStatus");
const leaderA = document.getElementById("leaderA");
const leaderB = document.getElementById("leaderB");
const leaderCenter = document.getElementById("leaderCenter");
const fillA = document.getElementById("fillA");
const fillB = document.getElementById("fillB");
const turnsAElement = document.getElementById("turnsA");
const turnsBElement = document.getElementById("turnsB");
const pipsA = document.getElementById("pipsA");
const pipsB = document.getElementById("pipsB");
const toastElement = document.getElementById("toast");
let windingTurns = 6;
let phase = "ready";
let countdownElapsed = 0;
let raceElapsed = 0;
let raceDuration = 6;
let lastUiUpdate = 0;
let toastTimer;
function makePips(container) {
for (let i = 0; i < MAX_TURNS; i++) {
const pip = document.createElement("span");
pip.className = "pip";
container.appendChild(pip);
}
}
makePips(pipsA);
makePips(pipsB);
function remainingTurns() {
if (phase === "racing") {
const progress = Math.min(raceElapsed / raceDuration, 1);
return windingTurns * (1 - progress);
}
return windingTurns;
}
function updateUI() {
const running = phase === "countdown" || phase === "racing";
const remaining = remainingTurns();
windButton.disabled = running || windingTurns >= MAX_TURNS;
presetButton.disabled = running;
startButton.disabled = running || windingTurns <= 0;
resetButton.disabled = running;
startButton.textContent = phase === "finished" ? "RACE AGAIN" : "START RACE";
turnsAElement.textContent = `${remaining.toFixed(1)} turns`;
turnsBElement.textContent = `${remaining.toFixed(1)} turns`;
const activePips = Math.ceil(remaining);
[...pipsA.children].forEach((pip, index) => {
pip.classList.toggle("on", index < activePips);
});
[...pipsB.children].forEach((pip, index) => {
pip.classList.toggle("on", index < activePips);
});
updateCounter(carA.userData.counter, remaining);
updateCounter(carB.userData.counter, remaining);
}
function showToast(message) {
toastElement.textContent = message;
toastElement.classList.add("show");
clearTimeout(toastTimer);
toastTimer = setTimeout(() => {
toastElement.classList.remove("show");
}, 1500);
}
function syncWoundKeys() {
for (const car of cars) {
car.userData.keyTarget = windingTurns * Math.PI * 1.1;
}
}
function windBoth() {
if (phase === "countdown" || phase === "racing") return;
if (windingTurns >= MAX_TURNS) {
showToast("MAXIMUM FAIR WINDING REACHED");
return;
}
windingTurns += 1;
for (const car of cars) {
car.userData.keyVelocity += 8.5;
car.userData.keyTarget = windingTurns * Math.PI * 1.1;
}
updateUI();
showToast("+1 TURN · LOCKED TO BOTH CARS");
}
function loadSixTurns() {
if (phase === "countdown" || phase === "racing") return;
windingTurns = 6;
syncWoundKeys();
for (const car of cars) {
car.userData.keyVelocity += 5;
}
updateUI();
showToast("6 IDENTICAL TURNS LOADED");
}
function resetCars(showMessage = true) {
phase = "ready";
countdownElapsed = 0;
raceElapsed = 0;
countdownElement.classList.remove("show");
for (const car of cars) {
car.position.set(START_X, 0, car.userData.laneZ);
car.userData.keyPivot.rotation.x = windingTurns * Math.PI * 1.1;
car.userData.keyVelocity = 0;
}
raceStatus.textContent = "READY · EQUAL WIND";
leaderA.textContent = "A · 0%";
leaderB.textContent = "0% · B";
leaderCenter.textContent = "IDENTICAL INPUT";
fillA.style.width = "0%";
fillB.style.width = "0%";
updateUI();
if (showMessage) {
showToast("CARS RESET · WINDING PRESERVED");
}
}
function startRace() {
if (phase === "countdown" || phase === "racing") return;
if (windingTurns <= 0) {
showToast("WIND BOTH CARS FIRST");
return;
}
if (phase === "finished") {
resetCars(false);
}
phase = "countdown";
countdownElapsed = 0;
raceElapsed = 0;
raceDuration = THREE.MathUtils.clamp(8.4 - windingTurns * 0.38, 4.5, 8.1);
for (const car of cars) {
car.userData.keyStartRotation = car.userData.keyPivot.rotation.x;
}
raceStatus.textContent = "STARTING · IDENTICAL INPUT";
leaderCenter.textContent = "SPRINGS LOCKED";
countdownElement.textContent = "3";
countdownElement.classList.add("show");
updateUI();
}
windButton.addEventListener("click", windBoth);
presetButton.addEventListener("click", loadSixTurns);
startButton.addEventListener("click", startRace);
resetButton.addEventListener("click", () => resetCars(true));
window.addEventListener("keydown", (event) => {
if (event.code === "KeyW") windBoth();
if (event.code === "Space") {
event.preventDefault();
startRace();
}
if (event.code === "KeyR") resetCars(true);
});
// -------------------------------------------------------------------------
// Custom camera controls — no external controls module
// -------------------------------------------------------------------------
const cameraState = {
theta: 0.76,
phi: 0.96,
radius: 48,
target: new THREE.Vector3(0, 0.85, 0),
desiredTarget: new THREE.Vector3(0, 0.85, 0),
mode: "track"
};
const cameraButtons = [...document.querySelectorAll("[data-camera]")];
function setCameraMode(mode) {
cameraState.mode = mode;
for (const button of cameraButtons) {
button.classList.toggle("active", button.dataset.camera === mode);
}
if (mode === "track") {
cameraState.theta = 0.76;
cameraState.phi = 0.96;
cameraState.radius = 48 * Math.max(1, 1.05 / camera.aspect);
cameraState.desiredTarget.set(0, 0.85, 0);
}
if (mode === "follow") {
cameraState.theta = -Math.PI / 2;
cameraState.phi = 1.08;
cameraState.radius = 17;
}
if (mode === "top") {
cameraState.theta = 0.76;
cameraState.phi = 0.18;
cameraState.radius = 43 * Math.max(1, 1.05 / camera.aspect);
}
}
cameraButtons.forEach((button) => {
button.addEventListener("click", () => setCameraMode(button.dataset.camera));
});
const pointers = new Map();
let previousPinchDistance = 0;
let dragging = false;
let previousX = 0;
let previousY = 0;
renderer.domElement.addEventListener("pointerdown", (event) => {
renderer.domElement.setPointerCapture(event.pointerId);
pointers.set(event.pointerId, {
x: event.clientX,
y: event.clientY
});
if (pointers.size === 1) {
dragging = true;
previousX = event.clientX;
previousY = event.clientY;
}
if (pointers.size === 2) {
const values = [...pointers.values()];
previousPinchDistance = Math.hypot(
values[0].x - values[1].x,
values[0].y - values[1].y
);
}
});
renderer.domElement.addEventListener("pointermove", (event) => {
if (!pointers.has(event.pointerId)) return;
pointers.set(event.pointerId, {
x: event.clientX,
y: event.clientY
});
if (pointers.size === 2) {
const values = [...pointers.values()];
const distance = Math.hypot(
values[0].x - values[1].x,
values[0].y - values[1].y
);
cameraState.radius = THREE.MathUtils.clamp(
cameraState.radius * (previousPinchDistance / Math.max(distance, 1)),
10,
85
);
previousPinchDistance = distance;
return;
}
if (!dragging) return;
const dx = event.clientX - previousX;
const dy = event.clientY - previousY;
previousX = event.clientX;
previousY = event.clientY;
cameraState.theta -= dx * 0.005;
cameraState.phi = THREE.MathUtils.clamp(cameraState.phi - dy * 0.004, 0.14, 1.38);
cameraState.mode = "free";
cameraButtons.forEach((button) => button.classList.remove("active"));
});
function endPointer(event) {
pointers.delete(event.pointerId);
if (pointers.size < 2) previousPinchDistance = 0;
if (pointers.size === 0) dragging = false;
}
renderer.domElement.addEventListener("pointerup", endPointer);
renderer.domElement.addEventListener("pointercancel", endPointer);
renderer.domElement.addEventListener(
"wheel",
(event) => {
event.preventDefault();
cameraState.radius = THREE.MathUtils.clamp(
cameraState.radius * Math.exp(event.deltaY * 0.001),
10,
85
);
},
{ passive: false }
);
function updateCamera(dt) {
const raceX = (carA.position.x + carB.position.x) * 0.5;
if (cameraState.mode === "follow" || cameraState.mode === "top") {
cameraState.desiredTarget.set(raceX, 0.85, 0);
}
const targetBlend = 1 - Math.exp(-3.5 * dt);
cameraState.target.lerp(cameraState.desiredTarget, targetBlend);
const sinPhi = Math.sin(cameraState.phi);
camera.position.set(
cameraState.target.x +
cameraState.radius * sinPhi * Math.sin(cameraState.theta),
cameraState.target.y + cameraState.radius * Math.cos(cameraState.phi),
cameraState.target.z +
cameraState.radius * sinPhi * Math.cos(cameraState.theta)
);
camera.lookAt(cameraState.target);
}
// -------------------------------------------------------------------------
// Race animation
// -------------------------------------------------------------------------
function updateCountdown(dt) {
countdownElapsed += dt;
if (countdownElapsed < 3) {
const number = 3 - Math.floor(countdownElapsed);
countdownElement.textContent = String(number);
} else {
countdownElement.textContent = "GO!";
}
if (countdownElapsed >= 3.6) {
phase = "racing";
raceElapsed = 0;
countdownElement.classList.remove("show");
raceStatus.textContent = "RACING · PERFECTLY LEVEL";
leaderCenter.textContent = "PERFECTLY LEVEL";
updateUI();
}
}
function updateRace(dt) {
raceElapsed += dt;
const progress = Math.min(raceElapsed / raceDuration, 1);
// A spring-powered launch followed by a natural coast.
const travel = 1 - Math.pow(1 - progress, 1.72);
for (const car of cars) {
car.position.x = THREE.MathUtils.lerp(START_X, FINISH_X, travel);
car.position.y = Math.sin(raceElapsed * 12 + car.userData.laneZ) * 0.012;
const wheelRotation = -(car.position.x - START_X) / 0.43;
for (const wheel of car.userData.wheels) {
wheel.rotation.z = wheelRotation;
}
const keyUnwind = windingTurns * progress * Math.PI * 1.1;
car.userData.keyPivot.rotation.x =
car.userData.keyStartRotation - keyUnwind;
}
const percentA = ((carA.position.x - START_X) / (FINISH_X - START_X)) * 100;
const percentB = ((carB.position.x - START_X) / (FINISH_X - START_X)) * 100;
leaderA.textContent = `A · ${Math.min(100, percentA).toFixed(0)}%`;
leaderB.textContent = `${Math.min(100, percentB).toFixed(0)}% · B`;
fillA.style.width = `${Math.min(100, percentA)}%`;
fillB.style.width = `${Math.min(100, percentB)}%`;
if (progress >= 1) {
phase = "finished";
raceStatus.textContent = "DEAD HEAT · IDENTICAL WIND";
leaderCenter.textContent = "EXACT TIE";
leaderA.textContent = "A · 100%";
leaderB.textContent = "100% · B";
fillA.style.width = "100%";
fillB.style.width = "100%";
showToast("DEAD HEAT · IDENTICAL WINDING");
updateUI();
}
}
const clock = new THREE.Clock();
function animate() {
requestAnimationFrame(animate);
const dt = Math.min(clock.getDelta(), 0.05);
const now = clock.elapsedTime;
if (phase === "countdown") {
updateCountdown(dt);
} else if (phase === "racing") {
updateRace(dt);
} else if (phase === "ready") {
// Relax the keys to their wound position after a manual winding.
for (const car of cars) {
car.userData.keyPivot.rotation.x = THREE.MathUtils.damp(
car.userData.keyPivot.rotation.x,
car.userData.keyTarget,
8,
dt
);
}
}
// Residual key spin after clicking the winding button.
for (const car of cars) {
if (phase !== "racing") {
car.userData.keyPivot.rotation.x += car.userData.keyVelocity * dt;
car.userData.keyVelocity *= Math.exp(-6 * dt);
}
}
if (now - lastUiUpdate > 0.08) {
if (phase === "racing" || phase === "finished") {
updateUI();
}
lastUiUpdate = now;
}
updateCamera(dt);
renderer.render(scene, camera);
}
window.addEventListener("resize", () => {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
if (cameraState.mode === "track") {
cameraState.radius = 48 * Math.max(1, 1.05 / camera.aspect);
}
if (cameraState.mode === "top") {
cameraState.radius = 43 * Math.max(1, 1.05 / camera.aspect);
}
});
// Initialize the equal-wind setup.
syncWoundKeys();
for (const car of cars) {
car.userData.keyPivot.rotation.x = car.userData.keyTarget;
updateCounter(car.userData.counter, windingTurns);
}
updateUI();
updateCamera(1);
animate();
</script>
</body>
</html>
```