Prompt specification
Build or customize the Three.js 3D scene "Light-direction growth 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: Light-direction growth sandbox
Category: Biology & Nature · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/light-direction-growth-sandbox-x0764
Scene Description Prompt:
Create a single self-contained HTML file using Three.js from cdnjs that shows plant phototropism. Create a controlled planter with adjustable light positions and obstacles; a stated toy growth algorithm extends stems incrementally, showing how local responses produce different overall forms. Low-poly.
Working Three.js Starter (light-direction-growth-sandbox-x0764):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Plant Phototropism Laboratory</title>
<style>
:root {
color-scheme: dark;
--bg: #101722;
--panel: rgba(18, 27, 39, 0.92);
--panel-border: rgba(173, 205, 224, 0.18);
--text: #e8f2f3;
--muted: #9db0bd;
--accent: #74d69b;
--light: #ffd466;
--danger: #ff7b72;
}
* { box-sizing: border-box; }
html, body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: var(--bg);
color: var(--text);
font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
#viewport {
position: fixed;
inset: 0;
}
#viewport canvas {
display: block;
width: 100%;
height: 100%;
touch-action: none;
}
.brand {
position: fixed;
top: 18px;
left: 18px;
z-index: 5;
width: min(440px, calc(100vw - 390px));
padding: 16px 18px;
border: 1px solid var(--panel-border);
border-radius: 16px;
background: rgba(14, 22, 32, 0.82);
backdrop-filter: blur(14px);
box-shadow: 0 12px 38px rgba(0, 0, 0, 0.2);
pointer-events: none;
}
.eyebrow {
color: var(--accent);
font-size: 0.72rem;
font-weight: 800;
letter-spacing: 0.14em;
text-transform: uppercase;
}
.brand h1 {
margin: 5px 0 8px;
font-size: clamp(1.25rem, 2.2vw, 1.8rem);
line-height: 1.1;
}
.brand p {
margin: 0;
color: var(--muted);
font-size: 0.83rem;
line-height: 1.45;
}
.stats {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 8px;
margin-top: 12px;
}
.stat {
padding: 8px;
border-radius: 10px;
background: rgba(255, 255, 255, 0.045);
}
.stat span {
display: block;
color: var(--muted);
font-size: 0.65rem;
text-transform: uppercase;
letter-spacing: 0.08em;
}
.stat strong {
display: block;
margin-top: 2px;
font-size: 0.93rem;
}
.panel {
position: fixed;
z-index: 10;
top: 18px;
right: 18px;
width: 340px;
max-height: calc(100vh - 36px);
overflow: auto;
border: 1px solid var(--panel-border);
border-radius: 16px;
background: var(--panel);
backdrop-filter: blur(16px);
box-shadow: 0 18px 50px rgba(0, 0, 0, 0.28);
}
.panel-header {
position: sticky;
top: 0;
z-index: 2;
display: flex;
align-items: center;
justify-content: space-between;
padding: 14px 16px;
border-bottom: 1px solid var(--panel-border);
background: rgba(18, 27, 39, 0.96);
}
.panel-header strong {
font-size: 0.95rem;
}
.panel.collapsed .panel-body {
display: none;
}
.panel-body {
padding: 6px 16px 16px;
}
button {
border: 1px solid rgba(255, 255, 255, 0.13);
border-radius: 9px;
padding: 9px 11px;
color: var(--text);
background: #263548;
font: inherit;
font-size: 0.78rem;
font-weight: 700;
cursor: pointer;
transition: transform 120ms ease, background 120ms ease;
}
button:hover {
background: #32465d;
transform: translateY(-1px);
}
button:active { transform: translateY(0); }
button.primary {
color: #10251a;
background: var(--accent);
border-color: transparent;
}
button.primary:hover { background: #8ae2ae; }
button.icon-button {
width: 30px;
height: 30px;
padding: 0;
}
.button-row {
display: grid;
grid-template-columns: 1fr 1fr 1fr;
gap: 7px;
margin: 10px 0 14px;
}
details {
border-top: 1px solid var(--panel-border);
padding: 12px 0;
}
summary {
color: #dcebed;
font-size: 0.82rem;
font-weight: 800;
cursor: pointer;
user-select: none;
}
.section-note {
margin: 8px 0 12px;
color: var(--muted);
font-size: 0.72rem;
line-height: 1.45;
}
.control {
margin: 11px 0;
}
.control-label {
display: flex;
justify-content: space-between;
gap: 10px;
margin-bottom: 5px;
color: #d8e5e8;
font-size: 0.75rem;
}
output {
color: var(--accent);
font-variant-numeric: tabular-nums;
}
input[type="range"] {
width: 100%;
height: 4px;
margin: 5px 0;
accent-color: var(--accent);
cursor: pointer;
}
.check-row {
display: flex;
align-items: center;
justify-content: space-between;
gap: 10px;
margin: 8px 0;
color: #d8e5e8;
font-size: 0.77rem;
}
.check-row label {
display: flex;
align-items: center;
gap: 8px;
cursor: pointer;
}
input[type="checkbox"] {
width: 16px;
height: 16px;
accent-color: var(--accent);
}
.preset-row {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 6px;
margin: 9px 0;
}
.preset-row button {
padding: 7px 5px;
font-size: 0.7rem;
}
.obstacle-card {
margin-top: 10px;
padding: 10px;
border: 1px solid rgba(255, 255, 255, 0.08);
border-radius: 11px;
background: rgba(255, 255, 255, 0.025);
}
.obstacle-title {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 7px;
font-size: 0.78rem;
font-weight: 800;
}
.dot {
display: inline-block;
width: 9px;
height: 9px;
margin-right: 6px;
border-radius: 50%;
}
.dot.a { background: #f39a61; }
.dot.b { background: #ae8cff; }
.status {
display: flex;
align-items: center;
gap: 8px;
margin-top: 12px;
color: var(--muted);
font-size: 0.75rem;
}
.status-dot {
width: 8px;
height: 8px;
border-radius: 50%;
background: #8c9ba8;
}
.status-dot.running {
background: var(--accent);
box-shadow: 0 0 12px rgba(116, 214, 155, 0.75);
}
.algorithm {
position: fixed;
z-index: 6;
left: 18px;
bottom: 18px;
width: min(440px, calc(100vw - 390px));
border: 1px solid var(--panel-border);
border-radius: 14px;
background: rgba(14, 22, 32, 0.84);
backdrop-filter: blur(14px);
box-shadow: 0 12px 38px rgba(0, 0, 0, 0.2);
}
.algorithm summary {
padding: 12px 15px;
}
.algorithm-content {
padding: 0 15px 13px;
color: var(--muted);
font-size: 0.74rem;
line-height: 1.5;
}
.formula {
margin: 8px 0;
padding: 8px 10px;
border-radius: 8px;
color: #dcebed;
background: rgba(255, 255, 255, 0.045);
font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
font-size: 0.68rem;
overflow-wrap: anywhere;
}
.legend {
display: flex;
flex-wrap: wrap;
gap: 8px 13px;
margin-top: 9px;
}
.legend span {
display: inline-flex;
align-items: center;
gap: 5px;
}
.legend i {
width: 16px;
height: 3px;
border-radius: 2px;
}
.hint {
position: fixed;
z-index: 4;
left: 50%;
bottom: 20px;
transform: translateX(-50%);
padding: 7px 11px;
border: 1px solid rgba(255,255,255,0.09);
border-radius: 20px;
color: rgba(222,235,239,0.72);
background: rgba(12,18,27,0.58);
font-size: 0.68rem;
pointer-events: none;
}
.world-label {
position: fixed;
z-index: 3;
transform: translate(-50%, -100%);
padding: 4px 7px;
border: 1px solid rgba(255,255,255,0.15);
border-radius: 6px;
color: white;
background: rgba(12,18,27,0.72);
font-size: 0.64rem;
font-weight: 800;
letter-spacing: 0.04em;
pointer-events: none;
white-space: nowrap;
}
#light-label {
color: #ffe38c;
border-color: rgba(255, 212, 102, 0.35);
}
#obstacle-a-label { color: #ffb184; }
#obstacle-b-label { color: #c7b4ff; }
@media (max-width: 760px) {
.brand {
top: 10px;
left: 10px;
width: calc(100vw - 20px);
padding: 12px 14px;
}
.brand p { display: none; }
.stats { margin-top: 8px; }
.panel {
top: 145px;
right: 10px;
width: calc(100vw - 20px);
max-height: 53vh;
}
.algorithm {
left: 10px;
bottom: 10px;
width: calc(100vw - 20px);
}
.algorithm:not([open]) {
width: auto;
}
.hint { display: none; }
}
</style>
</head>
<body>
<div id="viewport"></div>
<header class="brand">
<div class="eyebrow">Interactive botany lab</div>
<h1>Plant Phototropism Laboratory</h1>
<p>
Move the light and reshape the planter. New stem segments react locally,
producing different global growth forms.
</p>
<div class="stats">
<div class="stat">
<span>Segments</span>
<strong id="segment-count">0</strong>
</div>
<div class="stat">
<span>Tip height</span>
<strong id="tip-height">0.0</strong>
</div>
<div class="stat">
<span>Mean turn</span>
<strong id="mean-turn">0.0°</strong>
</div>
</div>
</header>
<aside id="panel" class="panel">
<div class="panel-header">
<strong>Experiment controls</strong>
<button id="panel-toggle" class="icon-button" title="Collapse controls">−</button>
</div>
<div class="panel-body">
<div class="button-row">
<button id="grow-button" class="primary">Pause growth</button>
<button id="step-button">Step</button>
<button id="reset-button">Reset</button>
</div>
<div class="status">
<span id="status-dot" class="status-dot running"></span>
<span id="status-text">Growing incrementally</span>
</div>
<details open>
<summary>Light position</summary>
<p class="section-note">
The light affects each new segment. Its intensity changes visual
brightness, not the direction sampled by the growth rule.
</p>
<div class="preset-row">
<button data-light-preset="left">From left</button>
<button data-light-preset="right">From right</button>
<button data-light-preset="high">Overhead</button>
</div>
<div class="control">
<div class="control-label">
<span>Horizontal X</span><output id="light-x-out">−4.5</output>
</div>
<input id="light-x" type="range" min="-7" max="7" step="0.1" value="-4.5">
</div>
<div class="control">
<div class="control-label">
<span>Depth Z</span><output id="light-z-out">−2.8</output>
</div>
<input id="light-z" type="range" min="-6" max="6" step="0.1" value="-2.8">
</div>
<div class="control">
<div class="control-label">
<span>Elevation</span><output id="light-y-out">3.4</output>
</div>
<input id="light-y" type="range" min="1.5" max="8" step="0.1" value="3.4">
</div>
<div class="control">
<div class="control-label">
<span>Brightness</span><output id="light-intensity-out">1.2×</output>
</div>
<input id="light-intensity" type="range" min="0.3" max="3" step="0.1" value="1.2">
</div>
</details>
<details open>
<summary>Obstacles</summary>
<p class="section-note">
Obstacles introduce repulsion and tangential avoidance. Editing an
obstacle resets the plant so comparisons remain controlled.
</p>
<div class="obstacle-card">
<div class="obstacle-title">
<span><i class="dot a"></i>Obstacle A</span>
<label class="check-row">
<input id="obstacle-a-enabled" type="checkbox" checked> Enabled
</label>
</div>
<div class="control">
<div class="control-label"><span>X</span><output id="obstacle-a-x-out">−1.5</output></div>
<input id="obstacle-a-x" type="range" min="-4.2" max="4.2" step="0.1" value="-1.5">
</div>
<div class="control">
<div class="control-label"><span>Depth Z</span><output id="obstacle-a-z-out">−1.4</output></div>
<input id="obstacle-a-z" type="range" min="-3.2" max="3.2" step="0.1" value="-1.4">
</div>
<div class="control">
<div class="control-label"><span>Width</span><output id="obstacle-a-width-out">1.5</output></div>
<input id="obstacle-a-width" type="range" min="0.4" max="3" step="0.1" value="1.5">
</div>
<div class="control">
<div class="control-label"><span>Depth</span><output id="obstacle-a-depth-out">1.4</output></div>
<input id="obstacle-a-depth" type="range" min="0.4" max="3" step="0.1" value="1.4">
</div>
<div class="control">
<div class="control-label"><span>Height</span><output id="obstacle-a-height-out">2.4</output></div>
<input id="obstacle-a-height" type="range" min="0.5" max="5" step="0.1" value="2.4">
</div>
</div>
<div class="obstacle-card">
<div class="obstacle-title">
<span><i class="dot b"></i>Obstacle B</span>
<label class="check-row">
<input id="obstacle-b-enabled" type="checkbox"> Enabled
</label>
</div>
<div class="control">
<div class="control-label"><span>X</span><output id="obstacle-b-x-out">2.4</output></div>
<input id="obstacle-b-x" type="range" min="-4.2" max="4.2" step="0.1" value="2.4">
</div>
<div class="control">
<div class="control-label"><span>Depth Z</span><output id="obstacle-b-z-out">1.8</output></div>
<input id="obstacle-b-z" type="range" min="-3.2" max="3.2" step="0.1" value="1.8">
</div>
<div class="control">
<div class="control-label"><span>Width</span><output id="obstacle-b-width-out">1.0</output></div>
<input id="obstacle-b-width" type="range" min="0.4" max="3" step="0.1" value="1.0">
</div>
<div class="control">
<div class="control-label"><span>Depth</span><output id="obstacle-b-depth-out">1.1</output></div>
<input id="obstacle-b-depth" type="range" min="0.4" max="3" step="0.1" value="1.1">
</div>
<div class="control">
<div class="control-label"><span>Height</span><output id="obstacle-b-height-out">1.6</output></div>
<input id="obstacle-b-height" type="range" min="0.5" max="5" step="0.1" value="1.6">
</div>
</div>
</details>
<details open>
<summary>Growth speed</summary>
<div class="control">
<div class="control-label">
<span>Segments per second</span><output id="speed-out">8</output>
</div>
<input id="growth-speed" type="range" min="2" max="20" step="1" value="8">
</div>
</details>
</div>
</aside>
<details class="algorithm" open>
<summary>Toy growth algorithm</summary>
<div class="algorithm-content">
At every step, the growing tip samples the current heading
<b>h</b>, the unit vector <b>l</b> toward the light, a local obstacle
response <b>r</b>, and a small deterministic curl <b>c</b>.
<div class="formula">
candidate = normalize(1.20h + 0.95l + 1.85r + 0.08c)<br>
next heading = heading rotated toward candidate, maximum 18°<br>
next point = tip + 0.13 × next heading
</div>
The proposed segment is collision-checked against the obstacle boxes.
The rule is qualitative: it demonstrates how local directional responses
can create different whole-plant shapes, but is not a biological model.
<div class="legend">
<span><i style="background:#ffd466"></i>Light response</span>
<span><i style="background:#ff7b72"></i>Obstacle response</span>
<span><i style="background:#74d69b"></i>Selected heading</span>
</div>
</div>
</details>
<div class="hint">Drag to orbit · scroll to zoom · double-click to reset view</div>
<div id="light-label" class="world-label">LIGHT</div>
<div id="obstacle-a-label" class="world-label">BLOCK A</div>
<div id="obstacle-b-label" class="world-label">BLOCK B</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);
const viewport = $("viewport");
// -----------------------------------------------------------------------------
// Renderer, scene, and camera
// -----------------------------------------------------------------------------
const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.08;
viewport.appendChild(renderer.domElement);
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x101722);
scene.fog = new THREE.Fog(0x101722, 18, 36);
const camera = new THREE.PerspectiveCamera(
43,
window.innerWidth / window.innerHeight,
0.1,
100
);
const cameraState = {
radius: 15,
theta: 0.72,
phi: 1.02,
target: new THREE.Vector3(0, 2.1, 0)
};
function updateCamera() {
const sinPhi = Math.sin(cameraState.phi);
camera.position.set(
cameraState.target.x + cameraState.radius * sinPhi * Math.sin(cameraState.theta),
cameraState.target.y + cameraState.radius * Math.cos(cameraState.phi),
cameraState.target.z + cameraState.radius * sinPhi * Math.cos(cameraState.theta)
);
camera.lookAt(cameraState.target);
}
updateCamera();
const hemisphere = new THREE.HemisphereLight(0xc5ddff, 0x263521, 1.65);
scene.add(hemisphere);
const keyLight = new THREE.DirectionalLight(0xfff3dc, 2.1);
keyLight.position.set(7, 12, 8);
keyLight.castShadow = true;
keyLight.shadow.mapSize.set(2048, 2048);
keyLight.shadow.camera.left = -10;
keyLight.shadow.camera.right = 10;
keyLight.shadow.camera.top = 10;
keyLight.shadow.camera.bottom = -10;
keyLight.shadow.camera.near = 1;
keyLight.shadow.camera.far = 30;
keyLight.shadow.bias = -0.0005;
scene.add(keyLight);
// -----------------------------------------------------------------------------
// Low-poly environment
// -----------------------------------------------------------------------------
const SOIL_TOP = 0.54;
const PLANTER_X = 4.85;
const PLANTER_Z = 3.75;
const groundMaterial = new THREE.MeshStandardMaterial({
color: 0x182723,
roughness: 1,
flatShading: true
});
const ground = new THREE.Mesh(
new THREE.CircleGeometry(18, 32),
groundMaterial
);
ground.rotation.x = -Math.PI / 2;
ground.position.y = -0.035;
ground.receiveShadow = true;
scene.add(ground);
const grid = new THREE.GridHelper(28, 28, 0x365149, 0x243630);
grid.position.y = -0.02;
grid.material.transparent = true;
grid.material.opacity = 0.45;
scene.add(grid);
const planter = new THREE.Group();
scene.add(planter);
const wallMaterial = new THREE.MeshStandardMaterial({
color: 0xa85f45,
roughness: 0.9,
flatShading: true
});
const rimMaterial = new THREE.MeshStandardMaterial({
color: 0xcc7956,
roughness: 0.85,
flatShading: true
});
const soilMaterial = new THREE.MeshStandardMaterial({
color: 0x403127,
roughness: 1,
flatShading: true
});
function addBox(parent, size, position, material, castShadow = true) {
const mesh = new THREE.Mesh(new THREE.BoxGeometry(...size), material);
mesh.position.set(...position);
mesh.castShadow = castShadow;
mesh.receiveShadow = true;
parent.add(mesh);
return mesh;
}
addBox(planter, [10.5, 0.28, 8.5], [0, 0.14, 0], wallMaterial);
addBox(planter, [9.7, 0.16, 7.7], [0, 0.46, 0], soilMaterial, false);
addBox(planter, [10.5, 0.78, 0.36], [0, 0.59, 4.02], wallMaterial);
addBox(planter, [10.5, 0.78, 0.36], [0, 0.59, -4.02], wallMaterial);
addBox(planter, [0.36, 0.78, 7.7], [5.07, 0.59, 0], wallMaterial);
addBox(planter, [0.36, 0.78, 7.7], [-5.07, 0.59, 0], wallMaterial);
addBox(planter, [10.65, 0.12, 0.44], [0, 1.01, 4.02], rimMaterial);
addBox(planter, [10.65, 0.12, 0.44], [0, 1.01, -4.02], rimMaterial);
addBox(planter, [0.44, 0.12, 7.7], [5.07, 1.01, 0], rimMaterial);
addBox(planter, [0.44, 0.12, 7.7], [-5.07, 1.01, 0], rimMaterial);
// A few low-poly stones on the soil.
const stoneMaterial = new THREE.MeshStandardMaterial({
color: 0x77685a,
roughness: 1,
flatShading: true
});
[
[-3.5, 0.64, 2.6, 0.24],
[3.7, 0.62, -2.5, 0.19],
[-3.9, 0.61, -2.9, 0.16],
[3.2, 0.65, 2.9, 0.22]
].forEach(([x, y, z, scale]) => {
const stone = new THREE.Mesh(
new THREE.DodecahedronGeometry(scale, 0),
stoneMaterial
);
stone.position.set(x, y, z);
stone.scale.y = 0.55;
stone.rotation.set(0.3, x, 0.1);
stone.castShadow = true;
stone.receiveShadow = true;
scene.add(stone);
});
// -----------------------------------------------------------------------------
// Light and obstacles
// -----------------------------------------------------------------------------
const lightPosition = new THREE.Vector3(-4.5, 3.4, -2.8);
const lightGroup = new THREE.Group();
scene.add(lightGroup);
const lightMaterial = new THREE.MeshStandardMaterial({
color: 0xffd466,
emissive: 0xffa928,
emissiveIntensity: 1.7,
roughness: 0.35,
flatShading: true
});
const lightOrb = new THREE.Mesh(
new THREE.IcosahedronGeometry(0.29, 1),
lightMaterial
);
lightOrb.castShadow = true;
lightGroup.add(lightOrb);
const lightRing = new THREE.Mesh(
new THREE.TorusGeometry(0.43, 0.035, 6, 24),
new THREE.MeshStandardMaterial({
color: 0xffed9d,
emissive: 0xffb52e,
emissiveIntensity: 0.9,
roughness: 0.4
})
);
lightGroup.add(lightRing);
const pointLight = new THREE.PointLight(0xffd277, 32, 18, 2);
pointLight.castShadow = true;
pointLight.shadow.mapSize.set(1024, 1024);
lightGroup.add(pointLight);
function createObstacle(color) {
const group = new THREE.Group();
const material = new THREE.MeshStandardMaterial({
color,
roughness: 0.82,
flatShading: true
});
const mesh = new THREE.Mesh(new THREE.BoxGeometry(1, 1, 1), material);
mesh.castShadow = true;
mesh.receiveShadow = true;
group.add(mesh);
const edgeMaterial = new THREE.LineBasicMaterial({
color: 0x231d1b,
transparent: true,
opacity: 0.55
});
const edges = new THREE.LineSegments(
new THREE.EdgesGeometry(new THREE.BoxGeometry(1, 1, 1)),
edgeMaterial
);
group.add(edges);
scene.add(group);
return { group, mesh, edges };
}
const obstacles = [
{
id: "a",
x: -1.5,
z: -1.4,
width: 1.5,
depth: 1.4,
height: 2.4,
enabled: true,
color: 0xd98254,
visual: createObstacle(0xd98254)
},
{
id: "b",
x: 2.4,
z: 1.8,
width: 1.0,
depth: 1.1,
height: 1.6,
enabled: false,
color: 0x9270e8,
visual: createObstacle(0x9270e8)
}
];
function obstacleBounds(obstacle, padding = 0) {
return {
min: new THREE.Vector3(
obstacle.x - obstacle.width / 2 - padding,
SOIL_TOP,
obstacle.z - obstacle.depth / 2 - padding
),
max: new THREE.Vector3(
obstacle.x + obstacle.width / 2 + padding,
SOIL_TOP + obstacle.height,
obstacle.z + obstacle.depth / 2 + padding
)
};
}
function syncObstacle(obstacle) {
obstacle.visual.group.visible = obstacle.enabled;
obstacle.visual.group.position.set(
obstacle.x,
SOIL_TOP + obstacle.height / 2,
obstacle.z
);
obstacle.visual.group.scale.set(
obstacle.width,
obstacle.height,
obstacle.depth
);
}
obstacles.forEach(syncObstacle);
// -----------------------------------------------------------------------------
// Plant rendering
// -----------------------------------------------------------------------------
const plantGroup = new THREE.Group();
scene.add(plantGroup);
const stemMaterials = [
new THREE.MeshStandardMaterial({
color: 0x328a4b,
roughness: 0.88,
flatShading: true
}),
new THREE.MeshStandardMaterial({
color: 0x3d9b55,
roughness: 0.88,
flatShading: true
})
];
const leafMaterial = new THREE.MeshStandardMaterial({
color: 0x65bd65,
roughness: 0.9,
side: THREE.DoubleSide,
flatShading: true
});
const tipMaterial = new THREE.MeshStandardMaterial({
color: 0xa4e780,
emissive: 0x285c24,
emissiveIntensity: 0.45,
roughness: 0.7,
flatShading: true
});
const tipMarker = new THREE.Mesh(
new THREE.IcosahedronGeometry(0.115, 1),
tipMaterial
);
tipMarker.castShadow = true;
scene.add(tipMarker);
function makeLeafGeometry() {
const geometry = new THREE.BufferGeometry();
geometry.setAttribute("position", new THREE.Float32BufferAttribute([
0, 0, 0,
0.43, 0.015, 0,
0, 0.085, 0.15,
0, 0.085, -0.15
], 3));
geometry.setIndex([
0, 1, 2,
0, 2, 3,
0, 3, 1,
0, 1, 3
]);
geometry.computeVertexNormals();
return geometry;
}
const leafGeometry = makeLeafGeometry();
const directLine = new THREE.Line(
new THREE.BufferGeometry().setFromPoints([lightPosition, lightPosition]),
new THREE.LineDashedMaterial({
color: 0xffd466,
dashSize: 0.18,
gapSize: 0.12,
transparent: true,
opacity: 0.32
})
);
scene.add(directLine);
const lightArrow = new THREE.ArrowHelper(
new THREE.Vector3(0, 1, 0),
new THREE.Vector3(),
1.2,
0xffd466,
0.25,
0.13
);
const obstacleArrow = new THREE.ArrowHelper(
new THREE.Vector3(1, 0, 0),
new THREE.Vector3(),
1.1,
0xff7b72,
0.25,
0.13
);
const headingArrow = new THREE.ArrowHelper(
new THREE.Vector3(0, 1, 0),
new THREE.Vector3(),
0.85,
0x74d69b,
0.21,
0.11
);
scene.add(lightArrow, obstacleArrow, headingArrow);
// -----------------------------------------------------------------------------
// Toy growth model
// -----------------------------------------------------------------------------
const MAX_SEGMENTS = 125;
const SEGMENT_LENGTH = 0.13;
const MAX_TURN = THREE.MathUtils.degToRad(18);
let points = [new THREE.Vector3(0, SOIL_TOP + 0.035, 0)];
let heading = new THREE.Vector3(0, 1, 0);
let running = true;
let growthSpeed = 8;
let growthAccumulator = 0;
function clamp(value, min, max) {
return Math.max(min, Math.min(max, value));
}
function segmentIntersectsBox(start, end, bounds) {
let tMin = 0;
let tMax = 1;
const axes = ["x", "y", "z"];
for (const axis of axes) {
const delta = end[axis] - start[axis];
const min = bounds.min[axis];
const max = bounds.max[axis];
if (Math.abs(delta) < 1e-8) {
if (start[axis] < min || start[axis] > max) return false;
} else {
let t1 = (min - start[axis]) / delta;
let t2 = (max - start[axis]) / delta;
if (t1 > t2) [t1, t2] = [t2, t1];
tMin = Math.max(tMin, t1);
tMax = Math.min(tMax, t2);
if (tMin > tMax) return false;
}
}
return true;
}
function hitsAnyObstacle(start, end) {
return obstacles.some(obstacle => {
if (!obstacle.enabled) return false;
return segmentIntersectsBox(start, end, obstacleBounds(obstacle, 0.015));
});
}
function horizontalLength(vector) {
return Math.hypot(vector.x, vector.z);
}
function obstacleResponse(position, lightDirection) {
const response = new THREE.Vector3();
const desiredHorizontal = new THREE.Vector3(lightDirection.x, 0, lightDirection.z);
if (desiredHorizontal.lengthSq() < 1e-8) {
desiredHorizontal.set(0, 0, 1);
} else {
desiredHorizontal.normalize();
}
obstacles.forEach((obstacle, index) => {
if (!obstacle.enabled) return;
const bounds = obstacleBounds(obstacle);
const closest = new THREE.Vector3(
clamp(position.x, bounds.min.x, bounds.max.x),
clamp(position.y, bounds.min.y, bounds.max.y),
clamp(position.z, bounds.min.z, bounds.max.z)
);
let away = new THREE.Vector3(
position.x - closest.x,
0,
position.z - closest.z
);
if (away.lengthSq() < 1e-8) {
away = new THREE.Vector3(
position.x - obstacle.x,
0,
position.z - obstacle.z
);
}
if (away.lengthSq() < 1e-8) {
away.copy(desiredHorizontal).multiplyScalar(-1);
} else {
away.normalize();
}
const centerOffset = new THREE.Vector3(
obstacle.x - position.x,
0,
obstacle.z - position.z
);
const cross = desiredHorizontal.x * centerOffset.z
- desiredHorizontal.z * centerOffset.x;
const side = Math.abs(cross) < 1e-6
? (index % 2 === 0 ? 1 : -1)
: Math.sign(cross);
const tangent = new THREE.Vector3(
-desiredHorizontal.z * side,
0,
desiredHorizontal.x * side
);
const horizontalDistance = Math.hypot(
position.x - obstacle.x,
position.z - obstacle.z
);
const influenceRadius = Math.max(obstacle.width, obstacle.depth) * 0.72 + 1.25;
if (
position.y <= bounds.max.y + 0.55 &&
horizontalDistance < influenceRadius
) {
const falloff = 1 - horizontalDistance / influenceRadius;
response.addScaledVector(away, 1.25 * falloff);
response.addScaledVector(tangent, 1.05 * falloff);
}
// If the straight ray toward the light enters an inflated obstacle,
// emphasize the tangential route around that obstacle.
const rayEnd = position.clone().addScaledVector(lightDirection, 3.5);
const padded = obstacleBounds(obstacle, 0.28);
if (segmentIntersectsBox(position, rayEnd, padded)) {
response.addScaledVector(tangent, 1.8);
response.addScaledVector(away, 0.55);
}
});
return response;
}
function rotateY(vector, angle) {
return vector.clone().applyAxisAngle(new THREE.Vector3(0, 1, 0), angle);
}
function selectSafeDirection(position, proposed) {
const yawAttempts = [
0,
THREE.MathUtils.degToRad(24),
THREE.MathUtils.degToRad(-24),
THREE.MathUtils.degToRad(48),
THREE.MathUtils.degToRad(-48),
THREE.MathUtils.degToRad(74),
THREE.MathUtils.degToRad(-74),
THREE.MathUtils.degToRad(100),
THREE.MathUtils.degToRad(-100)
];
for (const angle of yawAttempts) {
const candidate = rotateY(proposed, angle);
const end = position.clone().addScaledVector(candidate, SEGMENT_LENGTH);
if (!hitsAnyObstacle(position, end)) return candidate;
}
// A more vertical escape can clear a low obstacle when a purely horizontal
// detour is impossible.
for (const angle of yawAttempts) {
const candidate = rotateY(proposed, angle);
candidate.y = Math.max(candidate.y, 0.55);
candidate.normalize();
const end = position.clone().addScaledVector(candidate, SEGMENT_LENGTH);
if (!hitsAnyObstacle(position, end)) return candidate;
}
return proposed;
}
function growOneSegment() {
if (points.length - 1 >= MAX_SEGMENTS) {
running = false;
updateStatus();
return false;
}
const tip = points[points.length - 1];
const lightDirection = lightPosition.clone().sub(tip).normalize();
const avoidance = obstacleResponse(tip, lightDirection);
const curl = new THREE.Vector3(
Math.sin(points.length * 1.73) * 0.52,
Math.sin(points.length * 0.41) * 0.12,
Math.cos(points.length * 1.17) * 0.52
).normalize();
const candidate = new THREE.Vector3()
.addScaledVector(heading, 1.20)
.addScaledVector(lightDirection, 0.95)
.addScaledVector(avoidance, 1.85)
.addScaledVector(curl, 0.08)
.normalize();
const axis = heading.clone().cross(candidate);
let nextHeading;
if (axis.lengthSq() < 1e-10) {
nextHeading = candidate.clone();
} else {
axis.normalize();
const angle = Math.acos(clamp(heading.dot(candidate), -1, 1));
nextHeading = heading.clone().applyAxisAngle(
axis,
Math.min(angle, MAX_TURN)
);
}
nextHeading = selectSafeDirection(tip, nextHeading);
const nextPoint = tip.clone().addScaledVector(nextHeading, SEGMENT_LENGTH);
// Keep the plant within the planter. Boundary contact redirects the heading
// inward rather than allowing the stem to leave the controlled environment.
if (Math.abs(nextPoint.x) > PLANTER_X) {
nextHeading.x *= -0.72;
nextPoint.x = clamp(nextPoint.x, -PLANTER_X, PLANTER_X);
}
if (Math.abs(nextPoint.z) > PLANTER_Z) {
nextHeading.z *= -0.72;
nextPoint.z = clamp(nextPoint.z, -PLANTER_Z, PLANTER_Z);
}
if (nextPoint.y > 8.1) {
nextHeading.y *= -0.4;
nextPoint.y = 8.1;
}
const segmentStart = points[points.length - 1];
const direction = nextPoint.clone().sub(segmentStart);
const length = direction.length();
direction.normalize();
const progress = (points.length - 1) / MAX_SEGMENTS;
const radiusBottom = THREE.MathUtils.lerp(0.105, 0.052, progress);
const radiusTop = THREE.MathUtils.lerp(0.094, 0.043, progress);
const segment = new THREE.Mesh(
new THREE.CylinderGeometry(radiusTop, radiusBottom, length, 5, 1, false),
stemMaterials[points.length % stemMaterials.length]
);
segment.position.copy(segmentStart).add(nextPoint).multiplyScalar(0.5);
segment.quaternion.setFromUnitVectors(
new THREE.Vector3(0, 1, 0),
direction
);
segment.castShadow = true;
segment.receiveShadow = true;
plantGroup.add(segment);
points.push(nextPoint);
heading.copy(nextHeading).normalize();
if (points.length % 5 === 0) {
const leafAngle = points.length * 2.39996 + (points.length % 2) * Math.PI;
const leafDirection = new THREE.Vector3(
Math.cos(leafAngle),
0.12,
Math.sin(leafAngle)
).normalize();
const leaf = new THREE.Mesh(leafGeometry, leafMaterial);
leaf.position.copy(nextPoint);
leaf.quaternion.setFromUnitVectors(
new THREE.Vector3(1, 0, 0),
leafDirection
);
leaf.castShadow = true;
plantGroup.add(leaf);
}
updateResponseVisuals();
updateStatus();
return true;
}
function clearPlantGeometry() {
plantGroup.traverse(object => {
if (object.geometry) object.geometry.dispose();
});
plantGroup.clear();
}
function resetPlant(stop = true) {
clearPlantGeometry();
points = [new THREE.Vector3(0, SOIL_TOP + 0.035, 0)];
heading.set(0, 1, 0);
growthAccumulator = 0;
if (stop) running = false;
updateResponseVisuals();
updateStatus();
}
function updateResponseVisuals() {
const tip = points[points.length - 1];
const lightDirection = lightPosition.clone().sub(tip).normalize();
const avoidance = obstacleResponse(tip, lightDirection);
tipMarker.position.copy(tip);
lightArrow.position.copy(tip);
lightArrow.setDirection(lightDirection);
lightArrow.setLength(1.18, 0.24, 0.12);
headingArrow.position.copy(tip);
headingArrow.setDirection(heading);
headingArrow.setLength(0.86, 0.2, 0.1);
if (avoidance.lengthSq() > 0.012) {
obstacleArrow.visible = true;
obstacleArrow.position.copy(tip);
obstacleArrow.setDirection(avoidance.clone().normalize());
obstacleArrow.setLength(1.05, 0.24, 0.12);
} else {
obstacleArrow.visible = false;
}
directLine.geometry.dispose();
directLine.geometry = new THREE.BufferGeometry().setFromPoints([
lightPosition,
tip
]);
directLine.computeLineDistances();
}
function meanTurnDegrees() {
if (points.length < 3) return 0;
let total = 0;
for (let i = 1; i < points.length - 1; i++) {
const a = points[i].clone().sub(points[i - 1]).normalize();
const b = points[i + 1].clone().sub(points[i]).normalize();
total += Math.acos(clamp(a.dot(b), -1, 1));
}
return THREE.MathUtils.radToDeg(total / (points.length - 2));
}
function updateStatus() {
const count = points.length - 1;
const complete = count >= MAX_SEGMENTS;
$("segment-count").textContent = count;
$("tip-height").textContent =
Math.max(0, points[points.length - 1].y - SOIL_TOP).toFixed(1);
$("mean-turn").textContent = `${meanTurnDegrees().toFixed(1)}°`;
$("status-dot").classList.toggle("running", running);
if (complete) {
$("status-text").textContent = "Growth limit reached";
} else if (running) {
$("status-text").textContent = "Growing incrementally";
} else {
$("status-text").textContent = "Paused — ready for another step";
}
$("grow-button").textContent = running
? "Pause growth"
: complete
? "Restart growth"
: "Start growth";
}
// -----------------------------------------------------------------------------
// Controls
// -----------------------------------------------------------------------------
function bindRange(inputId, outputId, onChange, format = value => value.toFixed(1)) {
const input = $(inputId);
const output = $(outputId);
const sync = () => {
const value = Number(input.value);
output.textContent = format(value);
if (onChange) onChange(value);
};
input.addEventListener("input", sync);
sync();
}
function updateLight() {
lightPosition.set(
Number($("light-x").value),
Number($("light-y").value),
Number($("light-z").value)
);
lightGroup.position.copy(lightPosition);
const intensity = Number($("light-intensity").value);
pointLight.intensity = 24 + intensity * 13;
lightMaterial.emissiveIntensity = 0.8 + intensity * 0.75;
updateResponseVisuals();
}
bindRange("light-x", "light-x-out", updateLight);
bindRange("light-y", "light-y-out", updateLight);
bindRange("light-z", "light-z-out", updateLight);
bindRange(
"light-intensity",
"light-intensity-out",
updateLight,
value => `${value.toFixed(1)}×`
);
function updateObstacleFromControls(obstacle) {
const prefix = `obstacle-${obstacle.id}`;
obstacle.x = Number($(`${prefix}-x`).value);
obstacle.z = Number($(`${prefix}-z`).value);
obstacle.width = Number($(`${prefix}-width`).value);
obstacle.depth = Number($(`${prefix}-depth`).value);
obstacle.height = Number($(`${prefix}-height`).value);
obstacle.enabled = $(`${prefix}-enabled`).checked;
syncObstacle(obstacle);
resetPlant(false);
}
obstacles.forEach(obstacle => {
const prefix = `obstacle-${obstacle.id}`;
bindRange(`${prefix}-x`, `${prefix}-x-out`, () =>
updateObstacleFromControls(obstacle)
);
bindRange(`${prefix}-z`, `${prefix}-z-out`, () =>
updateObstacleFromControls(obstacle)
);
bindRange(`${prefix}-width`, `${prefix}-width-out`, () =>
updateObstacleFromControls(obstacle)
);
bindRange(`${prefix}-depth`, `${prefix}-depth-out`, () =>
updateObstacleFromControls(obstacle)
);
bindRange(`${prefix}-height`, `${prefix}-height-out`, () =>
updateObstacleFromControls(obstacle)
);
$(`${prefix}-enabled`).addEventListener("change", () =>
updateObstacleFromControls(obstacle)
);
});
bindRange(
"growth-speed",
"speed-out",
value => {
growthSpeed = value;
},
value => String(Math.round(value))
);
$("grow-button").addEventListener("click", () => {
if (points.length - 1 >= MAX_SEGMENTS) {
resetPlant(false);
}
running = !running;
growthAccumulator = 0;
updateStatus();
});
$("step-button").addEventListener("click", () => {
running = false;
if (points.length - 1 >= MAX_SEGMENTS) resetPlant(false);
growOneSegment();
updateStatus();
});
$("reset-button").addEventListener("click", () => {
resetPlant(true);
});
$("panel-toggle").addEventListener("click", () => {
const panel = $("panel");
panel.classList.toggle("collapsed");
$("panel-toggle").textContent = panel.classList.contains("collapsed") ? "+" : "−";
});
document.querySelectorAll("[data-light-preset]").forEach(button => {
button.addEventListener("click", () => {
const preset = button.dataset.lightPreset;
if (preset === "left") {
$("light-x").value = "-5.2";
$("light-z").value = "-2.4";
$("light-y").value = "3.2";
} else if (preset === "right") {
$("light-x").value = "5.2";
$("light-z").value = "2.4";
$("light-y").value = "3.2";
} else {
$("light-x").value = "0";
$("light-z").value = "0";
$("light-y").value = "6.8";
}
["light-x", "light-z", "light-y"].forEach(id => {
$(id).dispatchEvent(new Event("input"));
});
});
});
// -----------------------------------------------------------------------------
// Direct camera controls: orbit, zoom, pan-free reset
// -----------------------------------------------------------------------------
let dragging = false;
let dragX = 0;
let dragY = 0;
renderer.domElement.addEventListener("pointerdown", event => {
dragging = true;
dragX = event.clientX;
dragY = event.clientY;
renderer.domElement.setPointerCapture(event.pointerId);
renderer.domElement.style.cursor = "grabbing";
});
renderer.domElement.addEventListener("pointermove", event => {
if (!dragging) return;
const deltaX = event.clientX - dragX;
const deltaY = event.clientY - dragY;
dragX = event.clientX;
dragY = event.clientY;
cameraState.theta -= deltaX * 0.006;
cameraState.phi = clamp(
cameraState.phi - deltaY * 0.005,
0.25,
Math.PI * 0.49
);
});
function endDrag(event) {
dragging = false;
if (renderer.domElement.hasPointerCapture(event.pointerId)) {
renderer.domElement.releasePointerCapture(event.pointerId);
}
renderer.domElement.style.cursor = "grab";
}
renderer.domElement.addEventListener("pointerup", endDrag);
renderer.domElement.addEventListener("pointercancel", endDrag);
renderer.domElement.style.cursor = "grab";
renderer.domElement.addEventListener("wheel", event => {
event.preventDefault();
cameraState.radius = clamp(
cameraState.radius + event.deltaY * 0.012,
7,
28
);
}, { passive: false });
renderer.domElement.addEventListener("dblclick", () => {
cameraState.radius = 15;
cameraState.theta = 0.72;
cameraState.phi = 1.02;
cameraState.target.set(0, 2.1, 0);
});
// -----------------------------------------------------------------------------
// Labels, resize, and animation
// -----------------------------------------------------------------------------
const projected = new THREE.Vector3();
function placeLabel(element, worldPosition) {
projected.copy(worldPosition).project(camera);
const visible = projected.z > -1 && projected.z < 1;
element.style.display = visible ? "block" : "none";
if (!visible) return;
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 updateLabels() {
placeLabel(
$("light-label"),
lightPosition.clone().add(new THREE.Vector3(0, 0.58, 0))
);
const obstacleA = obstacles[0];
const obstacleB = obstacles[1];
placeLabel(
$("obstacle-a-label"),
new THREE.Vector3(
obstacleA.x,
SOIL_TOP + obstacleA.height + 0.28,
obstacleA.z
)
);
placeLabel(
$("obstacle-b-label"),
new THREE.Vector3(
obstacleB.x,
SOIL_TOP + obstacleB.height + 0.28,
obstacleB.z
)
);
}
window.addEventListener("resize", () => {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
});
if (window.innerWidth < 760) {
$("panel").classList.add("collapsed");
$("panel-toggle").textContent = "+";
}
resetPlant(false);
let lastTime = performance.now();
function animate(now) {
const delta = Math.min((now - lastTime) / 1000, 0.1);
lastTime = now;
if (running) {
growthAccumulator += delta * growthSpeed;
while (growthAccumulator >= 1) {
if (!growOneSegment()) {
growthAccumulator = 0;
break;
}
growthAccumulator -= 1;
}
} else {
growthAccumulator = 0;
}
updateCamera();
lightRing.rotation.y += delta * 0.8;
lightRing.rotation.x += delta * 0.35;
renderer.render(scene, camera);
updateLabels();
requestAnimationFrame(animate);
}
requestAnimationFrame(animate);
</script>
</body>
</html>
```