Prompt specification
Build or customize the Three.js 3D scene "Counted kelp grazers with an otter toggle" 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: Counted kelp grazers with an otter toggle
Category: Voxel Worlds · Style: Voxel 3D
License: MIT · Reference: https://three3d.app/scene/counted-kelp-grazers-with-an-otter-toggle-x0707
Scene Description Prompt:
Build matched kelp patches with counted urchins; toggling one otter changes a labeled toy predation rule, producing contrasting grazer counts and visible kelp-grazing marks. Use Three.js from cdnjs in a single HTML file, with visible voxel blocks.
Working Three.js Starter (counted-kelp-grazers-with-an-otter-toggle-x0707):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Voxel Kelp & Urchin Lab</title>
<style>
:root {
--ink: #163c43;
--muted: #61787b;
--paper: #f8fbf7;
--line: #dce8e3;
--green: #3faa72;
--teal: #228f8a;
--orange: #f28a48;
--purple: #654292;
--shadow: 0 12px 30px rgba(25, 66, 70, 0.10);
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
}
body {
overflow: hidden;
color: var(--ink);
background: #d6ece7;
font-family:
Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
button {
font: inherit;
}
.app {
display: grid;
grid-template-rows: 68px minmax(0, 1fr);
width: 100%;
height: 100%;
}
.topbar {
z-index: 10;
display: flex;
align-items: center;
justify-content: space-between;
gap: 18px;
padding: 0 22px;
background: rgba(248, 251, 247, 0.94);
border-bottom: 1px solid rgba(35, 83, 86, 0.12);
box-shadow: 0 4px 18px rgba(27, 73, 74, 0.06);
}
.brand {
display: flex;
align-items: center;
gap: 12px;
min-width: 0;
}
.brand-mark {
display: grid;
grid-template-columns: repeat(2, 10px);
grid-template-rows: repeat(2, 10px);
gap: 3px;
transform: rotate(-6deg);
}
.brand-mark span {
display: block;
background: var(--green);
border-radius: 2px;
box-shadow: inset -2px -2px 0 rgba(0, 0, 0, 0.08);
}
.brand-mark span:nth-child(2) {
background: var(--teal);
}
.brand-mark span:nth-child(3) {
background: #7bcf9c;
}
.brand h1 {
margin: 0;
font-size: 17px;
line-height: 1.1;
letter-spacing: 0.02em;
white-space: nowrap;
}
.brand p {
margin: 4px 0 0;
color: var(--muted);
font-size: 12px;
white-space: nowrap;
}
.trial-meta {
display: flex;
align-items: center;
gap: 9px;
color: var(--muted);
font-size: 12px;
white-space: nowrap;
}
.clock {
min-width: 62px;
padding: 7px 10px;
color: var(--ink);
font-weight: 800;
font-variant-numeric: tabular-nums;
text-align: center;
background: #eaf4ee;
border: 1px solid #d2e5dc;
border-radius: 9px;
}
main {
display: grid;
grid-template-columns: 310px minmax(0, 1fr);
min-height: 0;
}
.sidebar {
z-index: 5;
min-height: 0;
overflow-y: auto;
padding: 20px;
background: var(--paper);
border-right: 1px solid rgba(35, 83, 86, 0.12);
}
.eyebrow {
margin: 0 0 7px;
color: var(--teal);
font-size: 10px;
font-weight: 900;
letter-spacing: 0.15em;
text-transform: uppercase;
}
.intro {
margin: 0 0 18px;
color: var(--muted);
font-size: 13px;
line-height: 1.55;
}
.control-card,
.rule-card,
.stat-card,
.notes {
background: #fff;
border: 1px solid var(--line);
border-radius: 14px;
box-shadow: 0 5px 18px rgba(36, 79, 80, 0.045);
}
.control-card {
padding: 14px;
margin-bottom: 12px;
}
.control-heading {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
}
.control-heading strong {
font-size: 13px;
}
.switch {
display: inline-flex;
align-items: center;
gap: 8px;
padding: 5px 8px 5px 5px;
color: #65797a;
font-size: 11px;
font-weight: 900;
letter-spacing: 0.06em;
background: #edf2ef;
border: 1px solid #dbe4df;
border-radius: 999px;
cursor: pointer;
transition: 160ms ease;
}
.switch:focus-visible {
outline: 3px solid rgba(34, 143, 138, 0.25);
outline-offset: 2px;
}
.switch-track {
position: relative;
width: 37px;
height: 21px;
background: #b8c7c4;
border-radius: 99px;
transition: 160ms ease;
}
.switch-knob {
position: absolute;
top: 3px;
left: 3px;
width: 15px;
height: 15px;
background: #fff;
border-radius: 4px;
box-shadow: 0 2px 5px rgba(0, 0, 0, 0.16);
transition: 160ms ease;
}
.switch.on {
color: #fff;
background: var(--teal);
border-color: var(--teal);
}
.switch.on .switch-track {
background: #55b6ae;
}
.switch.on .switch-knob {
transform: translateX(16px);
}
.switch-label {
margin-top: 10px;
color: var(--muted);
font-size: 11px;
}
.rule-card {
position: relative;
overflow: hidden;
padding: 15px;
margin-bottom: 15px;
border-left: 5px solid #b7c6c2;
}
.rule-card.active {
border-left-color: var(--orange);
background: #fffaf5;
}
.rule-title {
display: flex;
align-items: center;
justify-content: space-between;
gap: 8px;
margin-bottom: 7px;
}
.rule-title strong {
font-size: 11px;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.rule-state {
padding: 4px 7px;
color: #6c7b79;
font-size: 9px;
font-weight: 900;
letter-spacing: 0.08em;
background: #edf1ef;
border-radius: 99px;
}
.rule-card.active .rule-state {
color: #a64d19;
background: #ffe2cc;
}
.rule-text {
margin: 0;
color: #516b6e;
font-size: 12px;
line-height: 1.55;
}
.stats-title {
margin: 0 0 9px;
font-size: 11px;
font-weight: 900;
letter-spacing: 0.1em;
text-transform: uppercase;
}
.stat-card {
position: relative;
padding: 13px 13px 12px;
margin-bottom: 9px;
overflow: hidden;
}
.stat-card::before {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 4px;
content: "";
background: var(--teal);
}
.stat-card.otter::before {
background: var(--orange);
}
.stat-head {
display: flex;
align-items: center;
justify-content: space-between;
gap: 8px;
margin-bottom: 9px;
}
.stat-head strong {
font-size: 12px;
}
.stat-tag {
color: var(--muted);
font-size: 9px;
font-weight: 900;
letter-spacing: 0.06em;
text-transform: uppercase;
}
.stat-grid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 8px;
}
.stat-number {
display: block;
font-size: 27px;
font-weight: 900;
line-height: 1;
font-variant-numeric: tabular-nums;
}
.stat-label {
display: block;
margin-top: 4px;
color: var(--muted);
font-size: 10px;
}
.difference {
margin: 10px 1px 15px;
padding: 9px 10px;
color: #5c7273;
font-size: 11px;
font-weight: 700;
text-align: center;
background: #edf4f0;
border-radius: 9px;
}
.reset-button {
width: 100%;
padding: 11px 12px;
color: #fff;
font-size: 12px;
font-weight: 900;
letter-spacing: 0.02em;
background: var(--ink);
border: 0;
border-radius: 10px;
cursor: pointer;
transition: 150ms ease;
}
.reset-button:hover {
background: #225a62;
transform: translateY(-1px);
}
.reset-button:focus-visible {
outline: 3px solid rgba(34, 143, 138, 0.25);
outline-offset: 2px;
}
.notes {
margin-top: 15px;
padding: 13px;
}
.notes h3 {
margin: 0 0 8px;
font-size: 11px;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.legend {
display: grid;
gap: 7px;
margin: 0;
padding: 0;
list-style: none;
}
.legend li {
display: flex;
align-items: center;
gap: 8px;
color: var(--muted);
font-size: 11px;
}
.swatch {
width: 13px;
height: 13px;
flex: 0 0 auto;
border-radius: 3px;
box-shadow: inset -2px -2px 0 rgba(0, 0, 0, 0.08);
}
.swatch.kelp {
background: #45a85f;
}
.swatch.urchin {
background: #654292;
}
.swatch.mark {
background: #ffae45;
}
.viewport {
position: relative;
min-width: 0;
min-height: 0;
overflow: hidden;
background: #b9dfdc;
}
.viewport canvas {
display: block;
width: 100%;
height: 100%;
touch-action: none;
cursor: grab;
}
.viewport canvas:active {
cursor: grabbing;
}
.world-label {
position: absolute;
z-index: 3;
min-width: 156px;
padding: 9px 11px;
pointer-events: none;
background: rgba(255, 255, 255, 0.92);
border: 1px solid rgba(31, 82, 83, 0.14);
border-radius: 11px;
box-shadow: var(--shadow);
transform: translate(-50%, -100%);
}
.world-label::after {
position: absolute;
bottom: -7px;
left: 50%;
width: 12px;
height: 12px;
content: "";
background: rgba(255, 255, 255, 0.92);
border-right: 1px solid rgba(31, 82, 83, 0.14);
border-bottom: 1px solid rgba(31, 82, 83, 0.14);
transform: translateX(-50%) rotate(45deg);
}
.world-label.orange {
border-top: 4px solid var(--orange);
}
.world-label.teal {
border-top: 4px solid var(--teal);
}
.world-label h2 {
margin: 0 0 5px;
font-size: 10px;
font-weight: 900;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.world-label p {
margin: 2px 0 0;
color: var(--muted);
font-size: 10px;
}
.world-label b {
color: var(--ink);
font-size: 13px;
}
.scene-hint {
position: absolute;
right: 16px;
bottom: 15px;
z-index: 3;
padding: 8px 11px;
pointer-events: none;
color: rgba(22, 60, 67, 0.74);
font-size: 10px;
font-weight: 800;
letter-spacing: 0.03em;
background: rgba(246, 252, 249, 0.75);
border: 1px solid rgba(27, 76, 78, 0.10);
border-radius: 9px;
backdrop-filter: blur(8px);
}
.scene-badge {
position: absolute;
top: 14px;
left: 16px;
z-index: 3;
padding: 8px 10px;
pointer-events: none;
color: #315e61;
font-size: 10px;
font-weight: 900;
letter-spacing: 0.07em;
text-transform: uppercase;
background: rgba(246, 252, 249, 0.78);
border: 1px solid rgba(27, 76, 78, 0.10);
border-radius: 9px;
backdrop-filter: blur(8px);
}
@media (max-width: 820px) {
body {
overflow: auto;
}
.app {
min-height: 100dvh;
height: auto;
grid-template-rows: 62px auto;
}
.topbar {
padding: 0 14px;
}
.brand p,
.trial-meta > span:first-child {
display: none;
}
main {
display: flex;
flex-direction: column;
}
.viewport {
order: 1;
height: 58dvh;
min-height: 380px;
}
.sidebar {
order: 2;
overflow: visible;
padding: 18px;
border-top: 1px solid rgba(35, 83, 86, 0.12);
border-right: 0;
}
}
@media (max-width: 480px) {
.brand h1 {
font-size: 14px;
}
.world-label {
min-width: 128px;
padding: 7px 8px;
}
.world-label h2 {
font-size: 8px;
}
.world-label p {
font-size: 8px;
}
.scene-hint {
right: 8px;
bottom: 8px;
font-size: 8px;
}
}
</style>
</head>
<body>
<div class="app">
<header class="topbar">
<div class="brand">
<div class="brand-mark" aria-hidden="true">
<span></span><span></span><span></span><span></span>
</div>
<div>
<h1>Voxel Kelp & Urchin Lab</h1>
<p>Two matched habitats, one otter-controlled toy rule</p>
</div>
</div>
<div class="trial-meta">
<span>12 kelp stacks + 12 urchins per patch at reset</span>
<span class="clock" id="clock">00:00</span>
</div>
</header>
<main>
<aside class="sidebar">
<p class="eyebrow">Interactive field toy</p>
<p class="intro">
Switch the single otter on or off. Predation happens only in the
left patch, while the right patch remains a matched control.
</p>
<section class="control-card">
<div class="control-heading">
<strong>Otter switch</strong>
<button
id="otterSwitch"
class="switch on"
type="button"
role="switch"
aria-checked="true"
aria-label="Otter predation rule"
>
<span class="switch-track">
<span class="switch-knob"></span>
</span>
<span id="switchState">ON</span>
</button>
</div>
<div class="switch-label" id="switchLabel">
The otter is patrolling the left patch.
</div>
</section>
<section class="rule-card active" id="ruleCard">
<div class="rule-title">
<strong>Toy predation rule</strong>
<span class="rule-state" id="ruleState">ACTIVE</span>
</div>
<p class="rule-text" id="ruleText">
OTTER ON → every 3 seconds, remove 1 urchin from the left patch.
The right patch has no predator.
</p>
</section>
<p class="stats-title">Live patch counts</p>
<article class="stat-card otter">
<div class="stat-head">
<strong>Otter patch</strong>
<span class="stat-tag">Predator patch</span>
</div>
<div class="stat-grid">
<div>
<span class="stat-number" id="urchinsA">12</span>
<span class="stat-label">urchins</span>
</div>
<div>
<span class="stat-number" id="marksA">0</span>
<span class="stat-label">graze marks</span>
</div>
</div>
</article>
<article class="stat-card">
<div class="stat-head">
<strong>Control patch</strong>
<span class="stat-tag">No predator</span>
</div>
<div class="stat-grid">
<div>
<span class="stat-number" id="urchinsB">12</span>
<span class="stat-label">urchins</span>
</div>
<div>
<span class="stat-number" id="marksB">0</span>
<span class="stat-label">graze marks</span>
</div>
</div>
</article>
<div class="difference" id="difference">Patches are matched</div>
<button class="reset-button" id="resetButton" type="button">
Reset & rematch patches
</button>
<section class="notes">
<h3>Read the habitat</h3>
<ul class="legend">
<li><span class="swatch kelp"></span>Green voxel stacks are kelp.</li>
<li><span class="swatch urchin"></span>Purple voxel clusters are urchins.</li>
<li><span class="swatch mark"></span>Orange cubes mark grazing damage.</li>
</ul>
</section>
</aside>
<section class="viewport" id="viewport" aria-label="Interactive kelp patch scene">
<div class="scene-badge">Matched-patch grazing experiment</div>
<div class="world-label orange" id="labelA">
<h2>Otter patch</h2>
<p><b>12</b> urchins · <b>0</b> graze marks</p>
</div>
<div class="world-label teal" id="labelB">
<h2>Matched control</h2>
<p><b>12</b> urchins · <b>0</b> graze marks</p>
</div>
<div class="scene-hint">
Drag: orbit · Wheel: zoom · O: otter · R: reset
</div>
</section>
</main>
</div>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
const viewport = document.getElementById("viewport");
const clockElement = document.getElementById("clock");
const switchElement = document.getElementById("otterSwitch");
const switchState = document.getElementById("switchState");
const switchLabel = document.getElementById("switchLabel");
const ruleCard = document.getElementById("ruleCard");
const ruleState = document.getElementById("ruleState");
const ruleText = document.getElementById("ruleText");
const differenceElement = document.getElementById("difference");
const resetButton = document.getElementById("resetButton");
const countElements = {
urchinsA: document.getElementById("urchinsA"),
marksA: document.getElementById("marksA"),
urchinsB: document.getElementById("urchinsB"),
marksB: document.getElementById("marksB")
};
const labelA = document.getElementById("labelA");
const labelB = document.getElementById("labelB");
// ------------------------------------------------------------
// Three.js setup
// ------------------------------------------------------------
const scene = new THREE.Scene();
scene.background = new THREE.Color(0xb9dfdc);
scene.fog = new THREE.Fog(0xb9dfdc, 25, 48);
const camera = new THREE.PerspectiveCamera(42, 1, 0.1, 100);
const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 2));
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.08;
renderer.domElement.setAttribute(
"aria-label",
"Two voxel kelp patches with urchins and a controllable otter"
);
viewport.prepend(renderer.domElement);
const hemisphere = new THREE.HemisphereLight(0xf1ffff, 0x806c4e, 2.25);
scene.add(hemisphere);
const sun = new THREE.DirectionalLight(0xfff6dc, 3.1);
sun.position.set(-7, 15, 9);
sun.castShadow = true;
sun.shadow.mapSize.set(2048, 2048);
sun.shadow.camera.left = -15;
sun.shadow.camera.right = 15;
sun.shadow.camera.top = 15;
sun.shadow.camera.bottom = -15;
sun.shadow.camera.near = 1;
sun.shadow.camera.far = 40;
sun.shadow.bias = -0.00035;
scene.add(sun);
const fill = new THREE.DirectionalLight(0x8dd8e8, 1.0);
fill.position.set(9, 7, -8);
scene.add(fill);
const cubeGeometry = new THREE.BoxGeometry(1, 1, 1);
const materialCache = new Map();
function material(color) {
if (color?.isMaterial) return color;
if (!materialCache.has(color)) {
materialCache.set(
color,
new THREE.MeshStandardMaterial({
color,
roughness: 0.78,
metalness: 0.02
})
);
}
return materialCache.get(color);
}
function addBox(
parent,
width,
height,
depth,
color,
x = 0,
y = 0,
z = 0,
castShadow = true
) {
const mesh = new THREE.Mesh(cubeGeometry, material(color));
mesh.scale.set(width, height, depth);
mesh.position.set(x, y, z);
mesh.castShadow = castShadow;
mesh.receiveShadow = true;
parent.add(mesh);
return mesh;
}
function seededRandom(seed) {
return function () {
let t = (seed += 0x6d2b79f5);
t = Math.imul(t ^ (t >>> 15), t | 1);
t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
};
}
// Large blocky aquarium floor.
addBox(
scene,
38,
0.35,
28,
0x79b8b2,
0,
-0.72,
0,
false
);
// ------------------------------------------------------------
// Habitat construction
// ------------------------------------------------------------
const kelpLayout = [
[-3.05, -2.45],
[-1.80, -2.60],
[-0.45, -2.35],
[1.00, -2.55],
[2.65, -2.25],
[-3.15, -0.65],
[-1.55, -0.75],
[0.05, -0.70],
[1.65, -0.70],
[3.15, -0.55],
[-2.55, 1.25],
[-0.85, 1.20],
[0.85, 1.20],
[2.45, 1.15]
];
const urchinLayout = [
[-3.30, -1.25],
[-2.15, -1.65],
[-1.05, -1.05],
[-0.05, -1.65],
[1.05, -1.20],
[2.10, -1.70],
[3.05, -1.15],
[-2.85, 0.38],
[-1.75, 0.45],
[-0.45, 0.38],
[0.80, 0.48],
[2.35, 0.38]
];
const kelpColors = [
0x3b9f5c,
0x48ad65,
0x2f8f54,
0x61b975,
0x399b64
];
function createKelp(patch, index, x, z) {
const group = new THREE.Group();
group.position.set(x, 0.18, z);
patch.group.add(group);
const levels = 8 + (index % 4);
const leaves = [];
const phase = index * 0.72;
for (let level = 0; level < levels; level++) {
const trunkColor =
level % 3 === 0
? kelpColors[(index + 1) % kelpColors.length]
: kelpColors[index % kelpColors.length];
addBox(
group,
0.17,
0.49,
0.17,
trunkColor,
0,
0.28 + level * 0.50,
0
);
if (level > 0) {
for (const side of [-1, 1]) {
const leaf = addBox(
group,
0.64,
0.15,
0.27,
kelpColors[(index + level + (side > 0 ? 1 : 0)) % kelpColors.length],
side * 0.31,
0.39 + level * 0.50,
((level + index) % 2) * 0.08 - 0.04
);
leaf.rotation.z = side * 0.20;
leaves.push(leaf);
}
}
}
const plant = { group, leaves, phase, index };
patch.plants.push(plant);
return plant;
}
function createPatch(cx, name) {
const group = new THREE.Group();
group.position.x = cx;
scene.add(group);
const patch = {
cx,
name,
group,
plants: [],
urchins: [],
marks: [],
markCount: 0
};
// Raised voxel sand platform.
addBox(group, 9.2, 0.50, 8.4, 0xcfae75, 0, -0.12, 0);
addBox(group, 9.0, 0.09, 8.2, 0xe4c995, 0, 0.15, 0);
// Teal frame blocks.
addBox(group, 9.30, 0.13, 0.18, 0x317e79, 0, 0.25, -4.20);
addBox(group, 9.30, 0.13, 0.18, 0x317e79, 0, 0.25, 4.20);
addBox(group, 0.18, 0.13, 8.4, 0x317e79, -4.60, 0.25, 0);
addBox(group, 0.18, 0.13, 8.4, 0x317e79, 4.60, 0.25, 0);
kelpLayout.forEach(([x, z], index) => {
createKelp(patch, index, x, z);
});
// Matched arrangements of small sand and stone voxels.
const random = seededRandom(8128);
for (let i = 0; i < 24; i++) {
const size = 0.12 + random() * 0.22;
const x = -3.9 + random() * 7.8;
const z = -3.55 + random() * 7.1;
const color = i % 4 === 0 ? 0x8e9d90 : 0xb89b70;
addBox(
group,
size,
size * 0.60,
size,
color,
x,
0.24,
z
);
}
patch.labelAnchor = new THREE.Vector3(cx, 6.35, 0.15);
return patch;
}
const patchA = createPatch(-4.9, "Otter patch");
const patchB = createPatch(4.9, "Matched control");
// ------------------------------------------------------------
// Urchins
// ------------------------------------------------------------
function createUrchin(patch, index) {
const group = new THREE.Group();
patch.group.add(group);
addBox(group, 0.34, 0.34, 0.34, 0x5b3d86, 0, 0, 0);
addBox(group, 0.39, 0.18, 0.39, 0x7452a1, 0, 0, 0);
addBox(group, 0.13, 0.13, 0.13, 0x463071, 0.23, 0, 0);
addBox(group, 0.13, 0.13, 0.13, 0x463071, -0.23, 0, 0);
addBox(group, 0.13, 0.13, 0.13, 0x463071, 0, 0.23, 0);
addBox(group, 0.13, 0.13, 0.13, 0x463071, 0, -0.23, 0);
addBox(group, 0.13, 0.13, 0.13, 0x463071, 0, 0, 0.23);
addBox(group, 0.13, 0.13, 0.13, 0x463071, 0, 0, -0.23);
const urchin = {
group,
index,
alive: true,
plantIndex: index % patch.plants.length,
phase: index * 0.83,
speed: 0.22 + (index % 4) * 0.025,
radius: 0.42 + (index % 3) * 0.08,
nextGraze: 1.1 + (index % 6) * 0.52,
grazeInterval: 5.4 + (index % 5) * 0.58,
chew: 0
};
const [x, z] = urchinLayout[index];
group.position.set(x, 0.38, z);
patch.urchins.push(urchin);
return urchin;
}
function populateUrchins(patch) {
for (let i = 0; i < urchinLayout.length; i++) {
createUrchin(patch, i);
}
}
populateUrchins(patchA);
populateUrchins(patchB);
// ------------------------------------------------------------
// One block-built otter and its little dock
// ------------------------------------------------------------
const dock = new THREE.Group();
dock.position.set(-4.9, 0, 4.72);
scene.add(dock);
addBox(dock, 2.45, 0.18, 1.22, 0x936947, 0, 0.05, 0);
addBox(dock, 2.10, 0.10, 0.18, 0xb88758, 0, 0.17, -0.32);
addBox(dock, 2.10, 0.10, 0.18, 0xb88758, 0, 0.17, 0.32);
const otter = new THREE.Group();
scene.add(otter);
addBox(otter, 0.98, 0.45, 0.50, 0x795033, 0, 0.35, 0);
addBox(otter, 0.70, 0.15, 0.53, 0xc09261, 0.06, 0.25, 0);
addBox(otter, 0.43, 0.42, 0.44, 0x855937, 0.62, 0.49, 0);
addBox(otter, 0.27, 0.18, 0.30, 0xd5ad78, 0.86, 0.40, 0);
addBox(otter, 0.14, 0.16, 0.14, 0x70482d, 0.50, 0.75, -0.15);
addBox(otter, 0.14, 0.16, 0.14, 0x70482d, 0.50, 0.75, 0.15);
addBox(otter, 0.075, 0.075, 0.06, 0x172326, 0.78, 0.58, -0.16);
addBox(otter, 0.075, 0.075, 0.06, 0x172326, 0.78, 0.58, 0.16);
addBox(otter, 0.06, 0.05, 0.06, 0x292024, 0.99, 0.42, 0);
for (const x of [-0.30, 0.30]) {
for (const z of [-0.20, 0.20]) {
addBox(otter, 0.17, 0.28, 0.17, 0x67442b, x, 0.10, z);
}
}
addBox(otter, 0.38, 0.18, 0.18, 0x765035, -0.60, 0.29, 0);
addBox(otter, 0.34, 0.15, 0.16, 0x765035, -0.88, 0.32, 0);
addBox(otter, 0.27, 0.12, 0.14, 0x68462d, -1.12, 0.36, 0);
let otterOn = true;
let otterMix = 1;
let otterLunge = 0;
// ------------------------------------------------------------
// Grazing and predation
// ------------------------------------------------------------
const particles = [];
function spawnBurst(position, color) {
for (let i = 0; i < 9; i++) {
const mesh = addBox(
scene,
0.13 + Math.random() * 0.08,
0.13 + Math.random() * 0.08,
0.13 + Math.random() * 0.08,
color,
position.x,
position.y,
position.z,
false
);
particles.push({
mesh,
velocity: new THREE.Vector3(
(Math.random() - 0.5) * 2.2,
0.6 + Math.random() * 1.5,
(Math.random() - 0.5) * 2.2
),
life: 0.70,
maxLife: 0.70
});
}
}
function addGrazeMark(patch, plant) {
const side = patch.markCount % 2 === 0 ? -1 : 1;
const level = 0.55 + (patch.markCount % 6) * 0.68;
const z = ((patch.markCount + plant.index) % 3 - 1) * 0.055;
const mark = addBox(
plant.group,
0.17,
0.20,
0.17,
0xffae45,
side * 0.115,
level,
z
);
patch.marks.push(mark);
patch.markCount++;
}
function graze(patch, urchin) {
const plant = patch.plants[urchin.plantIndex];
const visibleLeaf = plant.leaves.find((leaf) => leaf.visible);
// A hidden leaf voxel represents a bite taken from the kelp.
if (visibleLeaf) visibleLeaf.visible = false;
addGrazeMark(patch, plant);
urchin.chew = 1;
urchin.nextGraze = urchin.grazeInterval;
updateReadouts();
}
function removeUrchin(patch) {
if (!patch.urchins.length) return;
const victim = patch.urchins[patch.urchins.length - 1];
victim.alive = false;
const position = new THREE.Vector3();
victim.group.getWorldPosition(position);
patch.group.remove(victim.group);
patch.urchins.pop();
spawnBurst(position, 0x654292);
otterLunge = 1;
updateReadouts();
}
function updateReadouts() {
countElements.urchinsA.textContent = patchA.urchins.length;
countElements.marksA.textContent = patchA.markCount;
countElements.urchinsB.textContent = patchB.urchins.length;
countElements.marksB.textContent = patchB.markCount;
labelA.innerHTML = `
<h2>Otter patch</h2>
<p><b>${patchA.urchins.length}</b> urchins · <b>${patchA.markCount}</b> graze marks</p>
`;
labelB.innerHTML = `
<h2>Matched control</h2>
<p><b>${patchB.urchins.length}</b> urchins · <b>${patchB.markCount}</b> graze marks</p>
`;
const difference = patchB.urchins.length - patchA.urchins.length;
if (difference > 0) {
differenceElement.textContent =
`${difference} fewer urchin${difference === 1 ? "" : "s"} in the otter patch`;
} else {
differenceElement.textContent = "Urchin counts are matched";
}
}
function setOtterState(on) {
otterOn = on;
switchElement.classList.toggle("on", on);
switchElement.setAttribute("aria-checked", String(on));
switchState.textContent = on ? "ON" : "OFF";
ruleCard.classList.toggle("active", on);
ruleState.textContent = on ? "ACTIVE" : "PAUSED";
if (on) {
switchLabel.textContent = "The otter is patrolling the left patch.";
ruleText.textContent =
"OTTER ON → every 3 seconds, remove 1 urchin from the left patch. The right patch has no predator.";
} else {
switchLabel.textContent = "The otter has returned to its dock.";
ruleText.textContent =
"OTTER OFF → no more urchins are removed. Previously removed urchins do not return; reset to rematch.";
}
}
switchElement.addEventListener("click", () => {
setOtterState(!otterOn);
});
// ------------------------------------------------------------
// Reset
// ------------------------------------------------------------
let simTime = 0;
let predationTimer = 0;
function resetExperiment() {
simTime = 0;
predationTimer = 0;
for (const patch of [patchA, patchB]) {
for (const urchin of patch.urchins) {
patch.group.remove(urchin.group);
}
patch.urchins.length = 0;
patch.markCount = 0;
for (const mark of patch.marks) {
mark.parent?.remove(mark);
}
patch.marks.length = 0;
for (const plant of patch.plants) {
for (const leaf of plant.leaves) leaf.visible = true;
}
populateUrchins(patch);
}
for (const particle of particles) {
particle.mesh.parent?.remove(particle.mesh);
}
particles.length = 0;
setOtterState(true);
updateReadouts();
}
resetButton.addEventListener("click", resetExperiment);
// ------------------------------------------------------------
// Camera controls implemented directly, without add-ons
// ------------------------------------------------------------
const cameraState = {
yaw: 0,
pitch: 0.69,
radius: 20.5,
target: new THREE.Vector3(0, 1.55, 0),
dragging: false,
lastX: 0,
lastY: 0
};
function updateCamera() {
const aspect = viewport.clientWidth / Math.max(1, viewport.clientHeight);
const fittedRadius =
cameraState.radius * (aspect < 1.05 ? 1.05 / aspect : 1);
const horizontal = Math.cos(cameraState.pitch) * fittedRadius;
camera.position.set(
cameraState.target.x + horizontal * Math.sin(cameraState.yaw),
cameraState.target.y + Math.sin(cameraState.pitch) * fittedRadius,
cameraState.target.z + horizontal * Math.cos(cameraState.yaw)
);
camera.lookAt(cameraState.target);
}
function resetCamera() {
cameraState.yaw = 0;
cameraState.pitch = 0.69;
cameraState.radius = 20.5;
}
renderer.domElement.addEventListener("pointerdown", (event) => {
cameraState.dragging = true;
cameraState.lastX = event.clientX;
cameraState.lastY = event.clientY;
renderer.domElement.setPointerCapture(event.pointerId);
});
renderer.domElement.addEventListener("pointermove", (event) => {
if (!cameraState.dragging) return;
const dx = event.clientX - cameraState.lastX;
const dy = event.clientY - cameraState.lastY;
cameraState.yaw -= dx * 0.006;
cameraState.pitch = THREE.MathUtils.clamp(
cameraState.pitch + dy * 0.0045,
0.30,
1.25
);
cameraState.lastX = event.clientX;
cameraState.lastY = event.clientY;
});
function stopDragging(event) {
cameraState.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(
"wheel",
(event) => {
event.preventDefault();
cameraState.radius = THREE.MathUtils.clamp(
cameraState.radius + event.deltaY * 0.012,
13,
31
);
},
{ passive: false }
);
renderer.domElement.addEventListener("dblclick", resetCamera);
window.addEventListener("keydown", (event) => {
if (event.key.toLowerCase() === "o") {
setOtterState(!otterOn);
} else if (event.key.toLowerCase() === "r") {
resetExperiment();
} else if (event.key === "0") {
resetCamera();
}
});
function resize() {
const width = Math.max(1, viewport.clientWidth);
const height = Math.max(1, viewport.clientHeight);
camera.aspect = width / height;
camera.updateProjectionMatrix();
renderer.setSize(width, height, false);
updateCamera();
}
new ResizeObserver(resize).observe(viewport);
resize();
// ------------------------------------------------------------
// Floating voxel bubbles
// ------------------------------------------------------------
const bubbleMaterial = new THREE.MeshBasicMaterial({
color: 0xeaffff,
transparent: true,
opacity: 0.38,
depthWrite: false
});
const bubbles = [];
const bubbleRandom = seededRandom(441);
for (let i = 0; i < 28; i++) {
const size = 0.06 + bubbleRandom() * 0.12;
const mesh = new THREE.Mesh(cubeGeometry, bubbleMaterial);
mesh.scale.set(size, size, size);
mesh.position.set(
-10 + bubbleRandom() * 20,
0.4 + bubbleRandom() * 6.5,
-4.4 + bubbleRandom() * 9
);
scene.add(mesh);
bubbles.push({
mesh,
speed: 0.18 + bubbleRandom() * 0.25,
phase: bubbleRandom() * Math.PI * 2
});
}
// ------------------------------------------------------------
// Animation loop
// ------------------------------------------------------------
const clock = new THREE.Clock();
function updateUrchins(patch, dt) {
for (const urchin of patch.urchins) {
const plant = patch.plants[urchin.plantIndex];
urchin.nextGraze -= dt;
if (urchin.nextGraze <= 0) {
graze(patch, urchin);
}
const angle = urchin.phase + simTime * urchin.speed;
const radius =
urchin.radius + Math.sin(simTime * 0.8 + urchin.phase) * 0.05;
urchin.group.position.x =
plant.group.position.x + Math.cos(angle) * radius;
urchin.group.position.z =
plant.group.position.z + Math.sin(angle) * radius;
urchin.group.position.y =
0.38 + Math.sin(simTime * 2.1 + urchin.phase) * 0.035;
urchin.group.rotation.y += dt * 0.28;
urchin.chew = Math.max(0, urchin.chew - dt * 1.8);
const chewScale = 1 + urchin.chew * 0.22;
urchin.group.scale.set(chewScale, chewScale, chewScale);
}
}
function updateOtter(dt) {
otterMix = THREE.MathUtils.clamp(
otterMix + (otterOn ? dt : -dt) * 0.8,
0,
1
);
const patrolX = -4.9 + Math.sin(simTime * 0.62) * 2.45;
const onPosition = new THREE.Vector3(
patrolX,
0.18 + Math.sin(simTime * 3) * 0.035,
3.62
);
const offPosition = new THREE.Vector3(-4.9, 0.17, 4.72);
otter.position.lerpVectors(offPosition, onPosition, otterMix);
const desiredRotation =
otterMix > 0.15 && Math.cos(simTime * 0.62) < 0 ? Math.PI : 0;
otter.rotation.y = THREE.MathUtils.lerp(
otter.rotation.y,
desiredRotation,
1 - Math.exp(-dt * 6)
);
otterLunge = Math.max(0, otterLunge - dt * 1.7);
const lungeScale = 1 + otterLunge * 0.08;
otter.scale.set(lungeScale, lungeScale, lungeScale);
}
function updateParticles(dt) {
for (let i = particles.length - 1; i >= 0; i--) {
const particle = particles[i];
particle.life -= dt;
if (particle.life <= 0) {
particle.mesh.parent?.remove(particle.mesh);
particles.splice(i, 1);
continue;
}
particle.mesh.position.addScaledVector(particle.velocity, dt);
particle.velocity.y += dt * 0.4;
const scale = particle.life / particle.maxLife;
particle.mesh.scale.multiplyScalar(0.975);
particle.mesh.rotation.x += dt * 3;
particle.mesh.rotation.y += dt * 2;
particle.mesh.material.opacity = scale;
}
}
function placeLabel(element, worldPosition) {
const projected = worldPosition.clone().project(camera);
const x = (projected.x * 0.5 + 0.5) * viewport.clientWidth;
const y = (-projected.y * 0.5 + 0.5) * viewport.clientHeight;
element.style.left = `${x}px`;
element.style.top = `${y}px`;
element.style.visibility = projected.z > 1 ? "hidden" : "visible";
}
function formatTime(seconds) {
const minutes = Math.floor(seconds / 60);
const remainder = Math.floor(seconds % 60);
return `${String(minutes).padStart(2, "0")}:${String(remainder).padStart(2, "0")}`;
}
renderer.setAnimationLoop(() => {
const dt = Math.min(clock.getDelta(), 0.05);
simTime += dt;
updateUrchins(patchA, dt);
updateUrchins(patchB, dt);
updateOtter(dt);
updateParticles(dt);
// Toy predation rule: only the left patch is affected.
if (otterOn) {
predationTimer += dt;
if (predationTimer >= 3.0) {
predationTimer -= 3.0;
removeUrchin(patchA);
}
}
// Gentle kelp swaying, built from rigid voxel blocks.
for (const patch of [patchA, patchB]) {
for (const plant of patch.plants) {
plant.group.rotation.z =
Math.sin(simTime * 0.72 + plant.phase) * 0.027;
plant.group.rotation.x =
Math.cos(simTime * 0.58 + plant.phase) * 0.012;
}
}
for (const bubble of bubbles) {
bubble.mesh.position.y += dt * bubble.speed;
bubble.mesh.position.x +=
Math.sin(simTime * 0.6 + bubble.phase) * dt * 0.035;
if (bubble.mesh.position.y > 7.0) {
bubble.mesh.position.y = 0.35;
}
}
updateCamera();
placeLabel(labelA, patchA.labelAnchor);
placeLabel(labelB, patchB.labelAnchor);
clockElement.textContent = formatTime(simTime);
renderer.render(scene, camera);
});
updateReadouts();
</script>
</body>
</html>
```