Prompt specification
Build or customize the Three.js 3D scene "One Pond Food-Web Update" 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: One Pond Food-Web Update
Category: Voxel Worlds · Style: Voxel 3D
License: MIT · Reference: https://three3d.app/scene/one-pond-food-web-update-x3534
Scene Description Prompt:
Build a self-contained HTML scene with Three.js from cdnjs featuring ecological feedback under fictional game rules. Animate one discrete update in a small pond game with explicit resource rules. Show consumption, growth, and losses separately while preventing negative counts. Voxel style.
Working Three.js Starter (one-pond-food-web-update-x3534):
```html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Voxel Pond — Ecological Feedback Lab</title>
<style>
:root {
--ink: #102b2a;
--panel: rgba(13, 38, 37, 0.94);
--panel-soft: rgba(21, 55, 52, 0.9);
--cream: #f4f0dc;
--muted: #a9c6b9;
--green: #8ddd72;
--blue: #66d8e8;
--amber: #ffc766;
--coral: #ff806f;
--line: rgba(220, 239, 220, 0.16);
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: #c8e2d8;
color: var(--cream);
font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas,
"Liberation Mono", monospace;
}
button,
summary {
font: inherit;
}
button:focus-visible,
summary:focus-visible {
outline: 3px solid var(--amber);
outline-offset: 3px;
}
#app {
position: relative;
width: 100%;
height: 100%;
isolation: isolate;
}
#viewport {
position: absolute;
inset: 0;
z-index: 0;
}
#viewport canvas {
display: block;
width: 100%;
height: 100%;
cursor: grab;
touch-action: none;
}
#viewport canvas.dragging {
cursor: grabbing;
}
#vignette {
position: absolute;
inset: 0;
z-index: 1;
pointer-events: none;
box-shadow:
inset 0 0 100px rgba(18, 53, 48, 0.16),
inset 0 -100px 120px rgba(18, 53, 48, 0.12);
}
#hud {
position: absolute;
inset: 0;
z-index: 2;
pointer-events: none;
}
.header {
position: absolute;
top: 22px;
left: 24px;
max-width: 470px;
text-shadow: 0 2px 14px rgba(12, 37, 34, 0.55);
}
.eyebrow {
display: inline-flex;
align-items: center;
gap: 8px;
margin-bottom: 9px;
padding: 6px 9px;
border: 1px solid rgba(255, 255, 255, 0.38);
background: rgba(18, 54, 50, 0.78);
color: #eaf5df;
font-size: 10px;
font-weight: 800;
letter-spacing: 0.16em;
text-transform: uppercase;
}
.eyebrow::before {
content: "";
width: 7px;
height: 7px;
background: var(--green);
box-shadow: 0 0 0 3px rgba(141, 221, 114, 0.2);
}
h1 {
margin: 0;
font-family: system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI",
sans-serif;
font-size: clamp(30px, 4.2vw, 58px);
line-height: 0.96;
letter-spacing: -0.055em;
}
.subtitle {
max-width: 430px;
margin: 11px 0 0;
color: #e2eee2;
font-size: 12px;
line-height: 1.55;
}
.stats {
display: flex;
flex-wrap: wrap;
gap: 7px;
margin-top: 15px;
}
.stat {
min-width: 82px;
padding: 7px 9px;
border: 1px solid rgba(255, 255, 255, 0.24);
background: rgba(15, 43, 40, 0.79);
backdrop-filter: blur(8px);
}
.stat span {
display: block;
color: var(--muted);
font-size: 9px;
letter-spacing: 0.1em;
text-transform: uppercase;
}
.stat b {
display: block;
margin-top: 2px;
font-size: 17px;
font-variant-numeric: tabular-nums;
}
.status {
position: absolute;
top: 22px;
right: 22px;
padding: 9px 12px;
border: 1px solid rgba(255, 255, 255, 0.28);
background: rgba(15, 43, 40, 0.85);
color: #edf5e9;
font-size: 10px;
font-weight: 800;
letter-spacing: 0.12em;
text-transform: uppercase;
backdrop-filter: blur(8px);
}
#ledger {
position: absolute;
top: 76px;
right: 22px;
width: 366px;
max-height: calc(100vh - 230px);
overflow: auto;
padding: 16px;
border: 1px solid rgba(255, 255, 255, 0.2);
background: var(--panel);
box-shadow: 0 18px 60px rgba(18, 44, 40, 0.23);
pointer-events: auto;
scrollbar-width: thin;
scrollbar-color: #53756b transparent;
}
.panel-title {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
margin-bottom: 4px;
}
.panel-title h2 {
margin: 0;
font-family: system-ui, sans-serif;
font-size: 15px;
letter-spacing: 0.01em;
}
.panel-kicker {
color: var(--muted);
font-size: 9px;
letter-spacing: 0.1em;
text-transform: uppercase;
}
.panel-note {
margin: 0 0 12px;
color: var(--muted);
font-size: 10px;
line-height: 1.45;
}
table {
width: 100%;
border-collapse: collapse;
font-size: 10px;
font-variant-numeric: tabular-nums;
}
th,
td {
padding: 9px 5px;
border-bottom: 1px solid var(--line);
text-align: right;
}
th {
color: var(--muted);
font-size: 8px;
font-weight: 700;
letter-spacing: 0.06em;
text-transform: uppercase;
}
th:first-child,
td:first-child {
padding-left: 0;
text-align: left;
}
th:last-child,
td:last-child {
padding-right: 0;
}
td:first-child b {
font-size: 12px;
}
td:first-child small {
display: block;
margin-top: 2px;
color: #71968b;
font-size: 8px;
}
.use {
color: var(--amber);
}
.grow {
color: var(--green);
}
.loss {
color: var(--coral);
}
.zero {
opacity: 0.35;
}
.flow-legend {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 5px;
margin-top: 10px;
color: var(--muted);
font-size: 8px;
line-height: 1.4;
}
.flow-legend span::before {
content: "";
display: inline-block;
width: 6px;
height: 6px;
margin-right: 5px;
vertical-align: 1px;
background: currentColor;
}
.flow-legend .use::before {
color: var(--amber);
}
.flow-legend .grow::before {
color: var(--green);
}
.flow-legend .loss::before {
color: var(--coral);
}
details {
margin-top: 14px;
border-top: 1px solid var(--line);
}
summary {
padding: 12px 0 5px;
color: #e6f1df;
cursor: pointer;
font-size: 10px;
font-weight: 800;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.rules {
margin: 8px 0 0;
padding: 0 0 0 16px;
color: #b9cec1;
font-size: 9px;
line-height: 1.6;
}
.rules li {
margin-bottom: 6px;
}
.rules code {
color: #f0f3dc;
font-size: 9px;
}
.rule-foot {
margin: 9px 0 0;
padding: 9px;
border-left: 3px solid var(--green);
background: rgba(141, 221, 114, 0.08);
color: #c8dbc9;
font-size: 9px;
line-height: 1.5;
}
#console {
position: absolute;
bottom: 22px;
left: 50%;
width: min(560px, calc(100vw - 44px));
transform: translateX(-50%);
padding: 14px;
border: 1px solid rgba(255, 255, 255, 0.22);
background: var(--panel);
box-shadow: 0 18px 60px rgba(18, 44, 40, 0.26);
pointer-events: auto;
}
.console-top {
display: flex;
align-items: center;
gap: 9px;
}
#stepButton {
flex: 1;
min-height: 42px;
padding: 10px 14px;
border: 0;
border-bottom: 4px solid #4f9f58;
background: var(--green);
color: #143329;
cursor: pointer;
font-size: 12px;
font-weight: 900;
letter-spacing: 0.04em;
text-transform: uppercase;
}
#stepButton:hover {
filter: brightness(1.06);
}
#stepButton:active {
transform: translateY(2px);
border-bottom-width: 2px;
}
#stepButton:disabled {
cursor: wait;
filter: saturate(0.45);
opacity: 0.7;
}
#resetButton {
width: 72px;
min-height: 42px;
border: 1px solid #617f76;
background: #244a45;
color: #eaf3e3;
cursor: pointer;
font-size: 10px;
font-weight: 800;
text-transform: uppercase;
}
#resetButton:hover {
background: #315b53;
}
.phase {
display: flex;
align-items: flex-start;
gap: 10px;
margin-top: 11px;
}
.phase-dots {
display: flex;
gap: 4px;
padding-top: 4px;
}
.phase-dots span {
width: 9px;
height: 9px;
border: 1px solid #638278;
background: transparent;
}
.phase-dots span.complete {
border-color: var(--green);
background: var(--green);
}
.phase-dots span.active {
border-color: var(--amber);
background: var(--amber);
box-shadow: 0 0 0 3px rgba(255, 199, 102, 0.14);
}
#phaseTitle {
margin: 0;
font-size: 11px;
font-weight: 800;
}
#phaseText {
margin: 3px 0 0;
color: var(--muted);
font-size: 9px;
line-height: 1.45;
}
.progress {
height: 3px;
margin-top: 10px;
overflow: hidden;
background: #294d47;
}
#progressFill {
width: 0;
height: 100%;
background: var(--amber);
}
#eventLog {
max-height: 76px;
margin-top: 9px;
overflow: hidden;
color: #a8c4b7;
font-size: 8px;
line-height: 1.6;
}
.log-line {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.log-line:first-child {
color: #e2ebd8;
}
#legend {
position: absolute;
bottom: 24px;
left: 24px;
padding: 10px 12px;
border-left: 3px solid rgba(255, 255, 255, 0.7);
background: rgba(16, 43, 40, 0.78);
color: #dce9dc;
font-size: 9px;
line-height: 1.65;
backdrop-filter: blur(8px);
}
#legend b {
color: white;
font-size: 9px;
letter-spacing: 0.08em;
text-transform: uppercase;
}
#legend span {
color: var(--muted);
}
@media (max-width: 900px) {
.header {
top: 15px;
left: 15px;
}
.subtitle {
display: none;
}
.stats {
margin-top: 9px;
}
.stat {
min-width: 63px;
padding: 5px 7px;
}
.stat b {
font-size: 13px;
}
.status {
top: 15px;
right: 15px;
}
#ledger {
top: 83px;
right: 12px;
width: min(366px, calc(100vw - 24px));
max-height: 36vh;
padding: 13px;
}
#console {
right: 12px;
bottom: 12px;
left: 12px;
width: auto;
transform: none;
}
#legend {
display: none;
}
}
@media (max-width: 520px) {
h1 {
font-size: 30px;
}
.stats {
max-width: 240px;
}
.status {
top: 15px;
right: 12px;
max-width: 116px;
text-align: right;
}
#ledger {
top: 88px;
max-height: 33vh;
}
th,
td {
padding: 7px 3px;
}
.flow-legend,
.rules {
font-size: 8px;
}
#eventLog {
max-height: 34px;
}
}
</style>
</head>
<body>
<main id="app">
<div id="viewport" aria-label="Interactive voxel pond scene"></div>
<div id="vignette"></div>
<div id="hud">
<header class="header">
<div class="eyebrow">Fictional ecology game</div>
<h1>Pond Feedback</h1>
<p class="subtitle">
Every click commits one atomic simulation tick. The animation reveals
each rule in order, but no resource may fall below zero or exceed its cap.
</p>
<div class="stats" aria-label="Current pond totals">
<div class="stat"><span>Algae</span><b id="statAlgae">12</b></div>
<div class="stat"><span>Fish</span><b id="statFish">5</b></div>
<div class="stat"><span>Nutrients</span><b id="statNutrient">14</b></div>
<div class="stat"><span>Oxygen</span><b id="statOxygen">11</b></div>
</div>
</header>
<div id="status" class="status">Ready · tick 0</div>
<section id="ledger" aria-label="Resource balance ledger">
<div class="panel-title">
<h2>Resource ledger</h2>
<span class="panel-kicker">One tick</span>
</div>
<p class="panel-note">
Amounts used, created, and lost are recorded separately.
Hover a value for its source.
</p>
<table>
<thead>
<tr>
<th>Current</th>
<th>Consumed</th>
<th>Grew</th>
<th>Lost</th>
</tr>
</thead>
<tbody>
<tr>
<td><b id="rowAlgae">12</b><small>algae / 24</small></td>
<td id="flowAlgaeUse" class="use">0</td>
<td id="flowAlgaeGrow" class="grow">0</td>
<td id="flowAlgaeLoss" class="loss">0</td>
</tr>
<tr>
<td><b id="rowNutrient">14</b><small>nutrients / 20</small></td>
<td id="flowNutrientUse" class="use">0</td>
<td id="flowNutrientGrow" class="grow">0</td>
<td id="flowNutrientLoss" class="loss">0</td>
</tr>
<tr>
<td><b id="rowOxygen">11</b><small>oxygen / 16</small></td>
<td id="flowOxygenUse" class="use">0</td>
<td id="flowOxygenGrow" class="grow">0</td>
<td id="flowOxygenLoss" class="loss">0</td>
</tr>
<tr>
<td><b id="rowFish">5</b><small>fish / 12</small></td>
<td id="flowFishUse" class="use">0</td>
<td id="flowFishGrow" class="grow">0</td>
<td id="flowFishLoss" class="loss">0</td>
</tr>
</tbody>
</table>
<div class="flow-legend">
<span class="use">Used by another resource</span>
<span class="grow">Created this tick</span>
<span class="loss">Removed this tick</span>
</div>
<details open>
<summary>Explicit game rules</summary>
<ol class="rules">
<li>
Caps: algae 24, nutrients 20, oxygen 16, fish 12. All totals
are clamped to <code>0…cap</code>.
</li>
<li>
Runoff adds up to 3 nutrients. Settling removes
<code>1 + floor(algae / 8)</code> nutrients.
</li>
<li>
Algae grows by
<code>min(2, floor(nutrients / 4), free algae space)</code>.
Each new algae unit consumes one nutrient.
</li>
<li>
If algae exceeds 18, decomposition removes
<code>ceil((algae - 18) / 2)</code>.
</li>
<li>
Each fish may eat one algae. Fish births equal
<code>floor(algae eaten / 3)</code>, capped by free space.
</li>
<li>
Fish losses are unfed fish plus
<code>max(0, 6 - oxygen)</code> oxygen deaths plus
<code>max(0, ceil((fish - 10) / 2))</code> crowding deaths.
</li>
<li>
Algae produces up to <code>ceil(algae / 2)</code> oxygen.
Every two fish consume one oxygen. One oxygen escapes when
the resulting total exceeds 12.
</li>
</ol>
<p class="rule-foot">
Every subtraction is capped by the amount currently available.
Final values are clamped again, so negative resource counts are
impossible.
</p>
</details>
</section>
<section id="console" aria-label="Discrete simulation controls">
<div class="console-top">
<button id="stepButton" type="button">▶ Run one update</button>
<button id="resetButton" type="button">Reset</button>
</div>
<div class="phase">
<div class="phase-dots" aria-hidden="true">
<span></span><span></span><span></span><span></span><span></span>
</div>
<div aria-live="polite">
<p id="phaseTitle">Ready for one discrete update</p>
<p id="phaseText">
The pond starts at algae 12, fish 5, nutrients 14, oxygen 11.
</p>
</div>
</div>
<div class="progress"><div id="progressFill"></div></div>
<div id="eventLog" aria-live="polite">
<div class="log-line">No update yet. Each click advances exactly one tick.</div>
</div>
</section>
<div id="legend">
<b>Scene key</b><br>
<span style="color:#8ddd72">■</span> algae blocks
<span style="color:#ffc766">■</span> nutrient meter<br>
<span style="color:#66d8e8">■</span> oxygen meter
<span style="color:#ff9c57">■</span> fish<br>
Drag to orbit · wheel to zoom
</div>
</div>
</main>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
// -------------------------------------------------------------------------
// DOM and simulation constants
// -------------------------------------------------------------------------
const $ = (id) => document.getElementById(id);
const LIMITS = Object.freeze({
algae: 24,
nutrient: 20,
oxygen: 16,
fish: 12
});
const INITIAL = Object.freeze({
algae: 12,
nutrient: 14,
oxygen: 11,
fish: 5
});
let state = { ...INITIAL };
const visual = { ...INITIAL };
let tickNumber = 0;
let animation = null;
let phaseTimers = [];
const clamp = (value, min, max) =>
Math.max(min, Math.min(max, value));
const zeroFlows = () => ({
algaeConsumption: 0,
algaeGrowth: 0,
algaeLoss: 0,
nutrientConsumption: 0,
nutrientGrowth: 0,
nutrientLoss: 0,
oxygenConsumption: 0,
oxygenGrowth: 0,
oxygenLoss: 0,
fishConsumption: 0,
fishGrowth: 0,
fishLoss: 0
});
// -------------------------------------------------------------------------
// Three.js setup
// -------------------------------------------------------------------------
const viewport = $("viewport");
const scene = new THREE.Scene();
scene.background = new THREE.Color(0xc9e4db);
scene.fog = new THREE.Fog(0xc9e4db, 29, 58);
const renderer = new THREE.WebGLRenderer({
antialias: true,
alpha: false,
powerPreference: "high-performance"
});
renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 2));
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.08;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.domElement.tabIndex = 0;
renderer.domElement.setAttribute(
"aria-label",
"Voxel pond. Drag to orbit and use the mouse wheel to zoom."
);
viewport.appendChild(renderer.domElement);
const camera = new THREE.OrthographicCamera(-10, 10, 7, -7, 0.1, 100);
const controls = {
theta: 0.63,
phi: 0.73,
zoom: 1,
target: new THREE.Vector3(0, 0.1, 0)
};
const hemisphere = new THREE.HemisphereLight(0xeaffef, 0x567565, 2.1);
scene.add(hemisphere);
const sun = new THREE.DirectionalLight(0xfff0c8, 3.3);
sun.position.set(-9, 16, 8);
sun.castShadow = true;
sun.shadow.mapSize.set(2048, 2048);
sun.shadow.camera.left = -15;
sun.shadow.camera.right = 15;
sun.shadow.camera.top = 15;
sun.shadow.camera.bottom = -15;
sun.shadow.camera.near = 1;
sun.shadow.camera.far = 40;
sun.shadow.bias = -0.0008;
scene.add(sun);
const rim = new THREE.DirectionalLight(0x8ad9e6, 1.1);
rim.position.set(11, 7, -10);
scene.add(rim);
const world = new THREE.Group();
scene.add(world);
function standardMaterial(color, extra = {}) {
return new THREE.MeshStandardMaterial({
color,
roughness: 0.88,
metalness: 0,
flatShading: true,
...extra
});
}
function addBox(parent, size, position, material, castShadow = true) {
const mesh = new THREE.Mesh(
new THREE.BoxGeometry(size[0], size[1], size[2]),
material
);
mesh.position.set(position[0], position[1], position[2]);
mesh.castShadow = castShadow;
mesh.receiveShadow = true;
parent.add(mesh);
return mesh;
}
function mulberry32(seed) {
return function random() {
let value = seed += 0x6D2B79F5;
value = Math.imul(value ^ value >>> 15, value | 1);
value ^= value + Math.imul(value ^ value >>> 7, value | 61);
return ((value ^ value >>> 14) >>> 0) / 4294967296;
};
}
const random = mulberry32(72139);
// -------------------------------------------------------------------------
// Voxel terrain and pond
// -------------------------------------------------------------------------
const soilMaterial = standardMaterial(0x5b6550);
const floorMaterial = standardMaterial(0x315b57);
const landMaterials = [
standardMaterial(0x6e965a),
standardMaterial(0x789f60),
standardMaterial(0x628b54),
standardMaterial(0x87aa68)
];
const treeTrunkMaterial = standardMaterial(0x79533c);
const leafMaterials = [
standardMaterial(0x3f7652),
standardMaterial(0x4d8755),
standardMaterial(0x66995b)
];
const reedMaterial = standardMaterial(0x568a49);
const reedTipMaterial = standardMaterial(0x75503b);
const stoneMaterial = standardMaterial(0x8a9380);
// Broad background and the raised diorama slab.
addBox(
world,
[70, 0.2, 70],
[0, -1.03, 0],
standardMaterial(0xb9d7c8),
false
);
addBox(world, [13.45, 0.56, 10.15], [0, -0.58, 0], soilMaterial);
addBox(world, [8.95, 0.12, 5.62], [0, -0.27, 0], floorMaterial, false);
const cellSize = 1.1;
const outerColumns = 12;
const outerRows = 9;
const waterTiles = [];
for (let row = 0; row < outerRows; row++) {
for (let column = 0; column < outerColumns; column++) {
const isPond = column >= 2 && column < 10 && row >= 2 && row < 7;
if (isPond) continue;
const height = 0.54 + random() * 0.26;
const x = (column - (outerColumns - 1) / 2) * cellSize;
const z = (row - (outerRows - 1) / 2) * cellSize;
addBox(
world,
[1.04, height, 1.04],
[x, -0.3 + height / 2, z],
landMaterials[Math.floor(random() * landMaterials.length)]
);
if (random() > 0.82) {
addBox(
world,
[0.3, 0.2, 0.28],
[x + 0.23, -0.3 + height + 0.1, z - 0.18],
stoneMaterial
);
}
}
}
const waterMaterial = standardMaterial(0x3f9daa, {
transparent: true,
opacity: 0.56,
depthWrite: false,
roughness: 0.32
});
for (let row = 0; row < 5; row++) {
for (let column = 0; column < 8; column++) {
const x = (column - 3.5) * cellSize;
const z = (row - 2) * cellSize;
const tile = addBox(
world,
[1.055, 0.14, 1.055],
[x, -0.105, z],
waterMaterial,
false
);
tile.userData.baseY = tile.position.y;
tile.userData.phase = random() * Math.PI * 2;
waterTiles.push(tile);
}
}
function createTree(x, z, scale = 1) {
const tree = new THREE.Group();
tree.position.set(x, 0.18, z);
tree.scale.setScalar(scale);
addBox(tree, [0.24, 1.05, 0.24], [0, 0.52, 0], treeTrunkMaterial);
addBox(tree, [0.92, 0.72, 0.86], [0, 1.22, 0], leafMaterials[0]);
addBox(tree, [0.68, 0.58, 0.7], [0.42, 1.55, 0.06], leafMaterials[1]);
addBox(tree, [0.58, 0.52, 0.62], [-0.35, 1.63, -0.08], leafMaterials[2]);
tree.userData.crown = tree.children.slice(1);
world.add(tree);
return tree;
}
createTree(-5.3, -3.7, 0.9);
createTree(5.35, -3.65, 1.05);
createTree(5.35, 3.65, 0.84);
createTree(-2.6, -4.0, 0.64);
function createReed(x, z, height) {
const group = new THREE.Group();
group.position.set(x, 0.12, z);
addBox(group, [0.08, height, 0.08], [0, height / 2, 0], reedMaterial);
addBox(
group,
[0.13, 0.27, 0.13],
[0, height + 0.08, 0],
reedTipMaterial
);
world.add(group);
}
[
[-4.62, -2.1, 0.65],
[-4.58, 1.95, 0.85],
[4.62, -1.8, 0.72],
[4.58, 2.05, 0.92],
[-2.9, -2.52, 0.56],
[2.9, 2.5, 0.62]
].forEach(([x, z, height]) => createReed(x, z, height));
// -------------------------------------------------------------------------
// Algae units: one visible voxel cluster per algae count
// -------------------------------------------------------------------------
const algaeUnits = [];
const algaeScales = [];
const pondCells = [];
for (let row = 0; row < 5; row++) {
for (let column = 0; column < 8; column++) {
pondCells.push({
x: (column - 3.5) * cellSize,
z: (row - 2) * cellSize
});
}
}
// Fisher-Yates shuffle so the visible algae are spread across the pond.
for (let i = pondCells.length - 1; i > 0; i--) {
const j = Math.floor(random() * (i + 1));
[pondCells[i], pondCells[j]] = [pondCells[j], pondCells[i]];
}
const algaeStemMaterial = standardMaterial(0x39724c);
const algaeCapMaterials = [
standardMaterial(0x83cf61),
standardMaterial(0x68b955),
standardMaterial(0x9ad66b)
];
for (let i = 0; i < LIMITS.algae; i++) {
const cell = pondCells[i];
const angle = random() * Math.PI * 2;
const radius = 0.1 + random() * 0.22;
const unit = new THREE.Group();
unit.position.set(
cell.x + Math.cos(angle) * radius,
-0.01,
cell.z + Math.sin(angle) * radius
);
addBox(unit, [0.1, 0.28, 0.1], [0, 0.14, 0], algaeStemMaterial);
addBox(
unit,
[0.29, 0.21, 0.28],
[0, 0.31, 0],
algaeCapMaterials[i % algaeCapMaterials.length]
);
unit.scale.setScalar(0.001);
world.add(unit);
algaeUnits.push(unit);
algaeScales.push(0);
}
// -------------------------------------------------------------------------
// Fish: fully voxel-built creatures
// -------------------------------------------------------------------------
const fishMeshes = [];
const fishScales = [];
const fishBodyMaterial = standardMaterial(0xf39a52);
const fishFinMaterial = standardMaterial(0xd66d3d);
const fishEyeMaterial = standardMaterial(0x122926);
for (let i = 0; i < LIMITS.fish; i++) {
const fish = new THREE.Group();
addBox(fish, [0.5, 0.22, 0.25], [0, 0, 0], fishBodyMaterial);
addBox(fish, [0.15, 0.2, 0.3], [0.28, 0, 0], fishBodyMaterial);
const tailPivot = new THREE.Group();
tailPivot.position.set(-0.27, 0, 0);
addBox(tailPivot, [0.22, 0.2, 0.09], [-0.1, 0, 0], fishFinMaterial);
addBox(tailPivot, [0.18, 0.16, 0.25], [-0.08, 0, 0], fishFinMaterial);
fish.add(tailPivot);
addBox(fish, [0.12, 0.1, 0.12], [-0.05, 0.16, 0], fishFinMaterial);
addBox(fish, [0.075, 0.075, 0.035], [0.2, 0.045, 0.142], fishEyeMaterial);
addBox(fish, [0.075, 0.075, 0.035], [0.2, 0.045, -0.142], fishEyeMaterial);
fish.userData.tail = tailPivot;
fish.scale.setScalar(0.001);
world.add(fish);
fishMeshes.push(fish);
fishScales.push(0);
}
// -------------------------------------------------------------------------
// Nutrient and oxygen voxel meters
// -------------------------------------------------------------------------
function createTextSprite(text, color = "#f4f0dc") {
const canvas = document.createElement("canvas");
canvas.width = 128;
canvas.height = 64;
const context = canvas.getContext("2d");
context.fillStyle = "#173d39";
context.fillRect(0, 0, 128, 64);
context.strokeStyle = color;
context.lineWidth = 5;
context.strokeRect(4, 4, 120, 56);
context.fillStyle = color;
context.font = "900 29px monospace";
context.textAlign = "center";
context.textBaseline = "middle";
context.fillText(text, 64, 34);
const texture = new THREE.CanvasTexture(canvas);
texture.colorSpace = THREE.SRGBColorSpace;
const sprite = new THREE.Sprite(
new THREE.SpriteMaterial({
map: texture,
transparent: true,
depthTest: false,
depthWrite: false
})
);
sprite.scale.set(0.9, 0.45, 1);
sprite.renderOrder = 10;
return sprite;
}
const meterBlocks = [];
function createMeter(x, z, label, color, max) {
const group = new THREE.Group();
group.position.set(x, 0.25, z);
const baseMaterial = standardMaterial(0x264a45);
const blockMaterial = standardMaterial(color);
addBox(group, [0.9, 0.16, 0.72], [0, 0.08, 0], baseMaterial);
const rows = Math.ceil(max / 2);
for (let i = 0; i < max; i++) {
const column = Math.floor(i / rows);
const row = i % rows;
const block = addBox(
group,
[0.29, 0.11, 0.29],
[(column - 0.5) * 0.34, 0.25 + row * 0.125, 0],
blockMaterial
);
block.scale.setScalar(0.001);
meterBlocks.push({ block, resource: label === "N" ? "nutrient" : "oxygen", index: i });
}
const sprite = createTextSprite(label, color);
sprite.position.set(0, rows * 0.125 + 0.48, 0);
group.add(sprite);
world.add(group);
}
createMeter(-5.43, 3.45, "N", "#ffc766", LIMITS.nutrient);
createMeter(-5.43, 2.35, "O₂", "#66d8e8", LIMITS.oxygen);
// -------------------------------------------------------------------------
// Tick pulses: voxel square outlines used to emphasize each phase
// -------------------------------------------------------------------------
const pulses = [];
function spawnPulse(color) {
const group = new THREE.Group();
group.position.set(0, 0.42, 0);
const material = new THREE.MeshBasicMaterial({
color,
transparent: true,
opacity: 0.75,
depthWrite: false
});
const thickness = 0.09;
const size = 5.2;
addBox(group, [size, thickness, thickness], [0, 0, -size / 2], material, false);
addBox(group, [size, thickness, thickness], [0, 0, size / 2], material, false);
addBox(group, [thickness, thickness, size], [-size / 2, 0, 0], material, false);
addBox(group, [thickness, thickness, size], [size / 2, 0, 0], material, false);
world.add(group);
pulses.push({ group, material, born: performance.now() });
}
function clearPulses() {
for (const pulse of pulses) {
world.remove(pulse.group);
pulse.group.traverse((object) => {
if (object.geometry) object.geometry.dispose();
});
pulse.material.dispose();
}
pulses.length = 0;
}
// -------------------------------------------------------------------------
// Exact discrete simulation
// -------------------------------------------------------------------------
function simulateTick(before) {
let algae = before.algae;
let nutrient = before.nutrient;
let oxygen = before.oxygen;
let fish = before.fish;
// 1. Runoff and settling.
const nutrientGrowth = Math.min(3, LIMITS.nutrient - nutrient);
nutrient += nutrientGrowth;
const nutrientLoss = Math.min(
nutrient,
1 + Math.floor(algae / 8)
);
nutrient -= nutrientLoss;
const afterNutrientCycle = {
algae,
nutrient,
oxygen,
fish
};
// 2. Algae growth and nutrient uptake.
const algaeGrowth = Math.min(
2,
Math.floor(nutrient / 4),
LIMITS.algae - algae
);
algae += algaeGrowth;
nutrient = Math.max(0, nutrient - algaeGrowth);
const afterAlgaeGrowth = {
algae,
nutrient,
oxygen,
fish
};
// 3. Excess algae decomposes before fish feed.
const algaeLoss = algae > 18
? Math.min(algae, Math.ceil((algae - 18) / 2))
: 0;
algae -= algaeLoss;
const afterAlgaeLoss = {
algae,
nutrient,
oxygen,
fish
};
// 4. Each existing fish may consume one algae unit.
const algaeConsumption = Math.min(algae, fish);
algae -= algaeConsumption;
const starvationLoss = fish - algaeConsumption;
const afterFeeding = {
algae,
nutrient,
oxygen,
fish
};
// 5. Births and losses.
const fishGrowth = Math.min(
LIMITS.fish - fish,
Math.floor(algaeConsumption / 3)
);
fish += fishGrowth;
const lowOxygenLoss = Math.max(0, 6 - oxygen);
const crowdingLoss = fish > 10
? Math.ceil((fish - 10) / 2)
: 0;
const fishLoss = Math.min(
fish,
starvationLoss + lowOxygenLoss + crowdingLoss
);
fish -= fishLoss;
const afterFish = {
algae,
nutrient,
oxygen,
fish
};
// 6. Oxygen production, respiration, and surface escape.
const oxygenGrowth = Math.min(
LIMITS.oxygen - oxygen,
Math.ceil(afterFeeding.algae / 2)
);
oxygen += oxygenGrowth;
const oxygenConsumption = Math.min(
oxygen,
Math.ceil(fish / 2)
);
oxygen -= oxygenConsumption;
const oxygenLoss = oxygen > 12 ? 1 : 0;
oxygen -= oxygenLoss;
const final = {
algae: clamp(algae, 0, LIMITS.algae),
nutrient: clamp(nutrient, 0, LIMITS.nutrient),
oxygen: clamp(oxygen, 0, LIMITS.oxygen),
fish: clamp(fish, 0, LIMITS.fish)
};
return {
before: { ...before },
final,
afterNutrientCycle,
afterAlgaeGrowth,
afterAlgaeLoss,
afterFeeding,
afterFish,
flows: {
algaeConsumption,
algaeGrowth,
algaeLoss,
nutrientConsumption: algaeGrowth,
nutrientGrowth,
nutrientLoss,
oxygenConsumption,
oxygenGrowth,
oxygenLoss,
fishConsumption: 0,
fishGrowth,
fishLoss
}
};
}
// -------------------------------------------------------------------------
// Ledger and status rendering
// -------------------------------------------------------------------------
const flowElements = {
algaeUse: $("flowAlgaeUse"),
algaeGrow: $("flowAlgaeGrow"),
algaeLoss: $("flowAlgaeLoss"),
nutrientUse: $("flowNutrientUse"),
nutrientGrow: $("flowNutrientGrow"),
nutrientLoss: $("flowNutrientLoss"),
oxygenUse: $("flowOxygenUse"),
oxygenGrow: $("flowOxygenGrow"),
oxygenLoss: $("flowOxygenLoss"),
fishUse: $("flowFishUse"),
fishGrow: $("flowFishGrow"),
fishLoss: $("flowFishLoss")
};
function setFlow(element, amount, description) {
element.textContent = String(amount);
element.title = description;
element.classList.toggle("zero", amount === 0);
}
function renderFlows(flows) {
setFlow(
flowElements.algaeUse,
flows.algaeConsumption,
"Algae units consumed by fish"
);
setFlow(
flowElements.algaeGrow,
flows.algaeGrowth,
"New algae produced by nutrient-supported growth"
);
setFlow(
flowElements.algaeLoss,
flows.algaeLoss,
"Algae removed by decomposition"
);
setFlow(
flowElements.nutrientUse,
flows.nutrientConsumption,
"Nutrients consumed by algal growth"
);
setFlow(
flowElements.nutrientGrow,
flows.nutrientGrowth,
"Nutrients added by runoff"
);
setFlow(
flowElements.nutrientLoss,
flows.nutrientLoss,
"Nutrients removed by settling"
);
setFlow(
flowElements.oxygenUse,
flows.oxygenConsumption,
"Oxygen consumed by fish respiration"
);
setFlow(
flowElements.oxygenGrow,
flows.oxygenGrowth,
"Oxygen produced by photosynthesis"
);
setFlow(
flowElements.oxygenLoss,
flows.oxygenLoss,
"Oxygen lost from the water surface"
);
setFlow(
flowElements.fishUse,
flows.fishConsumption,
"No predators exist in this fictional ruleset"
);
setFlow(
flowElements.fishGrow,
flows.fishGrowth,
"New fish born after successful feeding"
);
setFlow(
flowElements.fishLoss,
flows.fishLoss,
"Fish lost to starvation, low oxygen, or crowding"
);
}
function updateCounts(values) {
const rounded = {
algae: Math.round(values.algae),
nutrient: Math.round(values.nutrient),
oxygen: Math.round(values.oxygen),
fish: Math.round(values.fish)
};
$("statAlgae").textContent = rounded.algae;
$("statNutrient").textContent = rounded.nutrient;
$("statOxygen").textContent = rounded.oxygen;
$("statFish").textContent = rounded.fish;
$("rowAlgae").textContent = rounded.algae;
$("rowNutrient").textContent = rounded.nutrient;
$("rowOxygen").textContent = rounded.oxygen;
$("rowFish").textContent = rounded.fish;
}
function addLog(result) {
const flows = result.flows;
const line = document.createElement("div");
line.className = "log-line";
line.textContent =
`Tick ${tickNumber}: ` +
`Algae +${flows.algaeGrowth}/−${flows.algaeConsumption}/−${flows.algaeLoss} → ${result.final.algae}; ` +
`Fish +${flows.fishGrowth}/−${flows.fishLoss} → ${result.final.fish}; ` +
`N ${result.before.nutrient}→${result.final.nutrient}; ` +
`O₂ ${result.before.oxygen}→${result.final.oxygen}.`;
const log = $("eventLog");
log.prepend(line);
while (log.children.length > 4) {
log.lastElementChild.remove();
}
}
// -------------------------------------------------------------------------
// One-tick animation
// -------------------------------------------------------------------------
const phaseDots = [...document.querySelectorAll(".phase-dots span")];
function setPhase(index) {
phaseDots.forEach((dot, dotIndex) => {
dot.classList.toggle("complete", dotIndex < index);
dot.classList.toggle("active", dotIndex === index);
});
}
function sampleKeyframes(keyframes, time) {
if (time <= keyframes[0].time) return keyframes[0].value;
for (let i = 1; i < keyframes.length; i++) {
const previous = keyframes[i - 1];
const current = keyframes[i];
if (time <= current.time) {
const amount = (time - previous.time) / (current.time - previous.time);
const eased = 1 - Math.pow(1 - amount, 3);
return THREE.MathUtils.lerp(previous.value, current.value, eased);
}
}
return keyframes[keyframes.length - 1].value;
}
function beginTickAnimation(result) {
const start = performance.now();
const duration = 1850;
animation = {
result,
start,
duration,
keyframes: {
algae: [
{ time: 0, value: result.before.algae },
{ time: 260, value: result.afterAlgaeGrowth.algae },
{ time: 430, value: result.afterAlgaeLoss.algae },
{ time: 700, value: result.afterFeeding.algae }
],
nutrient: [
{ time: 0, value: result.before.nutrient },
{ time: 130, value: result.afterNutrientCycle.nutrient },
{ time: 320, value: result.afterAlgaeGrowth.nutrient }
],
oxygen: [
{ time: 0, value: result.before.oxygen },
{ time: 1320, value: result.final.oxygen }
],
fish: [
{ time: 0, value: result.before.fish },
{ time: 900, value: result.afterFish.fish }
]
}
};
const flows = result.flows;
const phases = [
{
delay: 0,
title: "1 / 5 · Runoff and settling",
text:
`Runoff added ${flows.nutrientGrowth} nutrients; ` +
`${flows.nutrientLoss} nutrients settled out.`,
color: 0xffc766
},
{
delay: 260,
title: "2 / 5 · Algal growth and uptake",
text:
`Algae grew by ${flows.algaeGrowth} and consumed ` +
`${flows.nutrientConsumption} nutrients.`,
color: 0x8ddd72
},
{
delay: 620,
title: "3 / 5 · Fish feeding",
text:
`${result.before.fish} fish consumed ${flows.algaeConsumption} algae units.`,
color: 0xffc766
},
{
delay: 880,
title: "4 / 5 · Births and losses",
text:
`${flows.fishGrowth} fish were born; ${flows.fishLoss} were lost ` +
`to starvation, oxygen stress, or crowding.`,
color: 0xff806f
},
{
delay: 1280,
title: "5 / 5 · Oxygen balance",
text:
`Photosynthesis added ${flows.oxygenGrowth} oxygen; ` +
`${flows.oxygenConsumption} was consumed and ${flows.oxygenLoss} escaped.`,
color: 0x66d8e8
}
];
phases.forEach((phase, index) => {
phaseTimers.push(setTimeout(() => {
setPhase(index);
$("phaseTitle").textContent = phase.title;
$("phaseText").textContent = phase.text;
spawnPulse(phase.color);
}, phase.delay));
});
phaseTimers.push(setTimeout(() => {
animation = null;
Object.assign(visual, result.final);
updateCounts(visual);
setPhase(5);
$("phaseTitle").textContent = `Tick ${tickNumber} complete`;
$("phaseText").textContent =
`Final totals: algae ${result.final.algae}, fish ${result.final.fish}, ` +
`nutrients ${result.final.nutrient}, oxygen ${result.final.oxygen}.`;
$("progressFill").style.width = "100%";
$("status").textContent = `Tick ${tickNumber} complete`;
$("stepButton").disabled = false;
$("stepButton").textContent = "▶ Run one update";
addLog(result);
}, duration + 30));
}
function runTick() {
if (animation) return;
tickNumber += 1;
const result = simulateTick(state);
state = { ...result.final };
renderFlows(result.flows);
$("stepButton").disabled = true;
$("stepButton").textContent = "Updating tick…";
$("status").textContent = `Updating · tick ${tickNumber}`;
beginTickAnimation(result);
}
function resetSimulation() {
phaseTimers.forEach(clearTimeout);
phaseTimers = [];
animation = null;
clearPulses();
state = { ...INITIAL };
Object.assign(visual, INITIAL);
tickNumber = 0;
renderFlows(zeroFlows());
updateCounts(visual);
setPhase(0);
$("status").textContent = "Ready · tick 0";
$("phaseTitle").textContent = "Ready for one discrete update";
$("phaseText").textContent =
"The pond starts at algae 12, fish 5, nutrients 14, oxygen 11.";
$("progressFill").style.width = "0%";
$("stepButton").disabled = false;
$("stepButton").textContent = "▶ Run one update";
$("eventLog").innerHTML =
'<div class="log-line">No update yet. Each click advances exactly one tick.</div>';
}
$("stepButton").addEventListener("click", runTick);
$("resetButton").addEventListener("click", resetSimulation);
// -------------------------------------------------------------------------
// Direct camera controls — no Three.js addons
// -------------------------------------------------------------------------
function updateCamera() {
const radius = 25;
const sinPhi = Math.sin(controls.phi);
camera.position.set(
controls.target.x + radius * sinPhi * Math.sin(controls.theta),
controls.target.y + radius * Math.cos(controls.phi),
controls.target.z + radius * sinPhi * Math.cos(controls.theta)
);
camera.zoom = controls.zoom;
camera.updateProjectionMatrix();
camera.lookAt(controls.target);
}
let dragging = false;
let pointerX = 0;
let pointerY = 0;
renderer.domElement.addEventListener("pointerdown", (event) => {
dragging = true;
pointerX = event.clientX;
pointerY = event.clientY;
renderer.domElement.classList.add("dragging");
renderer.domElement.setPointerCapture(event.pointerId);
});
renderer.domElement.addEventListener("pointermove", (event) => {
if (!dragging) return;
const deltaX = event.clientX - pointerX;
const deltaY = event.clientY - pointerY;
pointerX = event.clientX;
pointerY = event.clientY;
controls.theta -= deltaX * 0.006;
controls.phi = clamp(controls.phi + deltaY * 0.005, 0.38, 1.22);
updateCamera();
});
function endDrag(event) {
dragging = false;
renderer.domElement.classList.remove("dragging");
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("wheel", (event) => {
event.preventDefault();
controls.zoom = clamp(
controls.zoom * Math.exp(-event.deltaY * 0.001),
0.72,
1.8
);
updateCamera();
}, { passive: false });
window.addEventListener("keydown", (event) => {
const tag = event.target?.tagName?.toLowerCase();
if (tag === "button" || tag === "input" || tag === "textarea") return;
if (event.code === "Space") {
event.preventDefault();
runTick();
}
if (event.code === "KeyR") {
resetSimulation();
}
if (event.code === "ArrowLeft") {
controls.theta += 0.08;
updateCamera();
}
if (event.code === "ArrowRight") {
controls.theta -= 0.08;
updateCamera();
}
});
// -------------------------------------------------------------------------
// Scene animation and rendering
// -------------------------------------------------------------------------
function resize() {
const width = viewport.clientWidth;
const height = viewport.clientHeight;
const aspect = width / Math.max(1, height);
// Maintain enough horizontal room on narrow screens.
const halfHeight = Math.max(6.6, 7.5 / aspect);
camera.left = -halfHeight * aspect;
camera.right = halfHeight * aspect;
camera.top = halfHeight;
camera.bottom = -halfHeight;
camera.updateProjectionMatrix();
renderer.setSize(width, height, false);
updateCamera();
}
window.addEventListener("resize", resize);
function updateAnimation(time) {
if (!animation) return;
const elapsed = time - animation.start;
const progress = clamp(elapsed / animation.duration, 0, 1);
visual.algae = sampleKeyframes(
animation.keyframes.algae,
elapsed
);
visual.nutrient = sampleKeyframes(
animation.keyframes.nutrient,
elapsed
);
visual.oxygen = sampleKeyframes(
animation.keyframes.oxygen,
elapsed
);
visual.fish = sampleKeyframes(
animation.keyframes.fish,
elapsed
);
$("progressFill").style.width = `${progress * 100}%`;
updateCounts(visual);
}
function updateScene(time, delta) {
const smoothing = 1 - Math.exp(-delta * 11);
for (let i = 0; i < algaeUnits.length; i++) {
const desired = i < visual.algae ? 1 : 0;
algaeScales[i] += (desired - algaeScales[i]) * smoothing;
if (desired === 0 && algaeScales[i] < 0.015) {
algaeScales[i] = 0;
}
algaeUnits[i].scale.setScalar(Math.max(0.001, algaeScales[i]));
}
for (let i = 0; i < fishMeshes.length; i++) {
const desired = i < visual.fish ? 1 : 0;
fishScales[i] += (desired - fishScales[i]) * smoothing;
if (desired === 0 && fishScales[i] < 0.015) {
fishScales[i] = 0;
}
const fish = fishMeshes[i];
const angle = time * 0.00019 + i * 2.399;
const nextAngle = angle + 0.01;
const x = Math.cos(angle) * 3.0;
const z = Math.sin(angle) * 1.48;
const nextX = Math.cos(nextAngle) * 3.0;
const nextZ = Math.sin(nextAngle) * 1.48;
fish.position.set(
x,
0.08 + Math.sin(time * 0.002 + i) * 0.035,
z
);
fish.rotation.y = -Math.atan2(nextZ - z, nextX - x);
fish.userData.tail.rotation.y =
Math.sin(time * 0.009 + i * 1.7) * 0.34;
fish.scale.setScalar(Math.max(0.001, fishScales[i]));
}
for (const meter of meterBlocks) {
const desired = meter.index < visual[meter.resource] ? 1 : 0;
meter.block.userData.scale = meter.block.userData.scale || 0;
meter.block.userData.scale +=
(desired - meter.block.userData.scale) * smoothing;
meter.block.scale.setScalar(
Math.max(0.001, meter.block.userData.scale)
);
}
for (const tile of waterTiles) {
tile.position.y =
tile.userData.baseY +
Math.sin(time * 0.0014 + tile.userData.phase) * 0.012;
}
for (let i = pulses.length - 1; i >= 0; i--) {
const pulse = pulses[i];
const age = (time - pulse.born) / 1000;
if (age > 1.2) {
world.remove(pulse.group);
pulse.group.traverse((object) => {
if (object.geometry) object.geometry.dispose();
});
pulse.material.dispose();
pulses.splice(i, 1);
continue;
}
const scale = 0.55 + age * 1.25;
pulse.group.scale.set(scale, 1, scale);
pulse.group.position.y = 0.42 + age * 0.7;
pulse.material.opacity = Math.max(0, 0.72 * (1 - age / 1.2));
}
}
let previousTime = performance.now();
function frame(time) {
requestAnimationFrame(frame);
const delta = Math.min(0.05, (time - previousTime) / 1000);
previousTime = time;
updateAnimation(time);
updateScene(time, delta);
renderer.render(scene, camera);
}
renderFlows(zeroFlows());
updateCounts(visual);
resize();
requestAnimationFrame(frame);
</script>
</body>
</html>
```