Prompt specification
Build or customize the Three.js 3D scene "Route a Boat With Limited Water" 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: Route a Boat With Limited Water
Category: Voxel Worlds · Style: Voxel 3D
License: MIT · Reference: https://three3d.app/scene/route-a-boat-with-limited-water-x3520
Scene Description Prompt:
Please create one self-contained HTML file with Three.js from cdnjs showing water levels, connected tanks, and lock gates. Create a playable two-lock puzzle with a finite reservoir and explicit toy volume accounting. Track every transfer and reject moves that require unavailable water. Voxel style.
Working Three.js Starter (route-a-boat-with-limited-water-x3520):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Lock & Block — A Two-Lock Water Puzzle</title>
<style>
:root {
color-scheme: dark;
--bg: #07131d;
--panel: rgba(9, 24, 35, 0.88);
--panel-strong: rgba(7, 18, 28, 0.96);
--line: rgba(148, 210, 230, 0.22);
--text: #e8f7fb;
--muted: #8eb0bc;
--cyan: #53d7f5;
--blue: #368eff;
--green: #62e6a7;
--red: #ff7272;
--amber: #ffc45d;
--shadow: 0 14px 45px rgba(0, 0, 0, 0.34);
}
* { box-sizing: border-box; }
html, body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: var(--bg);
color: var(--text);
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
}
button { font: inherit; }
#scene {
position: fixed;
inset: 0;
width: 100%;
height: 100%;
display: block;
cursor: grab;
touch-action: none;
}
#scene:active { cursor: grabbing; }
.panel {
position: fixed;
z-index: 10;
background:
linear-gradient(135deg, rgba(255,255,255,0.035), transparent 55%),
var(--panel);
border: 1px solid var(--line);
border-radius: 14px;
box-shadow: var(--shadow);
backdrop-filter: blur(12px);
}
#header {
top: 16px;
left: 16px;
width: 310px;
padding: 15px 16px;
}
.eyebrow {
color: var(--cyan);
font-size: 10px;
font-weight: 800;
letter-spacing: 0.2em;
text-transform: uppercase;
}
h1 {
margin: 4px 0 3px;
font-size: 25px;
line-height: 1;
letter-spacing: -0.04em;
}
.subtitle {
color: var(--muted);
font-size: 11px;
line-height: 1.45;
}
.header-actions {
display: flex;
align-items: center;
justify-content: space-between;
gap: 8px;
margin-top: 12px;
}
.chip {
padding: 5px 8px;
border: 1px solid var(--line);
border-radius: 7px;
color: var(--muted);
font-size: 10px;
}
.reset {
border: 1px solid rgba(255, 114, 114, 0.45);
border-radius: 8px;
padding: 7px 10px;
color: #ffb0b0;
background: rgba(255, 114, 114, 0.08);
cursor: pointer;
}
.reset:hover { background: rgba(255, 114, 114, 0.18); }
.reset:disabled { opacity: 0.4; cursor: wait; }
#status {
top: 16px;
right: 16px;
width: 300px;
padding: 14px;
}
.status-head {
display: flex;
align-items: baseline;
justify-content: space-between;
gap: 12px;
margin-bottom: 10px;
}
.status-head strong { font-size: 12px; }
#total {
color: var(--cyan);
font-size: 19px;
font-weight: 900;
}
.stat {
display: grid;
grid-template-columns: 1fr auto;
gap: 4px 10px;
margin: 8px 0;
color: var(--muted);
font-size: 11px;
}
.stat b {
color: var(--text);
font-size: 11px;
}
.meter {
grid-column: 1 / -1;
height: 7px;
overflow: hidden;
border-radius: 3px;
background: rgba(255,255,255,0.07);
}
.meter i {
display: block;
width: 0;
height: 100%;
border-radius: inherit;
background: linear-gradient(90deg, var(--blue), var(--cyan));
transition: width 240ms ease;
}
.invariant {
margin-top: 11px;
padding-top: 10px;
border-top: 1px solid var(--line);
color: var(--green);
font-size: 10px;
}
.invariant.bad { color: var(--red); }
#mission {
left: 16px;
bottom: 154px;
width: 315px;
padding: 14px;
}
#mission h2 {
margin: 4px 0 8px;
font-size: 14px;
}
#mission p {
margin: 7px 0;
color: var(--muted);
font-size: 11px;
line-height: 1.55;
}
.goals {
display: grid;
grid-template-columns: repeat(2, 1fr);
gap: 6px;
margin-top: 10px;
}
.goal {
padding: 7px 8px;
border: 1px solid var(--line);
border-radius: 8px;
background: rgba(255,255,255,0.025);
color: var(--muted);
font-size: 9px;
}
.goal b {
display: block;
margin-top: 3px;
color: var(--text);
font-size: 12px;
}
.goal.done {
border-color: rgba(98, 230, 167, 0.55);
background: rgba(98, 230, 167, 0.08);
}
.goal.done b { color: var(--green); }
.rule-note {
margin-top: 10px !important;
padding-top: 9px;
border-top: 1px solid var(--line);
color: var(--amber) !important;
}
#ledger {
right: 16px;
bottom: 154px;
width: 420px;
max-height: 254px;
overflow: hidden;
padding: 13px;
}
.ledger-head {
display: flex;
align-items: center;
justify-content: space-between;
gap: 10px;
margin-bottom: 8px;
}
.ledger-head strong { font-size: 12px; }
.ledger-head span {
color: var(--muted);
font-size: 9px;
}
.ledger-columns,
.ledger-row {
display: grid;
grid-template-columns: 30px 53px 1fr 1fr 35px;
gap: 7px;
align-items: center;
}
.ledger-columns {
padding: 5px 7px;
color: #63828d;
font-size: 8px;
letter-spacing: 0.08em;
}
#ledgerRows {
max-height: 186px;
overflow-y: auto;
scrollbar-width: thin;
scrollbar-color: #31515d transparent;
}
.ledger-row {
min-height: 30px;
margin-top: 4px;
padding: 6px 7px;
border: 1px solid rgba(148, 210, 230, 0.09);
border-radius: 7px;
background: rgba(255,255,255,0.025);
font-size: 9px;
}
.ledger-row .num { color: #65838f; }
.ledger-row .route { color: var(--cyan); }
.ledger-row .sum { color: var(--green); text-align: right; }
.ledger-empty { padding: 20px 8px; color: #66838e; font-size: 10px; text-align: center; }
#controls {
left: 16px;
right: 16px;
bottom: 16px;
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 10px;
padding: 10px;
}
.connection {
min-width: 0;
padding: 10px;
border: 1px solid var(--line);
border-radius: 11px;
background: rgba(255,255,255,0.025);
transition: border-color 150ms ease, background 150ms ease;
}
.connection.open {
border-color: rgba(98, 230, 167, 0.62);
background: rgba(98, 230, 167, 0.065);
}
.conn-head {
display: grid;
grid-template-columns: 30px minmax(0, 1fr) auto;
align-items: center;
gap: 8px;
margin-bottom: 9px;
}
.gate-letter {
display: grid;
place-items: center;
width: 29px;
height: 29px;
border: 1px solid #3c6471;
border-radius: 7px;
color: var(--cyan);
background: #102b37;
font-weight: 900;
}
.conn-head strong {
display: block;
overflow: hidden;
font-size: 12px;
text-overflow: ellipsis;
white-space: nowrap;
}
.conn-head small {
display: block;
margin-top: 2px;
color: var(--muted);
font-size: 9px;
}
.gate-state {
padding: 4px 6px;
border-radius: 5px;
color: var(--amber);
background: rgba(255, 196, 93, 0.08);
font-size: 8px;
font-weight: 900;
}
.open .gate-state {
color: var(--green);
background: rgba(98, 230, 167, 0.1);
}
.conn-actions {
display: grid;
grid-template-columns: 0.85fr 1.15fr;
gap: 7px;
}
.conn-actions button {
min-height: 34px;
padding: 7px 8px;
border-radius: 8px;
cursor: pointer;
font-size: 10px;
font-weight: 800;
transition: transform 100ms ease, background 100ms ease;
}
.conn-actions button:active { transform: translateY(1px); }
.gate-btn {
border: 1px solid #3b6070;
color: var(--text);
background: #102a35;
}
.gate-btn:hover { background: #173c4a; }
.move-btn {
border: 1px solid rgba(83, 215, 245, 0.45);
color: #d9faff;
background: linear-gradient(135deg, #16789b, #2252ad);
}
.move-btn:hover { filter: brightness(1.14); }
#toast {
position: fixed;
z-index: 40;
left: 50%;
bottom: 157px;
max-width: min(540px, calc(100% - 30px));
padding: 11px 15px;
border: 1px solid var(--line);
border-radius: 10px;
background: var(--panel-strong);
box-shadow: var(--shadow);
color: var(--text);
font-size: 11px;
opacity: 0;
pointer-events: none;
transform: translate(-50%, 10px);
transition: opacity 150ms ease, transform 150ms ease;
}
#toast.show {
opacity: 1;
transform: translate(-50%, 0);
}
#toast.reject {
border-color: rgba(255, 114, 114, 0.65);
color: #ffc0c0;
background: rgba(48, 14, 20, 0.96);
}
#toast.success {
border-color: rgba(98, 230, 167, 0.65);
color: #b9ffda;
background: rgba(9, 43, 29, 0.96);
}
#win {
position: fixed;
z-index: 60;
inset: 0;
display: grid;
place-items: center;
padding: 20px;
background: rgba(2, 10, 16, 0.7);
backdrop-filter: blur(7px);
opacity: 0;
visibility: hidden;
transition: opacity 220ms ease, visibility 220ms ease;
}
#win.show {
opacity: 1;
visibility: visible;
}
.win-card {
width: min(480px, 100%);
padding: 27px;
border: 1px solid rgba(98, 230, 167, 0.55);
border-radius: 18px;
background: linear-gradient(145deg, #102b2a, #0a1924 65%);
box-shadow: 0 25px 90px rgba(0,0,0,0.55);
text-align: center;
}
.win-icon {
display: grid;
place-items: center;
width: 58px;
height: 58px;
margin: 0 auto 13px;
border-radius: 14px;
color: #07221a;
background: var(--green);
box-shadow: 0 0 35px rgba(98, 230, 167, 0.35);
font-size: 28px;
font-weight: 900;
}
.win-card h2 {
margin: 5px 0 9px;
font-size: 25px;
letter-spacing: -0.04em;
}
.win-card p {
color: var(--muted);
font-size: 12px;
line-height: 1.6;
}
.win-stats {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 7px;
margin: 18px 0;
}
.win-stat {
padding: 9px 5px;
border: 1px solid var(--line);
border-radius: 9px;
color: var(--muted);
font-size: 8px;
}
.win-stat b {
display: block;
margin-top: 4px;
color: var(--green);
font-size: 15px;
}
.win-actions {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 8px;
}
.win-actions button {
padding: 10px;
border-radius: 9px;
cursor: pointer;
font-weight: 800;
}
#inspectBtn {
border: 1px solid var(--line);
color: var(--text);
background: rgba(255,255,255,0.05);
}
#playAgainBtn {
border: 1px solid rgba(98, 230, 167, 0.5);
color: #072219;
background: var(--green);
}
@media (max-width: 900px) {
#header {
width: 270px;
transform: scale(0.88);
transform-origin: top left;
}
#status {
width: 245px;
transform: scale(0.88);
transform-origin: top right;
}
#mission {
width: 280px;
transform: scale(0.9);
transform-origin: bottom left;
}
#ledger {
width: 350px;
max-height: 205px;
transform: scale(0.9);
transform-origin: bottom right;
}
#controls { gap: 7px; }
.conn-head { grid-template-columns: 28px minmax(0,1fr); }
.gate-state { display: none; }
}
@media (max-width: 650px) {
#status {
top: 108px;
right: 10px;
width: 220px;
transform: scale(0.78);
}
#mission { display: none; }
#ledger {
right: 10px;
bottom: 228px;
width: calc(100% - 20px);
max-height: 145px;
transform: none;
}
#ledgerRows { max-height: 94px; }
.ledger-columns, .ledger-row { grid-template-columns: 25px 47px 1fr 1fr 30px; }
#controls {
left: 10px;
right: 10px;
bottom: 10px;
grid-template-columns: 1fr;
gap: 6px;
}
.connection { padding: 7px; }
.conn-head { margin-bottom: 6px; }
.conn-actions button { min-height: 30px; }
#toast { bottom: 222px; }
}
</style>
</head>
<body>
<canvas id="scene" aria-label="Interactive voxel-style water tank puzzle"></canvas>
<header id="header" class="panel">
<div class="eyebrow">Finite-water toy system</div>
<h1>LOCK & BLOCK</h1>
<div class="subtitle">Two lock chambers. One finite reservoir. Every block is counted.</div>
<div class="header-actions">
<span class="chip">1 block = 1 volume unit</span>
<button id="reset" class="reset">Reset puzzle</button>
</div>
</header>
<section id="status" class="panel" aria-label="Water volume accounting">
<div class="status-head">
<strong>VOLUME ACCOUNTING</strong>
<span id="total">Σ 12</span>
</div>
<div class="stat">
<span>Source reservoir</span><b id="reservoirValue">12 / 12</b>
<div class="meter"><i id="reservoirBar"></i></div>
</div>
<div class="stat">
<span>Upper lock</span><b id="upperValue">0 / 6</b>
<div class="meter"><i id="upperBar"></i></div>
</div>
<div class="stat">
<span>Lower lock</span><b id="lowerValue">0 / 8</b>
<div class="meter"><i id="lowerBar"></i></div>
</div>
<div class="stat">
<span>Tailwater basin</span><b id="tailValue">0 / 12</b>
<div class="meter"><i id="tailBar"></i></div>
</div>
<div id="invariant" class="invariant">✓ Conservation verified: 12 blocks remain</div>
</section>
<section id="mission" class="panel">
<div class="eyebrow">Mission</div>
<h2>Fill the lower lock with 8 blocks</h2>
<p>
Keep exactly <b>4 blocks</b> in the finite reservoir.
The upper lock and tailwater basin must finish empty.
</p>
<p>
The upper lock holds only <b>6 blocks</b>, so the lower lock needs
<b>two deliveries</b>.
</p>
<div class="goals">
<div id="lowerGoal" class="goal">LOWER LOCK<b>0 / 8</b></div>
<div id="reservoirGoal" class="goal">RESERVE LEFT<b>12 / 4</b></div>
<div id="upperGoal" class="goal">UPPER LOCK<b>0 / 0</b></div>
<div id="tailGoal" class="goal">TAILWATER<b>0 / 0</b></div>
</div>
<p class="rule-note">
Lock safety: only one gate may be open. Close the current gate before opening another.
Unavailable-water moves are rejected without changing any volume.
</p>
<p>
Drag to orbit · wheel to zoom · click a scene gate to toggle it ·
keys 1/2/3 toggle gates · Q/W/E move one block
</p>
</section>
<section id="ledger" class="panel">
<div class="ledger-head">
<strong>TRANSFER LEDGER</strong>
<span>R = reservoir · U = upper · L = lower · T = tailwater</span>
</div>
<div class="ledger-columns">
<span>#</span><span>ROUTE</span><span>FROM</span><span>TO</span><span style="text-align:right">Σ</span>
</div>
<div id="ledgerRows">
<div class="ledger-empty">No transfers yet. Open Gate A to begin.</div>
</div>
</section>
<section id="controls" class="panel" aria-label="Lock gate controls">
<article id="card0" class="connection">
<div class="conn-head">
<span class="gate-letter">A</span>
<div>
<strong>Reservoir → Upper</strong>
<small>Source lock gate · maximum destination: 6</small>
</div>
<span class="gate-state">CLOSED</span>
</div>
<div class="conn-actions">
<button class="gate-btn" data-gate-toggle="0">Open gate</button>
<button class="move-btn" data-transfer="0">Move 1 block</button>
</div>
</article>
<article id="card1" class="connection">
<div class="conn-head">
<span class="gate-letter">B</span>
<div>
<strong>Upper → Lower</strong>
<small>Middle lock gate · maximum destination: 8</small>
</div>
<span class="gate-state">CLOSED</span>
</div>
<div class="conn-actions">
<button class="gate-btn" data-gate-toggle="1">Open gate</button>
<button class="move-btn" data-transfer="1">Move 1 block</button>
</div>
</article>
<article id="card2" class="connection">
<div class="conn-head">
<span class="gate-letter">C</span>
<div>
<strong>Lower → Tailwater</strong>
<small>Outlet lock gate · any water here is wasted</small>
</div>
<span class="gate-state">CLOSED</span>
</div>
<div class="conn-actions">
<button class="gate-btn" data-gate-toggle="2">Open gate</button>
<button class="move-btn" data-transfer="2">Move 1 block</button>
</div>
</article>
</section>
<div id="toast" role="status" aria-live="polite"></div>
<div id="win" role="dialog" aria-modal="true" aria-labelledby="winTitle">
<div class="win-card">
<div class="win-icon">✓</div>
<div class="eyebrow">Puzzle complete</div>
<h2 id="winTitle">Both locks are working.</h2>
<p>
The lower lock now holds 8 blocks, exactly 4 blocks remain in the
finite reservoir, and no water was lost to the tailwater.
</p>
<div class="win-stats">
<div class="win-stat">DELIVERED<b>8</b></div>
<div class="win-stat">BLOCK MOVES<b id="moveCount">0</b></div>
<div class="win-stat">WASTED<b>0</b></div>
</div>
<div class="win-actions">
<button id="inspectBtn">Inspect scene</button>
<button id="playAgainBtn">Play again</button>
</div>
</div>
</div>
<script type="module">
import * as THREE from "https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
// -------------------------------------------------------------------------
// Explicit toy volume model. There is no hidden source and no magic water.
// -------------------------------------------------------------------------
const INITIAL_TOTAL = 12;
const capacities = {
reservoir: 12,
upper: 6,
lower: 8,
tail: 12
};
const tankSpecs = {
reservoir: { name: "SOURCE RESERVOIR", short: "R", x: -7.7, width: 4.6, depth: 3.6 },
upper: { name: "UPPER LOCK", short: "U", x: -2.7, width: 4.2, depth: 3.4 },
lower: { name: "LOWER LOCK", short: "L", x: 2.5, width: 4.2, depth: 3.4 },
tail: { name: "TAILWATER", short: "T", x: 7.4, width: 4.2, depth: 3.4 }
};
const paths = [
{ from: "reservoir", to: "upper", gate: 0, route: "R → U" },
{ from: "upper", to: "lower", gate: 1, route: "U → L" },
{ from: "lower", to: "tail", gate: 2, route: "L → T" }
];
const state = {
volumes: {
reservoir: 12,
upper: 0,
lower: 0,
tail: 0
},
gates: [false, false, false],
ledger: [],
transfers: 0,
rejected: 0,
won: false,
busy: false
};
const tankNames = {
reservoir: "Source reservoir",
upper: "Upper lock",
lower: "Lower lock",
tail: "Tailwater basin"
};
const $ = id => document.getElementById(id);
const canvas = $("scene");
// -------------------------------------------------------------------------
// Three.js scene
// -------------------------------------------------------------------------
const renderer = new THREE.WebGLRenderer({
canvas,
antialias: true,
alpha: false,
powerPreference: "high-performance"
});
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.15;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x07131d);
scene.fog = new THREE.Fog(0x07131d, 22, 46);
const camera = new THREE.OrthographicCamera(-12, 12, 8, -8, 0.1, 100);
const cameraTarget = new THREE.Vector3(0, 2.2, 0);
let cameraTheta = 0.28;
let cameraPhi = 1.06;
let cameraRadius = 24;
let cameraZoom = 1;
const hemisphere = new THREE.HemisphereLight(0xbcecff, 0x14202a, 2.15);
scene.add(hemisphere);
const sun = new THREE.DirectionalLight(0xffffff, 3.1);
sun.position.set(-8, 15, 10);
sun.castShadow = true;
sun.shadow.mapSize.set(2048, 2048);
sun.shadow.camera.left = -18;
sun.shadow.camera.right = 18;
sun.shadow.camera.top = 15;
sun.shadow.camera.bottom = -12;
sun.shadow.camera.near = 1;
sun.shadow.camera.far = 45;
scene.add(sun);
const rim = new THREE.DirectionalLight(0x39c8ff, 1.3);
rim.position.set(12, 7, -10);
scene.add(rim);
const materials = {
ground: new THREE.MeshStandardMaterial({ color: 0x0c202b, roughness: 0.94, flatShading: true }),
groundEdge: new THREE.MeshStandardMaterial({ color: 0x173544, roughness: 0.9, flatShading: true }),
wall: new THREE.MeshStandardMaterial({ color: 0x244656, roughness: 0.8, flatShading: true }),
wallDark: new THREE.MeshStandardMaterial({ color: 0x142d3a, roughness: 0.88, flatShading: true }),
trim: new THREE.MeshStandardMaterial({ color: 0x376579, roughness: 0.68, flatShading: true }),
channel: new THREE.MeshStandardMaterial({ color: 0x102e3c, roughness: 0.78, flatShading: true }),
gateFrame: new THREE.MeshStandardMaterial({ color: 0x567583, roughness: 0.64, flatShading: true }),
gateClosed: new THREE.MeshStandardMaterial({
color: 0xff8a55,
emissive: 0x401000,
emissiveIntensity: 0.7,
roughness: 0.55,
flatShading: true
}),
gateOpen: new THREE.MeshStandardMaterial({
color: 0x62e6a7,
emissive: 0x0d5734,
emissiveIntensity: 0.8,
roughness: 0.5,
flatShading: true
}),
glass: new THREE.MeshStandardMaterial({
color: 0x8ae7ff,
transparent: true,
opacity: 0.11,
roughness: 0.18,
metalness: 0.05,
depthWrite: false
})
};
const waterMaterials = [
new THREE.MeshStandardMaterial({
color: 0x32c9ef,
emissive: 0x063c58,
emissiveIntensity: 0.65,
roughness: 0.32,
metalness: 0.04,
transparent: true,
opacity: 0.91,
flatShading: true
}),
new THREE.MeshStandardMaterial({
color: 0x57def4,
emissive: 0x07465e,
emissiveIntensity: 0.55,
roughness: 0.35,
metalness: 0.03,
transparent: true,
opacity: 0.91,
flatShading: true
}),
new THREE.MeshStandardMaterial({
color: 0x20a9df,
emissive: 0x04364f,
emissiveIntensity: 0.65,
roughness: 0.34,
metalness: 0.04,
transparent: true,
opacity: 0.92,
flatShading: true
})
];
const waterGeometry = new THREE.BoxGeometry(1.48, 0.62, 2.48);
function box(parent, width, height, depth, x, y, z, material, cast = true) {
const mesh = new THREE.Mesh(
new THREE.BoxGeometry(width, height, depth),
material
);
mesh.position.set(x, y, z);
mesh.castShadow = cast;
mesh.receiveShadow = true;
parent.add(mesh);
return mesh;
}
// Ground and grid.
box(scene, 25, 0.5, 13, 0, -0.28, 0, materials.ground);
box(scene, 25.2, 0.16, 13.2, 0, -0.04, 0, materials.groundEdge);
const gridPoints = [];
for (let x = -12; x <= 12; x += 1) {
gridPoints.push(x, 0.055, -6.2, x, 0.055, 6.2);
}
for (let z = -6; z <= 6; z += 1) {
gridPoints.push(-12, 0.055, z, 12, 0.055, z);
}
const gridGeometry = new THREE.BufferGeometry();
gridGeometry.setAttribute("position", new THREE.Float32BufferAttribute(gridPoints, 3));
const grid = new THREE.LineSegments(
gridGeometry,
new THREE.LineBasicMaterial({ color: 0x285061, transparent: true, opacity: 0.28 })
);
scene.add(grid);
// Decorative voxel terrain.
const sceneryMaterial = new THREE.MeshStandardMaterial({
color: 0x12303d,
roughness: 0.95,
flatShading: true
});
const sceneryMaterial2 = new THREE.MeshStandardMaterial({
color: 0x193a48,
roughness: 0.95,
flatShading: true
});
const scenery = [
[-11.7, 0.7, -4.4, 1.8, 1.4, 1.8],
[-10.6, 1.6, -4.9, 1.2, 1.0, 1.2],
[-11.2, 2.3, -4.4, 0.7, 0.7, 0.7],
[10.9, 0.8, -4.7, 1.6, 1.6, 1.6],
[10.1, 1.8, -4.5, 1.0, 1.0, 1.0],
[10.6, 2.5, -4.7, 0.6, 0.6, 0.6],
[-5.4, 0.45, -4.9, 2.4, 0.9, 1.0],
[4.7, 0.6, -4.8, 2.8, 1.2, 1.0]
];
scenery.forEach((p, i) => {
box(
scene, p[3], p[4], p[5], p[0], p[1], p[2],
i % 2 ? sceneryMaterial2 : sceneryMaterial
);
});
// -------------------------------------------------------------------------
// Canvas sprite labels, implemented without external renderers or addons.
// -------------------------------------------------------------------------
function createLabel(width = 512, height = 128) {
const labelCanvas = document.createElement("canvas");
labelCanvas.width = width;
labelCanvas.height = height;
const context = labelCanvas.getContext("2d");
const texture = new THREE.CanvasTexture(labelCanvas);
texture.colorSpace = THREE.SRGBColorSpace;
texture.minFilter = THREE.LinearFilter;
const material = new THREE.SpriteMaterial({
map: texture,
transparent: true,
depthTest: false,
depthWrite: false
});
const sprite = new THREE.Sprite(material);
sprite.userData.canvas = labelCanvas;
sprite.userData.context = context;
sprite.userData.texture = texture;
sprite.renderOrder = 20;
return sprite;
}
function setLabel(sprite, top, bottom = "", accent = "#53d7f5") {
const context = sprite.userData.context;
const canvas = sprite.userData.canvas;
const w = canvas.width;
const h = canvas.height;
context.clearRect(0, 0, w, h);
context.fillStyle = "rgba(6, 20, 29, 0.90)";
context.fillRect(0, 0, w, h);
context.strokeStyle = accent;
context.lineWidth = 4;
context.strokeRect(2, 2, w - 4, h - 4);
context.textAlign = "center";
context.textBaseline = "middle";
context.fillStyle = accent;
context.font = "bold 30px monospace";
context.fillText(top, w / 2, bottom ? 40 : h / 2);
if (bottom) {
context.fillStyle = "#e8f7fb";
context.font = "bold 24px monospace";
context.fillText(bottom, w / 2, 91);
}
sprite.userData.texture.needsUpdate = true;
}
const tankVisuals = {};
function createTank(id, spec) {
const group = new THREE.Group();
group.position.x = spec.x;
scene.add(group);
const wallHeight = 5.45;
const wallThickness = 0.28;
const halfWidth = spec.width / 2;
const halfDepth = spec.depth / 2;
// Floor and dark back.
box(group, spec.width, 0.32, spec.depth, 0, 0.16, 0, materials.wallDark);
box(group, spec.width, wallHeight, wallThickness, 0, wallHeight / 2 + 0.28, -halfDepth + wallThickness / 2, materials.wall);
// Side walls.
box(group, wallThickness, wallHeight, spec.depth, -halfWidth + wallThickness / 2, wallHeight / 2 + 0.28, 0, materials.wall);
box(group, wallThickness, wallHeight, spec.depth, halfWidth - wallThickness / 2, wallHeight / 2 + 0.28, 0, materials.wall);
// Transparent front pane.
const glass = box(
group,
spec.width - 0.1,
wallHeight - 0.15,
0.08,
0,
wallHeight / 2 + 0.28,
halfDepth - 0.04,
materials.glass,
false
);
glass.renderOrder = 3;
// Voxel corner posts and top rails.
[-1, 1].forEach(sx => {
[-1, 1].forEach(sz => {
box(
group,
0.38,
wallHeight + 0.12,
0.38,
sx * (halfWidth - 0.18),
wallHeight / 2 + 0.28,
sz * (halfDepth - 0.18),
materials.trim
);
});
});
box(group, spec.width, 0.22, 0.22, 0, wallHeight + 0.35, halfDepth - 0.14, materials.trim);
box(group, spec.width, 0.22, 0.22, 0, wallHeight + 0.35, -halfDepth + 0.14, materials.trim);
// Capacity ticks on the left front edge.
for (let i = 1; i <= 6; i++) {
const tick = box(
group,
0.25,
0.055,
0.10,
-halfWidth + 0.16,
0.43 + (i - 1) * 0.70,
halfDepth + 0.02,
materials.trim,
false
);
tick.castShadow = false;
}
const waterGroup = new THREE.Group();
group.add(waterGroup);
const label = createLabel();
label.position.set(0, 6.12, 0);
label.scale.set(4.35, 1.09, 1);
group.add(label);
tankVisuals[id] = {
group,
waterGroup,
label,
spec
};
}
Object.entries(tankSpecs).forEach(([id, spec]) => createTank(id, spec));
// -------------------------------------------------------------------------
// Connected channels and physical gate panels.
// -------------------------------------------------------------------------
const gateVisuals = [];
const interactiveGateMeshes = [];
function createGate(path, index) {
const from = tankSpecs[path.from];
const to = tankSpecs[path.to];
const fromEdge = from.x + from.width / 2;
const toEdge = to.x - to.width / 2;
const gap = toEdge - fromEdge;
const midpoint = (fromEdge + toEdge) / 2;
box(scene, gap + 0.12, 0.26, 2.45, midpoint, 0.92, 0, materials.channel);
box(scene, gap + 0.12, 0.20, 0.16, midpoint, 1.10, 1.24, materials.trim);
box(scene, gap + 0.12, 0.20, 0.16, midpoint, 1.10, -1.24, materials.trim);
box(scene, 0.24, 3.15, 0.24, midpoint, 1.70, 1.38, materials.gateFrame);
box(scene, 0.24, 3.15, 0.24, midpoint, 1.70, -1.38, materials.gateFrame);
box(scene, 0.28, 0.25, 2.95, midpoint, 3.27, 0, materials.gateFrame);
const panelMaterial = materials.gateClosed.clone();
const panel = box(
scene,
0.20,
2.42,
2.58,
midpoint,
1.42,
0,
panelMaterial
);
panel.userData.gateIndex = index;
interactiveGateMeshes.push(panel);
// Small raised block details make the panel read as voxel construction.
for (let y = 0.55; y <= 2.35; y += 0.45) {
box(panel, 0.27, 0.13, 0.42, 0, y - 1.42, 0.73, materials.trim, false);
box(panel, 0.27, 0.13, 0.42, 0, y - 1.42, -0.73, materials.trim, false);
}
const label = createLabel(256, 96);
label.position.set(midpoint, 4.16, 0);
label.scale.set(1.50, 0.56, 1);
scene.add(label);
gateVisuals.push({
index,
panel,
material: panelMaterial,
label,
closedY: 1.42,
openY: 3.56
});
}
paths.forEach(createGate);
// -------------------------------------------------------------------------
// Water-level rendering. Two visible cubes represent one displayed level.
// Every cube still represents exactly one volume unit.
// -------------------------------------------------------------------------
function rebuildWater(id) {
const visual = tankVisuals[id];
const volume = state.volumes[id];
while (visual.waterGroup.children.length) {
visual.waterGroup.remove(visual.waterGroup.children[0]);
}
for (let i = 0; i < volume; i++) {
const layer = Math.floor(i / 2);
const column = i % 2;
const mesh = new THREE.Mesh(
waterGeometry,
waterMaterials[(i + layer + column) % waterMaterials.length]
);
mesh.position.set(
column === 0 ? -0.79 : 0.79,
0.57 + layer * 0.70,
0
);
mesh.receiveShadow = true;
visual.waterGroup.add(mesh);
}
}
// -------------------------------------------------------------------------
// Transfer animation
// -------------------------------------------------------------------------
const tweens = [];
function animateTransfer(path) {
return new Promise(resolve => {
const geometry = new THREE.BoxGeometry(0.54, 0.54, 0.54);
const material = new THREE.MeshStandardMaterial({
color: 0x8ceaff,
emissive: 0x1aa9d0,
emissiveIntensity: 1.5,
roughness: 0.25,
transparent: true,
opacity: 1
});
const mesh = new THREE.Mesh(geometry, material);
mesh.castShadow = true;
scene.add(mesh);
const startX = tankSpecs[path.from].x;
const endX = tankSpecs[path.to].x;
tweens.push({
start: performance.now(),
duration: 620,
startX,
endX,
mesh,
resolve
});
});
}
function updateTweens(now) {
for (let i = tweens.length - 1; i >= 0; i--) {
const tween = tweens[i];
const raw = Math.min(1, (now - tween.start) / tween.duration);
const eased = raw * raw * (3 - 2 * raw);
tween.mesh.position.x = THREE.MathUtils.lerp(tween.startX, tween.endX, eased);
tween.mesh.position.y = 1.35 + Math.sin(raw * Math.PI) * 0.72;
tween.mesh.rotation.x = raw * Math.PI * 2;
tween.mesh.rotation.y = raw * Math.PI * 2;
if (raw >= 1) {
scene.remove(tween.mesh);
tween.mesh.geometry.dispose();
tween.mesh.material.dispose();
tweens.splice(i, 1);
tween.resolve();
}
}
}
// -------------------------------------------------------------------------
// UI, validation, ledger, and puzzle state
// -------------------------------------------------------------------------
let toastTimer = 0;
function toast(message, type = "info") {
const element = $("toast");
element.textContent = message;
element.className = "show " + type;
clearTimeout(toastTimer);
toastTimer = setTimeout(() => {
element.className = "";
}, 2600);
}
function reject(message) {
state.rejected++;
toast("REJECTED — " + message, "reject");
}
function totalVolume() {
return Object.values(state.volumes).reduce((sum, value) => sum + value, 0);
}
function updateGoalCard(id, complete, text) {
const element = $(id);
element.classList.toggle("done", complete);
element.querySelector("b").textContent = text;
}
function refresh() {
const volumes = state.volumes;
for (const id of Object.keys(tankSpecs)) {
const value = volumes[id];
const cap = capacities[id];
$(id + "Value").textContent = `${value} / ${cap}`;
$(id + "Bar").style.width = `${(value / cap) * 100}%`;
rebuildWater(id);
setLabel(
tankVisuals[id].label,
tankSpecs[id].name,
`${value} / ${cap} BLOCKS`
);
}
const total = totalVolume();
$("total").textContent = `Σ ${total}`;
const invariant = $("invariant");
invariant.classList.toggle("bad", total !== INITIAL_TOTAL);
invariant.textContent = total === INITIAL_TOTAL
? `✓ Conservation verified: ${total} blocks remain`
: `✗ Conservation error: expected ${INITIAL_TOTAL}, found ${total}`;
gateVisuals.forEach((gate, index) => {
const isOpen = state.gates[index];
gate.panel.position.y = isOpen ? gate.openY : gate.closedY;
gate.material.color.setHex(isOpen ? 0x62e6a7 : 0xff8a55);
gate.material.emissive.setHex(isOpen ? 0x0d5734 : 0x401000);
setLabel(
gate.label,
`${"ABC"[index]} · ${isOpen ? "OPEN" : "CLOSED"}`,
"",
isOpen ? "#62e6a7" : "#ffc45d"
);
const card = $("card" + index);
card.classList.toggle("open", isOpen);
card.querySelector(".gate-state").textContent = isOpen ? "OPEN" : "CLOSED";
card.querySelector(".gate-btn").textContent = isOpen ? "Close gate" : "Open gate";
});
updateGoalCard("lowerGoal", volumes.lower === 8, `${volumes.lower} / 8`);
updateGoalCard("reservoirGoal", volumes.reservoir === 4, `${volumes.reservoir} / 4`);
updateGoalCard("upperGoal", volumes.upper === 0, `${volumes.upper} / 0`);
updateGoalCard("tailGoal", volumes.tail === 0, `${volumes.tail} / 0`);
renderLedger();
checkWin();
$("reset").disabled = state.busy;
}
function renderLedger() {
const rows = $("ledgerRows");
rows.innerHTML = "";
if (state.ledger.length === 0) {
rows.innerHTML = '<div class="ledger-empty">No transfers yet. Open Gate A to begin.</div>';
return;
}
state.ledger.slice().reverse().forEach(entry => {
const row = document.createElement("div");
row.className = "ledger-row";
row.innerHTML = `
<span class="num">${String(entry.number).padStart(2, "0")}</span>
<span class="route">${entry.route}</span>
<span>${entry.fromShort} ${entry.fromBefore}→${entry.fromAfter}</span>
<span>${entry.toShort} ${entry.toBefore}→${entry.toAfter}</span>
<span class="sum">Σ${entry.total}</span>
`;
rows.appendChild(row);
});
}
function toggleGate(index) {
if (state.busy) {
toast("Wait for the current block transfer to finish.", "reject");
return;
}
if (state.gates[index]) {
state.gates[index] = false;
refresh();
toast(`Gate ${"ABC"[index]} closed.`, "info");
return;
}
const openIndex = state.gates.findIndex(Boolean);
if (openIndex !== -1) {
reject(`safety interlock — close Gate ${"ABC"[openIndex]} before opening Gate ${"ABC"[index]}.`);
return;
}
state.gates[index] = true;
refresh();
toast(`Gate ${"ABC"[index]} open.`, "success");
}
async function transfer(index) {
if (state.busy) {
toast("A transfer is already in progress.", "reject");
return;
}
const path = paths[index];
if (!state.gates[index]) {
reject(`Gate ${"ABC"[index]} is closed. Open it before moving water.`);
return;
}
if (state.volumes[path.from] <= 0) {
reject(`${tankNames[path.from]} has no water available.`);
return;
}
if (state.volumes[path.to] >= capacities[path.to]) {
reject(`${tankNames[path.to]} is full (${capacities[path.to]}/${capacities[path.to]}).`);
return;
}
state.busy = true;
$("reset").disabled = true;
refresh();
const fromBefore = state.volumes[path.from];
const toBefore = state.volumes[path.to];
const totalBefore = totalVolume();
await animateTransfer(path);
state.volumes[path.from] -= 1;
state.volumes[path.to] += 1;
state.transfers++;
const totalAfter = totalVolume();
state.ledger.push({
number: state.transfers,
route: path.route,
fromShort: tankSpecs[path.from].short,
toShort: tankSpecs[path.to].short,
fromBefore,
fromAfter: state.volumes[path.from],
toBefore,
toAfter: state.volumes[path.to],
total: totalAfter
});
if (totalBefore !== totalAfter) {
console.error("Conservation invariant failed", { totalBefore, totalAfter });
}
state.busy = false;
refresh();
toast(`Moved 1 block: ${tankNames[path.from]} → ${tankNames[path.to]}.`, "success");
}
function checkWin() {
const v = state.volumes;
const complete =
v.lower === 8 &&
v.reservoir === 4 &&
v.upper === 0 &&
v.tail === 0;
if (complete && !state.won) {
state.won = true;
$("moveCount").textContent = state.transfers;
setTimeout(() => $("win").classList.add("show"), 450);
}
}
function resetPuzzle() {
if (state.busy) return;
state.volumes = {
reservoir: 12,
upper: 0,
lower: 0,
tail: 0
};
state.gates = [false, false, false];
state.ledger = [];
state.transfers = 0;
state.rejected = 0;
state.won = false;
$("win").classList.remove("show");
refresh();
toast("Puzzle reset. The reservoir is full again.", "info");
}
document.querySelectorAll("[data-gate-toggle]").forEach(button => {
button.addEventListener("click", () => {
toggleGate(Number(button.dataset.gateToggle));
});
});
document.querySelectorAll("[data-transfer]").forEach(button => {
button.addEventListener("click", () => {
transfer(Number(button.dataset.transfer));
});
});
$("reset").addEventListener("click", resetPuzzle);
$("playAgainBtn").addEventListener("click", resetPuzzle);
$("inspectBtn").addEventListener("click", () => $("win").classList.remove("show"));
window.addEventListener("keydown", event => {
if ($("win").classList.contains("show")) return;
if (event.ctrlKey || event.metaKey || event.altKey) return;
const gateKeys = { "1": 0, "2": 1, "3": 2 };
const transferKeys = { q: 0, w: 1, e: 2 };
const key = event.key.toLowerCase();
if (key in gateKeys) {
event.preventDefault();
toggleGate(gateKeys[key]);
} else if (key in transferKeys) {
event.preventDefault();
transfer(transferKeys[key]);
}
});
// -------------------------------------------------------------------------
// Direct camera controls: orbit, zoom, and clickable gate panels.
// -------------------------------------------------------------------------
function updateCamera() {
const sinPhi = Math.sin(cameraPhi);
camera.position.set(
cameraTarget.x + cameraRadius * sinPhi * Math.sin(cameraTheta),
cameraTarget.y + cameraRadius * Math.cos(cameraPhi),
cameraTarget.z + cameraRadius * sinPhi * Math.cos(cameraTheta)
);
camera.lookAt(cameraTarget);
camera.zoom = cameraZoom;
camera.updateProjectionMatrix();
}
function resize() {
const width = window.innerWidth;
const height = window.innerHeight;
renderer.setSize(width, height);
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
const aspect = width / height;
const halfHeight = Math.max(7.4, 11.8 / aspect);
camera.left = -halfHeight * aspect;
camera.right = halfHeight * aspect;
camera.top = halfHeight;
camera.bottom = -halfHeight;
updateCamera();
}
window.addEventListener("resize", resize);
const pointer = {
down: false,
x: 0,
y: 0,
startX: 0,
startY: 0,
moved: false
};
const raycaster = new THREE.Raycaster();
const mouse = new THREE.Vector2();
canvas.addEventListener("pointerdown", event => {
pointer.down = true;
pointer.x = event.clientX;
pointer.y = event.clientY;
pointer.startX = event.clientX;
pointer.startY = event.clientY;
pointer.moved = false;
canvas.setPointerCapture(event.pointerId);
});
canvas.addEventListener("pointermove", event => {
if (!pointer.down) return;
const dx = event.clientX - pointer.x;
const dy = event.clientY - pointer.y;
if (Math.abs(event.clientX - pointer.startX) + Math.abs(event.clientY - pointer.startY) > 5) {
pointer.moved = true;
}
cameraTheta -= dx * 0.006;
cameraPhi = THREE.MathUtils.clamp(cameraPhi - dy * 0.005, 0.48, 1.42);
pointer.x = event.clientX;
pointer.y = event.clientY;
updateCamera();
});
canvas.addEventListener("pointerup", event => {
if (!pointer.down) return;
pointer.down = false;
if (!pointer.moved) {
const rect = canvas.getBoundingClientRect();
mouse.x = ((event.clientX - rect.left) / rect.width) * 2 - 1;
mouse.y = -((event.clientY - rect.top) / rect.height) * 2 + 1;
raycaster.setFromCamera(mouse, camera);
const hits = raycaster.intersectObjects(interactiveGateMeshes, false);
if (hits.length) {
toggleGate(hits[0].object.userData.gateIndex);
}
}
});
canvas.addEventListener("pointercancel", () => {
pointer.down = false;
});
canvas.addEventListener("wheel", event => {
event.preventDefault();
cameraZoom = THREE.MathUtils.clamp(
cameraZoom * Math.exp(-event.deltaY * 0.001),
0.68,
1.8
);
updateCamera();
}, { passive: false });
// -------------------------------------------------------------------------
// Start
// -------------------------------------------------------------------------
resize();
refresh();
renderer.setAnimationLoop(now => {
updateTweens(now);
renderer.render(scene, camera);
});
</script>
</body>
</html>
```