Prompt specification
Build or customize the Three.js 3D scene "Marble delivery routing 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: Marble delivery routing puzzle
Category: Games & Play · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/marble-delivery-routing-puzzle-x0356
Scene Description Prompt:
Create a low-poly marble-routing puzzle with gated continuous tracks leading to three assigned cups. One HTML file using Three.js from cdnjs.
Working Three.js Starter (marble-delivery-routing-puzzle-x0356):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Prism Run — Marble Routing Puzzle</title>
<style>
:root {
--ink: #142323;
--muted: #617271;
--glass: rgba(248, 252, 248, 0.86);
--line: rgba(31, 63, 59, 0.14);
--lime: #d9f47b;
--azure: #48a0ff;
--amber: #f5ad3d;
--rose: #ee679e;
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: #b9ccc6;
color: var(--ink);
font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
button {
font: inherit;
}
canvas {
position: fixed;
inset: 0;
display: block;
width: 100%;
height: 100%;
touch-action: none;
outline: none;
}
.hud {
position: fixed;
inset: 0;
z-index: 5;
pointer-events: none;
}
.brand {
position: absolute;
top: 24px;
left: 26px;
max-width: 340px;
pointer-events: auto;
}
.eyebrow {
display: flex;
align-items: center;
gap: 10px;
margin-bottom: 7px;
color: #314744;
font-size: 10px;
font-weight: 800;
letter-spacing: 0.18em;
text-transform: uppercase;
}
.eyebrow::before {
content: "";
width: 25px;
height: 3px;
border-radius: 4px;
background: #52726c;
}
h1 {
margin: 0;
font-size: clamp(30px, 4vw, 54px);
font-weight: 850;
letter-spacing: -0.065em;
line-height: 0.95;
}
.brand-subtitle {
margin-top: 10px;
color: #4d6561;
font-size: 12px;
font-weight: 650;
line-height: 1.45;
}
.top-actions {
position: absolute;
top: 22px;
right: 24px;
display: flex;
gap: 9px;
pointer-events: auto;
}
.icon-button {
height: 42px;
padding: 0 15px;
border: 1px solid rgba(25, 57, 53, 0.15);
border-radius: 13px;
background: rgba(248, 252, 248, 0.82);
color: #29423f;
box-shadow: 0 8px 30px rgba(39, 67, 62, 0.1);
backdrop-filter: blur(14px);
cursor: pointer;
font-size: 11px;
font-weight: 800;
letter-spacing: 0.06em;
text-transform: uppercase;
transition: transform 150ms ease, background 150ms ease;
}
.icon-button:hover {
transform: translateY(-2px);
background: #f9fff8;
}
.objective {
position: absolute;
left: 26px;
top: 145px;
width: 220px;
padding: 15px 17px;
border: 1px solid var(--line);
border-radius: 17px;
background: rgba(248, 252, 248, 0.68);
backdrop-filter: blur(12px);
box-shadow: 0 12px 32px rgba(38, 63, 59, 0.08);
}
.objective strong {
display: block;
margin-bottom: 5px;
font-size: 12px;
letter-spacing: 0.02em;
}
.objective span {
display: block;
color: var(--muted);
font-size: 11px;
line-height: 1.5;
}
.control-deck {
position: absolute;
left: 50%;
bottom: 20px;
display: grid;
grid-template-columns: 1.15fr 1.2fr 0.72fr;
gap: 12px;
width: min(1080px, calc(100% - 40px));
padding: 13px;
transform: translateX(-50%);
border: 1px solid rgba(30, 61, 57, 0.15);
border-radius: 22px;
background: var(--glass);
box-shadow: 0 18px 60px rgba(29, 55, 51, 0.2);
backdrop-filter: blur(18px);
pointer-events: auto;
}
.deck-section {
min-width: 0;
padding: 5px 8px;
}
.deck-label {
display: flex;
align-items: center;
justify-content: space-between;
margin: 0 0 9px;
color: #687b78;
font-size: 9px;
font-weight: 850;
letter-spacing: 0.16em;
text-transform: uppercase;
}
.deck-label small {
color: #91a09e;
font-size: 8px;
letter-spacing: 0.08em;
}
.marble-list,
.gate-list {
display: flex;
gap: 7px;
}
.marble-card,
.gate-card {
position: relative;
flex: 1;
min-width: 0;
height: 59px;
border: 1px solid rgba(34, 65, 61, 0.12);
border-radius: 13px;
background: rgba(255, 255, 255, 0.66);
color: var(--ink);
cursor: pointer;
transition: transform 150ms ease, border-color 150ms ease,
background 150ms ease, box-shadow 150ms ease;
}
.marble-card:hover,
.gate-card:hover:not(:disabled) {
transform: translateY(-2px);
border-color: rgba(34, 65, 61, 0.27);
}
.marble-card.active {
border-color: var(--marble-color);
background: color-mix(in srgb, var(--marble-color) 11%, white);
box-shadow: inset 0 0 0 1px var(--marble-color),
0 6px 15px rgba(40, 66, 61, 0.08);
}
.marble-card.done {
opacity: 0.68;
}
.marble-dot {
display: block;
width: 18px;
height: 18px;
margin: 9px auto 5px;
border-radius: 50%;
background: var(--marble-color);
box-shadow: inset -4px -4px 7px rgba(0, 0, 0, 0.14),
0 3px 7px color-mix(in srgb, var(--marble-color) 28%, transparent);
}
.marble-name {
display: block;
overflow: hidden;
font-size: 9px;
font-weight: 850;
letter-spacing: 0.08em;
text-overflow: ellipsis;
text-transform: uppercase;
white-space: nowrap;
}
.done-mark {
position: absolute;
top: 5px;
right: 6px;
display: none;
color: #3c7657;
font-size: 11px;
font-weight: 900;
}
.done .done-mark {
display: block;
}
.gate-card {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
gap: 2px;
padding: 0;
}
.gate-card:disabled {
cursor: default;
opacity: 0.5;
}
.gate-number {
color: #81918e;
font-size: 8px;
font-weight: 850;
letter-spacing: 0.12em;
}
.gate-direction {
font-size: 14px;
font-weight: 900;
letter-spacing: 0.06em;
}
.gate-direction.left {
color: #398d72;
}
.gate-direction.right {
color: #b57732;
}
.action-column {
display: flex;
flex-direction: column;
justify-content: flex-end;
gap: 8px;
}
.status {
min-height: 30px;
padding: 0 5px;
color: #60726f;
font-size: 10px;
font-weight: 650;
line-height: 1.35;
}
.status[data-tone="good"] {
color: #2f7851;
}
.status[data-tone="bad"] {
color: #a95757;
}
.release-button {
position: relative;
width: 100%;
height: 61px;
overflow: hidden;
border: 0;
border-radius: 14px;
background: var(--ink);
color: #f7fff8;
box-shadow: 0 8px 20px rgba(25, 48, 45, 0.2);
cursor: pointer;
font-size: 11px;
font-weight: 900;
letter-spacing: 0.09em;
text-transform: uppercase;
transition: transform 150ms ease, filter 150ms ease;
}
.release-button::after {
content: "";
position: absolute;
top: -30px;
right: -20px;
width: 90px;
height: 90px;
border-radius: 50%;
background: var(--lime);
opacity: 0.13;
}
.release-button:hover:not(:disabled) {
transform: translateY(-2px);
filter: brightness(1.08);
}
.release-button:disabled {
cursor: default;
opacity: 0.48;
}
.camera-hint {
position: absolute;
right: 25px;
bottom: 172px;
padding: 8px 11px;
border-radius: 10px;
background: rgba(246, 251, 248, 0.64);
color: rgba(35, 62, 58, 0.66);
font-size: 9px;
font-weight: 750;
letter-spacing: 0.04em;
backdrop-filter: blur(10px);
}
.tooltip {
position: fixed;
z-index: 20;
display: none;
padding: 7px 10px;
transform: translate(12px, 12px);
border-radius: 9px;
background: rgba(20, 35, 33, 0.9);
color: white;
font-size: 10px;
font-weight: 750;
pointer-events: none;
white-space: nowrap;
}
@media (max-width: 780px) {
.brand {
top: 17px;
left: 18px;
}
.brand-subtitle,
.objective,
.camera-hint {
display: none;
}
.top-actions {
top: 15px;
right: 15px;
}
.icon-button {
height: 37px;
padding: 0 11px;
font-size: 9px;
}
.control-deck {
bottom: 10px;
grid-template-columns: 1fr;
gap: 8px;
width: calc(100% - 20px);
max-height: 47vh;
overflow-y: auto;
border-radius: 18px;
}
.deck-section {
padding: 3px 5px;
}
.action-column {
display: grid;
grid-template-columns: 1fr 1fr;
align-items: end;
}
.status {
min-height: 44px;
display: flex;
align-items: center;
}
.release-button {
height: 50px;
}
}
@media (max-width: 450px) {
.top-actions .view-button {
display: none;
}
.marble-card,
.gate-card {
height: 54px;
}
h1 {
font-size: 31px;
}
}
</style>
</head>
<body>
<div class="hud">
<header class="brand">
<div class="eyebrow">Low-poly routing puzzle</div>
<h1>Prism Run</h1>
<div class="brand-subtitle">Guide each marble through the gates<br />and into its matching cup.</div>
</header>
<div class="top-actions">
<button class="icon-button view-button" id="resetView">Reset view</button>
<button class="icon-button" id="scramble">Scramble gates</button>
<button class="icon-button" id="resetPuzzle">Reset</button>
</div>
<aside class="objective">
<strong>Three marbles. Three cups.</strong>
<span>
Set the switches, or flip them while a marble is moving.
Each gate locks as the marble passes it.
</span>
</aside>
<div class="camera-hint">Drag to orbit · Scroll to zoom · Click a gate to flip it</div>
<section class="control-deck">
<div class="deck-section">
<div class="deck-label">
Select marble
<small>Match the cup</small>
</div>
<div class="marble-list" id="marbleList"></div>
</div>
<div class="deck-section">
<div class="deck-label">
Route switches
<small>Live during a run</small>
</div>
<div class="gate-list" id="gateList"></div>
</div>
<div class="action-column">
<div class="status" id="status" data-tone="neutral">
Choose a marble, set the gates, then release it.
</div>
<button class="release-button" id="release">Release Azure</button>
</div>
</section>
</div>
<div class="tooltip" id="tooltip"></div>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
const scene = new THREE.Scene();
scene.background = new THREE.Color(0xb9ccc6);
scene.fog = new THREE.Fog(0xb9ccc6, 31, 58);
const camera = new THREE.PerspectiveCamera(
39,
innerWidth / innerHeight,
0.1,
100
);
const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setSize(innerWidth, innerHeight);
renderer.setPixelRatio(Math.min(devicePixelRatio, 2));
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.08;
renderer.domElement.setAttribute(
"aria-label",
"Interactive 3D marble routing puzzle"
);
document.body.prepend(renderer.domElement);
const hemi = new THREE.HemisphereLight(0xf4fff5, 0x526a62, 2.25);
scene.add(hemi);
const sun = new THREE.DirectionalLight(0xfff4db, 3.3);
sun.position.set(-8, 17, 10);
sun.castShadow = true;
sun.shadow.mapSize.set(2048, 2048);
sun.shadow.camera.left = -15;
sun.shadow.camera.right = 15;
sun.shadow.camera.top = 15;
sun.shadow.camera.bottom = -15;
sun.shadow.camera.near = 1;
sun.shadow.camera.far = 40;
sun.shadow.bias = -0.00035;
scene.add(sun);
const fill = new THREE.DirectionalLight(0x8ec7d4, 1.25);
fill.position.set(12, 7, -8);
scene.add(fill);
const clock = new THREE.Clock();
const raycaster = new THREE.Raycaster();
const pointer = new THREE.Vector2();
const interactiveMeshes = [];
const sleepers = [];
const gateVisuals = [];
const cupBalls = [];
const TRACK_Y = 0.39;
const MARBLE_OFFSET = 0.235;
const palette = {
board: 0x35594f,
boardEdge: 0x243e39,
frame: 0x9f7047,
track: 0xd8b985,
trackEdge: 0xf1d8a9,
groove: 0x8d6647,
gate: 0xe9bc53,
gateBase: 0x294c46,
cream: 0xf2f4df,
reject: 0x66736e
};
const marbleDefs = [
{
id: "azure",
name: "Azure",
color: 0x48a0ff,
css: "#48a0ff",
code: "000",
exit: 0
},
{
id: "amber",
name: "Amber",
color: 0xf5ad3d,
css: "#f5ad3d",
code: "011",
exit: 3
},
{
id: "rose",
name: "Rose",
color: 0xee679e,
css: "#ee679e",
code: "101",
exit: 5
}
];
const gateStates = [0, 1, 0];
const lockedGates = [false, false, false];
let selectedMarble = 0;
let rolling = false;
let routeCode = 0;
// ---------------------------------------------------------------------
// Board and scenery
// ---------------------------------------------------------------------
const board = new THREE.Mesh(
new THREE.BoxGeometry(19, 0.62, 17.8),
new THREE.MeshStandardMaterial({
color: palette.boardEdge,
roughness: 0.92,
flatShading: true
})
);
board.position.set(0, -0.33, -0.5);
board.receiveShadow = true;
scene.add(board);
const boardTop = new THREE.Mesh(
new THREE.BoxGeometry(18.45, 0.12, 17.25),
new THREE.MeshStandardMaterial({
color: palette.board,
roughness: 0.98,
flatShading: true
})
);
boardTop.position.set(0, 0.025, -0.5);
boardTop.receiveShadow = true;
scene.add(boardTop);
const frameMaterial = new THREE.MeshStandardMaterial({
color: palette.frame,
roughness: 0.88,
flatShading: true
});
function addFrame(w, h, d, x, y, z) {
const piece = new THREE.Mesh(
new THREE.BoxGeometry(w, h, d),
frameMaterial
);
piece.position.set(x, y, z);
piece.castShadow = true;
piece.receiveShadow = true;
scene.add(piece);
}
addFrame(19.2, 0.42, 0.42, 0, 0.12, 8.35);
addFrame(19.2, 0.42, 0.42, 0, 0.12, -9.35);
addFrame(0.42, 0.42, 17.7, -9.45, 0.12, -0.5);
addFrame(0.42, 0.42, 17.7, 9.45, 0.12, -0.5);
const startPad = new THREE.Mesh(
new THREE.CylinderGeometry(1.65, 1.82, 0.16, 12),
new THREE.MeshStandardMaterial({
color: 0x75927d,
roughness: 0.9,
flatShading: true
})
);
startPad.position.set(0, 0.12, 7.15);
startPad.receiveShadow = true;
scene.add(startPad);
const startRing = new THREE.Mesh(
new THREE.TorusGeometry(1.28, 0.035, 5, 24),
new THREE.MeshBasicMaterial({ color: 0xc7dc9e })
);
startRing.rotation.x = Math.PI / 2;
startRing.position.set(0, 0.22, 7.15);
scene.add(startRing);
function addRock(x, z, scale, color = 0x8ba094) {
const rock = new THREE.Mesh(
new THREE.DodecahedronGeometry(scale, 0),
new THREE.MeshStandardMaterial({
color,
roughness: 0.95,
flatShading: true
})
);
rock.position.set(x, scale * 0.58, z);
rock.rotation.set(scale, scale * 0.7, scale * 1.4);
rock.castShadow = true;
rock.receiveShadow = true;
scene.add(rock);
}
[
[-8.4, 7.25, 0.38],
[-7.8, 7.55, 0.24],
[8.25, 7.2, 0.4],
[8.0, 6.65, 0.22],
[-8.5, -8.3, 0.35],
[8.45, -8.35, 0.42],
[8.0, -8.05, 0.2]
].forEach((v) => addRock(...v));
function addCrystal(x, z, color, height) {
const group = new THREE.Group();
group.position.set(x, 0.05, z);
const material = new THREE.MeshStandardMaterial({
color,
roughness: 0.42,
metalness: 0.08,
flatShading: true
});
for (let i = 0; i < 3; i++) {
const crystal = new THREE.Mesh(
new THREE.ConeGeometry(0.2 + i * 0.025, height - i * 0.14, 5),
material
);
crystal.position.set(
(i - 1) * 0.28,
(height - i * 0.14) / 2,
i % 2 ? 0.12 : -0.08
);
crystal.rotation.z = (i - 1) * 0.16;
crystal.castShadow = true;
group.add(crystal);
}
scene.add(group);
}
addCrystal(-8.2, -7.6, 0x75b6a5, 0.9);
addCrystal(8.2, -7.45, 0xb78bc1, 0.78);
addCrystal(8.25, 6.85, 0xe3bd5d, 0.72);
function makeTextSprite(text, color = "#17302c", background = null) {
const canvas = document.createElement("canvas");
canvas.width = 512;
canvas.height = 128;
const ctx = canvas.getContext("2d");
if (background) {
ctx.fillStyle = background;
ctx.beginPath();
ctx.roundRect(4, 4, 504, 120, 28);
ctx.fill();
}
ctx.fillStyle = color;
ctx.font = "800 46px system-ui, sans-serif";
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.fillText(text, 256, 65);
const texture = new THREE.CanvasTexture(canvas);
texture.colorSpace = THREE.SRGBColorSpace;
const material = new THREE.SpriteMaterial({
map: texture,
transparent: true,
depthWrite: false
});
const sprite = new THREE.Sprite(material);
sprite.scale.set(1.8, 0.45, 1);
return sprite;
}
const startLabel = makeTextSprite("START", "#eaf3ce");
startLabel.position.set(0, 1.35, 7.7);
startLabel.scale.set(1.45, 0.36, 1);
scene.add(startLabel);
// ---------------------------------------------------------------------
// Track graph
// ---------------------------------------------------------------------
const nodes = {};
const edges = {};
const adjacency = {};
function node(id, x, z) {
nodes[id] = new THREE.Vector3(x, TRACK_Y, z);
}
node("start", 0, 6.65);
node("g1", 0, 5.1);
node("l1L", -3.5, 3.0);
node("l1R", 3.5, 3.0);
node("l2LL", -5.8, 0.8);
node("l2LR", -1.8, 0.8);
node("l2RL", 1.8, 0.8);
node("l2RR", 5.8, 0.8);
const exitX = [-7.4, -5.4, -3.4, -1.4, 1.4, 3.4, 5.4, 7.4];
[
"LLL", "LLR", "LRL", "LRR", "RLL", "RLR", "RRL", "RRR"
].forEach((id, i) => node(`l3${id}`, exitX[i], -1.6));
for (let i = 0; i < 8; i++) {
node(`exit${i}`, exitX[i], -5.35);
}
function addEdge(id, startId, endId, control = null) {
const start = nodes[startId];
const end = nodes[endId];
if (!control) {
control = start.clone().lerp(end, 0.5);
}
const curve = new THREE.QuadraticBezierCurve3(start, control, end);
edges[id] = {
id,
start: startId,
end: endId,
curve,
length: curve.getLength()
};
adjacency[startId] ||= [];
adjacency[startId].push(id);
}
addEdge("start_g1", "start", "g1");
addEdge(
"g1_l1L",
"g1",
"l1L",
new THREE.Vector3(-1.8, TRACK_Y, 4.4)
);
addEdge(
"g1_l1R",
"g1",
"l1R",
new THREE.Vector3(1.8, TRACK_Y, 4.4)
);
addEdge(
"l1L_l2LL",
"l1L",
"l2LL",
new THREE.Vector3(-4.8, TRACK_Y, 2.0)
);
addEdge(
"l1L_l2LR",
"l1L",
"l2LR",
new THREE.Vector3(-2.55, TRACK_Y, 2.0)
);
addEdge(
"l1R_l2RL",
"l1R",
"l2RL",
new THREE.Vector3(2.55, TRACK_Y, 2.0)
);
addEdge(
"l1R_l2RR",
"l1R",
"l2RR",
new THREE.Vector3(4.8, TRACK_Y, 2.0)
);
addEdge(
"l2LL_l3LLL",
"l2LL",
"l3LLL",
new THREE.Vector3(-6.7, TRACK_Y, -0.35)
);
addEdge(
"l2LL_l3LLR",
"l2LL",
"l3LLR",
new THREE.Vector3(-5.2, TRACK_Y, -0.35)
);
addEdge(
"l2LR_l3LRL",
"l2LR",
"l3LRL",
new THREE.Vector3(-2.8, TRACK_Y, -0.35)
);
addEdge(
"l2LR_l3LRR",
"l2LR",
"l3LRR",
new THREE.Vector3(-1.4, TRACK_Y, -0.35)
);
addEdge(
"l2RL_l3RLL",
"l2RL",
"l3RLL",
new THREE.Vector3(1.4, TRACK_Y, -0.35)
);
addEdge(
"l2RL_l3RLR",
"l2RL",
"l3RLR",
new THREE.Vector3(2.8, TRACK_Y, -0.35)
);
addEdge(
"l2RR_l3RRL",
"l2RR",
"l3RRL",
new THREE.Vector3(5.2, TRACK_Y, -0.35)
);
addEdge(
"l2RR_l3RRR",
"l2RR",
"l3RRR",
new THREE.Vector3(6.7, TRACK_Y, -0.35)
);
const l3Names = [
"LLL", "LLR", "LRL", "LRR", "RLL", "RLR", "RRL", "RRR"
];
l3Names.forEach((name, i) => {
addEdge(`l3${name}_exit${i}`, `l3${name}`, `exit${i}`);
});
// ---------------------------------------------------------------------
// Low-poly track meshes
// ---------------------------------------------------------------------
const trackMaterial = new THREE.MeshStandardMaterial({
color: palette.track,
roughness: 0.88,
flatShading: true,
side: THREE.DoubleSide
});
const railMaterial = new THREE.MeshStandardMaterial({
color: palette.trackEdge,
roughness: 0.8,
flatShading: true
});
const grooveMaterial = new THREE.MeshStandardMaterial({
color: palette.groove,
roughness: 1,
flatShading: true
});
function createTrack(edge) {
const curve = edge.curve;
const samples = 30;
const positions = [];
const indices = [];
const up = new THREE.Vector3(0, 1, 0);
for (let i = 0; i <= samples; i++) {
const t = i / samples;
const p = curve.getPointAt(t);
const tangent = curve.getTangentAt(t);
const side = new THREE.Vector3().crossVectors(tangent, up).normalize();
const left = p.clone().addScaledVector(side, 0.29);
const center = p.clone();
const right = p.clone().addScaledVector(side, -0.29);
left.y += 0.045;
center.y -= 0.025;
right.y += 0.045;
positions.push(...left.toArray(), ...center.toArray(), ...right.toArray());
}
for (let i = 0; i < samples; i++) {
const a = i * 3;
const b = (i + 1) * 3;
indices.push(a, b, a + 1, a + 1, b, b + 1);
indices.push(a + 1, b + 1, a + 2, a + 2, b + 1, b + 2);
}
const geometry = new THREE.BufferGeometry();
geometry.setAttribute(
"position",
new THREE.Float32BufferAttribute(positions, 3)
);
geometry.setIndex(indices);
geometry.computeVertexNormals();
const ribbon = new THREE.Mesh(geometry, trackMaterial);
ribbon.receiveShadow = true;
scene.add(ribbon);
function createRail(offset, lift, radius, material) {
const railPoints = [];
for (let i = 0; i <= 28; i++) {
const t = i / 28;
const p = curve.getPointAt(t);
const tangent = curve.getTangentAt(t);
const side = new THREE.Vector3().crossVectors(tangent, up).normalize();
p.addScaledVector(side, offset);
p.y += lift;
railPoints.push(p);
}
const railCurve = new THREE.CatmullRomCurve3(railPoints);
const rail = new THREE.Mesh(
new THREE.TubeGeometry(railCurve, 32, radius, 5, false),
material
);
scene.add(rail);
}
createRail(0.285, 0.095, 0.042, railMaterial);
createRail(-0.285, 0.095, 0.042, railMaterial);
createRail(0, 0.015, 0.024, grooveMaterial);
const sleeperCount = Math.max(2, Math.floor(edge.length / 0.53));
for (let i = 0; i <= sleeperCount; i++) {
const t = i / sleeperCount;
const p = curve.getPointAt(t);
const tangent = curve.getTangentAt(t);
sleepers.push({
position: new THREE.Vector3(p.x, 0.17, p.z),
yaw: Math.atan2(tangent.x, tangent.z)
});
}
}
Object.values(edges).forEach(createTrack);
const sleeperGeometry = new THREE.BoxGeometry(0.72, 0.075, 0.13);
const sleeperMaterial = new THREE.MeshStandardMaterial({
color: 0x866244,
roughness: 0.95,
flatShading: true
});
const sleeperMesh = new THREE.InstancedMesh(
sleeperGeometry,
sleeperMaterial,
sleepers.length
);
const dummy = new THREE.Object3D();
sleepers.forEach((sleeper, i) => {
dummy.position.copy(sleeper.position);
dummy.rotation.set(0, sleeper.yaw, 0);
dummy.updateMatrix();
sleeperMesh.setMatrixAt(i, dummy.matrix);
});
sleeperMesh.receiveShadow = true;
scene.add(sleeperMesh);
// ---------------------------------------------------------------------
// Gate assemblies
// ---------------------------------------------------------------------
const gateRows = [
{
row: 0,
nodes: ["g1"],
edges: ["g1_l1L", "g1_l1R"]
},
{
row: 1,
nodes: ["l1L", "l1R"],
edges: ["l1L_l2LL", "l1R_l2RL"]
},
{
row: 2,
nodes: ["l2LL", "l2LR", "l2RL", "l2RR"],
edges: [
"l2LL_l3LLL",
"l2LR_l3LRL",
"l2RL_l3RLL",
"l2RR_l3RRL"
]
}
];
const gateBaseMaterial = new THREE.MeshStandardMaterial({
color: palette.gateBase,
roughness: 0.72,
flatShading: true
});
const gateArmMaterial = new THREE.MeshStandardMaterial({
color: palette.gate,
emissive: 0x8a5313,
emissiveIntensity: 0.18,
roughness: 0.48,
flatShading: true
});
const localForward = new THREE.Vector3(0, 0, 1);
function createGate(row, nodeId, edgeLeft, edgeRight) {
const position = nodes[nodeId];
const base = new THREE.Mesh(
new THREE.CylinderGeometry(0.39, 0.45, 0.19, 8),
gateBaseMaterial
);
base.position.set(position.x, 0.39, position.z);
base.castShadow = true;
base.userData.gateRow = row;
scene.add(base);
interactiveMeshes.push(base);
const pivot = new THREE.Group();
pivot.position.set(position.x, 0.98, position.z);
scene.add(pivot);
const arm = new THREE.Mesh(
new THREE.BoxGeometry(0.12, 0.12, 0.9),
gateArmMaterial
);
arm.position.z = 0.45;
arm.castShadow = true;
arm.userData.gateRow = row;
pivot.add(arm);
interactiveMeshes.push(arm);
const tip = new THREE.Mesh(
new THREE.OctahedronGeometry(0.14, 0),
new THREE.MeshStandardMaterial({
color: 0xfff1a4,
emissive: 0xe8a83e,
emissiveIntensity: 0.55,
flatShading: true
})
);
tip.position.z = 0.93;
pivot.add(tip);
const leftTangent = edges[edgeLeft].curve.getTangentAt(0.025);
const rightTangent = edges[edgeRight].curve.getTangentAt(0.025);
const leftQ = new THREE.Quaternion().setFromUnitVectors(
localForward,
leftTangent.normalize()
);
const rightQ = new THREE.Quaternion().setFromUnitVectors(
localForward,
rightTangent.normalize()
);
pivot.quaternion.copy(leftQ);
gateVisuals.push({ pivot, leftQ, rightQ, row });
}
createGate(0, "g1", "g1_l1L", "g1_l1R");
createGate(1, "l1L", "l1L_l2LL", "l1L_l2LR");
createGate(1, "l1R", "l1R_l2RL", "l1R_l2RR");
createGate(2, "l2LL", "l2LL_l3LLL", "l2LL_l3LLR");
createGate(2, "l2LR", "l2LR_l3LRL", "l2LR_l3LRR");
createGate(2, "l2RL", "l2RL_l3RLL", "l2RL_l3RLR");
createGate(2, "l2RR", "l2RR_l3RRL", "l2RR_l3RRR");
// ---------------------------------------------------------------------
// Cups and catch trays
// ---------------------------------------------------------------------
const cupGroups = [];
function createCup(marble, exitIndex) {
const group = new THREE.Group();
group.position.set(exitX[exitIndex], 0.07, -6.02);
const outerMaterial = new THREE.MeshStandardMaterial({
color: marble.color,
roughness: 0.42,
metalness: 0.03,
flatShading: true,
side: THREE.DoubleSide
});
const innerMaterial = new THREE.MeshStandardMaterial({
color: new THREE.Color(marble.color).multiplyScalar(0.42),
roughness: 0.58,
flatShading: true,
side: THREE.DoubleSide
});
const outer = new THREE.Mesh(
new THREE.CylinderGeometry(0.66, 0.48, 0.88, 12, 1, true),
outerMaterial
);
outer.position.y = 0.49;
outer.castShadow = true;
group.add(outer);
const inner = new THREE.Mesh(
new THREE.CylinderGeometry(0.56, 0.39, 0.79, 12, 1, true),
innerMaterial
);
inner.position.y = 0.48;
group.add(inner);
const bottom = new THREE.Mesh(
new THREE.CylinderGeometry(0.49, 0.49, 0.12, 12),
outerMaterial
);
bottom.position.y = 0.1;
bottom.castShadow = true;
group.add(bottom);
const rim = new THREE.Mesh(
new THREE.TorusGeometry(0.61, 0.065, 6, 16),
outerMaterial
);
rim.rotation.x = Math.PI / 2;
rim.position.y = 0.93;
rim.castShadow = true;
group.add(rim);
const label = makeTextSprite(marble.name.toUpperCase(), "#20332f");
label.position.set(0, 1.62, 0);
label.scale.set(1.25, 0.31, 1);
group.add(label);
const ball = new THREE.Mesh(
new THREE.SphereGeometry(0.225, 12, 8),
new THREE.MeshStandardMaterial({
color: marble.color,
roughness: 0.22,
metalness: 0.12,
flatShading: true
})
);
ball.position.set(0, 0.39, 0);
ball.castShadow = true;
ball.visible = false;
group.add(ball);
cupBalls.push(ball);
scene.add(group);
cupGroups.push(group);
return group;
}
createCup(marbleDefs[0], 0);
createCup(marbleDefs[1], 3);
createCup(marbleDefs[2], 5);
function createRejectTray(exitIndex) {
const group = new THREE.Group();
group.position.set(exitX[exitIndex], 0.07, -5.58);
const material = new THREE.MeshStandardMaterial({
color: palette.reject,
roughness: 0.92,
flatShading: true
});
const base = new THREE.Mesh(
new THREE.BoxGeometry(0.88, 0.09, 0.72),
material
);
base.position.y = 0.08;
base.receiveShadow = true;
group.add(base);
const wallGeometry = new THREE.BoxGeometry(0.88, 0.22, 0.08);
const front = new THREE.Mesh(wallGeometry, material);
front.position.set(0, 0.2, -0.32);
const back = front.clone();
back.position.z = 0.32;
const sideGeometry = new THREE.BoxGeometry(0.08, 0.22, 0.64);
const left = new THREE.Mesh(sideGeometry, material);
left.position.set(-0.4, 0.2, 0);
const right = left.clone();
right.position.x = 0.4;
group.add(front, back, left, right);
scene.add(group);
}
[1, 2, 4, 6, 7].forEach(createRejectTray);
// ---------------------------------------------------------------------
// Marbles and interface
// ---------------------------------------------------------------------
const marbleMeshes = [];
const queuePositions = [
new THREE.Vector3(-0.82, 0.73, 7.27),
new THREE.Vector3(0, 0.73, 7.55),
new THREE.Vector3(0.82, 0.73, 7.27)
];
marbleDefs.forEach((def, i) => {
const mesh = new THREE.Mesh(
new THREE.SphereGeometry(0.225, 12, 8),
new THREE.MeshStandardMaterial({
color: def.color,
roughness: 0.2,
metalness: 0.13,
flatShading: true
})
);
mesh.position.copy(queuePositions[i]);
mesh.castShadow = true;
mesh.userData.marbleIndex = i;
scene.add(mesh);
marbleMeshes.push(mesh);
interactiveMeshes.push(mesh);
});
const selectionRing = new THREE.Mesh(
new THREE.TorusGeometry(0.31, 0.035, 6, 24),
new THREE.MeshBasicMaterial({ color: 0xe8ff9b })
);
selectionRing.rotation.x = Math.PI / 2;
scene.add(selectionRing);
const marbleList = document.getElementById("marbleList");
const gateList = document.getElementById("gateList");
const statusElement = document.getElementById("status");
const releaseButton = document.getElementById("release");
const tooltip = document.getElementById("tooltip");
const marbleButtons = marbleDefs.map((def, index) => {
const button = document.createElement("button");
button.className = "marble-card";
button.style.setProperty("--marble-color", def.css);
button.innerHTML = `
<span class="done-mark">✓</span>
<span class="marble-dot"></span>
<span class="marble-name">${def.name}</span>
`;
button.addEventListener("click", () => selectMarble(index));
marbleList.appendChild(button);
return button;
});
const roman = ["I", "II", "III"];
const gateButtons = gateStates.map((_, index) => {
const button = document.createElement("button");
button.className = "gate-card";
button.innerHTML = `
<span class="gate-number">GATE ${roman[index]}</span>
<span class="gate-direction"></span>
`;
button.addEventListener("click", () => toggleGate(index));
gateList.appendChild(button);
return button;
});
function setStatus(text, tone = "neutral") {
statusElement.textContent = text;
statusElement.dataset.tone = tone;
}
function updateUI() {
marbleButtons.forEach((button, i) => {
button.classList.toggle("active", i === selectedMarble);
button.classList.toggle("done", cupBalls[i].visible);
button.disabled = rolling;
});
gateButtons.forEach((button, i) => {
const direction = button.querySelector(".gate-direction");
direction.textContent = gateStates[i] === 0 ? "◀ LEFT" : "RIGHT ▶";
direction.className = `gate-direction ${gateStates[i] === 0 ? "left" : "right"}`;
button.disabled = lockedGates[i];
});
releaseButton.disabled = rolling || cupBalls[selectedMarble].visible;
releaseButton.textContent = rolling
? "Marble rolling…"
: `Release ${marbleDefs[selectedMarble].name}`;
selectionRing.visible = !rolling && !cupBalls[selectedMarble].visible;
selectionRing.position.copy(queuePositions[selectedMarble]);
selectionRing.position.y = 0.66;
}
function selectMarble(index) {
if (rolling || cupBalls[index].visible) return;
selectedMarble = index;
setStatus(
`Guide the ${marbleDefs[index].name.toLowerCase()} marble into the matching cup.`
);
updateUI();
}
function toggleGate(index) {
if (lockedGates[index]) return;
gateStates[index] = 1 - gateStates[index];
updateUI();
}
// ---------------------------------------------------------------------
// Marble motion
// ---------------------------------------------------------------------
const marbleState = {
index: selectedMarble,
mode: "idle",
edgeId: null,
distance: 0,
progress: 0,
from: new THREE.Vector3(),
to: new THREE.Vector3(),
exitIndex: 0
};
function releaseMarble() {
if (rolling || cupBalls[selectedMarble].visible) return;
rolling = true;
routeCode = 0;
lockedGates.fill(false);
marbleState.index = selectedMarble;
marbleState.mode = "toStart";
marbleState.progress = 0;
marbleState.from.copy(marbleMeshes[selectedMarble].position);
marbleState.to.copy(nodes.start);
marbleState.to.y += MARBLE_OFFSET;
setStatus(
"The marble is rolling. Unpassed gates can still be flipped!"
);
updateUI();
}
function setMarbleOnEdge(edgeId) {
marbleState.mode = "edge";
marbleState.edgeId = edgeId;
marbleState.distance = 0;
}
function completeEdge(edge) {
const end = edge.end;
if (end === "g1") {
const bit = gateStates[0];
routeCode = bit;
lockedGates[0] = true;
setMarbleOnEdge(adjacency.g1[bit]);
updateUI();
return;
}
if (end === "l1L" || end === "l1R") {
const bit = gateStates[1];
routeCode = routeCode * 2 + bit;
lockedGates[1] = true;
setMarbleOnEdge(adjacency[end][bit]);
updateUI();
return;
}
if (end.startsWith("l2")) {
const bit = gateStates[2];
routeCode = routeCode * 2 + bit;
lockedGates[2] = true;
setMarbleOnEdge(adjacency[end][bit]);
updateUI();
return;
}
if (end.startsWith("l3")) {
const exitIndex = routeCode;
const fixedEdge = Object.values(edges).find(
(edgeItem) =>
edgeItem.start === end && edgeItem.end === `exit${exitIndex}`
);
setMarbleOnEdge(fixedEdge.id);
return;
}
if (end.startsWith("exit")) {
marbleState.exitIndex = Number(end.slice(4));
marbleState.mode = "drop";
marbleState.progress = 0;
marbleState.from.copy(marbleMeshes[marbleState.index].position);
marbleState.to.set(exitX[marbleState.exitIndex], 0.4, -6.0);
}
}
function finishDrop() {
const def = marbleDefs[marbleState.index];
const targetCode = parseInt(def.code, 2);
const correct = routeCode === targetCode;
if (correct) {
cupBalls[marbleState.index].visible = true;
marbleMeshes[marbleState.index].visible = false;
rolling = false;
setStatus(`${def.name} landed safely in its cup!`, "good");
const next = marbleDefs.findIndex(
(_, i) => !cupBalls[i].visible && i !== marbleState.index
);
if (next >= 0) {
setTimeout(() => {
if (!rolling) {
selectedMarble = next;
updateUI();
setStatus(
`Now guide the ${marbleDefs[next].name.toLowerCase()} marble.`
);
}
}, 800);
} else {
setStatus("Puzzle complete — every marble is in its cup!", "good");
}
} else {
rolling = false;
setStatus(
"That route ends in a catch tray. Try another switch combination.",
"bad"
);
setTimeout(() => {
if (!rolling) {
marbleMeshes[marbleState.index].visible = true;
marbleMeshes[marbleState.index].position.copy(
queuePositions[marbleState.index]
);
updateUI();
}
}, 650);
}
}
function updateMarble(dt) {
if (!rolling) return;
const mesh = marbleMeshes[marbleState.index];
if (marbleState.mode === "toStart") {
marbleState.progress += dt / 0.5;
const t = Math.min(marbleState.progress, 1);
mesh.position.lerpVectors(
marbleState.from,
marbleState.to,
t * t * (3 - 2 * t)
);
mesh.position.y += Math.sin(t * Math.PI) * 0.25;
if (t >= 1) {
setMarbleOnEdge("start_g1");
}
} else if (marbleState.mode === "edge") {
const edge = edges[marbleState.edgeId];
marbleState.distance += 3.35 * dt;
const t = Math.min(marbleState.distance / edge.length, 1);
const p = edge.curve.getPointAt(t);
mesh.position.copy(p);
mesh.position.y += MARBLE_OFFSET;
if (t >= 1) {
completeEdge(edge);
}
} else if (marbleState.mode === "drop") {
marbleState.progress += dt / 0.8;
const t = Math.min(marbleState.progress, 1);
const eased = t * t * (3 - 2 * t);
mesh.position.lerpVectors(
marbleState.from,
marbleState.to,
eased
);
mesh.position.y += Math.sin(t * Math.PI) * 0.16;
if (t >= 1) {
finishDrop();
}
}
}
// ---------------------------------------------------------------------
// Camera controls implemented directly
// ---------------------------------------------------------------------
const cameraState = {
radius: innerWidth < 700 ? 28.5 : 23.5,
theta: 0.58,
phi: 0.88,
target: new THREE.Vector3(0, 0.35, -0.7)
};
function updateCamera() {
const s = Math.sin(cameraState.phi);
camera.position.set(
cameraState.target.x +
cameraState.radius * s * Math.sin(cameraState.theta),
cameraState.target.y +
cameraState.radius * Math.cos(cameraState.phi),
cameraState.target.z +
cameraState.radius * s * Math.cos(cameraState.theta)
);
camera.lookAt(cameraState.target);
}
function resetCamera() {
cameraState.radius = innerWidth < 700 ? 28.5 : 23.5;
cameraState.theta = 0.58;
cameraState.phi = 0.88;
cameraState.target.set(0, 0.35, -0.7);
updateCamera();
}
updateCamera();
let dragging = false;
let moved = false;
let lastX = 0;
let lastY = 0;
renderer.domElement.addEventListener("contextmenu", (event) => {
event.preventDefault();
});
renderer.domElement.addEventListener("pointerdown", (event) => {
dragging = true;
moved = false;
lastX = event.clientX;
lastY = event.clientY;
renderer.domElement.setPointerCapture(event.pointerId);
});
renderer.domElement.addEventListener("pointermove", (event) => {
if (dragging) {
const dx = event.clientX - lastX;
const dy = event.clientY - lastY;
if (Math.abs(dx) + Math.abs(dy) > 3) moved = true;
if (event.shiftKey) {
const right = new THREE.Vector3(
Math.cos(cameraState.theta),
0,
-Math.sin(cameraState.theta)
);
const forward = new THREE.Vector3(
-Math.sin(cameraState.theta),
0,
-Math.cos(cameraState.theta)
);
cameraState.target.addScaledVector(right, -dx * 0.012);
cameraState.target.addScaledVector(forward, -dy * 0.012);
} else {
cameraState.theta -= dx * 0.006;
cameraState.phi = THREE.MathUtils.clamp(
cameraState.phi - dy * 0.005,
0.42,
1.25
);
}
lastX = event.clientX;
lastY = event.clientY;
updateCamera();
tooltip.style.display = "none";
} else {
updateHover(event);
}
});
renderer.domElement.addEventListener("pointerup", (event) => {
dragging = false;
if (!moved) {
handleSceneClick(event);
}
});
renderer.domElement.addEventListener("pointercancel", () => {
dragging = false;
});
renderer.domElement.addEventListener(
"wheel",
(event) => {
event.preventDefault();
cameraState.radius = THREE.MathUtils.clamp(
cameraState.radius * Math.exp(event.deltaY * 0.001),
13,
35
);
updateCamera();
},
{ passive: false }
);
function setPointerFromEvent(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 getIntersection(event) {
setPointerFromEvent(event);
raycaster.setFromCamera(pointer, camera);
return raycaster.intersectObjects(interactiveMeshes, false)[0];
}
function updateHover(event) {
const hit = getIntersection(event);
if (!hit) {
renderer.domElement.style.cursor = "grab";
tooltip.style.display = "none";
return;
}
renderer.domElement.style.cursor = "pointer";
if (hit.object.userData.gateRow !== undefined) {
const row = hit.object.userData.gateRow;
tooltip.textContent = `Gate ${roman[row]} — click to flip`;
} else if (hit.object.userData.marbleIndex !== undefined) {
const index = hit.object.userData.marbleIndex;
tooltip.textContent = `Select ${marbleDefs[index].name}`;
}
tooltip.style.left = `${event.clientX}px`;
tooltip.style.top = `${event.clientY}px`;
tooltip.style.display = "block";
}
function handleSceneClick(event) {
const hit = getIntersection(event);
if (!hit) return;
if (hit.object.userData.gateRow !== undefined) {
toggleGate(hit.object.userData.gateRow);
} else if (hit.object.userData.marbleIndex !== undefined) {
selectMarble(hit.object.userData.marbleIndex);
}
}
// ---------------------------------------------------------------------
// Reset and scramble
// ---------------------------------------------------------------------
function resetPuzzle() {
rolling = false;
routeCode = 0;
selectedMarble = 0;
gateStates[0] = 0;
gateStates[1] = 1;
gateStates[2] = 0;
lockedGates.fill(false);
marbleMeshes.forEach((mesh, i) => {
mesh.visible = true;
mesh.position.copy(queuePositions[i]);
});
cupBalls.forEach((ball) => {
ball.visible = false;
});
marbleState.mode = "idle";
setStatus("Fresh board. Guide each marble into its matching cup.");
updateUI();
}
function scrambleGates() {
const validCodes = new Set(
marbleDefs.map((def) => parseInt(def.code, 2))
);
let candidate;
do {
candidate =
Math.floor(Math.random() * 8);
} while (validCodes.has(candidate));
for (let i = 0; i < 3; i++) {
gateStates[i] = (candidate >> (2 - i)) & 1;
}
setStatus("The switches are scrambled. Find the matching routes.");
updateUI();
}
releaseButton.addEventListener("click", releaseMarble);
document.getElementById("resetPuzzle").addEventListener("click", resetPuzzle);
document.getElementById("scramble").addEventListener("click", scrambleGates);
document.getElementById("resetView").addEventListener("click", resetCamera);
addEventListener("resize", () => {
camera.aspect = innerWidth / innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(innerWidth, innerHeight);
renderer.setPixelRatio(Math.min(devicePixelRatio, 2));
});
// ---------------------------------------------------------------------
// Animation
// ---------------------------------------------------------------------
function animate() {
const dt = Math.min(clock.getDelta(), 0.05);
gateVisuals.forEach((visual) => {
const target =
gateStates[visual.row] === 0 ? visual.leftQ : visual.rightQ;
visual.pivot.quaternion.slerp(target, 1 - Math.exp(-dt * 10));
});
updateMarble(dt);
selectionRing.rotation.z += dt * 0.7;
selectionRing.scale.setScalar(1 + Math.sin(clock.elapsedTime * 3) * 0.035);
renderer.render(scene, camera);
requestAnimationFrame(animate);
}
updateUI();
animate();
</script>
</body>
</html>
```