Prompt specification
Build or customize the Three.js 3D scene "Choreography Collision Puzzle" 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: Choreography Collision Puzzle
Category: Art & Culture · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/choreography-collision-puzzle-x3300
Scene Description Prompt:
Make a standalone HTML scene with Three.js from cdnjs that depicts dance formations, spacing, and movement paths. Let users assign bounded paths and start times to six dancers. Replay the formation change and flag collisions while preserving a shared beat and final positions. Low-poly.
Working Three.js Starter (choreography-collision-puzzle-x3300):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Choreo — Formation Lab</title>
<style>
:root {
color-scheme: dark;
--bg: #08101c;
--panel: rgba(12, 21, 35, 0.9);
--panel-solid: #0c1523;
--line: rgba(151, 181, 213, 0.16);
--text: #edf5ff;
--muted: #91a5bd;
--cyan: #58e1dc;
--gold: #ffd166;
--red: #ff5964;
--pulse: 0;
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: var(--bg);
color: var(--text);
font-family:
Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
button,
input {
font: inherit;
}
button {
color: inherit;
}
#scene {
position: fixed;
inset: 0;
}
#scene canvas {
display: block;
width: 100%;
height: 100%;
touch-action: none;
}
.topbar {
position: fixed;
z-index: 10;
top: 14px;
left: 16px;
right: 16px;
min-height: 58px;
display: flex;
align-items: center;
gap: 14px;
padding: 10px 14px;
border: 1px solid var(--line);
border-radius: 14px;
background: rgba(8, 16, 28, 0.88);
backdrop-filter: blur(16px);
box-shadow: 0 12px 40px rgba(0, 0, 0, 0.22);
}
.brand {
min-width: 205px;
display: flex;
align-items: center;
gap: 10px;
}
.brand-mark {
position: relative;
width: 34px;
height: 34px;
border: 1px solid rgba(88, 225, 220, 0.45);
border-radius: 9px;
background:
radial-gradient(circle at 50% 48%, rgba(88, 225, 220, 0.18), transparent 58%),
rgba(88, 225, 220, 0.05);
overflow: hidden;
}
.brand-mark::before,
.brand-mark::after {
content: "";
position: absolute;
width: 7px;
height: 7px;
border-radius: 50%;
background: var(--cyan);
box-shadow: 0 0 14px rgba(88, 225, 220, 0.7);
animation: logoBeat 1.2s ease-in-out infinite alternate;
}
.brand-mark::before {
left: 7px;
top: 8px;
}
.brand-mark::after {
right: 7px;
bottom: 8px;
animation-delay: -0.6s;
}
@keyframes logoBeat {
to {
transform: scale(1.35);
opacity: 0.55;
}
}
.brand h1 {
margin: 0;
font-size: 16px;
letter-spacing: 0.12em;
text-transform: uppercase;
}
.brand p {
margin: 2px 0 0;
color: var(--muted);
font-size: 11px;
letter-spacing: 0.05em;
}
.top-spacer {
flex: 1;
}
.metric {
min-width: 82px;
display: grid;
gap: 2px;
}
.metric-label {
color: var(--muted);
font-size: 9px;
font-weight: 700;
letter-spacing: 0.14em;
text-transform: uppercase;
}
.metric-value {
font-size: 16px;
font-weight: 750;
font-variant-numeric: tabular-nums;
}
.metric-value.cyan {
color: var(--cyan);
}
.metric-value.red {
color: var(--red);
}
.beat-lamp {
width: 11px;
height: 11px;
display: inline-block;
margin-right: 7px;
border-radius: 50%;
background: var(--cyan);
opacity: calc(0.28 + var(--pulse) * 0.72);
box-shadow: 0 0 calc(5px + var(--pulse) * 18px) rgba(88, 225, 220, 0.8);
vertical-align: 1px;
}
.compact-field {
display: flex;
align-items: center;
gap: 7px;
color: var(--muted);
font-size: 11px;
white-space: nowrap;
}
input[type="number"] {
width: 64px;
height: 32px;
padding: 5px 7px;
border: 1px solid var(--line);
border-radius: 8px;
outline: none;
background: rgba(255, 255, 255, 0.045);
color: var(--text);
font-variant-numeric: tabular-nums;
}
input[type="number"]:focus {
border-color: rgba(88, 225, 220, 0.75);
box-shadow: 0 0 0 3px rgba(88, 225, 220, 0.09);
}
.icon-button,
.button {
border: 1px solid var(--line);
border-radius: 9px;
background: rgba(255, 255, 255, 0.055);
cursor: pointer;
transition:
background 140ms ease,
border-color 140ms ease,
transform 140ms ease;
}
.icon-button:hover,
.button:hover {
border-color: rgba(88, 225, 220, 0.42);
background: rgba(88, 225, 220, 0.09);
}
.icon-button:active,
.button:active {
transform: translateY(1px);
}
.icon-button {
height: 32px;
padding: 0 10px;
font-size: 11px;
white-space: nowrap;
}
.side-panel {
position: fixed;
z-index: 9;
top: 88px;
bottom: 102px;
left: 16px;
width: 348px;
overflow: auto;
padding: 14px;
border: 1px solid var(--line);
border-radius: 15px;
background: var(--panel);
backdrop-filter: blur(18px);
box-shadow: 0 18px 50px rgba(0, 0, 0, 0.27);
scrollbar-width: thin;
scrollbar-color: rgba(255, 255, 255, 0.16) transparent;
transition:
transform 180ms ease,
opacity 180ms ease;
}
.side-panel.collapsed {
transform: translateX(calc(-100% - 24px));
opacity: 0;
pointer-events: none;
}
.panel-section + .panel-section {
margin-top: 17px;
padding-top: 16px;
border-top: 1px solid var(--line);
}
.section-heading {
display: flex;
align-items: center;
justify-content: space-between;
gap: 8px;
margin-bottom: 10px;
}
.section-heading h2 {
margin: 0;
color: #cfe0f2;
font-size: 10px;
font-weight: 800;
letter-spacing: 0.15em;
text-transform: uppercase;
}
.eyebrow {
color: var(--muted);
font-size: 10px;
}
.dancer-list {
display: grid;
gap: 6px;
}
.dancer-row {
display: grid;
grid-template-columns: 1fr 68px 55px;
align-items: center;
gap: 7px;
min-height: 43px;
padding: 5px 7px 5px 5px;
border: 1px solid transparent;
border-radius: 10px;
background: rgba(255, 255, 255, 0.025);
}
.dancer-row.active {
border-color: rgba(88, 225, 220, 0.35);
background: rgba(88, 225, 220, 0.065);
}
.dancer-select {
min-width: 0;
display: flex;
align-items: center;
gap: 9px;
padding: 4px;
border: 0;
background: transparent;
text-align: left;
cursor: pointer;
}
.swatch {
width: 10px;
height: 27px;
flex: 0 0 auto;
border-radius: 5px;
background: var(--dancer-color);
box-shadow: 0 0 12px color-mix(in srgb, var(--dancer-color) 45%, transparent);
}
.dancer-name {
min-width: 0;
display: grid;
gap: 2px;
}
.dancer-name strong {
overflow: hidden;
font-size: 12px;
text-overflow: ellipsis;
white-space: nowrap;
}
.dancer-status {
color: var(--muted);
font-size: 9px;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.dancer-row.active .dancer-status {
color: var(--cyan);
}
.row-label {
color: var(--muted);
font-size: 9px;
font-weight: 700;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.dancer-row input {
width: 57px;
height: 29px;
padding: 4px 5px;
font-size: 11px;
}
.coordinate-grid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 9px;
}
.coordinate-box {
padding: 9px;
border: 1px solid var(--line);
border-radius: 10px;
background: rgba(255, 255, 255, 0.025);
}
.coordinate-box.final {
border-color: rgba(255, 209, 102, 0.25);
background: rgba(255, 209, 102, 0.035);
}
.coordinate-title {
display: flex;
align-items: center;
gap: 7px;
margin-bottom: 8px;
color: #cbd8e8;
font-size: 10px;
font-weight: 800;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.coordinate-title .dot {
width: 7px;
height: 7px;
border-radius: 50%;
background: var(--cyan);
}
.coordinate-box.final .coordinate-title .dot {
background: var(--gold);
}
.xy-fields {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 6px;
}
.xy-field {
display: grid;
gap: 4px;
}
.xy-field span {
color: var(--muted);
font-size: 9px;
}
.xy-field input {
width: 100%;
height: 31px;
font-size: 11px;
}
.range-row {
margin-top: 12px;
}
.range-label {
display: flex;
justify-content: space-between;
margin-bottom: 7px;
color: var(--muted);
font-size: 10px;
}
input[type="range"] {
width: 100%;
accent-color: var(--cyan);
cursor: pointer;
}
.hint {
margin: 9px 0 0;
color: var(--muted);
font-size: 10px;
line-height: 1.55;
}
.hint strong {
color: #d9e7f6;
font-weight: 650;
}
.button-row {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 8px;
margin-top: 11px;
}
.button {
min-height: 35px;
padding: 7px 9px;
font-size: 10px;
font-weight: 700;
}
.button.primary {
border-color: rgba(88, 225, 220, 0.36);
background: rgba(88, 225, 220, 0.12);
color: #bffaf6;
}
.collision-panel {
position: fixed;
z-index: 8;
top: 88px;
right: 16px;
width: 260px;
padding: 13px;
border: 1px solid var(--line);
border-radius: 14px;
background: rgba(12, 21, 35, 0.86);
backdrop-filter: blur(16px);
box-shadow: 0 18px 45px rgba(0, 0, 0, 0.22);
}
.collision-summary {
display: flex;
align-items: baseline;
justify-content: space-between;
margin-bottom: 10px;
}
.collision-summary strong {
font-size: 13px;
}
.collision-summary span {
color: var(--muted);
font-size: 10px;
}
.collision-list {
display: grid;
gap: 6px;
max-height: 220px;
overflow: auto;
}
.collision-event {
display: flex;
align-items: center;
gap: 9px;
padding: 7px 8px;
border: 1px solid rgba(255, 89, 100, 0.12);
border-radius: 8px;
background: rgba(255, 89, 100, 0.035);
}
.collision-event.active {
border-color: rgba(255, 89, 100, 0.55);
background: rgba(255, 89, 100, 0.13);
}
.collision-dot {
width: 7px;
height: 7px;
flex: 0 0 auto;
border-radius: 50%;
background: var(--red);
box-shadow: 0 0 10px rgba(255, 89, 100, 0.7);
}
.collision-copy {
display: grid;
gap: 2px;
}
.collision-copy strong {
font-size: 10px;
}
.collision-copy small {
color: var(--muted);
font-size: 9px;
}
.clear-state {
padding: 14px 8px;
color: var(--muted);
text-align: center;
font-size: 10px;
line-height: 1.5;
}
.timeline-panel {
position: fixed;
z-index: 10;
right: 16px;
bottom: 16px;
left: 380px;
min-height: 72px;
display: grid;
grid-template-columns: auto 1fr;
align-items: center;
gap: 15px;
padding: 11px 14px;
border: 1px solid var(--line);
border-radius: 14px;
background: rgba(8, 16, 28, 0.9);
backdrop-filter: blur(16px);
box-shadow: 0 15px 45px rgba(0, 0, 0, 0.27);
}
.transport {
display: flex;
align-items: center;
gap: 7px;
}
.transport .button {
min-width: 72px;
}
.timeline {
position: relative;
min-width: 0;
padding-top: 15px;
}
.timeline input {
position: relative;
z-index: 2;
display: block;
margin: 0;
}
.timeline-ticks {
position: absolute;
z-index: 1;
top: 0;
right: 0;
left: 0;
height: 15px;
}
.timeline-ticks span {
position: absolute;
top: 0;
width: 1px;
height: 7px;
background: rgba(255, 255, 255, 0.18);
}
.timeline-ticks span::after {
content: attr(data-label);
position: absolute;
top: 7px;
left: 0;
color: var(--muted);
font-size: 8px;
transform: translateX(-50%);
}
.timeline-labels {
display: flex;
justify-content: space-between;
margin-top: 4px;
color: var(--muted);
font-size: 9px;
}
.scene-help {
position: fixed;
z-index: 4;
right: 18px;
bottom: 96px;
padding: 6px 9px;
border: 1px solid rgba(255, 255, 255, 0.08);
border-radius: 8px;
background: rgba(8, 16, 28, 0.62);
color: var(--muted);
font-size: 9px;
pointer-events: none;
}
#toast {
position: fixed;
z-index: 30;
top: 82px;
left: 50%;
max-width: 360px;
padding: 10px 14px;
border: 1px solid rgba(88, 225, 220, 0.32);
border-radius: 10px;
background: rgba(12, 21, 35, 0.94);
color: #dffefa;
font-size: 11px;
opacity: 0;
pointer-events: none;
transform: translate(-50%, -8px);
transition:
opacity 180ms ease,
transform 180ms ease;
}
#toast.show {
opacity: 1;
transform: translate(-50%, 0);
}
@media (max-width: 1050px) {
.collision-panel {
display: none;
}
.timeline-panel {
left: 380px;
}
}
@media (max-width: 780px) {
.topbar {
gap: 8px;
padding: 9px;
}
.brand {
min-width: auto;
}
.brand p,
.top-metric.optional {
display: none;
}
.side-panel {
width: min(348px, calc(100vw - 32px));
}
.timeline-panel {
right: 12px;
bottom: 12px;
left: 12px;
grid-template-columns: 1fr;
gap: 9px;
}
.transport {
justify-content: center;
}
.scene-help {
display: none;
}
}
</style>
</head>
<body>
<div id="scene"></div>
<header class="topbar">
<div class="brand">
<div class="brand-mark"></div>
<div>
<h1>Choreo</h1>
<p>Formation & movement lab</p>
</div>
</div>
<div class="metric">
<span class="metric-label">Shared beat</span>
<span class="metric-value"><i class="beat-lamp"></i><span id="beatReadout">0.00</span></span>
</div>
<div class="metric">
<span class="metric-label">Live collisions</span>
<span class="metric-value red" id="collisionReadout">0</span>
</div>
<div class="top-spacer"></div>
<label class="compact-field">
BPM
<input id="bpmInput" type="number" min="30" max="240" value="112" />
</label>
<label class="compact-field">
Move beats
<input id="travelInput" type="number" min="1" max="16" value="4" />
</label>
<button class="icon-button" id="audioButton" type="button">Sound off</button>
<button class="icon-button" id="panelToggle" type="button">Hide panel</button>
</header>
<aside class="side-panel" id="sidePanel">
<section class="panel-section">
<div class="section-heading">
<h2>Dancer timing</h2>
<span class="eyebrow">start beat</span>
</div>
<div class="dancer-list" id="dancerList"></div>
</section>
<section class="panel-section">
<div class="section-heading">
<h2>Selected path</h2>
<span class="eyebrow" id="selectedName">Dancer 1</span>
</div>
<div class="coordinate-grid">
<div class="coordinate-box">
<div class="coordinate-title">
<i class="dot"></i>
Start target
</div>
<div class="xy-fields">
<label class="xy-field">
<span>X</span>
<input id="startX" type="number" step="0.1" />
</label>
<label class="xy-field">
<span>Z</span>
<input id="startZ" type="number" step="0.1" />
</label>
</div>
</div>
<div class="coordinate-box final">
<div class="coordinate-title">
<i class="dot"></i>
Final target
</div>
<div class="xy-fields">
<label class="xy-field">
<span>X</span>
<input id="finalX" type="number" step="0.1" />
</label>
<label class="xy-field">
<span>Z</span>
<input id="finalZ" type="number" step="0.1" />
</label>
</div>
</div>
</div>
<div class="range-row">
<div class="range-label">
<span>Path arc</span>
<span id="arcValue">0.00</span>
</div>
<input id="arcInput" type="range" min="-1" max="1" step="0.01" value="0" />
</div>
<p class="hint">
Drag the <strong>cyan S</strong> or <strong>gold F</strong> handle in the scene.
Targets remain inside the stage bounds. Gold targets are persistent finals.
</p>
<div class="button-row">
<button class="button" id="captureButton" type="button">
Capture playhead as finals
</button>
<button class="button" id="resetPathsButton" type="button">
Reset choreography
</button>
</div>
</section>
<section class="panel-section">
<div class="section-heading">
<h2>Playback rules</h2>
</div>
<p class="hint">
Every dancer uses the same BPM clock. A dancer waits at its start target
until its assigned beat, travels for the shared move duration, and then
holds its final target. Replays never overwrite those finals.
</p>
</section>
</aside>
<section class="collision-panel">
<div class="section-heading">
<h2>Collision monitor</h2>
<span class="eyebrow">swept path</span>
</div>
<div class="collision-summary">
<strong id="collisionStatus">No active collision</strong>
<span id="collisionTotal">0 detected events</span>
</div>
<div class="collision-list" id="collisionList"></div>
</section>
<footer class="timeline-panel">
<div class="transport">
<button class="button primary" id="replayButton" type="button">▶ Replay</button>
<button class="button" id="pauseButton" type="button">Pause</button>
<button class="button" id="resetButton" type="button">Starts</button>
</div>
<div class="timeline">
<div class="timeline-ticks" id="timelineTicks"></div>
<input
id="timelineRange"
type="range"
min="0"
max="12"
step="0.01"
value="0"
aria-label="Formation timeline"
/>
<div class="timeline-labels">
<span>Formation A</span>
<span id="timelineEndLabel">Final formation</span>
</div>
</div>
</footer>
<div class="scene-help">
Drag floor to orbit · wheel to zoom · drag S/F handles to edit
</div>
<div 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";
const $ = (id) => document.getElementById(id);
const clamp = (value, min, max) => Math.min(max, Math.max(min, value));
const smoothstep = (t) => t * t * (3 - 2 * t);
const copyDancers = (value) => JSON.parse(JSON.stringify(value));
const BOUNDS = {
minX: -8,
maxX: 8,
minZ: -5,
maxZ: 5
};
const COLLISION_DISTANCE = 0.76;
const STORAGE_KEY = "choreo-formation-lab-v1";
const defaults = [
{
name: "Dancer 1",
color: "#ff6b7a",
startBeat: 0,
start: { x: -5, z: -3 },
end: { x: 5, z: 3 },
arc: 0.12
},
{
name: "Dancer 2",
color: "#ffa857",
startBeat: 0,
start: { x: -2.5, z: -3 },
end: { x: 2.5, z: 3 },
arc: -0.22
},
{
name: "Dancer 3",
color: "#ffd166",
startBeat: 1,
start: { x: 0, z: -3 },
end: { x: 0, z: 3 },
arc: 0.2
},
{
name: "Dancer 4",
color: "#61d981",
startBeat: 2,
start: { x: -5, z: 3 },
end: { x: -5, z: -3 },
arc: 0.08
},
{
name: "Dancer 5",
color: "#58e1dc",
startBeat: 2,
start: { x: -2.5, z: 3 },
end: { x: -2.5, z: -3 },
arc: -0.12
},
{
name: "Dancer 6",
color: "#8e9dff",
startBeat: 3,
start: { x: 0, z: 3 },
end: { x: 0, z: -3 },
arc: -0.18
}
];
let dancers = copyDancers(defaults);
let settings = {
bpm: 112,
travel: 4
};
function loadSavedState() {
try {
const saved = JSON.parse(localStorage.getItem(STORAGE_KEY));
if (!saved || !Array.isArray(saved.dancers)) return;
if (saved.dancers.length === defaults.length) {
dancers = saved.dancers.map((dancer, index) => ({
...defaults[index],
...dancer,
start: { ...defaults[index].start, ...dancer.start },
end: { ...defaults[index].end, ...dancer.end }
}));
}
if (saved.settings) {
settings.bpm = clamp(Number(saved.settings.bpm) || 112, 30, 240);
settings.travel = clamp(Number(saved.settings.travel) || 4, 1, 16);
}
} catch (error) {
console.warn("Could not load saved choreography.", error);
}
}
function persistState() {
try {
localStorage.setItem(
STORAGE_KEY,
JSON.stringify({ dancers, settings })
);
} catch (error) {
console.warn("Could not save choreography.", error);
}
}
loadSavedState();
// ---------------------------------------------------------------------
// Three.js scene
// ---------------------------------------------------------------------
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x08101c);
scene.fog = new THREE.Fog(0x08101c, 22, 42);
const renderer = new THREE.WebGLRenderer({
antialias: true,
alpha: false
});
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.15;
$("scene").appendChild(renderer.domElement);
const camera = new THREE.PerspectiveCamera(
42,
window.innerWidth / window.innerHeight,
0.1,
100
);
const cameraState = {
theta: 0.62,
phi: 0.91,
radius: 21,
target: new THREE.Vector3(0, 0.25, 0)
};
function updateCamera() {
const { theta, phi, radius, target } = cameraState;
const sinPhi = Math.sin(phi);
camera.position.set(
target.x + radius * sinPhi * Math.sin(theta),
target.y + radius * Math.cos(phi),
target.z + radius * sinPhi * Math.cos(theta)
);
camera.lookAt(target);
}
updateCamera();
const hemisphere = new THREE.HemisphereLight(0xaed9ff, 0x162033, 2.2);
scene.add(hemisphere);
const keyLight = new THREE.DirectionalLight(0xffffff, 2.6);
keyLight.position.set(5, 11, 8);
keyLight.castShadow = true;
keyLight.shadow.mapSize.set(1024, 1024);
keyLight.shadow.camera.left = -13;
keyLight.shadow.camera.right = 13;
keyLight.shadow.camera.top = 10;
keyLight.shadow.camera.bottom = -10;
keyLight.shadow.camera.near = 1;
keyLight.shadow.camera.far = 30;
scene.add(keyLight);
const rimLight = new THREE.DirectionalLight(0x58e1dc, 1.5);
rimLight.position.set(-8, 5, -8);
scene.add(rimLight);
const warmLight = new THREE.PointLight(0xffc56f, 1.5, 18, 2);
warmLight.position.set(7, 4, -5);
scene.add(warmLight);
const stage = new THREE.Mesh(
new THREE.BoxGeometry(18, 0.2, 12),
new THREE.MeshStandardMaterial({
color: 0x111d2c,
roughness: 0.92,
metalness: 0.04,
flatShading: true
})
);
stage.position.y = -0.11;
stage.receiveShadow = true;
scene.add(stage);
const ground = new THREE.Mesh(
new THREE.PlaneGeometry(70, 70),
new THREE.MeshStandardMaterial({
color: 0x070d17,
roughness: 1,
metalness: 0
})
);
ground.rotation.x = -Math.PI / 2;
ground.position.y = -0.23;
ground.receiveShadow = true;
scene.add(ground);
const gridVertices = [];
for (let x = BOUNDS.minX; x <= BOUNDS.maxX; x += 1) {
gridVertices.push(x, 0.012, BOUNDS.minZ, x, 0.012, BOUNDS.maxZ);
}
for (let z = BOUNDS.minZ; z <= BOUNDS.maxZ; z += 1) {
gridVertices.push(BOUNDS.minX, 0.012, z, BOUNDS.maxX, 0.012, z);
}
const gridGeometry = new THREE.BufferGeometry();
gridGeometry.setAttribute(
"position",
new THREE.Float32BufferAttribute(gridVertices, 3)
);
const grid = new THREE.LineSegments(
gridGeometry,
new THREE.LineBasicMaterial({
color: 0x7894b6,
transparent: true,
opacity: 0.16
})
);
scene.add(grid);
const boundaryPoints = [
new THREE.Vector3(BOUNDS.minX, 0.025, BOUNDS.minZ),
new THREE.Vector3(BOUNDS.maxX, 0.025, BOUNDS.minZ),
new THREE.Vector3(BOUNDS.maxX, 0.025, BOUNDS.maxZ),
new THREE.Vector3(BOUNDS.minX, 0.025, BOUNDS.maxZ)
];
const boundary = new THREE.LineLoop(
new THREE.BufferGeometry().setFromPoints(boundaryPoints),
new THREE.LineBasicMaterial({
color: 0x58e1dc,
transparent: true,
opacity: 0.62
})
);
scene.add(boundary);
function makeTextSprite(text, color = "#dff8ff") {
const canvas = document.createElement("canvas");
canvas.width = 256;
canvas.height = 128;
const context = canvas.getContext("2d");
context.clearRect(0, 0, canvas.width, canvas.height);
context.fillStyle = "rgba(8,16,28,0.78)";
context.fillRect(22, 25, 212, 78);
context.strokeStyle = color;
context.lineWidth = 5;
context.strokeRect(22, 25, 212, 78);
context.fillStyle = color;
context.font = "800 56px system-ui";
context.textAlign = "center";
context.textBaseline = "middle";
context.fillText(text, 128, 65);
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(1.15, 0.58, 1);
return sprite;
}
const startFloorLabel = makeTextSprite("START", "#58e1dc");
startFloorLabel.position.set(-6.9, 0.18, -4.65);
scene.add(startFloorLabel);
const finalFloorLabel = makeTextSprite("FINAL", "#ffd166");
finalFloorLabel.position.set(6.9, 0.18, 4.65);
scene.add(finalFloorLabel);
const beatRing = new THREE.Mesh(
new THREE.RingGeometry(0.58, 0.67, 32),
new THREE.MeshBasicMaterial({
color: 0x58e1dc,
transparent: true,
opacity: 0.2,
side: THREE.DoubleSide,
depthWrite: false
})
);
beatRing.rotation.x = -Math.PI / 2;
beatRing.position.y = 0.025;
scene.add(beatRing);
const selectionRing = new THREE.Mesh(
new THREE.RingGeometry(0.54, 0.59, 24),
new THREE.MeshBasicMaterial({
color: 0xffffff,
transparent: true,
opacity: 0.72,
side: THREE.DoubleSide,
depthWrite: false
})
);
selectionRing.rotation.x = -Math.PI / 2;
selectionRing.position.y = 0.03;
scene.add(selectionRing);
const pathGroup = new THREE.Group();
scene.add(pathGroup);
const pathLines = [];
const startMarkers = [];
const finalMarkers = [];
for (let index = 0; index < dancers.length; index++) {
const color = new THREE.Color(dancers[index].color);
const pathLine = new THREE.Line(
new THREE.BufferGeometry(),
new THREE.LineDashedMaterial({
color,
dashSize: 0.18,
gapSize: 0.11,
transparent: true,
opacity: 0.45,
depthWrite: false
})
);
pathLine.frustumCulled = false;
pathGroup.add(pathLine);
pathLines.push(pathLine);
const startMarker = new THREE.Mesh(
new THREE.SphereGeometry(0.1, 8, 6),
new THREE.MeshBasicMaterial({
color,
transparent: true,
opacity: 0.8
})
);
startMarker.position.y = 0.08;
pathGroup.add(startMarker);
startMarkers.push(startMarker);
const finalMarker = new THREE.Mesh(
new THREE.OctahedronGeometry(0.13, 0),
new THREE.MeshBasicMaterial({
color: 0xffd166,
transparent: true,
opacity: 0.92
})
);
finalMarker.position.y = 0.13;
pathGroup.add(finalMarker);
finalMarkers.push(finalMarker);
}
function createHandle(type) {
const group = new THREE.Group();
group.userData.handleType = type;
if (type === "start") {
const ring = new THREE.Mesh(
new THREE.TorusGeometry(0.28, 0.055, 6, 18),
new THREE.MeshBasicMaterial({ color: 0x58e1dc })
);
ring.rotation.x = Math.PI / 2;
group.add(ring);
const stem = new THREE.Mesh(
new THREE.BoxGeometry(0.055, 0.7, 0.055),
new THREE.MeshBasicMaterial({
color: 0x58e1dc,
transparent: true,
opacity: 0.38
})
);
stem.position.y = 0.35;
group.add(stem);
const label = makeTextSprite("S", "#58e1dc");
label.position.y = 0.88;
group.add(label);
} else {
const gem = new THREE.Mesh(
new THREE.OctahedronGeometry(0.23, 0),
new THREE.MeshBasicMaterial({ color: 0xffd166 })
);
gem.position.y = 0.22;
group.add(gem);
const ring = new THREE.Mesh(
new THREE.TorusGeometry(0.3, 0.045, 6, 18),
new THREE.MeshBasicMaterial({
color: 0xffd166,
transparent: true,
opacity: 0.7
})
);
ring.rotation.x = Math.PI / 2;
ring.position.y = 0.05;
group.add(ring);
const label = makeTextSprite("F", "#ffd166");
label.position.y = 0.88;
group.add(label);
}
scene.add(group);
return group;
}
const startHandle = createHandle("start");
const finalHandle = createHandle("final");
// ---------------------------------------------------------------------
// Low-poly dancer rigs
// ---------------------------------------------------------------------
function createDancer(dancer, index) {
const root = new THREE.Group();
root.userData.dancerIndex = index;
const shadow = new THREE.Mesh(
new THREE.CircleGeometry(0.46, 12),
new THREE.MeshBasicMaterial({
color: 0x000000,
transparent: true,
opacity: 0.28,
depthWrite: false
})
);
shadow.rotation.x = -Math.PI / 2;
shadow.position.y = 0.018;
root.add(shadow);
const rig = new THREE.Group();
root.add(rig);
const color = new THREE.Color(dancer.color);
const skinMaterial = new THREE.MeshStandardMaterial({
color: index % 2 === 0 ? 0xd99b78 : 0x9a664f,
roughness: 0.85,
flatShading: true
});
const costumeMaterial = new THREE.MeshStandardMaterial({
color,
roughness: 0.64,
metalness: 0.05,
flatShading: true
});
const darkMaterial = new THREE.MeshStandardMaterial({
color: 0x17202e,
roughness: 0.88,
flatShading: true
});
const torso = new THREE.Mesh(
new THREE.CylinderGeometry(0.29, 0.4, 0.82, 6),
costumeMaterial
);
torso.position.y = 1.05;
torso.castShadow = true;
rig.add(torso);
const waist = new THREE.Mesh(
new THREE.BoxGeometry(0.5, 0.16, 0.34),
darkMaterial
);
waist.position.y = 0.65;
waist.castShadow = true;
rig.add(waist);
const head = new THREE.Mesh(
new THREE.DodecahedronGeometry(0.255, 0),
skinMaterial
);
head.position.y = 1.67;
head.castShadow = true;
rig.add(head);
const hair = new THREE.Mesh(
new THREE.ConeGeometry(0.27, 0.2, 7),
darkMaterial
);
hair.position.y = 1.86;
hair.rotation.y = 0.2;
hair.castShadow = true;
rig.add(hair);
const nose = new THREE.Mesh(
new THREE.ConeGeometry(0.055, 0.16, 4),
skinMaterial
);
nose.position.set(0, 1.67, 0.25);
nose.rotation.x = Math.PI / 2;
rig.add(nose);
function createLimb(x, y, length, width, material) {
const pivot = new THREE.Group();
pivot.position.set(x, y, 0);
const geometry = new THREE.BoxGeometry(width, length, width);
geometry.translate(0, -length / 2, 0);
const mesh = new THREE.Mesh(geometry, material);
mesh.castShadow = true;
pivot.add(mesh);
rig.add(pivot);
return pivot;
}
const legLeft = createLimb(-0.18, 0.7, 0.64, 0.17, darkMaterial);
const legRight = createLimb(0.18, 0.7, 0.64, 0.17, darkMaterial);
const armLeft = createLimb(-0.36, 1.37, 0.62, 0.13, costumeMaterial);
const armRight = createLimb(0.36, 1.37, 0.62, 0.13, costumeMaterial);
const shoeLeft = new THREE.Mesh(
new THREE.BoxGeometry(0.2, 0.11, 0.31),
darkMaterial
);
shoeLeft.position.set(-0.18, 0.055, 0.06);
shoeLeft.castShadow = true;
rig.add(shoeLeft);
const shoeRight = shoeLeft.clone();
shoeRight.position.x = 0.18;
rig.add(shoeRight);
const halo = new THREE.Mesh(
new THREE.RingGeometry(0.49, 0.64, 24),
new THREE.MeshBasicMaterial({
color: 0xff5964,
transparent: true,
opacity: 0.72,
side: THREE.DoubleSide,
depthWrite: false
})
);
halo.rotation.x = -Math.PI / 2;
halo.position.y = 0.035;
halo.visible = false;
root.add(halo);
const number = makeTextSprite(String(index + 1), dancer.color);
number.position.y = 2.28;
root.add(number);
scene.add(root);
return {
root,
rig,
legLeft,
legRight,
armLeft,
armRight,
halo
};
}
const dancerRigs = dancers.map(createDancer);
// ---------------------------------------------------------------------
// Path sampling
// ---------------------------------------------------------------------
function calculateControlPoint(dancer) {
const dx = dancer.end.x - dancer.start.x;
const dz = dancer.end.z - dancer.start.z;
const length = Math.hypot(dx, dz) || 1;
const perpendicularX = -dz / length;
const perpendicularZ = dx / length;
const bend = dancer.arc * length * 0.38;
return {
x: clamp(
(dancer.start.x + dancer.end.x) * 0.5 + perpendicularX * bend,
BOUNDS.minX,
BOUNDS.maxX
),
z: clamp(
(dancer.start.z + dancer.end.z) * 0.5 + perpendicularZ * bend,
BOUNDS.minZ,
BOUNDS.maxZ
)
};
}
function curvePoint(dancer, t, output = {}) {
const control = dancer._control;
const inverse = 1 - t;
output.x =
inverse * inverse * dancer.start.x +
2 * inverse * t * control.x +
t * t * dancer.end.x;
output.z =
inverse * inverse * dancer.start.z +
2 * inverse * t * control.z +
t * t * dancer.end.z;
return output;
}
function positionAt(dancer, beat) {
const localTime = beat - dancer.startBeat;
if (localTime <= 0) {
return { x: dancer.start.x, z: dancer.start.z };
}
if (localTime >= settings.travel) {
return { x: dancer.end.x, z: dancer.end.z };
}
const t = smoothstep(localTime / settings.travel);
return curvePoint(dancer, t);
}
function tangentAt(dancer, beat) {
const localTime = beat - dancer.startBeat;
if (localTime <= 0 || localTime >= settings.travel) {
return {
x: dancer.end.x - dancer.start.x,
z: dancer.end.z - dancer.start.z
};
}
const t = localTime / settings.travel;
const control = dancer._control;
const derivativeX =
2 * (1 - t) * (control.x - dancer.start.x) +
2 * t * (dancer.end.x - control.x);
const derivativeZ =
2 * (1 - t) * (control.z - dancer.start.z) +
2 * t * (dancer.end.z - control.z);
return { x: derivativeX, z: derivativeZ };
}
// ---------------------------------------------------------------------
// Collision analysis over the entire beat-based timeline
// ---------------------------------------------------------------------
let maxBeat = 12;
let collisionIntervals = new Map();
let collisionEvents = [];
let activeCollisionPairs = new Set();
function pairKey(a, b) {
return a < b ? `${a}-${b}` : `${b}-${a}`;
}
function rebuildCollisionData() {
collisionIntervals = new Map();
collisionEvents = [];
const step = 0.025;
const sampleCount = Math.ceil(maxBeat / step);
for (let a = 0; a < dancers.length; a++) {
for (let b = a + 1; b < dancers.length; b++) {
const key = pairKey(a, b);
const intervals = [];
let intervalStart = null;
for (let sample = 0; sample <= sampleCount; sample++) {
const beat = Math.min(sample * step, maxBeat);
const positionA = positionAt(dancers[a], beat);
const positionB = positionAt(dancers[b], beat);
const distance = Math.hypot(
positionA.x - positionB.x,
positionA.z - positionB.z
);
const colliding = distance < COLLISION_DISTANCE;
if (colliding && intervalStart === null) {
intervalStart = beat;
}
if (!colliding && intervalStart !== null) {
intervals.push({
start: intervalStart,
end: beat,
pair: key
});
intervalStart = null;
}
}
if (intervalStart !== null) {
intervals.push({
start: intervalStart,
end: maxBeat,
pair: key
});
}
if (intervals.length) {
collisionIntervals.set(key, intervals);
collisionEvents.push(...intervals);
}
}
}
collisionEvents.sort((a, b) => a.start - b.start);
renderCollisionEvents();
}
function renderCollisionEvents() {
const container = $("collisionList");
container.replaceChildren();
$("collisionTotal").textContent =
`${collisionEvents.length} detected event${collisionEvents.length === 1 ? "" : "s"}`;
if (!collisionEvents.length) {
const empty = document.createElement("div");
empty.className = "clear-state";
empty.textContent = "No path intersections detected in the current choreography.";
container.appendChild(empty);
return;
}
for (const event of collisionEvents) {
const [a, b] = event.pair.split("-").map(Number);
const row = document.createElement("div");
row.className = "collision-event";
row.dataset.pair = event.pair;
const dot = document.createElement("i");
dot.className = "collision-dot";
const copy = document.createElement("div");
copy.className = "collision-copy";
const title = document.createElement("strong");
title.textContent = `${dancers[a].name} × ${dancers[b].name}`;
const detail = document.createElement("small");
detail.textContent = `Beat ${event.start.toFixed(2)} → ${event.end.toFixed(2)}`;
copy.append(title, detail);
row.append(dot, copy);
container.appendChild(row);
}
}
function updateCollisionState(beat) {
activeCollisionPairs = new Set();
for (const [key, intervals] of collisionIntervals) {
for (const interval of intervals) {
if (beat >= interval.start && beat <= interval.end) {
activeCollisionPairs.add(key);
break;
}
}
}
const involved = new Set();
for (const key of activeCollisionPairs) {
const [a, b] = key.split("-").map(Number);
involved.add(a);
involved.add(b);
}
dancerRigs.forEach((rig, index) => {
rig.halo.visible = involved.has(index);
});
$("collisionReadout").textContent = activeCollisionPairs.size;
$("collisionStatus").textContent = activeCollisionPairs.size
? `${activeCollisionPairs.size} active collision${activeCollisionPairs.size === 1 ? "" : "s"}`
: "No active collision";
for (const row of document.querySelectorAll(".collision-event")) {
row.classList.toggle(
"active",
activeCollisionPairs.has(row.dataset.pair)
);
}
}
// ---------------------------------------------------------------------
// UI and editing
// ---------------------------------------------------------------------
let selectedIndex = 0;
let currentBeat = 0;
let isPlaying = false;
let lastFrameTime = performance.now();
function clampDancer(dancer) {
dancer.startBeat = clamp(Math.round(dancer.startBeat), 0, 24);
dancer.arc = clamp(dancer.arc, -1, 1);
dancer.start.x = clamp(dancer.start.x, BOUNDS.minX, BOUNDS.maxX);
dancer.start.z = clamp(dancer.start.z, BOUNDS.minZ, BOUNDS.maxZ);
dancer.end.x = clamp(dancer.end.x, BOUNDS.minX, BOUNDS.maxX);
dancer.end.z = clamp(dancer.end.z, BOUNDS.minZ, BOUNDS.maxZ);
}
function buildDancerRows() {
const list = $("dancerList");
list.replaceChildren();
dancers.forEach((dancer, index) => {
const row = document.createElement("div");
row.className = "dancer-row";
row.dataset.index = index;
const select = document.createElement("button");
select.type = "button";
select.className = "dancer-select";
select.style.setProperty("--dancer-color", dancer.color);
const swatch = document.createElement("i");
swatch.className = "swatch";
const copy = document.createElement("span");
copy.className = "dancer-name";
const name = document.createElement("strong");
name.textContent = dancer.name;
const status = document.createElement("span");
status.className = "dancer-status";
copy.append(name, status);
select.append(swatch, copy);
const label = document.createElement("span");
label.className = "row-label";
label.textContent = "Beat";
const input = document.createElement("input");
input.type = "number";
input.min = "0";
input.max = "24";
input.step = "1";
input.value = dancer.startBeat;
input.setAttribute("aria-label", `${dancer.name} start beat`);
input.addEventListener("change", () => {
const value = Number(input.value);
dancer.startBeat = clamp(
Number.isFinite(value) ? value : dancer.startBeat,
0,
24
);
input.value = dancer.startBeat;
refreshChoreography();
syncSelectedEditor();
});
select.addEventListener("click", () => {
selectDancer(index);
});
row.append(select, label, input);
list.appendChild(row);
});
updateDancerRows();
}
function updateDancerRows() {
document.querySelectorAll(".dancer-row").forEach((row) => {
const index = Number(row.dataset.index);
const dancer = dancers[index];
row.classList.toggle("active", index === selectedIndex);
const input = row.querySelector("input");
if (document.activeElement !== input) {
input.value = dancer.startBeat;
}
const status = row.querySelector(".dancer-status");
if (currentBeat < dancer.startBeat) {
status.textContent = "Waiting";
} else if (currentBeat < dancer.startBeat + settings.travel) {
status.textContent = "Moving";
} else {
status.textContent = "Final";
}
});
}
function selectDancer(index) {
selectedIndex = index;
syncSelectedEditor();
updateDancerRows();
updatePathStyling();
}
function syncSelectedEditor() {
const dancer = dancers[selectedIndex];
$("selectedName").textContent = dancer.name;
$("startX").value = dancer.start.x.toFixed(2);
$("startZ").value = dancer.start.z.toFixed(2);
$("finalX").value = dancer.end.x.toFixed(2);
$("finalZ").value = dancer.end.z.toFixed(2);
$("arcInput").value = dancer.arc;
$("arcValue").textContent = Number(dancer.arc).toFixed(2);
}
function updatePathStyling() {
pathLines.forEach((line, index) => {
line.material.opacity = index === selectedIndex ? 0.96 : 0.33;
});
}
function rebuildPaths() {
dancers.forEach((dancer, index) => {
dancer._control = calculateControlPoint(dancer);
const points = [];
for (let pointIndex = 0; pointIndex <= 48; pointIndex++) {
const point = curvePoint(dancer, pointIndex / 48);
points.push(new THREE.Vector3(point.x, 0.035, point.z));
}
pathLines[index].geometry.dispose();
pathLines[index].geometry = new THREE.BufferGeometry().setFromPoints(points);
pathLines[index].computeLineDistances();
startMarkers[index].position.set(dancer.start.x, 0.08, dancer.start.z);
finalMarkers[index].position.set(dancer.end.x, 0.13, dancer.end.z);
});
startHandle.position.set(
dancers[selectedIndex].start.x,
0,
dancers[selectedIndex].start.z
);
finalHandle.position.set(
dancers[selectedIndex].end.x,
0,
dancers[selectedIndex].end.z
);
}
function updateTimelineRange() {
const latestStart = Math.max(...dancers.map((dancer) => dancer.startBeat));
maxBeat = Math.max(4, latestStart + settings.travel + 1);
$("timelineRange").max = maxBeat;
$("timelineRange").value = Math.min(currentBeat, maxBeat);
$("timelineEndLabel").textContent = `Final formation · beat ${maxBeat}`;
const ticks = $("timelineTicks");
ticks.replaceChildren();
const tickCount = Math.ceil(maxBeat);
for (let beat = 0; beat <= tickCount; beat++) {
const tick = document.createElement("span");
const percentage = (beat / maxBeat) * 100;
tick.style.left = `${percentage}%`;
tick.dataset.label = beat;
ticks.appendChild(tick);
}
}
function refreshChoreography(save = true) {
dancers.forEach(clampDancer);
rebuildPaths();
updateTimelineRange();
rebuildCollisionData();
updatePathStyling();
if (save) persistState();
}
function setCoordinate(kind, axis, value) {
const dancer = dancers[selectedIndex];
const fallback = dancer[kind][axis];
const numeric = Number(value);
dancer[kind][axis] = clamp(
Number.isFinite(numeric) ? numeric : fallback,
axis === "x" ? BOUNDS.minX : BOUNDS.minZ,
axis === "x" ? BOUNDS.maxX : BOUNDS.maxZ
);
refreshChoreography();
syncSelectedEditor();
}
[
["startX", "start", "x"],
["startZ", "start", "z"],
["finalX", "end", "x"],
["finalZ", "end", "z"]
].forEach(([id, kind, axis]) => {
$(id).addEventListener("change", (event) => {
setCoordinate(kind, axis, event.target.value);
});
});
$("arcInput").addEventListener("input", (event) => {
dancers[selectedIndex].arc = Number(event.target.value);
$("arcValue").textContent = dancers[selectedIndex].arc.toFixed(2);
refreshChoreography();
});
$("bpmInput").addEventListener("change", (event) => {
const value = Number(event.target.value);
settings.bpm = clamp(Number.isFinite(value) ? value : settings.bpm, 30, 240);
event.target.value = settings.bpm;
persistState();
});
$("travelInput").addEventListener("change", (event) => {
const value = Number(event.target.value);
settings.travel = clamp(
Number.isFinite(value) ? value : settings.travel,
1,
16
);
event.target.value = settings.travel;
refreshChoreography();
});
// ---------------------------------------------------------------------
// Playback and optional metronome
// ---------------------------------------------------------------------
let audioEnabled = false;
let audioContext = null;
function toggleAudio() {
audioEnabled = !audioEnabled;
if (audioEnabled) {
const AudioContextClass = window.AudioContext || window.webkitAudioContext;
if (!AudioContextClass) {
audioEnabled = false;
showToast("Web Audio is not available in this browser.");
return;
}
if (!audioContext) audioContext = new AudioContextClass();
audioContext.resume();
}
$("audioButton").textContent = audioEnabled ? "Sound on" : "Sound off";
}
function playBeat(beatIndex) {
if (!audioEnabled || !audioContext) return;
const oscillator = audioContext.createOscillator();
const gain = audioContext.createGain();
const now = audioContext.currentTime;
oscillator.type = "sine";
oscillator.frequency.value = beatIndex % 4 === 0 ? 980 : 720;
gain.gain.setValueAtTime(0.0001, now);
gain.gain.exponentialRampToValueAtTime(0.055, now + 0.006);
gain.gain.exponentialRampToValueAtTime(0.0001, now + 0.075);
oscillator.connect(gain);
gain.connect(audioContext.destination);
oscillator.start(now);
oscillator.stop(now + 0.08);
}
function setPlaying(value) {
isPlaying = value;
$("pauseButton").textContent = isPlaying ? "Pause" : "Resume";
}
function replay() {
currentBeat = 0;
lastFrameTime = performance.now();
setPlaying(true);
}
function resetToStarts() {
currentBeat = 0;
setPlaying(false);
}
$("replayButton").addEventListener("click", replay);
$("pauseButton").addEventListener("click", () => {
if (currentBeat >= maxBeat && !isPlaying) {
replay();
} else {
setPlaying(!isPlaying);
}
});
$("resetButton").addEventListener("click", resetToStarts);
$("audioButton").addEventListener("click", toggleAudio);
$("timelineRange").addEventListener("input", (event) => {
currentBeat = Number(event.target.value);
setPlaying(false);
});
$("captureButton").addEventListener("click", () => {
dancers.forEach((dancer) => {
const position = positionAt(dancer, currentBeat);
dancer.end.x = position.x;
dancer.end.z = position.z;
});
refreshChoreography();
syncSelectedEditor();
showToast("Current playhead positions saved as the persistent final formation.");
});
$("resetPathsButton").addEventListener("click", () => {
dancers = copyDancers(defaults);
selectedIndex = 0;
currentBeat = 0;
setPlaying(false);
dancerRigs.forEach((rig, index) => {
rig.root.userData.dancerIndex = index;
});
buildDancerRows();
syncSelectedEditor();
refreshChoreography();
showToast("Choreography reset to the original six-dancer formation.");
});
$("panelToggle").addEventListener("click", () => {
const panel = $("sidePanel");
const collapsed = panel.classList.toggle("collapsed");
$("panelToggle").textContent = collapsed ? "Show panel" : "Hide panel";
});
let toastTimer = null;
function showToast(message) {
const toast = $("toast");
toast.textContent = message;
toast.classList.add("show");
clearTimeout(toastTimer);
toastTimer = setTimeout(() => {
toast.classList.remove("show");
}, 2800);
}
// ---------------------------------------------------------------------
// Custom camera controls and direct scene editing
// ---------------------------------------------------------------------
const raycaster = new THREE.Raycaster();
const pointer = new THREE.Vector2();
const dragPlane = new THREE.Plane(new THREE.Vector3(0, 1, 0), 0);
const planeIntersection = new THREE.Vector3();
let pointerDown = false;
let orbiting = false;
let draggingHandle = null;
let previousPointerX = 0;
let previousPointerY = 0;
function updatePointer(event) {
const rect = renderer.domElement.getBoundingClientRect();
pointer.x = ((event.clientX - rect.left) / rect.width) * 2 - 1;
pointer.y = -((event.clientY - rect.top) / rect.height) * 2 + 1;
}
function findHandle(object) {
let current = object;
while (current) {
if (current.userData?.handleType) return current;
current = current.parent;
}
return null;
}
function findDancerIndex(object) {
let current = object;
while (current) {
if (Number.isInteger(current.userData?.dancerIndex)) {
return current.userData.dancerIndex;
}
current = current.parent;
}
return -1;
}
renderer.domElement.addEventListener("contextmenu", (event) => {
event.preventDefault();
});
renderer.domElement.addEventListener("pointerdown", (event) => {
pointerDown = true;
previousPointerX = event.clientX;
previousPointerY = event.clientY;
renderer.domElement.setPointerCapture(event.pointerId);
updatePointer(event);
raycaster.setFromCamera(pointer, camera);
const handleHits = raycaster.intersectObjects(
[startHandle, finalHandle],
true
);
if (handleHits.length) {
const handle = findHandle(handleHits[0].object);
if (handle) {
draggingHandle = handle.userData.handleType;
setPlaying(false);
return;
}
}
const dancerHits = raycaster.intersectObjects(
dancerRigs.map((rig) => rig.root),
true
);
if (dancerHits.length) {
const index = findDancerIndex(dancerHits[0].object);
if (index >= 0) {
selectDancer(index);
return;
}
}
orbiting = true;
});
renderer.domElement.addEventListener("pointermove", (event) => {
if (!pointerDown) return;
if (draggingHandle) {
updatePointer(event);
raycaster.setFromCamera(pointer, camera);
if (raycaster.ray.intersectPlane(dragPlane, planeIntersection)) {
const dancer = dancers[selectedIndex];
if (draggingHandle === "start") {
dancer.start.x = clamp(planeIntersection.x, BOUNDS.minX, BOUNDS.maxX);
dancer.start.z = clamp(planeIntersection.z, BOUNDS.minZ, BOUNDS.maxZ);
} else {
dancer.end.x = clamp(planeIntersection.x, BOUNDS.minX, BOUNDS.maxX);
dancer.end.z = clamp(planeIntersection.z, BOUNDS.minZ, BOUNDS.maxZ);
}
refreshChoreography();
syncSelectedEditor();
}
return;
}
if (orbiting) {
const deltaX = event.clientX - previousPointerX;
const deltaY = event.clientY - previousPointerY;
cameraState.theta -= deltaX * 0.006;
cameraState.phi = clamp(
cameraState.phi - deltaY * 0.005,
0.38,
1.35
);
updateCamera();
}
previousPointerX = event.clientX;
previousPointerY = event.clientY;
});
function endPointerInteraction() {
pointerDown = false;
orbiting = false;
draggingHandle = null;
}
renderer.domElement.addEventListener("pointerup", endPointerInteraction);
renderer.domElement.addEventListener("pointercancel", endPointerInteraction);
renderer.domElement.addEventListener(
"wheel",
(event) => {
event.preventDefault();
cameraState.radius = clamp(
cameraState.radius * Math.exp(event.deltaY * 0.001),
11,
31
);
updateCamera();
},
{ passive: false }
);
// ---------------------------------------------------------------------
// Animation
// ---------------------------------------------------------------------
function updateDancers(beat) {
dancerRigs.forEach((rig, index) => {
const dancer = dancers[index];
const position = positionAt(dancer, beat);
const tangent = tangentAt(dancer, beat);
rig.root.position.set(position.x, 0, position.z);
rig.root.rotation.y = Math.atan2(tangent.x, tangent.z);
const moving =
beat >= dancer.startBeat &&
beat < dancer.startBeat + settings.travel;
const phase = (beat - dancer.startBeat) * Math.PI * 2;
const bob = moving ? Math.abs(Math.sin(phase)) * 0.045 : 0;
rig.rig.position.y = bob;
if (moving) {
const stride = Math.sin(phase) * 0.52;
rig.legLeft.rotation.x = stride;
rig.legRight.rotation.x = -stride;
rig.armLeft.rotation.x = -stride * 1.15;
rig.armRight.rotation.x = stride * 1.15;
rig.rig.rotation.z = Math.sin(phase) * 0.025;
} else {
rig.legLeft.rotation.x *= 0.88;
rig.legRight.rotation.x *= 0.88;
rig.armLeft.rotation.x *= 0.88;
rig.armRight.rotation.x *= 0.88;
rig.rig.rotation.z *= 0.88;
}
if (rig.halo.visible) {
const pulse = 0.5 + 0.5 * Math.sin(beat * Math.PI * 6);
rig.halo.material.opacity = 0.38 + pulse * 0.5;
rig.halo.scale.setScalar(1 + pulse * 0.1);
}
});
const selectedPosition = positionAt(dancers[selectedIndex], beat);
selectionRing.position.set(selectedPosition.x, 0.03, selectedPosition.z);
}
function animate(now) {
requestAnimationFrame(animate);
const deltaSeconds = Math.min((now - lastFrameTime) / 1000, 0.06);
lastFrameTime = now;
if (isPlaying) {
const previousBeat = currentBeat;
currentBeat += deltaSeconds * (settings.bpm / 60);
if (Math.floor(currentBeat) > Math.floor(previousBeat)) {
playBeat(Math.floor(currentBeat));
}
if (currentBeat >= maxBeat) {
currentBeat = maxBeat;
setPlaying(false);
showToast("Replay complete. Dancers are holding their final positions.");
}
}
$("timelineRange").value = currentBeat;
$("beatReadout").textContent = currentBeat.toFixed(2);
const beatPhase = currentBeat - Math.floor(currentBeat);
const pulse = Math.pow(1 - beatPhase, 3);
document.documentElement.style.setProperty("--pulse", pulse.toFixed(3));
beatRing.scale.setScalar(0.9 + pulse * 0.36);
beatRing.material.opacity = 0.12 + pulse * 0.38;
selectionRing.material.opacity = 0.48 + pulse * 0.35;
selectionRing.scale.setScalar(0.96 + pulse * 0.08);
updateDancers(currentBeat);
updateCollisionState(currentBeat);
updateDancerRows();
renderer.render(scene, camera);
}
function resize() {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
}
window.addEventListener("resize", resize);
// ---------------------------------------------------------------------
// Initialize
// ---------------------------------------------------------------------
$("bpmInput").value = settings.bpm;
$("travelInput").value = settings.travel;
buildDancerRows();
syncSelectedEditor();
refreshChoreography(false);
updateDancers(0);
updateCollisionState(0);
requestAnimationFrame(animate);
</script>
</body>
</html>
```