Prompt specification
Build or customize the Three.js 3D scene "Microclimate moisture-retention sandbox" 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: Microclimate moisture-retention sandbox
Category: Biology & Nature · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/microclimate-moisture-retention-sandbox-x0756
Scene Description Prompt:
Create stone, bark, and soil surfaces under adjustable shade and rain pulses; compare fictional moisture indicators and moss responses using openly stated illustrative parameters. Build this with Three.js from cdnjs as a low-poly scene in one self-contained HTML file.
Working Three.js Starter (microclimate-moisture-retention-sandbox-x0756):
```html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Microhabitat Pulse — Fictional Moss & Moisture Lab</title>
<style>
:root {
color-scheme: dark;
--ink: #eef3ec;
--muted: #aebbb1;
--panel: rgba(20, 29, 26, 0.82);
--panel-strong: rgba(25, 35, 31, 0.94);
--line: rgba(226, 240, 229, 0.14);
--green: #b7db79;
--cyan: #68bdd4;
--soil: #d09a6c;
--radius: 18px;
}
* { box-sizing: border-box; }
html, body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: #cad5ce;
color: var(--ink);
font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
button, input, summary { font: inherit; }
button { color: inherit; }
#scene {
position: fixed;
inset: 0;
width: 100%;
height: 100%;
display: block;
touch-action: none;
cursor: grab;
}
#scene:active { cursor: grabbing; }
.vignette {
position: fixed;
inset: 0;
pointer-events: none;
background:
linear-gradient(180deg, rgba(9, 18, 15, 0.18), transparent 28%),
radial-gradient(circle at 50% 45%, transparent 45%, rgba(9, 15, 13, 0.22));
}
header {
position: fixed;
z-index: 5;
top: 22px;
left: 26px;
right: 26px;
display: flex;
align-items: flex-start;
justify-content: space-between;
pointer-events: none;
}
.brand {
display: flex;
align-items: center;
gap: 13px;
color: #183027;
text-shadow: 0 1px 12px rgba(255,255,255,.28);
}
.brand-mark {
width: 43px;
height: 43px;
display: grid;
place-items: center;
border: 1px solid rgba(23, 49, 39, .32);
border-radius: 13px;
background: rgba(239, 246, 235, .48);
backdrop-filter: blur(10px);
box-shadow: 0 8px 30px rgba(25, 43, 35, .10);
}
.brand-mark::before {
content: "";
width: 17px;
height: 23px;
border-radius: 80% 20% 70% 30%;
transform: rotate(26deg);
background: #315b45;
box-shadow: 7px 4px 0 -3px #92ad5d;
}
.eyebrow {
margin: 0 0 3px;
font-size: 10px;
font-weight: 800;
letter-spacing: .19em;
text-transform: uppercase;
}
h1 {
margin: 0;
font-size: clamp(20px, 2.2vw, 31px);
line-height: 1;
letter-spacing: -.035em;
}
.header-status {
display: flex;
align-items: center;
gap: 9px;
padding: 9px 12px;
border: 1px solid rgba(20, 42, 32, .18);
border-radius: 999px;
background: rgba(235, 244, 234, .54);
color: #294437;
font-size: 11px;
font-weight: 800;
letter-spacing: .08em;
text-transform: uppercase;
backdrop-filter: blur(12px);
}
.status-dot {
width: 7px;
height: 7px;
border-radius: 50%;
background: #608b68;
box-shadow: 0 0 0 4px rgba(96, 139, 104, .13);
}
.status-dot.raining {
background: #3c91b3;
box-shadow: 0 0 0 4px rgba(60, 145, 179, .15);
animation: blink .8s infinite alternate;
}
@keyframes blink { to { opacity: .38; } }
.panel {
position: fixed;
z-index: 4;
top: 94px;
width: 310px;
max-height: calc(100vh - 122px);
overflow: auto;
padding: 18px;
border: 1px solid var(--line);
border-radius: var(--radius);
background: var(--panel);
box-shadow: 0 22px 70px rgba(8, 17, 13, .22);
backdrop-filter: blur(20px) saturate(120%);
scrollbar-width: thin;
scrollbar-color: rgba(220,240,225,.22) transparent;
}
.controls { left: 26px; }
.compare { right: 26px; width: 370px; }
.panel-heading {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
margin-bottom: 17px;
}
.panel-heading h2 {
margin: 0;
font-size: 15px;
letter-spacing: -.015em;
}
.panel-heading p {
margin: 4px 0 0;
color: var(--muted);
font-size: 11px;
line-height: 1.45;
}
.fiction-badge {
flex: 0 0 auto;
padding: 5px 8px;
border: 1px solid rgba(183,219,121,.23);
border-radius: 999px;
color: var(--green);
font-size: 9px;
font-weight: 800;
letter-spacing: .08em;
text-transform: uppercase;
}
.control-block {
padding: 15px 0;
border-top: 1px solid var(--line);
}
.control-block:first-of-type { border-top: 0; padding-top: 2px; }
.control-row {
display: flex;
align-items: baseline;
justify-content: space-between;
gap: 12px;
margin-bottom: 10px;
}
.control-row label {
font-size: 12px;
font-weight: 750;
}
output {
color: #dce8df;
font-size: 12px;
font-variant-numeric: tabular-nums;
}
.range-wrap { position: relative; }
input[type="range"] {
width: 100%;
height: 4px;
margin: 5px 0 0;
border-radius: 999px;
outline: none;
appearance: none;
background: linear-gradient(90deg, #7fa36d 0 55%, rgba(255,255,255,.14) 55%);
cursor: pointer;
}
input[type="range"]::-webkit-slider-thumb {
width: 17px;
height: 17px;
appearance: none;
border: 3px solid #263a31;
border-radius: 50%;
background: #dbe9cf;
box-shadow: 0 0 0 1px rgba(255,255,255,.24);
}
input[type="range"]::-moz-range-thumb {
width: 12px;
height: 12px;
border: 3px solid #263a31;
border-radius: 50%;
background: #dbe9cf;
}
.range-notes {
display: flex;
justify-content: space-between;
margin-top: 8px;
color: #8f9f95;
font-size: 9px;
}
.button-row {
display: grid;
grid-template-columns: 1fr auto;
gap: 9px;
margin-top: 13px;
}
button {
border: 1px solid var(--line);
border-radius: 11px;
background: rgba(255,255,255,.055);
cursor: pointer;
transition: background .18s, border-color .18s, transform .18s;
}
button:hover {
background: rgba(255,255,255,.10);
border-color: rgba(255,255,255,.25);
}
button:active { transform: translateY(1px); }
#pulseButton {
min-height: 43px;
padding: 0 16px;
border-color: rgba(104,189,212,.28);
background: linear-gradient(135deg, rgba(75,151,177,.38), rgba(45,94,112,.30));
font-size: 12px;
font-weight: 800;
}
#pulseButton.raining {
color: #e6f8ff;
border-color: rgba(125,211,235,.64);
box-shadow: inset 0 0 24px rgba(88,185,220,.12);
}
#resetView {
width: 43px;
height: 43px;
font-size: 17px;
}
.check-row {
display: flex;
align-items: center;
gap: 9px;
margin-top: 12px;
color: #b7c4bb;
font-size: 11px;
cursor: pointer;
}
.check-row input {
width: 15px;
height: 15px;
accent-color: #7ead68;
}
.segmented {
display: grid;
grid-template-columns: repeat(4, 1fr);
gap: 4px;
padding: 4px;
border: 1px solid var(--line);
border-radius: 12px;
background: rgba(0,0,0,.12);
}
.segmented button {
padding: 7px 3px;
border: 0;
border-radius: 8px;
color: #96a79c;
background: transparent;
font-size: 9px;
font-weight: 800;
letter-spacing: .035em;
text-transform: uppercase;
}
.segmented button.active {
color: #17261f;
background: #d9e5d7;
}
details {
margin-top: 14px;
border: 1px solid var(--line);
border-radius: 12px;
background: rgba(0,0,0,.10);
}
summary {
padding: 12px;
color: #cbd7ce;
font-size: 11px;
font-weight: 800;
cursor: pointer;
}
.details-body {
padding: 0 12px 13px;
color: #9eada3;
font-size: 10px;
line-height: 1.55;
}
.details-body p { margin: 8px 0; }
.table-wrap { overflow-x: auto; }
table {
width: 100%;
margin: 9px 0;
border-collapse: collapse;
font-size: 9px;
white-space: nowrap;
}
th, td {
padding: 5px 4px;
border-bottom: 1px solid rgba(255,255,255,.07);
text-align: right;
}
th:first-child, td:first-child { text-align: left; }
th { color: #d2ddd4; }
.legend {
display: flex;
flex-wrap: wrap;
gap: 7px;
margin-bottom: 12px;
}
.legend span {
display: flex;
align-items: center;
gap: 6px;
padding: 5px 8px;
border: 1px solid var(--line);
border-radius: 999px;
color: #aebbb2;
font-size: 9px;
}
.legend i {
width: 6px;
height: 6px;
border-radius: 50%;
}
.surface-card {
margin-bottom: 10px;
padding: 13px;
border: 1px solid var(--line);
border-radius: 14px;
background: rgba(255,255,255,.035);
}
.surface-head {
display: grid;
grid-template-columns: auto 1fr auto;
align-items: center;
gap: 9px;
margin-bottom: 12px;
}
.swatch {
width: 13px;
height: 13px;
border: 2px solid rgba(255,255,255,.18);
border-radius: 4px;
}
.surface-head h3 {
margin: 0;
font-size: 12px;
}
.surface-head small {
display: block;
margin-top: 1px;
color: #83938a;
font-size: 9px;
}
.surface-state {
padding: 4px 7px;
border-radius: 999px;
color: #c9d4cc;
background: rgba(255,255,255,.06);
font-size: 8px;
font-weight: 800;
letter-spacing: .07em;
text-transform: uppercase;
}
.metric {
display: grid;
grid-template-columns: 45px 1fr 28px;
align-items: center;
gap: 9px;
margin-top: 8px;
font-size: 9px;
}
.metric-label {
color: #8fa096;
font-weight: 800;
letter-spacing: .08em;
}
.meter {
height: 6px;
overflow: hidden;
border-radius: 999px;
background: rgba(255,255,255,.09);
}
.meter i {
display: block;
width: 0;
height: 100%;
border-radius: inherit;
transition: width .12s linear;
}
.metric strong {
color: #dce6df;
text-align: right;
font-size: 10px;
font-variant-numeric: tabular-nums;
}
.moss-row {
margin-top: 12px;
padding-top: 10px;
border-top: 1px solid rgba(255,255,255,.08);
}
.weather {
margin-top: 3px;
padding: 12px;
border: 1px solid var(--line);
border-radius: 13px;
background: rgba(0,0,0,.10);
}
.weather-head {
display: flex;
align-items: center;
justify-content: space-between;
gap: 10px;
margin-bottom: 10px;
}
.weather-head span {
color: #95a69c;
font-size: 9px;
font-weight: 800;
letter-spacing: .09em;
text-transform: uppercase;
}
.weather-head strong {
color: #cbd7cf;
font-size: 10px;
}
.pulse-track {
height: 4px;
overflow: hidden;
border-radius: 999px;
background: rgba(255,255,255,.08);
}
.pulse-track i {
display: block;
width: 0;
height: 100%;
background: linear-gradient(90deg, #477e99, #78c9e2);
}
.model-note {
margin: 12px 1px 0;
color: #83948a;
font-size: 9px;
line-height: 1.45;
}
#labels {
position: fixed;
inset: 0;
z-index: 3;
pointer-events: none;
overflow: hidden;
}
.scene-label {
position: absolute;
top: 0;
left: 0;
padding: 6px 9px;
border: 1px solid rgba(255,255,255,.25);
border-radius: 8px;
background: rgba(20,31,27,.68);
color: #eef5ef;
font-size: 8px;
font-weight: 800;
letter-spacing: .08em;
white-space: nowrap;
backdrop-filter: blur(8px);
box-shadow: 0 6px 20px rgba(0,0,0,.15);
}
.scene-label::after {
content: "";
position: absolute;
top: 100%;
left: 50%;
width: 1px;
height: 17px;
background: rgba(255,255,255,.38);
}
.hint {
position: fixed;
z-index: 3;
bottom: 22px;
left: 50%;
padding: 8px 12px;
border: 1px solid rgba(255,255,255,.16);
border-radius: 999px;
background: rgba(20,30,26,.58);
color: rgba(238,245,239,.76);
font-size: 9px;
letter-spacing: .04em;
transform: translateX(-50%);
pointer-events: none;
backdrop-filter: blur(10px);
}
#toast {
position: fixed;
z-index: 8;
left: 50%;
bottom: 70px;
padding: 10px 15px;
border: 1px solid rgba(154,218,241,.35);
border-radius: 999px;
background: rgba(28,66,80,.86);
color: #e8f8ff;
font-size: 11px;
opacity: 0;
transform: translate(-50%, 8px);
transition: opacity .2s, transform .2s;
pointer-events: none;
}
#toast.show {
opacity: 1;
transform: translate(-50%, 0);
}
@media (max-width: 900px) {
header { top: 15px; left: 16px; right: 16px; }
.panel { top: 78px; }
.controls { left: 14px; width: 285px; max-height: calc(100vh - 100px); }
.compare { right: 14px; width: 330px; max-height: calc(100vh - 100px); }
.hint { display: none; }
}
@media (max-width: 680px) {
.brand-mark { width: 37px; height: 37px; }
h1 { font-size: 19px; }
.header-status { display: none; }
.controls {
top: 69px;
left: 10px;
right: 10px;
width: auto;
max-height: 37vh;
}
.compare {
top: auto;
right: 10px;
bottom: 10px;
left: 10px;
width: auto;
max-height: 43vh;
}
.scene-label { display: none; }
}
</style>
</head>
<body>
<canvas id="scene" aria-label="Interactive low-poly microhabitat scene"></canvas>
<div class="vignette"></div>
<div id="labels"></div>
<header>
<div class="brand">
<div class="brand-mark" aria-hidden="true"></div>
<div>
<p class="eyebrow">Fictional microhabitat lab</p>
<h1>Microhabitat Pulse</h1>
</div>
</div>
<div class="header-status">
<i id="statusDot" class="status-dot"></i>
<span id="headerStatus">Dry interval</span>
</div>
</header>
<aside class="panel controls">
<div class="panel-heading">
<div>
<h2>Habitat controls</h2>
<p>Change the canopy and send a short rain pulse.</p>
</div>
</div>
<div class="control-block">
<div class="control-row">
<label for="shade">Canopy shade</label>
<output id="shadeOutput">55%</output>
</div>
<div class="range-wrap">
<input id="shade" type="range" min="0" max="1" value="0.55" step="0.01">
</div>
<div class="range-notes"><span>Open sun</span><span>Deep shade</span></div>
</div>
<div class="control-block">
<div class="control-row">
<label for="rainStrength">Pulse strength</label>
<output id="rainOutput">72%</output>
</div>
<div class="range-wrap">
<input id="rainStrength" type="range" min="0" max="1" value="0.72" step="0.01">
</div>
<div class="range-notes"><span>Light drizzle</span><span>Heavy pulse</span></div>
<div class="button-row">
<button id="pulseButton" type="button">↘ Send rain pulse</button>
<button id="resetView" type="button" title="Reset camera view" aria-label="Reset camera view">⌂</button>
</div>
<label class="check-row">
<input id="autoPulse" type="checkbox">
Auto pulse every 12 seconds
</label>
</div>
<div class="control-block">
<div class="control-row">
<label>Surface view</label>
</div>
<div class="segmented" role="group" aria-label="Surface visualization mode">
<button type="button" class="active" data-mode="habitat">Habitat</button>
<button type="button" data-mode="glint">Glint</button>
<button type="button" data-mode="loam">Loam</button>
<button type="button" data-mode="moss">Moss</button>
</div>
</div>
<details open>
<summary>Open illustrative parameters</summary>
<div class="details-body">
<p>
<strong>Glint</strong> and <strong>Loam</strong> are invented, normalized
0–100 indices—not measured units or scientific predictions.
Glint represents temporary surface wetness. Loam represents retained
substrate moisture.
</p>
<div class="table-wrap">
<table>
<thead>
<tr>
<th>Surface</th><th>Capture</th><th>Transfer</th><th>Drain</th>
<th>Evap.</th><th>Threshold</th><th>Ceiling</th>
</tr>
</thead>
<tbody>
<tr><td>Stone</td><td>.30</td><td>.16</td><td>.10</td><td>.22</td><td>20</td><td>.65</td></tr>
<tr><td>Bark</td><td>.45</td><td>.28</td><td>.07</td><td>.13</td><td>24</td><td>.85</td></tr>
<tr><td>Soil</td><td>.75</td><td>.52</td><td>.035</td><td>.07</td><td>26</td><td>1.00</td></tr>
</tbody>
</table>
</div>
<p>
Each pulse lasts 7 seconds. Rain inflow is
<code>20 × strength × capture</code> points per second. Evaporation is
multiplied by <code>1 − .35 × shade</code>. Transfer moves Glint into
Loam; Loam drains at its listed rate.
</p>
<p>
Moss target =
<code>ceiling × normalized(Loam above threshold) ×
(.75 + .25 × shade)</code>. The displayed response chases 12% of the
remaining gap per second while growing and 7% while shrinking.
</p>
<p>
Initial Glint/Loam pairs: stone 3/22, bark 6/32, soil 8/42.
Initial moss occupancy: 10%, 24%, and 40%.
</p>
</div>
</details>
</aside>
<aside class="panel compare">
<div class="panel-heading">
<div>
<h2>Compare substrates</h2>
<p>Live fictional readings from the same pulse.</p>
</div>
<span class="fiction-badge">Illustrative</span>
</div>
<div class="legend">
<span><i style="background:var(--cyan)"></i>Glint · surface film</span>
<span><i style="background:#7fbd8d"></i>Loam · retained store</span>
<span><i style="background:var(--green)"></i>Moss · patch occupancy</span>
</div>
<div id="surfaceCards"></div>
<div class="weather">
<div class="weather-head">
<span>Weather pulse</span>
<strong id="weatherState">Dry interval</strong>
</div>
<div class="pulse-track"><i id="pulseFill"></i></div>
</div>
<p class="model-note">
This model is intentionally fictional. It demonstrates relative behavior
and visual comparison rather than predicting real-world moisture or moss.
</p>
</aside>
<div class="hint">Drag to orbit · Shift/right-drag to pan · Scroll to zoom · R resets view</div>
<div id="toast" role="status" aria-live="polite"></div>
<script type="module">
import * as THREE from "https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
/* ------------------------------------------------------------------
Illustrative model parameters. All values are intentionally fictional.
------------------------------------------------------------------- */
const SURFACES = {
stone: {
name: "Stone",
subtitle: "cool mineral face",
swatch: "#7e8882",
capture: 0.30,
transfer: 0.16,
drain: 0.10,
evap: 0.22,
threshold: 20,
ceiling: 0.65,
glint: 3,
loam: 22,
moss: 0.10
},
bark: {
name: "Bark",
subtitle: "ridged woody skin",
swatch: "#77543b",
capture: 0.45,
transfer: 0.28,
drain: 0.07,
evap: 0.13,
threshold: 24,
ceiling: 0.85,
glint: 6,
loam: 32,
moss: 0.24
},
soil: {
name: "Soil",
subtitle: "porous ground layer",
swatch: "#79583d",
capture: 0.75,
transfer: 0.52,
drain: 0.035,
evap: 0.07,
threshold: 26,
ceiling: 1.00,
glint: 8,
loam: 42,
moss: 0.40
}
};
const state = {
shade: 0.55,
rain: 0.72,
pulseRemaining: 0,
pulseDuration: 7,
autoPulse: false,
mode: "habitat"
};
const $ = selector => document.querySelector(selector);
const clamp = THREE.MathUtils.clamp;
const lerp = THREE.MathUtils.lerp;
const surfaceKeys = Object.keys(SURFACES);
/* UI cards */
const cardRoot = $("#surfaceCards");
cardRoot.innerHTML = surfaceKeys.map(key => {
const s = SURFACES[key];
return `
<article class="surface-card" data-surface="${key}">
<div class="surface-head">
<span class="swatch" style="background:${s.swatch}"></span>
<div>
<h3>${s.name}</h3>
<small>${s.subtitle}</small>
</div>
<span class="surface-state" id="${key}-state">Dry</span>
</div>
<div class="metric">
<span class="metric-label">GLINT</span>
<div class="meter"><i id="${key}-glint-fill" style="background:var(--cyan)"></i></div>
<strong id="${key}-glint">0</strong>
</div>
<div class="metric">
<span class="metric-label">LOAM</span>
<div class="meter"><i id="${key}-loam-fill" style="background:#7fbd8d"></i></div>
<strong id="${key}-loam">0</strong>
</div>
<div class="metric moss-row">
<span class="metric-label">MOSS</span>
<div class="meter"><i id="${key}-moss-fill" style="background:var(--green)"></i></div>
<strong id="${key}-moss">0%</strong>
</div>
</article>`;
}).join("");
const ui = {};
for (const key of surfaceKeys) {
ui[key] = {
glintFill: $(`#${key}-glint-fill`),
glint: $(`#${key}-glint`),
loamFill: $(`#${key}-loam-fill`),
loam: $(`#${key}-loam`),
mossFill: $(`#${key}-moss-fill`),
moss: $(`#${key}-moss`),
state: $(`#${key}-state`)
};
}
/* ------------------------------------------------------------------
Renderer, scene, lights, and camera
------------------------------------------------------------------- */
const canvas = $("#scene");
const renderer = new THREE.WebGLRenderer({
canvas,
antialias: true,
powerPreference: "high-performance"
});
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight, false);
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.08;
const scene = new THREE.Scene();
scene.background = new THREE.Color("#cbd8d0");
scene.fog = new THREE.Fog("#cbd8d0", 13, 28);
const camera = new THREE.PerspectiveCamera(
38,
window.innerWidth / window.innerHeight,
0.1,
60
);
const hemisphere = new THREE.HemisphereLight(0xeaf6ff, 0x3c2e22, 1.75);
scene.add(hemisphere);
const sun = new THREE.DirectionalLight(0xffedc4, 3.0);
sun.position.set(-5.5, 9, 4.5);
sun.castShadow = true;
sun.shadow.mapSize.set(2048, 2048);
sun.shadow.camera.left = -8;
sun.shadow.camera.right = 8;
sun.shadow.camera.top = 8;
sun.shadow.camera.bottom = -8;
sun.shadow.camera.near = 1;
sun.shadow.camera.far = 25;
sun.shadow.bias = -0.00035;
scene.add(sun);
const fill = new THREE.DirectionalLight(0xa8d6e4, 0.72);
fill.position.set(6, 4, -5);
scene.add(fill);
/* Camera controls are implemented here rather than with an addon. */
const cameraState = {
yaw: 0.56,
pitch: 0.39,
distance: 11.7,
target: new THREE.Vector3(0, 1.65, 0)
};
function updateCamera() {
const { yaw, pitch, distance, target } = cameraState;
camera.position.set(
target.x + distance * Math.cos(pitch) * Math.sin(yaw),
target.y + distance * Math.sin(pitch),
target.z + distance * Math.cos(pitch) * Math.cos(yaw)
);
camera.lookAt(target);
}
updateCamera();
function resetCamera() {
cameraState.yaw = 0.56;
cameraState.pitch = 0.39;
cameraState.distance = 11.7;
cameraState.target.set(0, 1.65, 0);
updateCamera();
}
let drag = null;
canvas.addEventListener("pointerdown", event => {
if (event.button !== 0 && event.button !== 2) return;
drag = {
x: event.clientX,
y: event.clientY,
button: event.button,
moved: false
};
canvas.setPointerCapture(event.pointerId);
});
canvas.addEventListener("pointermove", event => {
if (!drag) return;
const dx = event.clientX - drag.x;
const dy = event.clientY - drag.y;
drag.x = event.clientX;
drag.y = event.clientY;
drag.moved = true;
if (event.shiftKey || drag.button === 2) {
const right = new THREE.Vector3(
Math.cos(cameraState.yaw),
0,
-Math.sin(cameraState.yaw)
);
const forward = new THREE.Vector3(
-Math.sin(cameraState.yaw),
0,
-Math.cos(cameraState.yaw)
);
const panScale = cameraState.distance * 0.00135;
cameraState.target.addScaledVector(right, -dx * panScale);
cameraState.target.addScaledVector(forward, dy * panScale * 0.55);
cameraState.target.x = clamp(cameraState.target.x, -4, 4);
cameraState.target.z = clamp(cameraState.target.z, -4, 4);
} else {
cameraState.yaw -= dx * 0.006;
cameraState.pitch = clamp(cameraState.pitch + dy * 0.005, 0.08, 1.08);
}
updateCamera();
});
function endDrag(event) {
if (drag && canvas.hasPointerCapture(event.pointerId)) {
canvas.releasePointerCapture(event.pointerId);
}
drag = null;
}
canvas.addEventListener("pointerup", endDrag);
canvas.addEventListener("pointercancel", endDrag);
canvas.addEventListener("contextmenu", event => event.preventDefault());
canvas.addEventListener("wheel", event => {
event.preventDefault();
cameraState.distance = clamp(
cameraState.distance + event.deltaY * 0.008,
6.3,
18.5
);
updateCamera();
}, { passive: false });
canvas.addEventListener("dblclick", resetCamera);
window.addEventListener("keydown", event => {
if (["INPUT", "BUTTON", "SUMMARY"].includes(document.activeElement?.tagName)) return;
if (event.key.toLowerCase() === "r") resetCamera();
if (event.key === "ArrowLeft") cameraState.yaw += 0.08;
if (event.key === "ArrowRight") cameraState.yaw -= 0.08;
if (event.key === "ArrowUp") cameraState.pitch = clamp(cameraState.pitch + 0.05, 0.08, 1.08);
if (event.key === "ArrowDown") cameraState.pitch = clamp(cameraState.pitch - 0.05, 0.08, 1.08);
updateCamera();
});
/* ------------------------------------------------------------------
Deterministic scene construction
------------------------------------------------------------------- */
function mulberry32(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;
};
}
const random = mulberry32(41729);
function terrainHeight(x, z) {
return -0.12
+ 0.07 * Math.sin(x * 0.82)
+ 0.05 * Math.cos(z * 1.08)
+ 0.025 * Math.sin((x + z) * 1.65);
}
/* Diorama base */
const base = new THREE.Mesh(
new THREE.BoxGeometry(12, 0.8, 10),
new THREE.MeshStandardMaterial({
color: 0x554132,
roughness: 1,
flatShading: true
})
);
base.position.y = -0.66;
base.receiveShadow = true;
scene.add(base);
/* Terrain mesh with per-vertex color */
const terrainPositions = [];
const terrainColors = [];
const terrainNoise = [];
const terrainIndices = [];
const nx = 24;
const nz = 20;
const terrainWidth = 12;
const terrainDepth = 10;
for (let iz = 0; iz <= nz; iz++) {
const z = -terrainDepth / 2 + iz / nz * terrainDepth;
for (let ix = 0; ix <= nx; ix++) {
const x = -terrainWidth / 2 + ix / nx * terrainWidth;
terrainPositions.push(x, terrainHeight(x, z), z);
terrainColors.push(0.43, 0.31, 0.22);
terrainNoise.push(random());
}
}
for (let iz = 0; iz < nz; iz++) {
for (let ix = 0; ix < nx; ix++) {
const a = iz * (nx + 1) + ix;
const b = a + 1;
const c = a + nx + 1;
const d = c + 1;
terrainIndices.push(a, c, b, b, c, d);
}
}
const terrainGeometry = new THREE.BufferGeometry();
terrainGeometry.setAttribute(
"position",
new THREE.Float32BufferAttribute(terrainPositions, 3)
);
const terrainColorAttribute = new THREE.Float32BufferAttribute(terrainColors, 3);
terrainGeometry.setAttribute("color", terrainColorAttribute);
terrainGeometry.setIndex(terrainIndices);
terrainGeometry.computeVertexNormals();
const groundMaterial = new THREE.MeshStandardMaterial({
vertexColors: true,
roughness: 1,
flatShading: true
});
const ground = new THREE.Mesh(terrainGeometry, groundMaterial);
ground.receiveShadow = true;
scene.add(ground);
/* Rock surfaces */
const stoneMaterial = new THREE.MeshStandardMaterial({
color: 0x7c8580,
roughness: 0.96,
flatShading: true
});
const rockGeometry = new THREE.DodecahedronGeometry(1, 0);
const rocks = [];
const rockSpecs = [
[-2.25, -0.65, 1.12, 0.72, 0.88],
[ 2.20, 1.00, 0.83, 0.55, 0.70],
[ 1.35, -2.05, 0.64, 0.43, 0.59],
[-3.05, 2.00, 0.60, 0.40, 0.53],
[ 3.05, -0.25, 0.48, 0.31, 0.44]
];
for (const [x, z, sx, sy, sz] of rockSpecs) {
const rock = new THREE.Mesh(rockGeometry, stoneMaterial);
rock.position.set(x, terrainHeight(x, z) + sy * 0.54, z);
rock.scale.set(sx, sy, sz);
rock.rotation.y = random() * Math.PI;
rock.rotation.z = (random() - 0.5) * 0.16;
rock.castShadow = true;
rock.receiveShadow = true;
scene.add(rock);
rocks.push(rock);
}
/* Additional pebbles */
const pebbleGeometry = new THREE.TetrahedronGeometry(1, 0);
for (let i = 0; i < 28; i++) {
const x = -4.7 + random() * 9.4;
const z = -3.8 + random() * 7.6;
const s = 0.055 + random() * 0.12;
const pebble = new THREE.Mesh(pebbleGeometry, stoneMaterial);
pebble.position.set(x, terrainHeight(x, z) + s * 0.35, z);
pebble.scale.set(s * 1.4, s * 0.7, s);
pebble.rotation.set(random() * 3, random() * 3, random() * 3);
pebble.castShadow = true;
scene.add(pebble);
}
/* Tree and bark */
const treeX = -0.25;
const treeZ = -0.45;
const treeBottom = terrainHeight(treeX, treeZ);
const trunkHeight = 4.25;
const barkMaterial = new THREE.MeshStandardMaterial({
color: 0x684a34,
roughness: 0.98,
flatShading: true
});
const trunk = new THREE.Mesh(
new THREE.CylinderGeometry(0.27, 0.46, trunkHeight, 7, 4),
barkMaterial
);
trunk.position.set(treeX, treeBottom + trunkHeight / 2, treeZ);
trunk.rotation.y = 0.25;
trunk.castShadow = true;
trunk.receiveShadow = true;
scene.add(trunk);
function branchBetween(a, b, bottomRadius, topRadius) {
const direction = new THREE.Vector3().subVectors(b, a);
const length = direction.length();
const mesh = new THREE.Mesh(
new THREE.CylinderGeometry(topRadius, bottomRadius, length, 6, 1),
barkMaterial
);
mesh.position.copy(a).add(b).multiplyScalar(0.5);
mesh.quaternion.setFromUnitVectors(
new THREE.Vector3(0, 1, 0),
direction.normalize()
);
mesh.castShadow = true;
scene.add(mesh);
return mesh;
}
const branchTips = [
new THREE.Vector3(-1.35, 4.65, -0.15),
new THREE.Vector3( 1.25, 4.50, -0.70),
new THREE.Vector3( 0.55, 5.05, 0.85),
new THREE.Vector3(-0.65, 5.15, -1.20),
new THREE.Vector3( 1.55, 4.20, 0.40)
];
for (const tip of branchTips) {
branchBetween(
new THREE.Vector3(treeX, treeBottom + 2.75, treeZ),
tip,
0.15,
0.065
);
}
/* Canopy */
const canopyMaterial = new THREE.MeshStandardMaterial({
color: 0x557b47,
roughness: 0.88,
flatShading: true,
transparent: true,
opacity: 0.74
});
const canopyGroup = new THREE.Group();
canopyGroup.position.set(treeX, 4.35, treeZ);
scene.add(canopyGroup);
const canopyGeometry = new THREE.IcosahedronGeometry(1, 1);
const canopyOffsets = [
[-1.12, 0.10, -0.08, 1.04],
[ 0.10, 0.28, -0.18, 1.18],
[ 1.02, 0.04, 0.03, 0.96],
[-0.36, 0.40, 0.86, 1.00],
[ 0.50, 0.48, 0.70, 0.92],
[-0.72, 0.67, -0.72, 0.92],
[ 0.22, 0.78, -0.15, 1.08]
];
for (const [x, y, z, s] of canopyOffsets) {
const leaf = new THREE.Mesh(canopyGeometry, canopyMaterial);
leaf.position.set(x, y, z);
leaf.scale.set(s, s * 0.83, s * 0.92);
leaf.rotation.set(random(), random(), random());
leaf.castShadow = true;
canopyGroup.add(leaf);
}
/* ------------------------------------------------------------------
Moss instancing: one mesh per surface
------------------------------------------------------------------- */
const mossGeometry = new THREE.IcosahedronGeometry(0.082, 0);
const mossMeshes = {};
const mossItems = { stone: [], bark: [], soil: [] };
function addMossItem(key, position, normal, scale) {
const quaternion = new THREE.Quaternion().setFromUnitVectors(
new THREE.Vector3(0, 1, 0),
normal.clone().normalize()
);
mossItems[key].push({ position, quaternion, scale });
}
const localRockPoint = new THREE.Vector3();
const worldRockPoint = new THREE.Vector3();
for (const rock of rocks) {
for (let i = 0; i < 27; i++) {
const theta = random() * Math.PI * 2;
const vertical = 0.05 + random() * 0.92;
const radial = Math.sqrt(1 - vertical * vertical);
localRockPoint.set(
Math.cos(theta) * radial * rock.scale.x * 0.94,
vertical * rock.scale.y * 0.94,
Math.sin(theta) * radial * rock.scale.z * 0.94
);
worldRockPoint.copy(localRockPoint)
.applyQuaternion(rock.quaternion)
.add(rock.position);
const normal = localRockPoint.clone().normalize().applyQuaternion(rock.quaternion);
worldRockPoint.addScaledVector(normal, 0.025);
addMossItem("stone", worldRockPoint, normal, 0.65 + random() * 0.75);
}
}
for (let i = 0; i < 72; i++) {
const angle = random() * Math.PI * 2;
const localY = 0.32 + random() * 2.65;
const radius = lerp(0.46, 0.28, localY / trunkHeight) + 0.015;
const normal = new THREE.Vector3(
Math.cos(angle),
0.06,
Math.sin(angle)
).normalize();
const position = new THREE.Vector3(
treeX + normal.x * radius,
treeBottom + localY,
treeZ + normal.z * radius
);
addMossItem("bark", position, normal, 0.55 + random() * 0.65);
}
for (let i = 0; i < 145; i++) {
const angle = random() * Math.PI * 2;
const radius = Math.sqrt(random()) * 3.25;
const x = treeX + Math.cos(angle) * radius;
const z = treeZ + Math.sin(angle) * radius;
if (Math.abs(x) > 5.5 || Math.abs(z) > 4.5) continue;
const position = new THREE.Vector3(x, terrainHeight(x, z) + 0.035, z);
const normal = new THREE.Vector3(0, 1, 0);
const rotation = new THREE.Quaternion().setFromAxisAngle(
new THREE.Vector3(0, 1, 0),
random() * Math.PI * 2
);
mossItems.soil.push({
position,
quaternion: rotation,
scale: 0.65 + random() * 0.85
});
}
for (const key of surfaceKeys) {
// Shuffle so the first N visible instances remain spatially distributed.
for (let i = mossItems[key].length - 1; i > 0; i--) {
const j = Math.floor(random() * (i + 1));
[mossItems[key][i], mossItems[key][j]] = [mossItems[key][j], mossItems[key][i]];
}
const material = new THREE.MeshStandardMaterial({
color: key === "stone" ? 0x789a4c : key === "bark" ? 0x638345 : 0x78a54a,
roughness: 1,
flatShading: true,
transparent: true,
opacity: 0.94
});
const mesh = new THREE.InstancedMesh(
mossGeometry,
material,
mossItems[key].length
);
mesh.instanceMatrix.setUsage(THREE.DynamicDrawUsage);
mesh.castShadow = true;
mesh.receiveShadow = true;
mesh.count = 0;
scene.add(mesh);
mossMeshes[key] = mesh;
for (let i = 0; i < mossItems[key].length; i++) {
const variation = 0.78 + random() * 0.30;
mesh.setColorAt(
i,
new THREE.Color().setRGB(
0.57 * variation,
0.77 * variation,
0.32 * variation
)
);
}
if (mesh.instanceColor) mesh.instanceColor.needsUpdate = true;
}
/* ------------------------------------------------------------------
Rain particles and pulse ring
------------------------------------------------------------------- */
const rainCount = 520;
const rainPositions = new Float32Array(rainCount * 3);
const rainSpeeds = new Float32Array(rainCount);
for (let i = 0; i < rainCount; i++) {
rainPositions[i * 3] = -6 + random() * 12;
rainPositions[i * 3 + 1] = random() * 9;
rainPositions[i * 3 + 2] = -5 + random() * 10;
rainSpeeds[i] = 0.7 + random() * 0.65;
}
const rainGeometry = new THREE.BufferGeometry();
rainGeometry.setAttribute(
"position",
new THREE.BufferAttribute(rainPositions, 3)
);
const rainMaterial = new THREE.PointsMaterial({
color: 0xb9e6f5,
size: 0.045,
sizeAttenuation: true,
transparent: true,
opacity: 0.75,
depthWrite: false
});
const rain = new THREE.Points(rainGeometry, rainMaterial);
rain.visible = false;
rain.frustumCulled = false;
scene.add(rain);
const pulseRing = new THREE.Mesh(
new THREE.RingGeometry(0.36, 0.405, 40),
new THREE.MeshBasicMaterial({
color: 0x7ac9e4,
transparent: true,
opacity: 0,
depthWrite: false,
side: THREE.DoubleSide
})
);
pulseRing.rotation.x = -Math.PI / 2;
pulseRing.position.set(treeX, 0.04, treeZ);
scene.add(pulseRing);
/* ------------------------------------------------------------------
Surface labels projected from 3D anchors
------------------------------------------------------------------- */
const labelRoot = $("#labels");
const labelDefinitions = [
{
key: "stone",
text: "STONE",
anchor: rocks[0].position.clone().add(new THREE.Vector3(0, 0.8, 0))
},
{
key: "bark",
text: "BARK",
anchor: new THREE.Vector3(treeX + 0.15, treeBottom + 1.65, treeZ + 0.25)
},
{
key: "soil",
text: "SOIL",
anchor: new THREE.Vector3(1.25, terrainHeight(1.25, 2.15) + 0.15, 2.15)
}
];
for (const definition of labelDefinitions) {
const element = document.createElement("div");
element.className = "scene-label";
element.textContent = definition.text;
labelRoot.appendChild(element);
definition.element = element;
}
function updateLabels() {
const width = window.innerWidth;
const height = window.innerHeight;
for (const definition of labelDefinitions) {
const projected = definition.anchor.clone().project(camera);
const visible = projected.z > -1 && projected.z < 1;
if (!visible) {
definition.element.style.display = "none";
continue;
}
definition.element.style.display = "block";
const x = (projected.x * 0.5 + 0.5) * width;
const y = (-projected.y * 0.5 + 0.5) * height;
definition.element.style.transform =
`translate(${x}px, ${y}px) translate(-50%, -115%)`;
definition.element.textContent =
`${definition.text} · LOAM ${Math.round(SURFACES[definition.key].loam)}`;
}
}
/* ------------------------------------------------------------------
Visualization modes
------------------------------------------------------------------- */
const colorDry = new THREE.Color("#a99e84");
const colorWet = new THREE.Color("#4e9db6");
const colorLoamDry = new THREE.Color("#826b4b");
const colorLoamWet = new THREE.Color("#315e52");
const scratchColor = new THREE.Color();
function moistureColor(value, loam = false) {
const dry = loam ? colorLoamDry : colorDry;
const wet = loam ? colorLoamWet : colorWet;
return scratchColor.copy(dry).lerp(wet, clamp(value / 100, 0, 1)).clone();
}
function updateTerrainColors() {
const color = new THREE.Color();
const soil = SURFACES.soil;
for (let i = 0; i < terrainNoise.length; i++) {
if (state.mode === "habitat") {
color.set("#76533b").lerp(
new THREE.Color("#44372d"),
clamp(soil.loam / 160, 0, 0.42)
);
} else if (state.mode === "glint") {
color.copy(moistureColor(soil.glint, false));
} else if (state.mode === "loam") {
color.copy(moistureColor(soil.loam, true));
} else {
color.set("#4c4035");
}
color.multiplyScalar(0.87 + terrainNoise[i] * 0.20);
terrainColorAttribute.setXYZ(i, color.r, color.g, color.b);
}
terrainColorAttribute.needsUpdate = true;
}
function updateCanopy() {
const shade = state.shade;
canopyGroup.scale.set(
0.88 + shade * 0.17,
0.94 + shade * 0.09,
0.88 + shade * 0.17
);
canopyMaterial.opacity = 0.43 + shade * 0.57;
sun.intensity = 3.0 - shade * 1.48;
hemisphere.intensity = 1.62 + shade * 0.18;
}
function applyViewMode() {
const stone = SURFACES.stone;
const bark = SURFACES.bark;
if (state.mode === "glint") {
stoneMaterial.color.copy(moistureColor(stone.glint, false));
barkMaterial.color.copy(moistureColor(bark.glint, false));
} else if (state.mode === "loam") {
stoneMaterial.color.copy(moistureColor(stone.loam, true));
barkMaterial.color.copy(moistureColor(bark.loam, true));
} else if (state.mode === "moss") {
stoneMaterial.color.set("#656c68");
barkMaterial.color.set("#493a30");
} else {
stoneMaterial.color.set("#7c8580");
barkMaterial.color.set("#684a34");
}
canopyMaterial.color.set(
state.mode === "habitat" ? "#557b47" : "#7c8e79"
);
canopyMaterial.opacity =
state.mode === "habitat" ? 0.43 + state.shade * 0.57 : 0.48;
for (const key of surfaceKeys) {
const material = mossMeshes[key].material;
if (state.mode === "moss") {
material.color.set(key === "stone" ? 0x9fd05a : 0x85bd52);
material.emissive.set(0x15290b);
material.emissiveIntensity = 0.35;
} else {
material.color.set(
key === "stone" ? 0x789a4c : key === "bark" ? 0x638345 : 0x78a54a
);
material.emissive.set(0x000000);
material.emissiveIntensity = 0;
}
}
updateTerrainColors();
}
/* ------------------------------------------------------------------
Simulation
------------------------------------------------------------------- */
function simulate(dt) {
const rainRate = state.pulseRemaining > 0 ? state.rain : 0;
const evaporationMultiplier = 1 - 0.35 * state.shade;
for (const key of surfaceKeys) {
const s = SURFACES[key];
const incoming = rainRate * s.capture * 20 * dt;
const evaporation = s.glint * s.evap * evaporationMultiplier * dt;
const provisionalGlint = s.glint + incoming - evaporation;
const transfer = provisionalGlint * s.transfer * dt;
s.glint = clamp(provisionalGlint - transfer, 0, 100);
s.loam = clamp(
s.loam + transfer - s.loam * s.drain * dt,
0,
100
);
const normalizedMoisture = clamp(
(s.loam - s.threshold) / (78 - s.threshold),
0,
1
);
const mossTarget =
normalizedMoisture *
s.ceiling *
(0.75 + 0.25 * state.shade);
const responseRate = mossTarget > s.moss ? 0.12 : 0.07;
s.moss += (mossTarget - s.moss) * responseRate * dt;
s.moss = clamp(s.moss, 0, 1);
}
}
const dummy = new THREE.Object3D();
function updateMossVisuals() {
for (const key of surfaceKeys) {
const mesh = mossMeshes[key];
const items = mossItems[key];
const coverage = SURFACES[key].moss;
const visible = Math.round(items.length * coverage);
mesh.count = visible;
for (let i = 0; i < visible; i++) {
const item = items[i];
const scale = item.scale * (0.70 + coverage * 0.30);
dummy.position.copy(item.position);
dummy.quaternion.copy(item.quaternion);
dummy.scale.set(scale, scale * 0.56, scale);
dummy.updateMatrix();
mesh.setMatrixAt(i, dummy.matrix);
}
mesh.instanceMatrix.needsUpdate = true;
}
}
/* ------------------------------------------------------------------
Rain and pulse behavior
------------------------------------------------------------------- */
let elapsed = 0;
let lastAutoPulse = 0;
let toastTimer = 0;
function showToast(message) {
const toast = $("#toast");
toast.textContent = message;
toast.classList.add("show");
clearTimeout(toastTimer);
toastTimer = setTimeout(() => toast.classList.remove("show"), 1500);
}
function triggerPulse(manual = true) {
state.pulseRemaining = state.pulseDuration;
lastAutoPulse = elapsed;
rain.visible = true;
pulseRing.visible = true;
if (manual) {
showToast(
state.rain > 0.65
? "Heavy rain pulse started"
: state.rain > 0.3
? "Rain pulse started"
: "Light rain pulse started"
);
}
}
function updateRain(dt) {
const active = state.pulseRemaining > 0;
rain.visible = active;
if (!active) {
pulseRing.material.opacity = 0;
return;
}
const activeCount = Math.floor(rainCount * (0.28 + state.rain * 0.72));
rainGeometry.setDrawRange(0, activeCount);
rainMaterial.opacity = 0.36 + state.rain * 0.52;
for (let i = 0; i < activeCount; i++) {
const index = i * 3;
rainPositions[index + 1] -= dt * (8.5 + rainSpeeds[i] * 3.2);
rainPositions[index] += dt * 0.30;
if (rainPositions[index + 1] < terrainHeight(
rainPositions[index],
rainPositions[index + 2]
)) {
rainPositions[index] = -6 + random() * 12;
rainPositions[index + 1] = 7.5 + random() * 2;
rainPositions[index + 2] = -5 + random() * 10;
}
}
rainGeometry.attributes.position.needsUpdate = true;
const progress = 1 - state.pulseRemaining / state.pulseDuration;
const scale = 0.5 + progress * 7.5;
pulseRing.scale.set(scale, scale, scale);
pulseRing.material.opacity = (1 - progress) * 0.48;
}
/* ------------------------------------------------------------------
UI updates
------------------------------------------------------------------- */
function updateUI() {
for (const key of surfaceKeys) {
const s = SURFACES[key];
const element = ui[key];
element.glintFill.style.width = `${s.glint}%`;
element.glint.textContent = Math.round(s.glint);
element.loamFill.style.width = `${s.loam}%`;
element.loam.textContent = Math.round(s.loam);
element.mossFill.style.width = `${s.moss * 100}%`;
element.moss.textContent = `${Math.round(s.moss * 100)}%`;
const status = s.loam < 24 ? "Dry" : s.loam < 52 ? "Damp" : "Wet";
element.state.textContent = status;
}
const raining = state.pulseRemaining > 0;
$("#pulseButton").classList.toggle("raining", raining);
$("#pulseButton").setAttribute("aria-pressed", String(raining));
$("#pulseButton").textContent = raining
? `↘ Rain pulse · ${state.pulseRemaining.toFixed(1)}s`
: "↘ Send rain pulse";
$("#statusDot").classList.toggle("raining", raining);
$("#headerStatus").textContent = raining ? "Rain pulse" : "Dry interval";
$("#weatherState").textContent = raining
? `${state.pulseRemaining.toFixed(1)} seconds remaining`
: "Dry interval";
$("#pulseFill").style.width =
`${state.pulseRemaining / state.pulseDuration * 100}%`;
}
$("#shade").addEventListener("input", event => {
state.shade = Number(event.target.value);
$("#shadeOutput").textContent = `${Math.round(state.shade * 100)}%`;
$("#shade").style.background =
`linear-gradient(90deg, #7fa36d 0 ${state.shade * 100}%, rgba(255,255,255,.14) ${state.shade * 100}%)`;
updateCanopy();
});
$("#rainStrength").addEventListener("input", event => {
state.rain = Number(event.target.value);
$("#rainOutput").textContent = `${Math.round(state.rain * 100)}%`;
$("#rainStrength").style.background =
`linear-gradient(90deg, #5a9ab5 0 ${state.rain * 100}%, rgba(255,255,255,.14) ${state.rain * 100}%)`;
});
$("#pulseButton").addEventListener("click", () => triggerPulse(true));
$("#resetView").addEventListener("click", resetCamera);
$("#autoPulse").addEventListener("change", event => {
state.autoPulse = event.target.checked;
if (state.autoPulse) {
lastAutoPulse = elapsed - 11.5;
showToast("Automatic pulses enabled");
} else {
showToast("Automatic pulses paused");
}
});
for (const button of document.querySelectorAll("[data-mode]")) {
button.addEventListener("click", () => {
state.mode = button.dataset.mode;
for (const candidate of document.querySelectorAll("[data-mode]")) {
candidate.classList.toggle("active", candidate === button);
}
applyViewMode();
updateMossVisuals();
});
}
/* ------------------------------------------------------------------
Resize and animation loop
------------------------------------------------------------------- */
function resize() {
const width = window.innerWidth;
const height = window.innerHeight;
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(width, height, false);
camera.aspect = width / height;
camera.updateProjectionMatrix();
}
window.addEventListener("resize", resize);
const clock = new THREE.Clock();
let lastVisualUpdate = 0;
function animate() {
requestAnimationFrame(animate);
const dt = Math.min(clock.getDelta(), 0.05);
elapsed += dt;
if (state.pulseRemaining > 0) {
state.pulseRemaining = Math.max(0, state.pulseRemaining - dt);
}
if (
state.autoPulse &&
state.pulseRemaining <= 0 &&
elapsed - lastAutoPulse >= 12
) {
triggerPulse(false);
}
simulate(dt);
updateRain(dt);
if (elapsed - lastVisualUpdate > 0.12) {
updateMossVisuals();
applyViewMode();
updateUI();
lastVisualUpdate = elapsed;
}
updateLabels();
renderer.render(scene, camera);
}
updateCanopy();
applyViewMode();
updateMossVisuals();
updateUI();
animate();
</script>
</body>
</html>
```