Prompt specification
Build or customize the Three.js 3D scene "Water distribution junction exhibit" 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: Water distribution junction exhibit
Category: Voxel Worlds · Style: Voxel 3D
License: MIT · Reference: https://three3d.app/scene/water-distribution-junction-exhibit-x1455
Scene Description Prompt:
Build a self-contained HTML scene with Three.js from cdnjs featuring flow continuity through pipes and junctions. Compose one inlet splitting into two branches with labeled flows; conserve total volumetric flow at the junction under an explicitly incompressible steady model. Voxel style.
Working Three.js Starter (water-distribution-junction-exhibit-x1455):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="color-scheme" content="dark">
<title>Voxel Flow Continuity</title>
<style>
:root {
--bg: #07111f;
--panel: rgba(9, 20, 35, 0.88);
--border: rgba(151, 191, 224, 0.18);
--text: #eef7ff;
--muted: #91a9bd;
--inlet: #5b8cff;
--upper: #22d3ee;
--lower: #46f0a0;
--accent: #ffe28a;
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: var(--bg);
color: var(--text);
font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
#viewport {
position: fixed;
inset: 0;
touch-action: none;
}
canvas {
display: block;
width: 100%;
height: 100%;
}
#labels {
position: fixed;
inset: 0;
z-index: 3;
overflow: hidden;
pointer-events: none;
}
.flow-label {
position: absolute;
top: 0;
left: 0;
min-width: 172px;
padding: 10px 12px;
border: 1px solid color-mix(in srgb, var(--c) 55%, transparent);
border-left: 4px solid var(--c);
border-radius: 8px;
background: rgba(5, 13, 24, 0.88);
box-shadow: 0 8px 28px rgba(0, 0, 0, 0.28);
backdrop-filter: blur(8px);
white-space: nowrap;
will-change: transform;
transition: opacity 120ms ease;
}
.flow-label::after {
content: "";
position: absolute;
left: 18px;
top: 100%;
width: 1px;
height: 18px;
background: linear-gradient(var(--c), transparent);
opacity: 0.7;
}
.flow-label .kicker {
display: block;
margin-bottom: 4px;
color: var(--c);
font-size: 10px;
font-weight: 800;
letter-spacing: 0.15em;
text-transform: uppercase;
}
.flow-label strong {
display: block;
font-size: 14px;
font-variant-numeric: tabular-nums;
}
.flow-label small {
display: block;
margin-top: 4px;
color: var(--muted);
font-size: 11px;
font-variant-numeric: tabular-nums;
}
#hud {
position: fixed;
z-index: 10;
top: 16px;
left: 16px;
width: min(360px, calc(100vw - 32px));
max-height: calc(100vh - 32px);
overflow: auto;
padding: 18px;
border: 1px solid var(--border);
border-radius: 14px;
background: var(--panel);
box-shadow: 0 24px 70px rgba(0, 0, 0, 0.36);
backdrop-filter: blur(15px);
}
.eyebrow {
color: var(--accent);
font-size: 10px;
font-weight: 800;
letter-spacing: 0.19em;
text-transform: uppercase;
}
h1 {
margin: 6px 0 8px;
font-size: 24px;
line-height: 1.05;
letter-spacing: -0.03em;
}
.subtitle {
margin: 0;
color: var(--muted);
font-size: 12px;
line-height: 1.55;
}
.status {
display: inline-flex;
align-items: center;
gap: 7px;
margin-top: 12px;
padding: 6px 9px;
border: 1px solid rgba(70, 240, 160, 0.25);
border-radius: 999px;
color: #9ff5ca;
background: rgba(70, 240, 160, 0.07);
font-size: 10px;
font-weight: 750;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.status-dot {
width: 7px;
height: 7px;
border-radius: 50%;
background: #46f0a0;
box-shadow: 0 0 12px #46f0a0;
}
.equation {
margin: 15px 0;
padding: 12px;
border: 1px solid rgba(255, 226, 138, 0.22);
border-radius: 10px;
background: rgba(255, 226, 138, 0.055);
}
.equation-main {
color: #fff2bd;
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 20px;
font-weight: 800;
text-align: center;
}
.equation-note {
margin-top: 6px;
color: var(--muted);
font-size: 10px;
line-height: 1.45;
text-align: center;
}
.stats {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 7px;
margin-bottom: 15px;
}
.stat {
padding: 9px 8px;
border: 1px solid var(--border);
border-radius: 8px;
background: rgba(255, 255, 255, 0.025);
}
.stat span {
display: block;
color: var(--muted);
font-size: 9px;
font-weight: 750;
letter-spacing: 0.09em;
text-transform: uppercase;
}
.stat strong {
display: block;
margin-top: 4px;
font-size: 13px;
font-variant-numeric: tabular-nums;
}
.control {
margin-top: 13px;
}
.control-head {
display: flex;
justify-content: space-between;
gap: 12px;
margin-bottom: 7px;
font-size: 11px;
}
.control-head label {
color: #c8d8e6;
font-weight: 650;
}
output {
color: var(--accent);
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-variant-numeric: tabular-nums;
}
input[type="range"] {
width: 100%;
height: 5px;
margin: 0;
border-radius: 999px;
outline: none;
appearance: none;
background: #1c3043;
}
input[type="range"]::-webkit-slider-thumb {
width: 17px;
height: 17px;
border: 3px solid #102033;
border-radius: 50%;
appearance: none;
background: var(--accent);
box-shadow: 0 0 0 1px var(--accent), 0 0 16px rgba(255, 226, 138, 0.35);
cursor: pointer;
}
input[type="range"]::-moz-range-thumb {
width: 13px;
height: 13px;
border: 3px solid #102033;
border-radius: 50%;
background: var(--accent);
cursor: pointer;
}
.actions {
display: flex;
gap: 8px;
margin-top: 16px;
}
button {
flex: 1;
padding: 9px 10px;
border: 1px solid var(--border);
border-radius: 8px;
color: var(--text);
background: rgba(255, 255, 255, 0.045);
font: inherit;
font-size: 11px;
font-weight: 700;
cursor: pointer;
transition: background 150ms ease, border-color 150ms ease;
}
button:hover {
border-color: rgba(255, 255, 255, 0.3);
background: rgba(255, 255, 255, 0.09);
}
.model-note {
margin: 14px 0 0;
padding-top: 13px;
border-top: 1px solid var(--border);
color: var(--muted);
font-size: 10px;
line-height: 1.55;
}
.model-note b {
color: #c9d9e6;
}
#legend {
position: fixed;
z-index: 8;
right: 16px;
bottom: 16px;
padding: 12px 14px;
border: 1px solid var(--border);
border-radius: 10px;
background: rgba(9, 20, 35, 0.82);
color: var(--muted);
font-size: 10px;
line-height: 1.8;
backdrop-filter: blur(10px);
}
.legend-row {
display: flex;
align-items: center;
gap: 8px;
}
.swatch {
width: 9px;
height: 9px;
border-radius: 2px;
box-shadow: 0 0 10px currentColor;
}
#help {
position: fixed;
z-index: 8;
left: 50%;
bottom: 17px;
transform: translateX(-50%);
color: rgba(205, 222, 235, 0.65);
font-size: 10px;
letter-spacing: 0.06em;
pointer-events: none;
white-space: nowrap;
}
@media (max-width: 760px) {
#hud {
padding: 14px;
}
h1 {
font-size: 20px;
}
.flow-label {
min-width: 145px;
padding: 8px 9px;
}
.flow-label strong {
font-size: 12px;
}
#legend {
display: none;
}
#help {
display: none;
}
}
</style>
</head>
<body>
<div id="viewport"></div>
<div id="labels"></div>
<section id="hud" aria-label="Flow model controls">
<div class="eyebrow">Hydraulic Network / 01</div>
<h1>Voxel Flow Continuity</h1>
<p class="subtitle">
One inlet divides into two equal-area branches. The junction has no
storage and the flow is explicitly constrained to remain conservative.
</p>
<div class="status">
<span class="status-dot"></span>
Steady · incompressible · solved
</div>
<div class="equation">
<div class="equation-main">
Q<sub>0</sub> = Q<sub>1</sub> + Q<sub>2</sub>
</div>
<div class="equation-note">
Junction balance: dV<sub>J</sub>/dt = Q<sub>0</sub> − Q<sub>1</sub> − Q<sub>2</sub> = 0
</div>
</div>
<div class="stats">
<div class="stat">
<span>Inlet Q₀</span>
<strong id="stat-q0">0.600</strong>
</div>
<div class="stat">
<span>Upper Q₁</span>
<strong id="stat-q1">0.360</strong>
</div>
<div class="stat">
<span>Lower Q₂</span>
<strong id="stat-q2">0.240</strong>
</div>
</div>
<div class="control">
<div class="control-head">
<label for="total-flow">Total inlet flow</label>
<output id="total-output" for="total-flow">0.60 m³/s</output>
</div>
<input
id="total-flow"
type="range"
min="0.10"
max="1.20"
step="0.01"
value="0.60"
>
</div>
<div class="control">
<div class="control-head">
<label for="split-flow">Upper / lower split</label>
<output id="split-output" for="split-flow">60% / 40%</output>
</div>
<input
id="split-flow"
type="range"
min="0"
max="1"
step="0.01"
value="0.60"
>
</div>
<div class="actions">
<button id="pause" type="button" aria-pressed="false">Pause flow</button>
<button id="reset-camera" type="button">Reset camera</button>
</div>
<p class="model-note">
<b>Model:</b> steady state, constant density, equal pipe area
A = 0.010 m², and zero junction storage. Branch flows are solved as
Q₁ = fQ₀ and Q₂ = (1 − f)Q₀. Mean velocity is v = Q/A.
Moving voxel parcels show flow direction; their motion is slowed for clarity.
</p>
</section>
<aside id="legend">
<div class="legend-row">
<span class="swatch" style="background:#5b8cff;color:#5b8cff"></span>
Inlet / Q₀
</div>
<div class="legend-row">
<span class="swatch" style="background:#22d3ee;color:#22d3ee"></span>
Upper branch / Q₁
</div>
<div class="legend-row">
<span class="swatch" style="background:#46f0a0;color:#46f0a0"></span>
Lower branch / Q₂
</div>
</aside>
<div id="help">DRAG TO ORBIT · WHEEL TO ZOOM · DOUBLE-CLICK TO RESET</div>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
// -------------------------------------------------------------------------
// Scene
// -------------------------------------------------------------------------
const viewport = document.getElementById("viewport");
const labelLayer = document.getElementById("labels");
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x07111f);
scene.fog = new THREE.FogExp2(0x07111f, 0.025);
const camera = new THREE.PerspectiveCamera(
38,
window.innerWidth / window.innerHeight,
0.1,
100
);
const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.15;
viewport.appendChild(renderer.domElement);
scene.add(new THREE.HemisphereLight(0x9bceff, 0x07101b, 2.1));
const keyLight = new THREE.DirectionalLight(0xffffff, 3.2);
keyLight.position.set(4, 11, 8);
keyLight.castShadow = true;
keyLight.shadow.mapSize.set(2048, 2048);
keyLight.shadow.camera.left = -16;
keyLight.shadow.camera.right = 16;
keyLight.shadow.camera.top = 12;
keyLight.shadow.camera.bottom = -12;
keyLight.shadow.camera.near = 0.5;
keyLight.shadow.camera.far = 40;
scene.add(keyLight);
const upperLight = new THREE.PointLight(0x22d3ee, 15, 14, 2);
upperLight.position.set(5, 5.4, 1.5);
scene.add(upperLight);
const lowerLight = new THREE.PointLight(0x46f0a0, 13, 14, 2);
lowerLight.position.set(5, -4.2, -1.5);
scene.add(lowerLight);
const unitBox = new THREE.BoxGeometry(1, 1, 1);
const dummy = new THREE.Object3D();
// -------------------------------------------------------------------------
// Voxel floor
// -------------------------------------------------------------------------
function createVoxelFloor() {
const nx = 27;
const nz = 17;
const tileSize = 1;
const geometry = new THREE.BoxGeometry(0.96, 0.08, 0.96);
const material = new THREE.MeshStandardMaterial({
color: 0xffffff,
roughness: 0.95,
metalness: 0.02
});
const floor = new THREE.InstancedMesh(geometry, material, nx * nz);
floor.receiveShadow = true;
const base = new THREE.Color(0x0d1b2a);
const alternate = new THREE.Color(0x102236);
const accent = new THREE.Color(0x153047);
let index = 0;
for (let x = 0; x < nx; x++) {
for (let z = 0; z < nz; z++) {
dummy.position.set(
x - (nx - 1) / 2,
-5.08,
z - (nz - 1) / 2
);
dummy.rotation.set(0, 0, 0);
dummy.scale.set(1, 1, 1);
dummy.updateMatrix();
floor.setMatrixAt(index, dummy.matrix);
const color = base.clone();
if ((x + z) % 2 === 0) color.lerp(alternate, 0.7);
if ((x === 13 && Math.abs(z - 8) < 4) ||
(x === 12 && z === 8)) {
color.lerp(accent, 0.45);
}
floor.setColorAt(index, color);
index++;
}
}
floor.instanceMatrix.needsUpdate = true;
floor.instanceColor.needsUpdate = true;
scene.add(floor);
}
createVoxelFloor();
// -------------------------------------------------------------------------
// Hydraulic model
//
// Steady, incompressible, zero storage at the junction:
//
// dVJ/dt = Q0 - Q1 - Q2 = 0
// Q0 = Q1 + Q2
// Q1 = f * Q0
// Q2 = (1 - f) * Q0
//
// Equal-area branches:
// v_i = Q_i / A
// -------------------------------------------------------------------------
const AREA = 0.010; // m²
const PARTICLE_COUNT = 54;
const ANIMATION_TIME_SCALE = 0.04;
const params = {
q0: 0.60,
fraction: 0.60,
q1: 0.36,
q2: 0.24,
residual: 0
};
const colors = {
inlet: 0x5b8cff,
upper: 0x22d3ee,
lower: 0x46f0a0,
junction: 0xffe28a
};
const pipeWidth = 1.05;
function pathMetrics(points) {
const lengths = [];
let total = 0;
for (let i = 0; i < points.length - 1; i++) {
const length = points[i].distanceTo(points[i + 1]);
lengths.push(length);
total += length;
}
return { lengths, total };
}
function samplePath(points, distance) {
const metrics = pathMetrics(points);
let remaining = Math.max(0, distance);
for (let i = 0; i < metrics.lengths.length; i++) {
const length = metrics.lengths[i];
if (remaining <= length || i === metrics.lengths.length - 1) {
const t = THREE.MathUtils.clamp(remaining / length, 0, 1);
return points[i].clone().lerp(points[i + 1], t);
}
remaining -= length;
}
return points[points.length - 1].clone();
}
function createPipeSegment(a, b, color) {
const delta = b.clone().sub(a);
const activeAxes = [];
if (Math.abs(delta.x) > 0.0001) activeAxes.push("x");
if (Math.abs(delta.y) > 0.0001) activeAxes.push("y");
if (Math.abs(delta.z) > 0.0001) activeAxes.push("z");
if (activeAxes.length !== 1) {
throw new Error("Pipe segments must be axis-aligned.");
}
const axis = activeAxes[0];
const axisIndex = { x: 0, y: 1, z: 2 }[axis];
const length = Math.abs(delta.getComponent(axisIndex));
const midpoint = a.clone().add(b).multiplyScalar(0.5);
const baseColor = new THREE.Color(color);
const casingMaterial = new THREE.MeshStandardMaterial({
color: baseColor.clone().multiplyScalar(0.45),
transparent: true,
opacity: 0.19,
roughness: 0.38,
metalness: 0.12,
depthWrite: false
});
const fluidMaterial = new THREE.MeshStandardMaterial({
color: baseColor,
emissive: baseColor,
emissiveIntensity: 0.13,
transparent: true,
opacity: 0.13,
roughness: 0.35,
metalness: 0.02,
depthWrite: false
});
const casing = new THREE.Mesh(unitBox, casingMaterial);
const casingScale = new THREE.Vector3(pipeWidth, pipeWidth, pipeWidth);
casingScale.setComponent(axisIndex, length + 0.04);
casing.scale.copy(casingScale);
casing.position.copy(midpoint);
casing.renderOrder = 1;
scene.add(casing);
const fluid = new THREE.Mesh(unitBox, fluidMaterial);
const fluidScale = new THREE.Vector3(
pipeWidth * 0.43,
pipeWidth * 0.43,
pipeWidth * 0.43
);
fluidScale.setComponent(axisIndex, length);
fluid.scale.copy(fluidScale);
fluid.position.copy(midpoint);
fluid.renderOrder = 2;
scene.add(fluid);
// Small opaque voxel corner pieces form repeating pipe ribs.
const perpendicular = axis === "x" ? ["y", "z"] :
axis === "y" ? ["x", "z"] : ["x", "y"];
const ribMaterial = new THREE.MeshStandardMaterial({
color: baseColor.clone().multiplyScalar(0.7),
emissive: baseColor,
emissiveIntensity: 0.12,
roughness: 0.42,
metalness: 0.2
});
const ribSize = 0.19;
const offset = pipeWidth / 2 - ribSize / 2 + 0.03;
for (let s = 0.45; s < length - 0.25; s += 1.05) {
const t = s / length;
const ribCenter = a.clone().lerp(b, t);
for (const sign1 of [-1, 1]) {
for (const sign2 of [-1, 1]) {
const rib = new THREE.Mesh(unitBox, ribMaterial);
rib.scale.setScalar(ribSize);
rib.position.copy(ribCenter);
rib.position[perpendicular[0]] += sign1 * offset;
rib.position[perpendicular[1]] += sign2 * offset;
rib.castShadow = true;
rib.renderOrder = 3;
scene.add(rib);
}
}
}
}
function createPipe(points, color) {
for (let i = 0; i < points.length - 1; i++) {
createPipeSegment(points[i], points[i + 1], color);
}
const metrics = pathMetrics(points);
const particleMaterial = new THREE.MeshStandardMaterial({
color,
emissive: color,
emissiveIntensity: 1.25,
roughness: 0.24,
metalness: 0.08
});
const particles = new THREE.InstancedMesh(
unitBox,
particleMaterial,
PARTICLE_COUNT
);
particles.instanceMatrix.setUsage(THREE.DynamicDrawUsage);
particles.frustumCulled = false;
particles.castShadow = true;
particles.renderOrder = 4;
particles.count = 0;
scene.add(particles);
return {
points,
length: metrics.total,
particles,
activeCount: 0,
offset: 0,
q: 0
};
}
// The routes use orthogonal segments so the entire network remains voxel-like.
const inletRoute = createPipe(
[
new THREE.Vector3(-10, 0, 0),
new THREE.Vector3(-3, 0, 0)
],
colors.inlet
);
const upperRoute = createPipe(
[
new THREE.Vector3(-3, 0, 0),
new THREE.Vector3(-3, 0, 0.9),
new THREE.Vector3(-1, 0, 0.9),
new THREE.Vector3(-1, 5.3, 0.9),
new THREE.Vector3(8.6, 5.3, 0.9)
],
colors.upper
);
const lowerRoute = createPipe(
[
new THREE.Vector3(-3, 0, 0),
new THREE.Vector3(-3, 0, -0.9),
new THREE.Vector3(-1.8, 0, -0.9),
new THREE.Vector3(-1.8, -4.3, -0.9),
new THREE.Vector3(8.6, -4.3, -0.9)
],
colors.lower
);
// -------------------------------------------------------------------------
// Voxel junction chamber
// -------------------------------------------------------------------------
function createJunction() {
const group = new THREE.Group();
group.position.set(-3, 0, 0);
const grid = 5;
const spacing = 0.27;
const shell = [];
for (let x = -2; x <= 2; x++) {
for (let y = -2; y <= 2; y++) {
for (let z = -2; z <= 2; z++) {
const maxAbs = Math.max(Math.abs(x), Math.abs(y), Math.abs(z));
if (maxAbs === 2) shell.push([x, y, z]);
}
}
}
const geometry = new THREE.BoxGeometry(0.245, 0.245, 0.245);
const material = new THREE.MeshStandardMaterial({
color: 0xffffff,
roughness: 0.38,
metalness: 0.24
});
const chamber = new THREE.InstancedMesh(
geometry,
material,
shell.length
);
const blue = new THREE.Color(colors.inlet);
const cyan = new THREE.Color(colors.upper);
const green = new THREE.Color(colors.lower);
const pale = new THREE.Color(0xa9c7df);
shell.forEach(([x, y, z], index) => {
dummy.position.set(
x * spacing,
y * spacing,
z * spacing
);
dummy.rotation.set(0, 0, 0);
dummy.scale.set(1, 1, 1);
dummy.updateMatrix();
chamber.setMatrixAt(index, dummy.matrix);
let color = pale;
if (x < 0) color = blue;
else if (y > 0) color = cyan;
else if (y < 0) color = green;
chamber.setColorAt(index, color);
});
chamber.instanceMatrix.needsUpdate = true;
chamber.instanceColor.needsUpdate = true;
chamber.castShadow = true;
group.add(chamber);
const coreMaterial = new THREE.MeshStandardMaterial({
color: colors.junction,
emissive: colors.junction,
emissiveIntensity: 0.8,
transparent: true,
opacity: 0.18,
roughness: 0.2,
depthWrite: false
});
const core = new THREE.Mesh(
new THREE.BoxGeometry(1.08, 1.08, 1.08),
coreMaterial
);
group.add(core);
const junctionLight = new THREE.PointLight(colors.junction, 12, 7, 2);
junctionLight.position.set(0, 0, 0);
group.add(junctionLight);
scene.add(group);
}
createJunction();
// -------------------------------------------------------------------------
// Projected HTML labels
// -------------------------------------------------------------------------
function createLabel(id, color, anchor, className = "") {
const element = document.createElement("div");
element.id = id;
element.className = `flow-label ${className}`;
element.style.setProperty("--c", color);
labelLayer.appendChild(element);
return {
element,
anchor: anchor.clone()
};
}
const labels = {
inlet: createLabel(
"label-inlet",
"#5b8cff",
new THREE.Vector3(-7.4, 1.2, 0)
),
junction: createLabel(
"label-junction",
"#ffe28a",
new THREE.Vector3(-3.0, 1.85, 0)
),
upper: createLabel(
"label-upper",
"#22d3ee",
new THREE.Vector3(5.1, 6.2, 0.9)
),
lower: createLabel(
"label-lower",
"#46f0a0",
new THREE.Vector3(5.1, -5.2, -0.9)
)
};
function updateProjectedLabels() {
for (const label of Object.values(labels)) {
const projected = label.anchor.clone().project(camera);
const visible = projected.z > -1 && projected.z < 1;
const x = (projected.x * 0.5 + 0.5) * window.innerWidth;
const y = (-projected.y * 0.5 + 0.5) * window.innerHeight;
label.element.style.transform =
`translate3d(${x}px, ${y}px, 0) translate(-50%, -100%)`;
label.element.style.opacity = visible ? "1" : "0";
}
}
// -------------------------------------------------------------------------
// Model UI and conservation solution
// -------------------------------------------------------------------------
const totalInput = document.getElementById("total-flow");
const splitInput = document.getElementById("split-flow");
const totalOutput = document.getElementById("total-output");
const splitOutput = document.getElementById("split-output");
const pauseButton = document.getElementById("pause");
function updateModel() {
params.q0 = Number(totalInput.value);
params.fraction = Number(splitInput.value);
// Solve the branch split directly from the continuity constraint.
params.q1 = params.fraction * params.q0;
params.q2 = params.q0 - params.q1;
params.residual = params.q0 - (params.q1 + params.q2);
// Eliminate floating-point dust in the displayed residual.
if (Math.abs(params.residual) < 1e-12) params.residual = 0;
const v0 = params.q0 / AREA;
const v1 = params.q1 / AREA;
const v2 = params.q2 / AREA;
totalOutput.textContent = `${params.q0.toFixed(2)} m³/s`;
splitOutput.textContent =
`${Math.round(params.fraction * 100)}% / ` +
`${Math.round((1 - params.fraction) * 100)}%`;
document.getElementById("stat-q0").textContent = params.q0.toFixed(3);
document.getElementById("stat-q1").textContent = params.q1.toFixed(3);
document.getElementById("stat-q2").textContent = params.q2.toFixed(3);
labels.inlet.element.innerHTML = `
<span class="kicker">Inlet · Section A</span>
<strong>Q<sub>0</sub> = ${params.q0.toFixed(3)} m³/s</strong>
<small>v<sub>0</sub> = ${v0.toFixed(1)} m/s</small>
`;
labels.upper.element.innerHTML = `
<span class="kicker">Upper branch A</span>
<strong>Q<sub>1</sub> = ${params.q1.toFixed(3)} m³/s</strong>
<small>v<sub>1</sub> = ${v1.toFixed(1)} m/s · ${Math.round(params.fraction * 100)}%</small>
`;
labels.lower.element.innerHTML = `
<span class="kicker">Lower branch B</span>
<strong>Q<sub>2</sub> = ${params.q2.toFixed(3)} m³/s</strong>
<small>v<sub>2</sub> = ${v2.toFixed(1)} m/s · ${Math.round((1 - params.fraction) * 100)}%</small>
`;
labels.junction.element.innerHTML = `
<span class="kicker">Junction J · zero storage</span>
<strong>Q<sub>0</sub> = Q<sub>1</sub> + Q<sub>2</sub></strong>
<small>Residual = ${params.residual.toFixed(6)} m³/s</small>
`;
inletRoute.q = params.q0;
upperRoute.q = params.q1;
lowerRoute.q = params.q2;
inletRoute.activeCount = PARTICLE_COUNT;
const upperCount = params.q1 > 0
? Math.max(1, Math.round(PARTICLE_COUNT * params.fraction))
: 0;
const lowerCount = params.q2 > 0
? Math.max(1, PARTICLE_COUNT - upperCount)
: 0;
upperRoute.activeCount = Math.min(PARTICLE_COUNT, upperCount);
lowerRoute.activeCount = Math.min(PARTICLE_COUNT, lowerCount);
}
totalInput.addEventListener("input", updateModel);
splitInput.addEventListener("input", updateModel);
updateModel();
// -------------------------------------------------------------------------
// Moving flow parcels
// -------------------------------------------------------------------------
function updateRouteParticles(route, deltaTime) {
const n = route.activeCount;
route.particles.count = n;
if (n === 0) return;
const physicalVelocity = route.q / AREA;
const visualVelocity = physicalVelocity * ANIMATION_TIME_SCALE;
route.offset =
(route.offset + visualVelocity * deltaTime) % route.length;
const spacing = route.length / n;
for (let i = 0; i < n; i++) {
const distance = (i * spacing + route.offset) % route.length;
const position = samplePath(route.points, distance);
dummy.position.copy(position);
dummy.rotation.set(0, 0, 0);
dummy.scale.setScalar(0.19);
dummy.updateMatrix();
route.particles.setMatrixAt(i, dummy.matrix);
}
route.particles.instanceMatrix.needsUpdate = true;
}
// -------------------------------------------------------------------------
// Camera controls implemented without external addons
// -------------------------------------------------------------------------
const cameraTarget = new THREE.Vector3(0, 0.15, 0);
const cameraState = {
radius: 23,
theta: 0.70,
phi: 1.16
};
function updateCamera() {
const offset = new THREE.Vector3().setFromSphericalCoords(
cameraState.radius,
cameraState.phi,
cameraState.theta
);
camera.position.copy(cameraTarget).add(offset);
camera.lookAt(cameraTarget);
camera.updateMatrixWorld();
}
function resetCamera() {
cameraState.radius = 23;
cameraState.theta = 0.70;
cameraState.phi = 1.16;
cameraTarget.set(0, 0.15, 0);
updateCamera();
}
let dragging = false;
let previousX = 0;
let previousY = 0;
renderer.domElement.addEventListener("pointerdown", event => {
dragging = true;
previousX = event.clientX;
previousY = event.clientY;
renderer.domElement.setPointerCapture(event.pointerId);
});
renderer.domElement.addEventListener("pointermove", event => {
if (!dragging) return;
const dx = event.clientX - previousX;
const dy = event.clientY - previousY;
previousX = event.clientX;
previousY = event.clientY;
cameraState.theta -= dx * 0.006;
cameraState.phi = THREE.MathUtils.clamp(
cameraState.phi - dy * 0.006,
0.38,
1.48
);
updateCamera();
});
function stopDragging(event) {
dragging = false;
if (
event.pointerId !== undefined &&
renderer.domElement.hasPointerCapture(event.pointerId)
) {
renderer.domElement.releasePointerCapture(event.pointerId);
}
}
renderer.domElement.addEventListener("pointerup", stopDragging);
renderer.domElement.addEventListener("pointercancel", stopDragging);
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),
12,
38
);
updateCamera();
}, { passive: false });
renderer.domElement.addEventListener("dblclick", resetCamera);
document.getElementById("reset-camera").addEventListener("click", resetCamera);
let paused = false;
pauseButton.addEventListener("click", () => {
paused = !paused;
pauseButton.textContent = paused ? "Resume flow" : "Pause flow";
pauseButton.setAttribute("aria-pressed", String(paused));
});
// -------------------------------------------------------------------------
// Resize and render loop
// -------------------------------------------------------------------------
function onResize() {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
}
window.addEventListener("resize", onResize);
const clock = new THREE.Clock();
function animate() {
requestAnimationFrame(animate);
const deltaTime = Math.min(clock.getDelta(), 0.05);
if (!paused) {
updateRouteParticles(inletRoute, deltaTime);
updateRouteParticles(upperRoute, deltaTime);
updateRouteParticles(lowerRoute, deltaTime);
}
updateProjectedLabels();
renderer.render(scene, camera);
}
updateCamera();
animate();
</script>
</body>
</html>
```