Prompt specification
Build or customize the Three.js 3D scene "Competing root-cue illustration" 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: Competing root-cue illustration
Category: Biology & Nature · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/competing-root-cue-illustration-x0772
Scene Description Prompt:
Please create one self-contained HTML file with Three.js from cdnjs showing root gravitropism. Create a schematic root-growth model with gravity and moisture cues shown separately; users vary declared rule weights while labels warn that real root behavior is more complex. Low-poly.
Working Three.js Starter (competing-root-cue-illustration-x0772):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Root Gravitropism — Schematic Cue Model</title>
<style>
:root {
--ink: #24372e;
--muted: #69786e;
--paper: #e8ede3;
--panel: rgba(249, 250, 244, 0.92);
--line: rgba(36, 55, 46, 0.14);
--orange: #e7833d;
--blue: #2f92b5;
--green: #587c61;
--shadow: 0 18px 55px rgba(38, 55, 45, 0.16);
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: var(--paper);
color: var(--ink);
font-family:
Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
button,
input {
font: inherit;
}
#scene {
position: fixed;
inset: 0;
z-index: 0;
}
#scene canvas {
display: block;
width: 100%;
height: 100%;
touch-action: none;
cursor: grab;
outline: none;
}
#scene canvas:active {
cursor: grabbing;
}
.header {
position: fixed;
z-index: 5;
top: 25px;
left: 28px;
width: min(520px, calc(100vw - 430px));
pointer-events: none;
}
.eyebrow {
margin-bottom: 8px;
color: var(--green);
font-size: 10px;
font-weight: 800;
letter-spacing: 0.18em;
text-transform: uppercase;
}
h1 {
margin: 0;
font-family: Georgia, "Times New Roman", serif;
font-size: clamp(31px, 4vw, 52px);
font-weight: 500;
letter-spacing: -0.045em;
line-height: 0.98;
}
h1 span {
color: var(--green);
font-style: italic;
}
.subtitle {
max-width: 430px;
margin: 12px 0 0;
color: var(--muted);
font-size: 14px;
line-height: 1.5;
}
.status {
display: inline-flex;
align-items: center;
gap: 7px;
margin-top: 13px;
padding: 7px 10px;
border: 1px solid var(--line);
border-radius: 999px;
background: rgba(249, 250, 244, 0.72);
backdrop-filter: blur(8px);
color: var(--muted);
font-size: 11px;
font-weight: 700;
letter-spacing: 0.04em;
text-transform: uppercase;
}
#liveDot {
width: 7px;
height: 7px;
border-radius: 50%;
background: #62a36e;
box-shadow: 0 0 0 4px rgba(98, 163, 110, 0.13);
}
#liveDot.paused {
background: #9a9385;
box-shadow: none;
}
.separator {
opacity: 0.45;
}
.panel {
position: fixed;
z-index: 6;
top: 22px;
right: 22px;
width: 340px;
max-height: calc(100vh - 44px);
overflow-y: auto;
padding: 19px;
border: 1px solid rgba(255, 255, 255, 0.7);
border-radius: 18px;
background: var(--panel);
box-shadow: var(--shadow);
backdrop-filter: blur(18px);
scrollbar-width: thin;
}
.panel-heading {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 12px;
margin-bottom: 15px;
}
.panel h2 {
margin: 0 0 3px;
font-size: 15px;
letter-spacing: -0.01em;
}
.panel-heading p {
margin: 0;
color: var(--muted);
font-size: 11px;
line-height: 1.4;
}
.icon-button {
display: grid;
flex: 0 0 auto;
width: 31px;
height: 31px;
place-items: center;
border: 1px solid var(--line);
border-radius: 9px;
background: rgba(255, 255, 255, 0.68);
color: var(--ink);
cursor: pointer;
transition: 160ms ease;
}
.icon-button:hover {
background: white;
transform: translateY(-1px);
}
.cue-cards {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 8px;
margin-bottom: 16px;
}
.cue-card {
min-width: 0;
padding: 10px;
border: 1px solid var(--line);
border-radius: 11px;
background: rgba(255, 255, 255, 0.55);
}
.cue-card.gravity {
border-top: 3px solid var(--orange);
}
.cue-card.moisture {
border-top: 3px solid var(--blue);
}
.cue-card strong {
display: block;
margin-bottom: 3px;
font-size: 11px;
}
.cue-card small {
display: block;
color: var(--muted);
font-size: 9px;
line-height: 1.35;
}
.control {
margin: 14px 0;
}
.control-label {
display: flex;
align-items: baseline;
justify-content: space-between;
gap: 10px;
margin-bottom: 7px;
}
.control-label label {
font-size: 12px;
font-weight: 750;
}
.control-label output {
min-width: 38px;
color: var(--muted);
font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
font-size: 11px;
text-align: right;
}
.control small {
display: block;
margin-top: 5px;
color: var(--muted);
font-size: 10px;
line-height: 1.35;
}
input[type="range"] {
width: 100%;
height: 4px;
margin: 0;
border-radius: 99px;
outline: none;
accent-color: var(--accent, var(--green));
cursor: pointer;
}
.equation {
margin: 16px 0;
padding: 11px 12px;
border: 1px solid var(--line);
border-radius: 10px;
background: rgba(223, 232, 220, 0.55);
color: #45564c;
font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
font-size: 10px;
line-height: 1.6;
}
.equation b {
color: var(--ink);
}
.section-title {
margin: 17px 0 8px;
color: var(--muted);
font-size: 9px;
font-weight: 800;
letter-spacing: 0.14em;
text-transform: uppercase;
}
.presets {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 6px;
}
.preset,
.main-button {
min-height: 34px;
border: 1px solid var(--line);
border-radius: 9px;
background: rgba(255, 255, 255, 0.6);
color: var(--ink);
font-size: 10px;
font-weight: 750;
cursor: pointer;
transition: 150ms ease;
}
.preset:hover,
.main-button:hover {
background: white;
border-color: rgba(36, 55, 46, 0.25);
}
.preset.active {
border-color: var(--green);
background: #e1eadc;
color: #34533e;
}
.button-row {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 7px;
margin-top: 11px;
}
.main-button {
min-height: 38px;
font-size: 11px;
}
.main-button.primary {
border-color: var(--green);
background: var(--green);
color: white;
}
.main-button.primary:hover {
background: #496c52;
}
.switches {
display: grid;
gap: 7px;
margin-top: 13px;
padding-top: 12px;
border-top: 1px solid var(--line);
}
.switch-row {
display: flex;
align-items: center;
justify-content: space-between;
color: var(--muted);
font-size: 10px;
font-weight: 650;
}
.switch-row input {
accent-color: var(--green);
}
.note {
position: fixed;
z-index: 5;
left: 28px;
bottom: 24px;
width: min(590px, calc(100vw - 420px));
padding: 13px 15px;
border: 1px solid rgba(231, 131, 61, 0.28);
border-radius: 12px;
background: rgba(255, 248, 236, 0.88);
box-shadow: 0 10px 30px rgba(61, 56, 44, 0.08);
backdrop-filter: blur(12px);
color: #6c5c48;
font-size: 10px;
line-height: 1.5;
pointer-events: none;
}
.note strong {
color: #a45b2b;
}
.note .camera-hint {
display: block;
margin-top: 5px;
color: #857764;
font-size: 9px;
}
#labels {
position: fixed;
inset: 0;
z-index: 3;
pointer-events: none;
}
.world-label {
position: absolute;
display: none;
align-items: center;
gap: 6px;
transform: translate(-50%, -50%);
padding: 6px 8px;
border: 1px solid rgba(255, 255, 255, 0.76);
border-radius: 7px;
background: rgba(250, 251, 247, 0.87);
box-shadow: 0 5px 18px rgba(35, 48, 40, 0.1);
backdrop-filter: blur(8px);
color: var(--ink);
font-size: 9px;
font-weight: 800;
letter-spacing: 0.07em;
white-space: nowrap;
text-transform: uppercase;
}
.world-label b {
padding-left: 5px;
border-left: 1px solid var(--line);
color: var(--muted);
font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
font-size: 9px;
}
.label-dot {
width: 7px;
height: 7px;
border-radius: 50%;
background: var(--green);
}
.world-label.orange .label-dot {
background: var(--orange);
}
.world-label.blue .label-dot {
background: var(--blue);
}
@media (max-width: 800px) {
.header {
top: 13px;
left: 14px;
width: calc(100vw - 28px);
}
.header h1 {
font-size: 31px;
}
.subtitle {
max-width: 310px;
margin-top: 7px;
font-size: 11px;
}
.status {
margin-top: 8px;
}
.panel {
top: auto;
right: 10px;
bottom: 10px;
left: 10px;
width: auto;
max-height: 47vh;
padding: 15px;
border-radius: 14px;
}
.cue-cards {
margin-bottom: 11px;
}
.control {
margin: 11px 0;
}
.note {
top: 139px;
right: 14px;
bottom: auto;
left: 14px;
width: auto;
padding: 9px 11px;
font-size: 9px;
}
.note .camera-hint {
display: none;
}
}
</style>
</head>
<body>
<div id="scene"></div>
<header class="header">
<div class="eyebrow">Schematic · low-poly growth model</div>
<h1>Root <span>gravitropism</span></h1>
<p class="subtitle">
A small rule-based experiment: gravity pulls the primary root downward,
while localized moisture redirects growth toward wetter soil.
</p>
<div class="status" aria-live="polite">
<span id="liveDot"></span>
<span id="statusText">Growing</span>
<span class="separator">·</span>
<span id="segmentCount">0 segments</span>
</div>
</header>
<aside class="panel" aria-label="Model controls">
<div class="panel-heading">
<div>
<h2>Declared rule weights</h2>
<p>Changing a growth rule restarts this trial.</p>
</div>
<button
id="cameraReset"
class="icon-button"
title="Reset camera"
aria-label="Reset camera"
>
⌖
</button>
</div>
<div class="cue-cards">
<div class="cue-card gravity">
<strong>Gravity cue</strong>
<small>Global direction<br>world −Y / downward</small>
</div>
<div class="cue-card moisture">
<strong>Moisture cue</strong>
<small>Local field<br>toward wetter pockets</small>
</div>
</div>
<div class="control" style="--accent: var(--orange)">
<div class="control-label">
<label for="gravity">Gravity response</label>
<output id="gravityValue" for="gravity">0.90</output>
</div>
<input
id="gravity"
type="range"
min="0"
max="1.5"
step="0.05"
value="0.9"
>
<small>Weight on the downward gravity vector.</small>
</div>
<div class="control" style="--accent: var(--blue)">
<div class="control-label">
<label for="moisture">Moisture response</label>
<output id="moistureValue" for="moisture">0.55</output>
</div>
<input
id="moisture"
type="range"
min="0"
max="1.5"
step="0.05"
value="0.55"
>
<small>Weight on attraction toward nearby wet-soil pockets.</small>
</div>
<div class="control" style="--accent: var(--green)">
<div class="control-label">
<label for="inertia">Heading persistence</label>
<output id="inertiaValue" for="inertia">1.15</output>
</div>
<input
id="inertia"
type="range"
min="0"
max="2"
step="0.05"
value="1.15"
>
<small>How strongly the root retains its previous direction.</small>
</div>
<div class="control" style="--accent: var(--green)">
<div class="control-label">
<label for="branch">Lateral branching</label>
<output id="branchValue" for="branch">0.55</output>
</div>
<input
id="branch"
type="range"
min="0"
max="1"
step="0.05"
value="0.55"
>
<small>Chance and frequency of lateral-root initiation.</small>
</div>
<div class="control" style="--accent: #8a8b7f">
<div class="control-label">
<label for="speed">Trial speed</label>
<output id="speedValue" for="speed">1.0×</output>
</div>
<input
id="speed"
type="range"
min="0.4"
max="1.8"
step="0.1"
value="1"
>
<small>Animation rate only; it does not change the declared rules.</small>
</div>
<div class="equation">
<b>heading′ = normalize</b>(<br>
persistence · heading<br>
+ w<sub>g</sub> · gravity<br>
+ w<sub>m</sub> · moisture<br>
)
</div>
<div class="section-title">Presets</div>
<div class="presets">
<button class="preset active" data-preset="balanced">Balanced</button>
<button class="preset" data-preset="gravity">Gravitropic</button>
<button class="preset" data-preset="moisture">Hydrotropic</button>
</div>
<div class="button-row">
<button id="pauseButton" class="main-button primary">Pause growth</button>
<button id="resetButton" class="main-button">Restart trial</button>
</div>
<div class="switches">
<label class="switch-row">
<span>Show gravity and moisture cue arrows</span>
<input id="showCues" type="checkbox" checked>
</label>
<label class="switch-row">
<span>Show moisture pockets</span>
<input id="showPatches" type="checkbox" checked>
</label>
</div>
</aside>
<div id="labels" aria-hidden="true">
<div id="gravityLabel" class="world-label orange">
<span class="label-dot"></span>
<span>Gravity cue</span>
<b id="gravityWorldValue">w g 0.90</b>
</div>
<div id="moistureLabel" class="world-label blue">
<span class="label-dot"></span>
<span>Moisture cue</span>
<b id="moistureWorldValue">w m 0.55</b>
</div>
<div id="patchLabel" class="world-label blue">
<span class="label-dot"></span>
<span>Moisture pocket</span>
</div>
<div id="surfaceLabel" class="world-label">
<span class="label-dot"></span>
<span>Soil surface</span>
</div>
</div>
<div class="note" role="note">
<strong>Interpret with care:</strong>
real root behavior is far more complex. Auxin transport, tissue mechanics,
local water gradients, obstacles, microbes, nutrient signals, and developmental
history all interact. These weights are illustrative declarations—not measured
biological parameters or predictive results.
<span class="camera-hint">
Drag to orbit · scroll to zoom · Space to pause · R to restart · C to reset camera
</span>
</div>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
const $ = (id) => document.getElementById(id);
// ---------------------------------------------------------------------
// Renderer, scene, camera, and direct (non-addon) camera controls
// ---------------------------------------------------------------------
const scene = new THREE.Scene();
scene.background = new THREE.Color(0xe8ede3);
scene.fog = new THREE.Fog(0xe8ede3, 19, 38);
const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.05;
renderer.domElement.tabIndex = 0;
renderer.domElement.setAttribute(
"aria-label",
"Interactive three-dimensional schematic of root growth"
);
$("scene").appendChild(renderer.domElement);
const camera = new THREE.PerspectiveCamera(
38,
window.innerWidth / window.innerHeight,
0.1,
100
);
const cameraState = {
target: new THREE.Vector3(0, -1.1, 0),
radius: 15.3,
theta: 0.64,
phi: 1.34
};
function applyCamera() {
const { target, radius, theta, phi } = cameraState;
camera.position.set(
target.x + radius * Math.sin(phi) * Math.sin(theta),
target.y + radius * Math.cos(phi),
target.z + radius * Math.sin(phi) * Math.cos(theta)
);
camera.lookAt(target);
}
applyCamera();
let dragging = false;
let pointerX = 0;
let pointerY = 0;
renderer.domElement.addEventListener("pointerdown", (event) => {
dragging = true;
pointerX = event.clientX;
pointerY = event.clientY;
renderer.domElement.setPointerCapture(event.pointerId);
});
renderer.domElement.addEventListener("pointermove", (event) => {
if (!dragging) return;
const dx = event.clientX - pointerX;
const dy = event.clientY - pointerY;
pointerX = event.clientX;
pointerY = event.clientY;
cameraState.theta -= dx * 0.005;
cameraState.phi = THREE.MathUtils.clamp(
cameraState.phi - dy * 0.0045,
0.56,
1.67
);
applyCamera();
});
function stopDragging() {
dragging = false;
}
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,
8.5,
25
);
applyCamera();
},
{ passive: false }
);
function resetCamera() {
cameraState.target.set(0, -1.1, 0);
cameraState.radius = 15.3;
cameraState.theta = 0.64;
cameraState.phi = 1.34;
applyCamera();
}
// ---------------------------------------------------------------------
// Lighting and low-poly scene construction
// ---------------------------------------------------------------------
scene.add(new THREE.HemisphereLight(0xfff8e8, 0x53634e, 1.8));
const sun = new THREE.DirectionalLight(0xfff4dc, 2.6);
sun.position.set(7, 11, 9);
scene.add(sun);
const fill = new THREE.DirectionalLight(0xb9d9db, 0.8);
fill.position.set(-8, 2, -7);
scene.add(fill);
const world = new THREE.Group();
scene.add(world);
function hash(n) {
const value = Math.sin(n * 127.1 + 311.7) * 43758.5453123;
return value - Math.floor(value);
}
let randomSeed = 741;
function seededRandom() {
randomSeed += 0x6d2b79f5;
let t = randomSeed;
t = Math.imul(t ^ (t >>> 15), t | 1);
t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
}
// Transparent cutaway soil volume: edges only, so roots remain visible.
const soilBox = new THREE.BoxGeometry(10, 9.6, 6);
const soilEdges = new THREE.LineSegments(
new THREE.EdgesGeometry(soilBox),
new THREE.LineBasicMaterial({
color: 0x6e644f,
transparent: true,
opacity: 0.2
})
);
soilEdges.position.y = -1.0;
world.add(soilEdges);
// Low-poly, triangulated soil surface occupying the rear half of the cutaway.
const surfacePositions = [];
const surfaceColors = [];
const surfaceLines = [];
const surfaceY = 3.8;
for (let ix = 0; ix < 5; ix++) {
for (let iz = 0; iz < 3; iz++) {
const x0 = -5 + ix * 2;
const x1 = x0 + 2;
const z0 = -3 + iz * 1.15;
const z1 = z0 + 1.15;
const color = new THREE.Color().setHSL(
0.095 + seededRandom() * 0.015,
0.25 + seededRandom() * 0.08,
0.51 + seededRandom() * 0.08
);
surfacePositions.push(
x0, surfaceY, z0,
x1, surfaceY, z0,
x1, surfaceY, z1,
x0, surfaceY, z0,
x1, surfaceY, z1,
x0, surfaceY, z1
);
for (let i = 0; i < 6; i++) {
surfaceColors.push(color.r, color.g, color.b);
}
surfaceLines.push(
x0, surfaceY + 0.012, z0,
x1, surfaceY + 0.012, z0,
x1, surfaceY + 0.012, z0,
x1, surfaceY + 0.012, z1,
x1, surfaceY + 0.012, z1,
x0, surfaceY + 0.012, z1,
x0, surfaceY + 0.012, z1,
x0, surfaceY + 0.012, z0
);
}
}
const surfaceGeometry = new THREE.BufferGeometry();
surfaceGeometry.setAttribute(
"position",
new THREE.Float32BufferAttribute(surfacePositions, 3)
);
surfaceGeometry.setAttribute(
"color",
new THREE.Float32BufferAttribute(surfaceColors, 3)
);
surfaceGeometry.computeVertexNormals();
const surface = new THREE.Mesh(
surfaceGeometry,
new THREE.MeshStandardMaterial({
vertexColors: true,
roughness: 1,
flatShading: true,
transparent: true,
opacity: 0.78,
depthWrite: false,
side: THREE.DoubleSide
})
);
world.add(surface);
const surfaceLineGeometry = new THREE.BufferGeometry();
surfaceLineGeometry.setAttribute(
"position",
new THREE.Float32BufferAttribute(surfaceLines, 3)
);
world.add(
new THREE.LineSegments(
surfaceLineGeometry,
new THREE.LineBasicMaterial({
color: 0x594f3e,
transparent: true,
opacity: 0.18
})
)
);
// Sparse particles suggest a porous soil volume.
const dustPositions = [];
for (let i = 0; i < 150; i++) {
dustPositions.push(
(seededRandom() - 0.5) * 9.5,
-5.5 + seededRandom() * 9.1,
(seededRandom() - 0.5) * 5.5
);
}
const dustGeometry = new THREE.BufferGeometry();
dustGeometry.setAttribute(
"position",
new THREE.Float32BufferAttribute(dustPositions, 3)
);
world.add(
new THREE.Points(
dustGeometry,
new THREE.PointsMaterial({
color: 0x76634a,
size: 0.035,
transparent: true,
opacity: 0.28,
sizeAttenuation: true
})
)
);
// A faceted seed/root crown at the soil surface.
const seed = new THREE.Mesh(
new THREE.DodecahedronGeometry(0.22, 0),
new THREE.MeshStandardMaterial({
color: 0xb28a58,
roughness: 1,
flatShading: true
})
);
seed.position.set(0, 3.72, 0.36);
seed.scale.set(1.25, 0.68, 1);
seed.castShadow = true;
world.add(seed);
// ---------------------------------------------------------------------
// Moisture field: separate blue cue from the orange gravity cue
// ---------------------------------------------------------------------
const patchGroup = new THREE.Group();
world.add(patchGroup);
const moisturePatches = [
{
position: new THREE.Vector3(-2.05, 1.75, 0.18),
radius: 1.25,
strength: 1.0
},
{
position: new THREE.Vector3(2.05, -3.8, -0.45),
radius: 1.15,
strength: 0.9
},
{
position: new THREE.Vector3(-0.7, -0.4, -1.55),
radius: 0.95,
strength: 0.72
}
];
moisturePatches.forEach((patch, index) => {
const geometry = new THREE.DodecahedronGeometry(1, 0);
const material = new THREE.MeshStandardMaterial({
color: index === 0 ? 0x50a9c6 : 0x3d91b4,
roughness: 0.55,
transparent: true,
opacity: 0.23,
depthWrite: false,
flatShading: true
});
const blob = new THREE.Mesh(geometry, material);
blob.position.copy(patch.position);
blob.scale.set(
patch.radius,
patch.radius * 0.72,
patch.radius * 0.82
);
patchGroup.add(blob);
const outline = new THREE.LineSegments(
new THREE.EdgesGeometry(geometry),
new THREE.LineBasicMaterial({
color: 0x2b8eb4,
transparent: true,
opacity: 0.38
})
);
outline.position.copy(blob.position);
outline.scale.copy(blob.scale);
patchGroup.add(outline);
});
function moistureCue(position) {
const sum = new THREE.Vector3();
for (const patch of moisturePatches) {
const delta = patch.position.clone().sub(position);
const distance = delta.length();
const range = patch.radius * 3.8;
if (distance > range || distance < 0.0001) continue;
const influence =
patch.strength * (1 - distance / range) / (1 + distance * 0.22);
sum.add(delta.normalize().multiplyScalar(influence));
}
if (sum.lengthSq() > 0.000001) sum.normalize();
return sum;
}
// ---------------------------------------------------------------------
// Cue arrows
// ---------------------------------------------------------------------
const cueGroup = new THREE.Group();
world.add(cueGroup);
const gravityArrow = new THREE.ArrowHelper(
new THREE.Vector3(0, -1, 0),
new THREE.Vector3(),
1.15,
0xe7833d,
0.24,
0.13
);
cueGroup.add(gravityArrow);
const moistureArrow = new THREE.ArrowHelper(
new THREE.Vector3(1, 0, 0),
new THREE.Vector3(),
1.7,
0x2f92b5,
0.27,
0.15
);
cueGroup.add(moistureArrow);
// ---------------------------------------------------------------------
// Root model
// ---------------------------------------------------------------------
const rootMaterial = new THREE.MeshStandardMaterial({
color: 0x895936,
roughness: 1,
flatShading: true
});
const branchMaterial = new THREE.MeshStandardMaterial({
color: 0xa16f43,
roughness: 1,
flatShading: true
});
const primaryTipMaterial = new THREE.MeshStandardMaterial({
color: 0xf0d19d,
roughness: 0.85,
flatShading: true
});
const branchTipMaterial = new THREE.MeshStandardMaterial({
color: 0xc99a62,
roughness: 0.9,
flatShading: true
});
const weights = {
gravity: 0.9,
moisture: 0.55,
inertia: 1.15,
branch: 0.55
};
let trialSpeed = 1;
let playing = true;
let rootGroup;
let roots = [];
let nextRootId = 1;
let primaryBranches = 0;
let segmentCount = 0;
let growthAccumulator = 0;
let elapsedTicks = 0;
const up = new THREE.Vector3(0, 1, 0);
function makeRoot(position, direction, depth, radius, maxAge) {
const marker = new THREE.Mesh(
new THREE.IcosahedronGeometry(depth === 0 ? 0.11 : 0.075, 0),
depth === 0 ? primaryTipMaterial : branchTipMaterial
);
marker.position.copy(position);
marker.castShadow = true;
rootGroup.add(marker);
const root = {
id: nextRootId++,
position: position.clone(),
direction: direction.clone().normalize(),
depth,
radius,
previousRadius: radius * (depth === 0 ? 1 : 0.78),
age: 0,
maxAge,
marker,
done: false
};
roots.push(root);
return root;
}
function addSegment(root, start, end, startRadius, endRadius) {
const direction = end.clone().sub(start);
const length = direction.length();
if (length < 0.0001) return;
const geometry = new THREE.CylinderGeometry(
endRadius,
startRadius,
length,
5,
1,
false
);
const mesh = new THREE.Mesh(
geometry,
root.depth === 0 ? rootMaterial : branchMaterial
);
mesh.position.copy(start).add(end).multiplyScalar(0.5);
mesh.quaternion.setFromUnitVectors(up, direction.clone().normalize());
mesh.castShadow = true;
rootGroup.add(mesh);
segmentCount++;
}
function spawnBranch(parent, direction) {
const root = makeRoot(
parent.position,
direction,
parent.depth + 1,
parent.depth === 0 ? 0.077 : 0.05,
parent.depth === 0 ? 58 : 35
);
root.previousRadius = parent.radius * 0.74;
primaryBranches++;
}
function branchDirection(parent) {
const seed = parent.id * 97 + parent.age * 11;
const side = hash(seed) > 0.5 ? 1 : -1;
const direction = new THREE.Vector3(
side * (0.78 + hash(seed + 1) * 0.32),
-0.3 - hash(seed + 2) * 0.24,
(hash(seed + 3) - 0.5) * 0.55
);
direction.addScaledVector(
moistureCue(parent.position),
weights.moisture * 0.16
);
return direction.normalize();
}
function resetTrial() {
if (rootGroup) {
rootGroup.traverse((object) => {
if (object.geometry) object.geometry.dispose();
});
world.remove(rootGroup);
}
rootGroup = new THREE.Group();
world.add(rootGroup);
roots = [];
nextRootId = 1;
primaryBranches = 0;
segmentCount = 0;
growthAccumulator = 0;
elapsedTicks = 0;
makeRoot(
new THREE.Vector3(0, 3.72, 0.36),
new THREE.Vector3(0, -1, 0),
0,
0.14,
125
);
}
function growOneTick() {
elapsedTicks++;
// Snapshot prevents newly spawned branches from growing in the same tick.
for (const root of [...roots]) {
if (root.done) continue;
const start = root.position.clone();
const oldRadius = root.radius;
const gravity = new THREE.Vector3(0, -1, 0);
const moisture = moistureCue(root.position);
const candidate = root.direction
.clone()
.multiplyScalar(weights.inertia)
.addScaledVector(gravity, weights.gravity)
.addScaledVector(moisture, weights.moisture);
if (candidate.lengthSq() < 0.000001) {
candidate.copy(root.direction);
}
const wobble = new THREE.Vector3(
Math.sin(root.id * 8.13 + root.age * 1.73),
0,
Math.cos(root.id * 5.41 + root.age * 1.19)
).multiplyScalar(0.025 + root.depth * 0.006);
candidate.add(wobble).normalize();
// Limit how abruptly a tip can change direction.
const angle = root.direction.angleTo(candidate);
const maximumTurn = 0.24;
if (angle > maximumTurn) {
root.direction
.lerp(candidate, maximumTurn / angle)
.normalize();
} else {
root.direction.copy(candidate);
}
root.position.addScaledVector(root.direction, 0.105);
root.age++;
const taper = root.depth === 0
? Math.max(0.043, 0.14 * (1 - root.age / 150))
: Math.max(0.022, root.radius * (1 - root.age / 72));
root.radius = taper;
root.marker.position.copy(root.position);
root.marker.scale.setScalar(root.depth === 0 ? 1 : 0.9);
addSegment(
root,
start,
root.position,
oldRadius,
root.radius
);
if (
root.position.y < -5.72 ||
Math.abs(root.position.x) > 4.78 ||
Math.abs(root.position.z) > 2.78 ||
root.age > root.maxAge
) {
root.done = true;
continue;
}
// Primary lateral roots.
if (
root.depth === 0 &&
root.age >= 9 &&
(root.age - 9) % 9 === 0 &&
primaryBranches < 3 &&
hash(root.id * 41 + root.age) < weights.branch
) {
spawnBranch(root, branchDirection(root));
}
// A small number of tertiary branches at high branching weights.
if (
root.depth === 1 &&
weights.branch > 0.55 &&
root.age >= 13 &&
(root.age - 13) % 13 === 0 &&
hash(root.id * 67 + root.age) <
(weights.branch - 0.55) * 0.6
) {
spawnBranch(root, branchDirection(root));
}
}
}
// ---------------------------------------------------------------------
// Controls
// ---------------------------------------------------------------------
function updateOutputs() {
$("gravityValue").textContent = weights.gravity.toFixed(2);
$("moistureValue").textContent = weights.moisture.toFixed(2);
$("inertiaValue").textContent = weights.inertia.toFixed(2);
$("branchValue").textContent = weights.branch.toFixed(2);
$("speedValue").textContent = `${trialSpeed.toFixed(1)}×`;
$("gravityWorldValue").textContent = `w g ${weights.gravity.toFixed(2)}`;
$("moistureWorldValue").textContent = `w m ${weights.moisture.toFixed(2)}`;
}
let restartTimer = null;
function scheduleRestart() {
clearTimeout(restartTimer);
$("statusText").textContent = "Restarting";
restartTimer = setTimeout(resetTrial, 130);
}
function bindWeight(id, key) {
$(id).addEventListener("input", (event) => {
weights[key] = Number(event.target.value);
updateOutputs();
scheduleRestart();
document
.querySelectorAll(".preset")
.forEach((button) => button.classList.remove("active"));
});
}
bindWeight("gravity", "gravity");
bindWeight("moisture", "moisture");
bindWeight("inertia", "inertia");
bindWeight("branch", "branch");
$("speed").addEventListener("input", (event) => {
trialSpeed = Number(event.target.value);
updateOutputs();
});
const presets = {
balanced: {
gravity: 0.9,
moisture: 0.55,
inertia: 1.15,
branch: 0.55
},
gravity: {
gravity: 1.35,
moisture: 0.05,
inertia: 1.0,
branch: 0.35
},
moisture: {
gravity: 0.15,
moisture: 1.3,
inertia: 0.85,
branch: 0.65
}
};
document.querySelectorAll(".preset").forEach((button) => {
button.addEventListener("click", () => {
const preset = presets[button.dataset.preset];
weights.gravity = preset.gravity;
weights.moisture = preset.moisture;
weights.inertia = preset.inertia;
weights.branch = preset.branch;
$("gravity").value = weights.gravity;
$("moisture").value = weights.moisture;
$("inertia").value = weights.inertia;
$("branch").value = weights.branch;
document
.querySelectorAll(".preset")
.forEach((item) => item.classList.remove("active"));
button.classList.add("active");
updateOutputs();
resetTrial();
});
});
function updatePauseUI() {
$("pauseButton").textContent = playing ? "Pause growth" : "Resume growth";
$("liveDot").classList.toggle("paused", !playing);
if (!playing) {
$("statusText").textContent = "Paused";
} else {
$("statusText").textContent = "Growing";
}
}
function togglePause() {
playing = !playing;
updatePauseUI();
}
$("pauseButton").addEventListener("click", togglePause);
$("resetButton").addEventListener("click", resetTrial);
$("cameraReset").addEventListener("click", resetCamera);
$("showCues").addEventListener("change", (event) => {
cueGroup.visible = event.target.checked;
});
$("showPatches").addEventListener("change", (event) => {
patchGroup.visible = event.target.checked;
});
window.addEventListener("keydown", (event) => {
if (["INPUT", "BUTTON"].includes(document.activeElement?.tagName)) return;
if (event.code === "Space") {
event.preventDefault();
togglePause();
} else if (event.key.toLowerCase() === "r") {
resetTrial();
} else if (event.key.toLowerCase() === "c") {
resetCamera();
}
});
// ---------------------------------------------------------------------
// Screen-space world labels
// ---------------------------------------------------------------------
const labelAnchors = {
gravity: new THREE.Vector3(),
moisture: new THREE.Vector3(),
patch: moisturePatches[0].position.clone().add(new THREE.Vector3(0, 0.8, 0)),
surface: new THREE.Vector3(-4.05, 3.86, -2.45)
};
function placeLabel(element, position, enabled = true) {
if (!enabled) {
element.style.display = "none";
return;
}
const projected = position.clone().project(camera);
const visible =
projected.z > -1 &&
projected.z < 1 &&
projected.x > -1.12 &&
projected.x < 1.12 &&
projected.y > -1.12 &&
projected.y < 1.12;
if (!visible) {
element.style.display = "none";
return;
}
element.style.display = "flex";
element.style.left = `${(projected.x * 0.5 + 0.5) * window.innerWidth}px`;
element.style.top = `${(-projected.y * 0.5 + 0.5) * window.innerHeight}px`;
}
function updateCuesAndLabels() {
const primary = roots[0];
const cuesEnabled = $("showCues").checked;
cueGroup.visible = cuesEnabled;
if (!primary) return;
gravityArrow.position
.copy(primary.position)
.add(new THREE.Vector3(1.0, 1.32, 0.12));
labelAnchors.gravity
.copy(gravityArrow.position)
.add(new THREE.Vector3(0, -0.62, 0));
const moistureDirection = moistureCue(primary.position);
const hasMoistureCue = moistureDirection.lengthSq() > 0.001;
moistureArrow.visible = hasMoistureCue;
if (hasMoistureCue) {
moistureArrow.position
.copy(primary.position)
.add(new THREE.Vector3(0, 0.02, 0.12));
moistureArrow.setDirection(moistureDirection);
moistureArrow.setLength(1.7, 0.27, 0.15);
labelAnchors.moisture
.copy(moistureArrow.position)
.addScaledVector(moistureDirection, 0.95)
.add(new THREE.Vector3(0, 0.12, 0));
}
placeLabel($("gravityLabel"), labelAnchors.gravity, cuesEnabled);
placeLabel(
$("moistureLabel"),
labelAnchors.moisture,
cuesEnabled && hasMoistureCue
);
placeLabel(
$("patchLabel"),
labelAnchors.patch,
$("showPatches").checked
);
placeLabel($("surfaceLabel"), labelAnchors.surface, true);
}
// ---------------------------------------------------------------------
// Animation and resize
// ---------------------------------------------------------------------
const clock = new THREE.Clock();
let uiTimer = 0;
function animate() {
requestAnimationFrame(animate);
const delta = Math.min(clock.getDelta(), 0.05);
if (playing) {
growthAccumulator += delta * 9 * trialSpeed;
let safety = 0;
while (growthAccumulator >= 1 && safety < 5) {
growOneTick();
growthAccumulator -= 1;
safety++;
}
}
updateCuesAndLabels();
uiTimer += delta;
if (uiTimer > 0.2) {
uiTimer = 0;
$("segmentCount").textContent = `${segmentCount} segments`;
if (playing && roots.length && roots.every((root) => root.done)) {
$("statusText").textContent = "Trial complete";
}
}
renderer.render(scene, camera);
}
window.addEventListener("resize", () => {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
});
updateOutputs();
resetTrial();
updatePauseUI();
animate();
</script>
</body>
</html>
```