Prompt specification
Build or customize the Three.js 3D scene "Equalizing Tank Platform" 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: Equalizing Tank Platform
Category: Games & Play · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/equalizing-tank-platform-x3518
Scene Description Prompt:
Open a gate between equal-footprint low-poly tanks; conserve water volume as levels equalize. Three.js from cdnjs, one HTML file.
Working Three.js Starter (equalizing-tank-platform-x3518):
```html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Gate Equalizer — Three.js Fluid Simulation</title>
<style>
:root {
color-scheme: dark;
--panel: rgba(13, 28, 34, 0.88);
--panel-border: rgba(255, 255, 255, 0.12);
--text: #eef8f7;
--muted: #91a8aa;
--cyan: #53d8e8;
--cyan-dark: #167f91;
--orange: #ff9b52;
--green: #72e6a8;
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: #dce7e8;
font-family:
Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
#scene {
position: fixed;
inset: 0;
}
#scene canvas {
display: block;
width: 100%;
height: 100%;
touch-action: none;
outline: none;
}
#hud {
position: fixed;
inset: 0;
pointer-events: none;
color: var(--text);
}
.glass {
background: var(--panel);
border: 1px solid var(--panel-border);
box-shadow: 0 18px 55px rgba(14, 35, 39, 0.18);
backdrop-filter: blur(16px);
-webkit-backdrop-filter: blur(16px);
}
.brand {
position: absolute;
top: 22px;
left: 22px;
width: 285px;
padding: 18px 19px;
border-radius: 18px;
}
.eyebrow {
color: var(--cyan);
font-size: 10px;
font-weight: 800;
letter-spacing: 0.2em;
text-transform: uppercase;
}
h1 {
margin: 5px 0 4px;
font-size: 25px;
line-height: 1.05;
letter-spacing: -0.035em;
}
.brand p {
margin: 0;
color: var(--muted);
font-size: 12px;
line-height: 1.45;
}
.metrics {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 8px;
margin-top: 14px;
padding-top: 13px;
border-top: 1px solid rgba(255, 255, 255, 0.1);
}
.metric span {
display: block;
color: var(--muted);
font-size: 9px;
font-weight: 700;
letter-spacing: 0.11em;
text-transform: uppercase;
}
.metric strong {
display: block;
margin-top: 3px;
font-size: 15px;
font-variant-numeric: tabular-nums;
}
.metric strong em {
color: var(--muted);
font-size: 10px;
font-style: normal;
font-weight: 600;
}
.readouts {
position: absolute;
top: 22px;
left: 50%;
display: flex;
gap: 9px;
transform: translateX(-50%);
}
.readout {
width: 145px;
padding: 12px 14px;
border-radius: 15px;
}
.readout .label {
display: flex;
align-items: center;
gap: 7px;
color: var(--muted);
font-size: 10px;
font-weight: 800;
letter-spacing: 0.12em;
}
.readout .dot {
width: 7px;
height: 7px;
border-radius: 50%;
background: var(--cyan);
box-shadow: 0 0 12px var(--cyan);
}
.readout.b .dot {
background: var(--orange);
box-shadow: 0 0 12px var(--orange);
}
.readout .level {
display: block;
margin-top: 5px;
font-size: 21px;
font-weight: 750;
font-variant-numeric: tabular-nums;
}
.readout .volume {
color: var(--muted);
font-size: 10px;
font-variant-numeric: tabular-nums;
}
.controls {
position: absolute;
bottom: 22px;
left: 50%;
width: min(820px, calc(100vw - 32px));
padding: 16px 18px;
border-radius: 19px;
transform: translateX(-50%);
pointer-events: auto;
}
.control-top {
display: flex;
align-items: center;
justify-content: space-between;
gap: 16px;
margin-bottom: 12px;
}
.control-title {
display: flex;
align-items: baseline;
gap: 9px;
min-width: 190px;
}
.control-title span {
color: var(--muted);
font-size: 11px;
font-weight: 700;
letter-spacing: 0.06em;
text-transform: uppercase;
}
.control-title strong {
font-size: 17px;
font-variant-numeric: tabular-nums;
}
.status {
display: flex;
align-items: center;
gap: 8px;
min-width: 170px;
justify-content: flex-end;
color: var(--muted);
font-size: 11px;
font-weight: 700;
}
.status::before {
width: 8px;
height: 8px;
border-radius: 50%;
background: #7f9294;
content: "";
}
.status.active::before {
background: var(--orange);
box-shadow: 0 0 12px var(--orange);
}
.status.balanced::before {
background: var(--green);
box-shadow: 0 0 12px var(--green);
}
.control-main {
display: grid;
grid-template-columns: minmax(180px, 1fr) auto;
align-items: center;
gap: 18px;
}
.slider-wrap {
display: grid;
grid-template-columns: 1fr auto;
align-items: center;
gap: 11px;
}
input[type="range"] {
width: 100%;
height: 5px;
margin: 0;
appearance: none;
border-radius: 99px;
outline: none;
background:
linear-gradient(
to right,
var(--cyan) 0%,
var(--cyan) var(--fill, 0%),
rgba(255, 255, 255, 0.15) var(--fill, 0%),
rgba(255, 255, 255, 0.15) 100%
);
cursor: pointer;
}
input[type="range"]::-webkit-slider-thumb {
width: 17px;
height: 17px;
appearance: none;
border: 3px solid #16383f;
border-radius: 50%;
background: var(--cyan);
box-shadow: 0 0 0 1px var(--cyan);
}
input[type="range"]::-moz-range-thumb {
width: 12px;
height: 12px;
border: 3px solid #16383f;
border-radius: 50%;
background: var(--cyan);
box-shadow: 0 0 0 1px var(--cyan);
}
.flow {
width: 120px;
color: var(--muted);
font-size: 10px;
line-height: 1.35;
text-align: right;
font-variant-numeric: tabular-nums;
}
.flow strong {
display: block;
color: var(--text);
font-size: 12px;
}
.buttons {
display: flex;
gap: 7px;
}
button {
min-height: 39px;
padding: 0 14px;
border: 1px solid rgba(255, 255, 255, 0.13);
border-radius: 10px;
color: var(--text);
background: rgba(255, 255, 255, 0.08);
font: inherit;
font-size: 11px;
font-weight: 750;
cursor: pointer;
transition:
transform 120ms ease,
background 120ms ease,
border-color 120ms ease;
}
button:hover {
transform: translateY(-1px);
border-color: rgba(255, 255, 255, 0.27);
background: rgba(255, 255, 255, 0.13);
}
button:active {
transform: translateY(0);
}
button.primary {
min-width: 105px;
border-color: transparent;
color: #08272d;
background: var(--cyan);
}
button.primary:hover {
background: #79e8f1;
}
.control-note {
display: flex;
justify-content: space-between;
gap: 12px;
margin-top: 11px;
padding-top: 10px;
border-top: 1px solid rgba(255, 255, 255, 0.09);
color: var(--muted);
font-size: 9px;
line-height: 1.4;
}
.control-note code {
color: #b8cbcd;
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
}
.tank-tag,
.gate-tag {
position: absolute;
top: 0;
left: 0;
transform: translate(-50%, -50%);
white-space: nowrap;
pointer-events: none;
transition: opacity 120ms linear;
}
.tank-tag {
padding: 7px 10px;
border: 1px solid rgba(255, 255, 255, 0.23);
border-radius: 10px;
color: #10272d;
background: rgba(239, 249, 249, 0.88);
box-shadow: 0 8px 25px rgba(10, 30, 35, 0.14);
font-size: 10px;
font-weight: 800;
letter-spacing: 0.06em;
}
.tank-tag span {
display: block;
margin-top: 2px;
color: #577176;
font-size: 9px;
font-weight: 650;
letter-spacing: 0;
font-variant-numeric: tabular-nums;
}
.gate-tag {
padding: 5px 8px;
border: 1px solid rgba(255, 155, 82, 0.45);
border-radius: 8px;
color: #ffe1c9;
background: rgba(69, 37, 25, 0.82);
font-size: 9px;
font-weight: 800;
letter-spacing: 0.11em;
text-transform: uppercase;
}
.hint {
position: absolute;
bottom: 24px;
left: 22px;
color: rgba(22, 49, 55, 0.72);
font-size: 10px;
font-weight: 700;
letter-spacing: 0.03em;
}
@media (max-width: 920px) {
.readouts {
top: auto;
bottom: 151px;
}
.hint {
display: none;
}
}
@media (max-width: 700px) {
.brand {
top: 12px;
left: 12px;
width: 230px;
padding: 13px 14px;
}
h1 {
font-size: 20px;
}
.brand p,
.metrics {
display: none;
}
.readouts {
display: none;
}
.controls {
bottom: 12px;
padding: 13px;
}
.control-top {
margin-bottom: 9px;
}
.control-main {
grid-template-columns: 1fr;
gap: 11px;
}
.flow {
width: auto;
text-align: left;
}
.buttons {
justify-content: stretch;
}
.buttons button {
flex: 1;
padding: 0 8px;
}
.control-note {
display: none;
}
}
</style>
</head>
<body>
<div id="scene"></div>
<div id="hud">
<section class="brand glass">
<div class="eyebrow">Fluid Dynamics Lab</div>
<h1>Gate Equalizer</h1>
<p>Two equal-footprint tanks. One conserved water volume.</p>
<div class="metrics">
<div class="metric">
<span>Total volume</span>
<strong id="totalVolume">30.80 <em>m³</em></strong>
</div>
<div class="metric">
<span>Conservation error</span>
<strong id="volumeError">0.000 <em>m³</em></strong>
</div>
</div>
</section>
<section class="readouts">
<div class="readout glass">
<div class="label"><i class="dot"></i> TANK A</div>
<span class="level" id="levelA">2.35 m</span>
<span class="volume" id="volumeA">23.35 m³</span>
</div>
<div class="readout b glass">
<div class="label"><i class="dot"></i> TANK B</div>
<span class="level" id="levelB">0.75 m</span>
<span class="volume" id="volumeB">7.45 m³</span>
</div>
</section>
<div id="tagA" class="tank-tag">
TANK A
<span id="tagAValue">2.35 m · 23.35 m³</span>
</div>
<div id="tagB" class="tank-tag">
TANK B
<span id="tagBValue">0.75 m · 7.45 m³</span>
</div>
<div id="gateTag" class="gate-tag">Sluice gate</div>
<section class="controls glass">
<div class="control-top">
<div class="control-title">
<span>Gate aperture</span>
<strong id="gateValue">0%</strong>
</div>
<div id="status" class="status">Gate closed</div>
</div>
<div class="control-main">
<div class="slider-wrap">
<input
id="gateSlider"
type="range"
min="0"
max="100"
step="1"
value="0"
aria-label="Gate aperture"
>
<div class="flow">
<strong id="flowRate">0.00 m³/s</strong>
<span id="flowDirection">No flow</span>
</div>
</div>
<div class="buttons">
<button id="openButton" class="primary" type="button">Open gate</button>
<button id="resetButton" type="button">Reset water</button>
<button id="speedButton" type="button">1×</button>
</div>
</div>
<div class="control-note">
<span>Drag to orbit · Scroll to zoom · Double-click to reset view</span>
<code>Q = C<sub>d</sub>A√(2gΔh)</code>
</div>
</section>
<div class="hint">CAMERA: DRAG TO ORBIT · SCROLL TO ZOOM</div>
</div>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
// ------------------------------------------------------------
// Scene and renderer
// ------------------------------------------------------------
const sceneHost = document.querySelector("#scene");
const renderer = new THREE.WebGLRenderer({
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.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.domElement.setAttribute(
"aria-label",
"Interactive equalization simulation between two water tanks"
);
sceneHost.appendChild(renderer.domElement);
const scene = new THREE.Scene();
scene.background = new THREE.Color(0xdce7e8);
scene.fog = new THREE.Fog(0xdce7e8, 15, 34);
const camera = new THREE.PerspectiveCamera(
42,
window.innerWidth / window.innerHeight,
0.1,
100
);
const cameraTarget = new THREE.Vector3(0, 1.25, 0);
const cameraState = {
yaw: 0.68,
pitch: 0.48,
radius: 11.8
};
const hemisphere = new THREE.HemisphereLight(
0xf4ffff,
0x52666c,
2.15
);
scene.add(hemisphere);
const sun = new THREE.DirectionalLight(0xfff7e8, 3.0);
sun.position.set(5.5, 10, 7);
sun.castShadow = true;
sun.shadow.mapSize.set(2048, 2048);
sun.shadow.camera.left = -10;
sun.shadow.camera.right = 10;
sun.shadow.camera.top = 10;
sun.shadow.camera.bottom = -10;
sun.shadow.camera.near = 0.5;
sun.shadow.camera.far = 30;
sun.shadow.normalBias = 0.035;
scene.add(sun);
const rimLight = new THREE.DirectionalLight(0x8bd9ee, 1.0);
rimLight.position.set(-7, 4, -6);
scene.add(rimLight);
// ------------------------------------------------------------
// Geometry constants, all in metres
// ------------------------------------------------------------
const TANK_WIDTH = 3.6;
const TANK_DEPTH = 3.2;
const TANK_HEIGHT = 3.2;
const WALL_THICKNESS = 0.16;
const DIVIDER_THICKNESS = 0.18;
const FLOOR_TOP = 0.12;
const LEFT_CENTER = -1.9;
const RIGHT_CENTER = 1.9;
// Equal interior footprint for both tanks.
const INNER_WIDTH = 3.45;
const INNER_DEPTH = 2.88;
const FOOTPRINT_AREA = INNER_WIDTH * INNER_DEPTH;
const INITIAL_HEIGHT_A = 2.35;
const INITIAL_HEIGHT_B = 0.75;
const TOTAL_VOLUME =
FOOTPRINT_AREA * (INITIAL_HEIGHT_A + INITIAL_HEIGHT_B);
const GATE_SILL = FLOOR_TOP;
const GATE_OPEN_HEIGHT = 0.72;
const GATE_OPEN_WIDTH = 0.8;
const GATE_PANEL_HEIGHT = GATE_OPEN_HEIGHT + 0.06;
const GRAVITY = 9.81;
const DISCHARGE_COEFFICIENT = 0.62;
let volumeA = FOOTPRINT_AREA * INITIAL_HEIGHT_A;
let targetOpening = 0;
let actualOpening = 0;
let simulationSpeed = 1;
let simulationTime = 0;
let currentFlow = 0;
let flowSign = 0;
// ------------------------------------------------------------
// Materials
// ------------------------------------------------------------
function standardMaterial(color, options = {}) {
return new THREE.MeshStandardMaterial({
color,
roughness: 0.78,
metalness: 0.02,
flatShading: true,
...options
});
}
const concreteMaterial = standardMaterial(0xb8c5c4);
const floorMaterial = standardMaterial(0x9eafae);
const rimMaterial = standardMaterial(0x536b70);
const dividerMaterial = standardMaterial(0x9eaeae);
const gateMaterial = standardMaterial(0xf07d3f, {
roughness: 0.52,
metalness: 0.18
});
const railMaterial = standardMaterial(0x33494f, {
roughness: 0.45,
metalness: 0.48
});
const darkMaterial = standardMaterial(0x10252a, {
roughness: 1
});
const frontGlassMaterial = standardMaterial(0x91c3ca, {
transparent: true,
opacity: 0.14,
depthWrite: false,
side: THREE.DoubleSide,
roughness: 0.25
});
const waterBodyMaterial = standardMaterial(0x168eae, {
transparent: true,
opacity: 0.38,
depthWrite: false,
side: THREE.DoubleSide,
roughness: 0.25
});
const waterSurfaceMaterial = standardMaterial(0x35b9cf, {
roughness: 0.22,
metalness: 0.06,
side: THREE.DoubleSide
});
const edgeMaterial = new THREE.LineBasicMaterial({
color: 0x304b52,
transparent: true,
opacity: 0.28
});
// ------------------------------------------------------------
// Geometry helpers
// ------------------------------------------------------------
function addBox(width, height, depth, material, x, y, z, parent = scene) {
const mesh = new THREE.Mesh(
new THREE.BoxGeometry(width, height, depth),
material
);
mesh.position.set(x, y, z);
mesh.castShadow = !material.transparent;
mesh.receiveShadow = true;
parent.add(mesh);
return mesh;
}
function addEdges(mesh, opacity = 0.28) {
const material = edgeMaterial.clone();
material.opacity = opacity;
const edges = new THREE.LineSegments(
new THREE.EdgesGeometry(mesh.geometry),
material
);
mesh.add(edges);
return edges;
}
const ground = new THREE.Mesh(
new THREE.PlaneGeometry(40, 40),
standardMaterial(0xc9d5d5, { roughness: 1 })
);
ground.rotation.x = -Math.PI / 2;
ground.position.y = -0.15;
ground.receiveShadow = true;
scene.add(ground);
const platform = addBox(
8.35,
0.14,
4.15,
standardMaterial(0xaab9b8),
0,
-0.07,
0
);
addEdges(platform, 0.18);
// ------------------------------------------------------------
// Tank construction
// ------------------------------------------------------------
function buildTank(centerX, isLeft) {
const floor = addBox(
TANK_WIDTH,
FLOOR_TOP,
TANK_DEPTH,
floorMaterial,
centerX,
FLOOR_TOP / 2,
0
);
addEdges(floor);
const outerSideX = isLeft
? centerX - TANK_WIDTH / 2 + WALL_THICKNESS / 2
: centerX + TANK_WIDTH / 2 - WALL_THICKNESS / 2;
const side = addBox(
WALL_THICKNESS,
TANK_HEIGHT,
TANK_DEPTH,
concreteMaterial,
outerSideX,
TANK_HEIGHT / 2,
0
);
addEdges(side);
const back = addBox(
TANK_WIDTH,
TANK_HEIGHT,
WALL_THICKNESS,
concreteMaterial,
centerX,
TANK_HEIGHT / 2,
-TANK_DEPTH / 2 + WALL_THICKNESS / 2
);
addEdges(back);
const front = addBox(
TANK_WIDTH,
TANK_HEIGHT,
WALL_THICKNESS,
frontGlassMaterial,
centerX,
TANK_HEIGHT / 2,
TANK_DEPTH / 2 - WALL_THICKNESS / 2
);
front.castShadow = false;
front.renderOrder = 4;
addEdges(front, 0.42);
const frontRim = addBox(
TANK_WIDTH + 0.06,
0.1,
0.13,
rimMaterial,
centerX,
TANK_HEIGHT,
TANK_DEPTH / 2 - 0.055
);
addEdges(frontRim, 0.18);
const backRim = addBox(
TANK_WIDTH + 0.06,
0.1,
0.13,
rimMaterial,
centerX,
TANK_HEIGHT,
-TANK_DEPTH / 2 + 0.055
);
addEdges(backRim, 0.18);
const sideRim = addBox(
0.13,
0.1,
TANK_DEPTH,
rimMaterial,
outerSideX,
TANK_HEIGHT,
0
);
addEdges(sideRim, 0.18);
}
buildTank(LEFT_CENTER, true);
buildTank(RIGHT_CENTER, false);
// Shared divider with a real rectangular opening.
const apertureTop = GATE_SILL + GATE_OPEN_HEIGHT;
const dividerSill = addBox(
DIVIDER_THICKNESS,
GATE_SILL,
TANK_DEPTH,
dividerMaterial,
0,
GATE_SILL / 2,
0
);
addEdges(dividerSill);
const dividerLintel = addBox(
DIVIDER_THICKNESS,
TANK_HEIGHT - apertureTop,
TANK_DEPTH,
dividerMaterial,
0,
(TANK_HEIGHT + apertureTop) / 2,
0
);
addEdges(dividerLintel);
const pierDepth = (TANK_DEPTH - GATE_OPEN_WIDTH) / 2;
const pierCenterZ = GATE_OPEN_WIDTH / 2 + pierDepth / 2;
for (const z of [-pierCenterZ, pierCenterZ]) {
const pier = addBox(
DIVIDER_THICKNESS,
GATE_OPEN_HEIGHT,
pierDepth,
dividerMaterial,
0,
GATE_SILL + GATE_OPEN_HEIGHT / 2,
z
);
addEdges(pier);
}
// Dark backing makes the sluice opening easy to read.
addBox(
0.018,
GATE_OPEN_HEIGHT,
GATE_OPEN_WIDTH,
darkMaterial,
-0.1,
GATE_SILL + GATE_OPEN_HEIGHT / 2,
0
);
const dividerCap = addBox(
0.24,
0.11,
TANK_DEPTH,
rimMaterial,
0,
TANK_HEIGHT,
0
);
addEdges(dividerCap, 0.18);
// Gate panel and handle move vertically.
const gateGroup = new THREE.Group();
scene.add(gateGroup);
const gatePanel = addBox(
0.12,
GATE_PANEL_HEIGHT,
GATE_OPEN_WIDTH,
gateMaterial,
0,
0,
0,
gateGroup
);
addEdges(gatePanel, 0.5);
const gateHandle = addBox(
0.22,
0.075,
0.34,
railMaterial,
0.13,
-0.2,
0,
gateGroup
);
addEdges(gateHandle, 0.2);
// Guide rails and top crossbar.
for (const z of [
-GATE_OPEN_WIDTH / 2 - 0.075,
GATE_OPEN_WIDTH / 2 + 0.075
]) {
addBox(
0.08,
1.72,
0.08,
railMaterial,
0.145,
GATE_SILL + 0.86,
z
);
}
addBox(
0.08,
0.08,
GATE_OPEN_WIDTH + 0.3,
railMaterial,
0.145,
GATE_SILL + 1.72,
0
);
// ------------------------------------------------------------
// Water meshes
// ------------------------------------------------------------
function createWater(centerX) {
const body = new THREE.Mesh(
new THREE.BoxGeometry(1, 1, 1),
waterBodyMaterial
);
body.position.x = centerX;
body.scale.set(INNER_WIDTH, 1, INNER_DEPTH);
body.renderOrder = 1;
scene.add(body);
const geometry = new THREE.PlaneGeometry(
INNER_WIDTH,
INNER_DEPTH,
8,
6
);
geometry.rotateX(-Math.PI / 2);
const surface = new THREE.Mesh(geometry, waterSurfaceMaterial);
surface.position.x = centerX;
surface.receiveShadow = true;
surface.renderOrder = 2;
scene.add(surface);
return {
body,
surface,
basePositions: geometry.attributes.position.array.slice()
};
}
const waterA = createWater(LEFT_CENTER);
const waterB = createWater(RIGHT_CENTER);
// ------------------------------------------------------------
// Flow indicators
// ------------------------------------------------------------
const flowMaterial = new THREE.MeshBasicMaterial({
color: 0xb9f8ff,
transparent: true,
opacity: 0,
depthTest: false,
depthWrite: false
});
const flowArrow = new THREE.Mesh(
new THREE.ConeGeometry(0.085, 0.22, 6),
flowMaterial
);
flowArrow.position.set(0, GATE_SILL + 0.42, 0);
flowArrow.renderOrder = 8;
scene.add(flowArrow);
const particles = [];
const particleGeometry = new THREE.TetrahedronGeometry(0.045, 0);
for (let i = 0; i < 16; i++) {
const material = flowMaterial.clone();
const particle = new THREE.Mesh(particleGeometry, material);
particle.renderOrder = 7;
scene.add(particle);
particles.push({
mesh: particle,
phase: i / 16,
ySeed: (i * 0.61803398875) % 1,
zSeed: (i * 0.41421356237) % 1,
spin: i * 0.71
});
}
// ------------------------------------------------------------
// Direct camera controls — no addon imports
// ------------------------------------------------------------
function updateCamera() {
const { yaw, pitch, radius } = cameraState;
const horizontal = Math.cos(pitch) * radius;
camera.position.set(
cameraTarget.x + Math.sin(yaw) * horizontal,
cameraTarget.y + Math.sin(pitch) * radius,
cameraTarget.z + Math.cos(yaw) * horizontal
);
camera.lookAt(cameraTarget);
}
function resetCamera() {
cameraState.yaw = 0.68;
cameraState.pitch = 0.48;
cameraState.radius = 11.8;
}
let dragging = false;
let pointerX = 0;
let pointerY = 0;
renderer.domElement.addEventListener("pointerdown", event => {
if (event.button !== 0) return;
dragging = true;
pointerX = event.clientX;
pointerY = event.clientY;
renderer.domElement.setPointerCapture(event.pointerId);
renderer.domElement.style.cursor = "grabbing";
});
renderer.domElement.addEventListener("pointermove", event => {
if (!dragging) return;
const dx = event.clientX - pointerX;
const dy = event.clientY - pointerY;
pointerX = event.clientX;
pointerY = event.clientY;
cameraState.yaw -= dx * 0.006;
cameraState.pitch = THREE.MathUtils.clamp(
cameraState.pitch + dy * 0.005,
0.18,
1.18
);
});
function endDrag(event) {
dragging = false;
renderer.domElement.style.cursor = "grab";
if (
event.pointerId !== undefined &&
renderer.domElement.hasPointerCapture(event.pointerId)
) {
renderer.domElement.releasePointerCapture(event.pointerId);
}
}
renderer.domElement.addEventListener("pointerup", endDrag);
renderer.domElement.addEventListener("pointercancel", endDrag);
renderer.domElement.addEventListener("contextmenu", event => {
event.preventDefault();
});
renderer.domElement.addEventListener("wheel", event => {
event.preventDefault();
cameraState.radius = THREE.MathUtils.clamp(
cameraState.radius * Math.exp(event.deltaY * 0.001),
6.8,
18
);
}, { passive: false });
renderer.domElement.addEventListener("dblclick", resetCamera);
renderer.domElement.style.cursor = "grab";
// ------------------------------------------------------------
// Physics
// ------------------------------------------------------------
function stepPhysics(dt) {
// Smoothly move the physical gate toward the requested aperture.
const openingLerp = 1 - Math.exp(-dt * 5.2);
actualOpening += (targetOpening - actualOpening) * openingLerp;
if (Math.abs(targetOpening - actualOpening) < 0.0001) {
actualOpening = targetOpening;
}
const heightA = volumeA / FOOTPRINT_AREA;
const heightB = (TOTAL_VOLUME - volumeA) / FOOTPRINT_AREA;
const headDifference = heightA - heightB;
if (Math.abs(headDifference) < 0.00003) {
volumeA = TOTAL_VOLUME / 2;
currentFlow = 0;
flowSign = 0;
return;
}
if (actualOpening <= 0.00001) {
currentFlow = 0;
flowSign = Math.sign(headDifference);
return;
}
const direction = Math.sign(headDifference);
const clearArea =
GATE_OPEN_WIDTH * GATE_OPEN_HEIGHT * actualOpening;
const flow =
DISCHARGE_COEFFICIENT *
clearArea *
Math.sqrt(2 * GRAVITY * Math.abs(headDifference));
let transferredVolume = flow * dt;
// Do not allow a numerical step to overshoot equilibrium.
const maximumTransfer =
FOOTPRINT_AREA * Math.abs(headDifference);
transferredVolume = Math.min(
transferredVolume,
maximumTransfer
);
volumeA -= direction * transferredVolume;
// The second volume is derived from the immutable total, so the
// total water volume remains conserved at every simulation step.
if (
maximumTransfer - transferredVolume < 0.000001 &&
Math.abs(headDifference) < 0.002
) {
volumeA = TOTAL_VOLUME / 2;
}
currentFlow = flow;
flowSign = direction;
}
// ------------------------------------------------------------
// Visual updates
// ------------------------------------------------------------
function updateWater(water, height) {
const safeHeight = Math.max(0.0001, height);
water.body.scale.y = safeHeight;
water.body.position.y = FLOOR_TOP + safeHeight / 2;
water.surface.position.y = FLOOR_TOP + safeHeight + 0.012;
const positions = water.surface.geometry.attributes.position;
const base = water.basePositions;
const waveAmplitude =
actualOpening > 0.001
? Math.min(0.065, 0.018 + Math.abs(currentFlow) * 0.022)
: 0;
for (let i = 0; i < positions.count; i++) {
const x = base[i * 3];
const z = base[i * 3 + 2];
const wave =
(Math.sin(x * 2.5 + simulationTime * 2.15) +
0.55 * Math.cos(z * 3.0 - simulationTime * 1.65)) *
waveAmplitude;
positions.setY(i, wave);
}
positions.needsUpdate = true;
water.surface.geometry.computeVertexNormals();
}
function updateGateVisual() {
gateGroup.position.y =
GATE_SILL +
GATE_OPEN_HEIGHT * actualOpening +
GATE_PANEL_HEIGHT / 2;
}
function updateFlowVisual() {
const visible =
actualOpening > 0.012 &&
currentFlow > 0.0005 &&
flowSign !== 0;
flowMaterial.opacity = visible
? Math.min(0.95, 0.35 + Math.abs(currentFlow) * 0.35)
: 0;
flowArrow.rotation.z = flowSign >= 0 ? -Math.PI / 2 : Math.PI / 2;
const clearHeight = GATE_OPEN_HEIGHT * actualOpening;
for (const particle of particles) {
if (!visible || clearHeight < 0.018) {
particle.mesh.visible = false;
continue;
}
particle.mesh.visible = true;
const phase = (particle.phase + simulationTime * 0.48) % 1;
const x = flowSign > 0
? THREE.MathUtils.lerp(-0.55, 0.55, phase)
: THREE.MathUtils.lerp(0.55, -0.55, phase);
const y =
GATE_SILL +
0.025 +
particle.ySeed * Math.max(0.01, clearHeight - 0.05);
const z =
(particle.zSeed - 0.5) * (GATE_OPEN_WIDTH - 0.14);
particle.mesh.position.set(x, y, z);
particle.mesh.rotation.set(
simulationTime * 2.1 + particle.spin,
simulationTime * 1.7 + particle.spin,
0
);
}
}
// ------------------------------------------------------------
// Screen-space labels
// ------------------------------------------------------------
const tagA = document.querySelector("#tagA");
const tagB = document.querySelector("#tagB");
const gateTag = document.querySelector("#gateTag");
function placeLabel(element, worldPosition) {
const projected = worldPosition.clone().project(camera);
const visible =
projected.z > -1 &&
projected.z < 1 &&
Math.abs(projected.x) < 1.2 &&
Math.abs(projected.y) < 1.2;
element.style.opacity = visible ? "1" : "0";
element.style.left =
`${(projected.x * 0.5 + 0.5) * window.innerWidth}px`;
element.style.top =
`${(-projected.y * 0.5 + 0.5) * window.innerHeight}px`;
}
const labelPositionA = new THREE.Vector3(LEFT_CENTER, 3.58, 0);
const labelPositionB = new THREE.Vector3(RIGHT_CENTER, 3.58, 0);
const labelPositionGate = new THREE.Vector3(0.15, 1.88, 0.62);
// ------------------------------------------------------------
// UI
// ------------------------------------------------------------
const gateSlider = document.querySelector("#gateSlider");
const openButton = document.querySelector("#openButton");
const resetButton = document.querySelector("#resetButton");
const speedButton = document.querySelector("#speedButton");
const gateValue = document.querySelector("#gateValue");
const statusElement = document.querySelector("#status");
const flowRateElement = document.querySelector("#flowRate");
const flowDirectionElement = document.querySelector("#flowDirection");
const levelAElement = document.querySelector("#levelA");
const levelBElement = document.querySelector("#levelB");
const volumeAElement = document.querySelector("#volumeA");
const volumeBElement = document.querySelector("#volumeB");
const totalVolumeElement = document.querySelector("#totalVolume");
const volumeErrorElement = document.querySelector("#volumeError");
const tagAValue = document.querySelector("#tagAValue");
const tagBValue = document.querySelector("#tagBValue");
gateSlider.addEventListener("input", () => {
targetOpening = Number(gateSlider.value) / 100;
});
openButton.addEventListener("click", () => {
targetOpening = targetOpening > 0.5 ? 0 : 1;
});
resetButton.addEventListener("click", () => {
volumeA = FOOTPRINT_AREA * INITIAL_HEIGHT_A;
targetOpening = 0;
actualOpening = 0;
currentFlow = 0;
flowSign = 0;
simulationTime = 0;
});
speedButton.addEventListener("click", () => {
simulationSpeed =
simulationSpeed === 1 ? 2 : simulationSpeed === 2 ? 4 : 1;
speedButton.textContent = `${simulationSpeed}×`;
});
function updateUI() {
const volumeB = TOTAL_VOLUME - volumeA;
const heightA = volumeA / FOOTPRINT_AREA;
const heightB = volumeB / FOOTPRINT_AREA;
const difference = Math.abs(heightA - heightB);
const conservationError = Math.abs(
volumeA + volumeB - TOTAL_VOLUME
);
const openingPercent = Math.round(actualOpening * 100);
gateValue.textContent = `${openingPercent}%`;
gateSlider.value = String(Math.round(targetOpening * 100));
gateSlider.style.setProperty(
"--fill",
`${Math.round(targetOpening * 100)}%`
);
openButton.textContent =
targetOpening > 0.5 ? "Close gate" : "Open gate";
statusElement.classList.remove("active", "balanced");
if (difference < 0.002) {
statusElement.textContent =
actualOpening > 0.01 ? "Balanced · gate open" : "Balanced";
statusElement.classList.add("balanced");
} else if (actualOpening < 0.01) {
statusElement.textContent = "Gate closed";
} else if (
targetOpening > actualOpening + 0.03 ||
targetOpening < actualOpening - 0.03
) {
statusElement.textContent =
targetOpening > actualOpening ? "Opening gate" : "Closing gate";
statusElement.classList.add("active");
} else {
statusElement.textContent = "Levels equalizing";
statusElement.classList.add("active");
}
flowRateElement.textContent =
`${currentFlow.toFixed(2)} m³/s`;
flowDirectionElement.textContent =
currentFlow > 0.0005
? flowSign > 0
? "Flow A → B"
: "Flow B → A"
: "No flow";
levelAElement.textContent = `${heightA.toFixed(2)} m`;
levelBElement.textContent = `${heightB.toFixed(2)} m`;
volumeAElement.textContent = `${volumeA.toFixed(2)} m³`;
volumeBElement.textContent = `${volumeB.toFixed(2)} m³`;
totalVolumeElement.innerHTML =
`${TOTAL_VOLUME.toFixed(2)} <em>m³</em>`;
volumeErrorElement.innerHTML =
`${conservationError.toFixed(3)} <em>m³</em>`;
tagAValue.textContent =
`${heightA.toFixed(2)} m · ${volumeA.toFixed(2)} m³`;
tagBValue.textContent =
`${heightB.toFixed(2)} m · ${volumeB.toFixed(2)} m³`;
}
// ------------------------------------------------------------
// Resize and animation
// ------------------------------------------------------------
function resize() {
const width = window.innerWidth;
const height = window.innerHeight;
camera.aspect = width / height;
camera.updateProjectionMatrix();
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(width, height, false);
}
window.addEventListener("resize", resize);
let previousTime = performance.now();
let uiAccumulator = 0;
renderer.setAnimationLoop(time => {
const realDelta = Math.min((time - previousTime) / 1000, 0.05);
previousTime = time;
const simulationDelta = realDelta * simulationSpeed;
simulationTime += simulationDelta;
// Substeps improve numerical stability near equilibrium.
const substeps = 4;
const physicsStep = simulationDelta / substeps;
for (let i = 0; i < substeps; i++) {
stepPhysics(physicsStep);
}
const volumeB = TOTAL_VOLUME - volumeA;
const heightA = volumeA / FOOTPRINT_AREA;
const heightB = volumeB / FOOTPRINT_AREA;
updateGateVisual();
updateWater(waterA, heightA);
updateWater(waterB, heightB);
updateFlowVisual();
updateCamera();
placeLabel(tagA, labelPositionA);
placeLabel(tagB, labelPositionB);
placeLabel(gateTag, labelPositionGate);
uiAccumulator += realDelta;
if (uiAccumulator > 0.045) {
updateUI();
uiAccumulator = 0;
}
renderer.render(scene, camera);
});
updateCamera();
updateUI();
</script>
</body>
</html>
```