Prompt specification
Build or customize the Three.js 3D scene "Competing-growth rule 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: Competing-growth rule sandbox
Category: Biology & Nature · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/competing-growth-rule-sandbox-x0724
Scene Description Prompt:
Make a standalone HTML scene with Three.js from cdnjs that depicts forest-canopy light competition. Create a toy forest where branches extend toward available light under stated rules; users alter starting positions and inspect emergent crown shapes without treating the model as ecological prediction. Low-poly.
Working Three.js Starter (competing-growth-rule-sandbox-x0724):
```html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Canopy — a light-competition toy</title>
<style>
:root {
color-scheme: light;
--ink: #19342c;
--muted: #5e716a;
--paper: #f7f3e8;
--paper-2: #eee9dc;
--line: rgba(25, 52, 44, 0.14);
--accent: #e6ad4d;
--accent-soft: #fff0c8;
--green: #467b57;
--shadow: 0 18px 50px rgba(25, 52, 44, 0.18);
}
* { box-sizing: border-box; }
html, body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: #dbe7df;
color: var(--ink);
font-family:
Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
button, input, select { font: inherit; }
button {
color: inherit;
cursor: pointer;
}
#stage {
position: fixed;
inset: 0;
}
#stage canvas {
display: block;
width: 100%;
height: 100%;
touch-action: none;
outline: none;
}
.title-card {
position: fixed;
z-index: 5;
top: 22px;
left: 22px;
width: min(390px, calc(100vw - 420px));
padding: 18px 20px 16px;
border: 1px solid rgba(255, 255, 255, 0.62);
border-radius: 18px;
background: rgba(247, 243, 232, 0.9);
box-shadow: var(--shadow);
backdrop-filter: blur(14px);
pointer-events: none;
}
.eyebrow {
margin-bottom: 6px;
color: var(--green);
font-size: 11px;
font-weight: 800;
letter-spacing: 0.16em;
text-transform: uppercase;
}
h1 {
margin: 0;
font-size: clamp(25px, 3vw, 38px);
font-weight: 760;
letter-spacing: -0.045em;
line-height: 0.98;
}
.title-card p {
max-width: 330px;
margin: 10px 0 0;
color: var(--muted);
font-size: 13px;
line-height: 1.45;
}
.mini-legend {
display: flex;
flex-wrap: wrap;
gap: 8px 14px;
margin-top: 13px;
color: #425c53;
font-size: 11px;
}
.mini-legend span {
display: inline-flex;
align-items: center;
gap: 6px;
}
.swatch {
width: 9px;
height: 9px;
border-radius: 50%;
background: var(--green);
}
.swatch.seed {
border: 2px solid var(--accent);
background: transparent;
}
#panel {
position: fixed;
z-index: 10;
top: 18px;
right: 18px;
bottom: 18px;
width: 350px;
overflow: auto;
padding: 18px;
border: 1px solid rgba(255, 255, 255, 0.65);
border-radius: 20px;
background: rgba(247, 243, 232, 0.94);
box-shadow: var(--shadow);
backdrop-filter: blur(16px);
scrollbar-width: thin;
}
.panel-head {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 10px;
margin-bottom: 15px;
}
.panel-head h2 {
margin: 0;
font-size: 17px;
letter-spacing: -0.02em;
}
.badge {
flex: none;
padding: 5px 8px;
border-radius: 999px;
background: var(--accent-soft);
color: #805c1d;
font-size: 10px;
font-weight: 800;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.section {
padding: 15px 0;
border-top: 1px solid var(--line);
}
.section:first-of-type {
padding-top: 0;
border-top: 0;
}
.section-title {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 11px;
font-size: 12px;
font-weight: 800;
letter-spacing: 0.05em;
text-transform: uppercase;
}
.section-title small {
color: var(--muted);
font-size: 10px;
font-weight: 650;
letter-spacing: 0;
text-transform: none;
}
.button-grid {
display: grid;
grid-template-columns: 1.25fr 1fr 1fr;
gap: 8px;
}
.button {
min-height: 38px;
padding: 9px 10px;
border: 1px solid var(--line);
border-radius: 10px;
background: rgba(255, 255, 255, 0.54);
font-size: 12px;
font-weight: 720;
transition: transform 120ms ease, background 120ms ease;
}
.button:hover {
transform: translateY(-1px);
background: white;
}
.button.primary {
border-color: var(--ink);
background: var(--ink);
color: var(--paper);
}
.button.primary:hover {
background: #27483e;
}
.button.subtle {
background: transparent;
}
.control-row {
display: grid;
grid-template-columns: 1fr auto;
align-items: center;
gap: 10px;
margin: 11px 0;
color: #425c53;
font-size: 12px;
}
.control-row output {
min-width: 42px;
color: var(--ink);
text-align: right;
font-variant-numeric: tabular-nums;
}
input[type="range"] {
width: 100%;
accent-color: var(--green);
}
select {
min-height: 34px;
padding: 5px 28px 5px 9px;
border: 1px solid var(--line);
border-radius: 9px;
background: rgba(255, 255, 255, 0.68);
color: var(--ink);
font-size: 12px;
}
.stats {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 7px;
}
.stat {
padding: 9px;
border: 1px solid var(--line);
border-radius: 11px;
background: rgba(255, 255, 255, 0.42);
}
.stat strong {
display: block;
font-size: 18px;
line-height: 1.05;
font-variant-numeric: tabular-nums;
}
.stat span {
display: block;
margin-top: 4px;
color: var(--muted);
font-size: 9px;
font-weight: 800;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.progress {
height: 4px;
overflow: hidden;
margin-top: 9px;
border-radius: 999px;
background: rgba(25, 52, 44, 0.1);
}
.progress > div {
width: 0;
height: 100%;
border-radius: inherit;
background: var(--accent);
transition: width 180ms ease;
}
details {
border: 1px solid var(--line);
border-radius: 12px;
background: rgba(255, 255, 255, 0.38);
}
summary {
padding: 10px 12px;
cursor: pointer;
font-size: 12px;
font-weight: 780;
}
.rules {
margin: 0;
padding: 0 13px 12px 28px;
color: var(--muted);
font-size: 11px;
line-height: 1.5;
}
.rules li + li { margin-top: 5px; }
.tree-list {
display: grid;
gap: 7px;
}
.tree-row {
display: grid;
grid-template-columns: 72px 1fr 52px;
align-items: center;
gap: 7px;
padding: 7px;
border: 1px solid var(--line);
border-radius: 11px;
background: rgba(255, 255, 255, 0.35);
transition: background 120ms ease, border-color 120ms ease;
}
.tree-row.selected {
border-color: rgba(230, 173, 77, 0.85);
background: var(--accent-soft);
}
.tree-select {
display: flex;
align-items: center;
gap: 6px;
padding: 4px;
border: 0;
background: transparent;
font-size: 11px;
font-weight: 800;
}
.tree-dot {
width: 10px;
height: 10px;
border-radius: 50%;
}
.coords {
display: flex;
gap: 5px;
}
.coords label {
display: flex;
align-items: center;
gap: 3px;
color: var(--muted);
font-size: 9px;
font-weight: 800;
}
.coords input {
width: 42px;
padding: 4px;
border: 1px solid var(--line);
border-radius: 6px;
background: rgba(255, 255, 255, 0.65);
color: var(--ink);
font-size: 10px;
font-variant-numeric: tabular-nums;
}
.metric {
color: var(--muted);
text-align: right;
font-size: 9px;
line-height: 1.3;
font-variant-numeric: tabular-nums;
}
.toggle {
display: flex;
align-items: center;
justify-content: space-between;
gap: 10px;
margin: 10px 0;
color: #425c53;
font-size: 12px;
}
.toggle input {
width: 17px;
height: 17px;
accent-color: var(--green);
}
.view-buttons {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 8px;
}
.disclaimer {
margin-top: 14px;
padding: 11px 12px;
border-left: 3px solid var(--accent);
border-radius: 4px 10px 10px 4px;
background: rgba(230, 173, 77, 0.11);
color: #5f512f;
font-size: 10px;
line-height: 1.45;
}
.disclaimer strong {
display: block;
margin-bottom: 3px;
font-size: 10px;
letter-spacing: 0.06em;
text-transform: uppercase;
}
.help {
position: fixed;
z-index: 4;
left: 22px;
bottom: 20px;
max-width: 430px;
padding: 9px 12px;
border: 1px solid rgba(255, 255, 255, 0.6);
border-radius: 10px;
background: rgba(247, 243, 232, 0.82);
color: #52675f;
box-shadow: 0 8px 24px rgba(25, 52, 44, 0.1);
backdrop-filter: blur(10px);
font-size: 10px;
line-height: 1.45;
pointer-events: none;
}
kbd {
padding: 1px 4px;
border: 1px solid var(--line);
border-bottom-width: 2px;
border-radius: 4px;
background: rgba(255, 255, 255, 0.55);
color: var(--ink);
font-size: 9px;
}
#loading {
position: fixed;
z-index: 100;
inset: 0;
display: grid;
place-items: center;
background: #dbe7df;
color: var(--ink);
font-size: 13px;
font-weight: 750;
letter-spacing: 0.05em;
}
@media (max-width: 850px) {
.title-card {
width: calc(100vw - 390px);
}
#panel {
width: 330px;
}
}
@media (max-width: 700px) {
.title-card {
top: 10px;
left: 10px;
width: calc(100vw - 20px);
padding: 13px 15px;
}
.title-card p, .mini-legend {
display: none;
}
#panel {
top: auto;
right: 10px;
bottom: 10px;
left: 10px;
width: auto;
max-height: 47vh;
border-radius: 16px;
}
.help {
display: none;
}
}
</style>
</head>
<body>
<div id="stage" aria-label="Interactive low-poly forest canopy scene"></div>
<header class="title-card">
<div class="eyebrow">A spatial rule toy</div>
<h1>Canopy</h1>
<p>
Move the seeds, grow the shoots, and watch each crown lean toward a
different patch of open sky.
</p>
<div class="mini-legend">
<span><i class="swatch seed"></i> draggable seed ring</span>
<span><i class="swatch"></i> crown foliage</span>
<span>wireframe = shade envelope</span>
</div>
</header>
<aside id="panel" aria-label="Simulation controls">
<div class="panel-head">
<div>
<div class="eyebrow">Light competition</div>
<h2>Forest controls</h2>
</div>
<div class="badge">Toy model</div>
</div>
<div class="section">
<div class="button-grid">
<button id="play" class="button primary">Play</button>
<button id="step" class="button">Step</button>
<button id="reset" class="button">Reset</button>
</div>
<div class="control-row">
<label for="pace">Growth pace</label>
<select id="pace">
<option value="1150">Slow</option>
<option value="700" selected>Normal</option>
<option value="330">Fast</option>
</select>
</div>
<div class="stats">
<div class="stat"><strong id="roundStat">00</strong><span>Round</span></div>
<div class="stat"><strong id="tipsStat">0</strong><span>Live tips</span></div>
<div class="stat"><strong id="heightStat">0.2</strong><span>Tallest</span></div>
</div>
<div class="progress"><div id="progressBar"></div></div>
</div>
<div class="section">
<div class="section-title">
Starting positions
<small>drag rings or edit X/Z</small>
</div>
<div class="control-row">
<label for="treeCount">Number of trees</label>
<output id="treeCountValue">5</output>
</div>
<input id="treeCount" type="range" min="3" max="7" value="5">
<div class="control-row">
<label for="spacing">Seed spacing</label>
<output id="spacingValue">2.2</output>
</div>
<input id="spacing" type="range" min="1.4" max="3.6" step="0.1" value="2.2">
<button id="randomize" class="button subtle" style="width:100%; margin-top:5px">
Randomize seed layout
</button>
<div id="treeList" class="tree-list" style="margin-top:10px"></div>
</div>
<div class="section">
<div class="section-title">
Stated rules
<small>deterministic interactions</small>
</div>
<details open>
<summary>How a shoot finds light</summary>
<ol class="rules">
<li>Every living tip advances by one short segment per round.</li>
<li>Eight compass probes test possible directions.</li>
<li>At each probe, ten vertical samples estimate open sky.</li>
<li>A tip grows toward the strongest light score, mixed with upward growth.</li>
<li>All crowns shade all trees; no tree is favored.</li>
<li>A tip stops after three failed growth probes below 8% openness.</li>
<li>Growth ends after 42 rounds or when a tree reaches its height limit.</li>
</ol>
</details>
</div>
<div class="section">
<div class="section-title">Inspection</div>
<label class="toggle">
<span>Show crown shade envelopes</span>
<input id="showCrowns" type="checkbox">
</label>
<label class="toggle">
<span>Show selected-tree sky probes</span>
<input id="showLight" type="checkbox" checked>
</label>
<div class="view-buttons">
<button id="isoView" class="button">Reset camera</button>
<button id="topView" class="button">Top view</button>
</div>
</div>
<div class="disclaimer">
<strong>Not an ecological prediction</strong>
This scene demonstrates a deliberately simple set of geometric growth rules.
It does not model tree physiology, mortality, climate, succession, resource
budgets, or real-world forest outcomes.
</div>
</aside>
<div class="help">
<kbd>drag</kbd> orbit · <kbd>wheel</kbd> zoom ·
<kbd>shift + drag</kbd> pan · <kbd>space</kbd> play/pause ·
<kbd>R</kbd> reset growth · drag numbered rings to move a seed
</div>
<div id="loading">Growing the scene…</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 stage = $("stage");
const MAX_ROUNDS = 42;
const TREE_COLORS = [
0x5f914f,
0x3f7d55,
0x78994b,
0x507f63,
0x8ca34f,
0x47765f,
0x6b8d54
];
const scene = new THREE.Scene();
scene.background = new THREE.Color(0xdbe7df);
scene.fog = new THREE.Fog(0xdbe7df, 19, 36);
const camera = new THREE.PerspectiveCamera(
42,
innerWidth / innerHeight,
0.1,
100
);
const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setPixelRatio(Math.min(devicePixelRatio, 2));
renderer.setSize(innerWidth, innerHeight);
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.12;
renderer.domElement.setAttribute("aria-label", "Three-dimensional canopy toy");
renderer.domElement.tabIndex = 0;
stage.appendChild(renderer.domElement);
// Lighting.
const hemi = new THREE.HemisphereLight(0xf4f7e9, 0x60755f, 2.25);
scene.add(hemi);
const sun = new THREE.DirectionalLight(0xffe5b0, 3.4);
sun.position.set(-7, 12, 6);
sun.castShadow = true;
sun.shadow.mapSize.set(1024, 1024);
sun.shadow.camera.left = -11;
sun.shadow.camera.right = 11;
sun.shadow.camera.top = 11;
sun.shadow.camera.bottom = -11;
sun.shadow.camera.near = 1;
sun.shadow.camera.far = 35;
sun.shadow.bias = -0.0008;
scene.add(sun);
// Low-poly ground.
const ground = new THREE.Mesh(
new THREE.CylinderGeometry(9.5, 9.8, 0.45, 48, 1),
new THREE.MeshStandardMaterial({
color: 0xb8c59e,
roughness: 1,
flatShading: true
})
);
ground.position.y = -0.27;
ground.receiveShadow = true;
scene.add(ground);
const underlay = new THREE.Mesh(
new THREE.CylinderGeometry(10.15, 10.5, 0.35, 40, 1),
new THREE.MeshStandardMaterial({
color: 0x789176,
roughness: 1,
flatShading: true
})
);
underlay.position.y = -0.58;
underlay.receiveShadow = true;
scene.add(underlay);
// Radial survey lines.
const surveyPositions = [];
for (let ring = 2; ring <= 8; ring += 2) {
const count = 48;
for (let i = 0; i < count; i++) {
const a = (i / count) * Math.PI * 2;
const b = ((i + 1) / count) * Math.PI * 2;
surveyPositions.push(
Math.cos(a) * ring, 0.012, Math.sin(a) * ring,
Math.cos(b) * ring, 0.012, Math.sin(b) * ring
);
}
}
for (let spoke = 0; spoke < 12; spoke++) {
const a = (spoke / 12) * Math.PI * 2;
surveyPositions.push(
0, 0.014, 0,
Math.cos(a) * 9.2, 0.014, Math.sin(a) * 9.2
);
}
const surveyGeometry = new THREE.BufferGeometry();
surveyGeometry.setAttribute(
"position",
new THREE.Float32BufferAttribute(surveyPositions, 3)
);
const survey = new THREE.LineSegments(
surveyGeometry,
new THREE.LineBasicMaterial({
color: 0x718968,
transparent: true,
opacity: 0.18
})
);
scene.add(survey);
// A small visual sun marker.
const sunMarker = new THREE.Mesh(
new THREE.IcosahedronGeometry(0.36, 1),
new THREE.MeshBasicMaterial({ color: 0xffd274 })
);
sunMarker.position.set(-6.4, 8.8, -5.6);
scene.add(sunMarker);
// Shared low-poly geometries and materials.
const branchGeometry = new THREE.CylinderGeometry(1, 1, 1, 5, 1);
const foliageGeometry = new THREE.IcosahedronGeometry(1, 0);
const markerGeometry = new THREE.TorusGeometry(0.29, 0.052, 4, 18);
const branchMaterial = new THREE.MeshStandardMaterial({
color: 0x594536,
roughness: 1,
flatShading: true
});
const foliageMaterial = new THREE.MeshStandardMaterial({
color: 0xffffff,
roughness: 0.96,
flatShading: true
});
const trees = [];
const crowns = [];
let lightCrowns = [];
let selectedTree = 0;
let layoutSeed = 8317;
let running = false;
let simulationRound = 0;
let lastStepTime = 0;
let tipCounter = 0;
const up = new THREE.Vector3(0, 1, 0);
const dummy = new THREE.Object3D();
const colorScratch = new THREE.Color();
function randomGenerator(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;
};
}
function deterministicNoise(...parts) {
const value = Math.sin(
parts[0] * 12.9898 +
parts[1] * 78.233 +
parts[2] * 37.719 +
parts[3] * 11.113
) * 43758.5453;
return value - Math.floor(value);
}
function generatePositions(count, spacing, seed) {
const rand = randomGenerator(seed);
const positions = [];
const goldenAngle = Math.PI * (3 - Math.sqrt(5));
for (let i = 0; i < count; i++) {
const angle = i * goldenAngle + (rand() - 0.5) * 0.25;
const radius = spacing * Math.sqrt((i + 0.5) / count) * 1.2;
positions.push(new THREE.Vector2(
Math.cos(angle) * radius,
Math.sin(angle) * radius
));
}
return positions;
}
function makeLabel(number) {
const canvas = document.createElement("canvas");
canvas.width = 128;
canvas.height = 64;
const ctx = canvas.getContext("2d");
ctx.fillStyle = "rgba(247,243,232,0.94)";
ctx.beginPath();
ctx.roundRect(8, 8, 112, 48, 16);
ctx.fill();
ctx.strokeStyle = "rgba(25,52,44,0.22)";
ctx.lineWidth = 3;
ctx.stroke();
ctx.fillStyle = "#19342c";
ctx.font = "800 27px system-ui, sans-serif";
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.fillText(`T${number}`, 64, 33);
const texture = new THREE.CanvasTexture(canvas);
texture.colorSpace = THREE.SRGBColorSpace;
const material = new THREE.SpriteMaterial({
map: texture,
transparent: true,
depthTest: false,
depthWrite: false
});
const sprite = new THREE.Sprite(material);
sprite.scale.set(0.78, 0.39, 1);
sprite.renderOrder = 9;
return sprite;
}
function createTree(index, position) {
const color = TREE_COLORS[index % TREE_COLORS.length];
const group = new THREE.Group();
const branchMesh = new THREE.InstancedMesh(
branchGeometry,
branchMaterial,
700
);
branchMesh.instanceMatrix.setUsage(THREE.DynamicDrawUsage);
branchMesh.count = 0;
branchMesh.castShadow = true;
branchMesh.receiveShadow = true;
branchMesh.frustumCulled = false;
const foliageMesh = new THREE.InstancedMesh(
foliageGeometry,
foliageMaterial,
900
);
foliageMesh.instanceMatrix.setUsage(THREE.DynamicDrawUsage);
foliageMesh.count = 0;
foliageMesh.castShadow = true;
foliageMesh.receiveShadow = true;
foliageMesh.frustumCulled = false;
const shellMaterial = new THREE.MeshBasicMaterial({
color,
wireframe: true,
transparent: true,
opacity: 0.16,
depthWrite: false
});
const shellMesh = new THREE.InstancedMesh(
foliageGeometry,
shellMaterial,
900
);
shellMesh.instanceMatrix.setUsage(THREE.DynamicDrawUsage);
shellMesh.count = 0;
shellMesh.visible = $("showCrowns").checked;
shellMesh.frustumCulled = false;
shellMesh.renderOrder = 3;
const handle = new THREE.Mesh(
markerGeometry,
new THREE.MeshBasicMaterial({ color })
);
handle.rotation.x = -Math.PI / 2;
handle.position.set(position.x, 0.08, position.y);
handle.userData.treeIndex = index;
handle.renderOrder = 8;
const label = makeLabel(index + 1);
label.position.set(position.x, 0.52, position.y);
group.add(branchMesh, foliageMesh, shellMesh, handle, label);
scene.add(group);
const rand = randomGenerator(1000 + index * 77 + layoutSeed);
return {
index,
position,
color,
group,
branchMesh,
foliageMesh,
shellMesh,
handle,
label,
tips: [],
trunkTip: null,
maxHeight: 5.35 + rand() * 0.8,
baseAngle: rand() * Math.PI * 2,
branchSerial: 0,
segmentSerial: 0,
foliageRecords: [],
maxY: 0.18,
metrics: { height: 0.18, reach: 0, clusters: 0 }
};
}
function disposeTree(tree) {
scene.remove(tree.group);
tree.shellMesh.material.dispose();
tree.handle.material.dispose();
tree.label.material.map.dispose();
tree.label.material.dispose();
}
function buildTrees() {
trees.forEach(disposeTree);
trees.length = 0;
const count = Number($("treeCount").value);
const spacing = Number($("spacing").value);
const positions = generatePositions(count, spacing, layoutSeed);
positions.forEach((position, index) => {
trees.push(createTree(index, position));
});
selectedTree = Math.min(selectedTree, trees.length - 1);
buildTreeRows();
resetSimulation();
}
function addBranchSegment(tree, from, to, isTrunk) {
const direction = new THREE.Vector3().subVectors(to, from);
const length = direction.length();
if (length < 0.0001) return;
direction.normalize();
const midpoint = new THREE.Vector3().addVectors(from, to).multiplyScalar(0.5);
const quaternion = new THREE.Quaternion().setFromUnitVectors(up, direction);
const radius = isTrunk
? Math.max(0.032, 0.074 - tree.segmentSerial * 0.00065)
: 0.038;
dummy.position.copy(midpoint);
dummy.quaternion.copy(quaternion);
dummy.scale.set(radius, length, radius);
dummy.updateMatrix();
const index = tree.branchMesh.count;
tree.branchMesh.setMatrixAt(index, dummy.matrix);
tree.branchMesh.count++;
tree.branchMesh.instanceMatrix.needsUpdate = true;
tree.segmentSerial++;
tree.maxY = Math.max(tree.maxY, to.y);
}
function addFoliage(tree, endpoint, branchSegment) {
const n = tree.segmentSerial;
const offset = new THREE.Vector3(
(deterministicNoise(n, tree.index, branchSegment, 3) - 0.5) * 0.48,
(deterministicNoise(n, tree.index, branchSegment, 4) - 0.5) * 0.32,
(deterministicNoise(n, tree.index, branchSegment, 5) - 0.5) * 0.48
);
const center = endpoint.clone().add(offset);
const size = branchSegment
? 0.58 + deterministicNoise(n, tree.index, branchSegment, 6) * 0.29
: 0.62 + deterministicNoise(n, tree.index, branchSegment, 6) * 0.25;
const scale = new THREE.Vector3(
size,
size * (0.82 + deterministicNoise(n, tree.index, branchSegment, 7) * 0.25),
size * (0.88 + deterministicNoise(n, tree.index, branchSegment, 8) * 0.24)
);
const quaternion = new THREE.Quaternion().setFromEuler(new THREE.Euler(
deterministicNoise(n, tree.index, branchSegment, 9) * Math.PI,
deterministicNoise(n, tree.index, branchSegment, 10) * Math.PI * 2,
deterministicNoise(n, tree.index, branchSegment, 11) * Math.PI
));
dummy.position.copy(center);
dummy.quaternion.copy(quaternion);
dummy.scale.copy(scale);
dummy.updateMatrix();
const index = tree.foliageMesh.count;
tree.foliageMesh.setMatrixAt(index, dummy.matrix);
colorScratch.set(tree.color);
colorScratch.offsetHSL(
(deterministicNoise(n, tree.index, branchSegment, 12) - 0.5) * 0.025,
(deterministicNoise(n, tree.index, branchSegment, 13) - 0.5) * 0.06,
(deterministicNoise(n, tree.index, branchSegment, 14) - 0.5) * 0.07
);
tree.foliageMesh.setColorAt(index, colorScratch);
tree.shellMesh.setMatrixAt(index, dummy.matrix);
tree.shellMesh.count = tree.foliageMesh.count;
tree.foliageMesh.instanceMatrix.needsUpdate = true;
tree.shellMesh.instanceMatrix.needsUpdate = true;
if (tree.foliageMesh.instanceColor) {
tree.foliageMesh.instanceColor.needsUpdate = true;
}
// The envelope is intentionally a little broader than the visible leaf
// cluster so that nearby tips experience a readable amount of shade.
const crown = {
treeId: tree.index,
x: center.x,
y: center.y,
z: center.z,
r: Math.max(scale.x, scale.z) * 1.14,
ry: scale.y * 1.22
};
crowns.push(crown);
tree.foliageRecords.push(crown);
}
function resetSimulation() {
simulationRound = 0;
crowns.length = 0;
lightCrowns = [];
tipCounter = 0;
for (const tree of trees) {
tree.tips = [];
tree.branchSerial = 0;
tree.segmentSerial = 0;
tree.foliageRecords = [];
tree.maxY = 0.18;
tree.metrics = { height: 0.18, reach: 0, clusters: 0 };
tree.branchMesh.count = 0;
tree.foliageMesh.count = 0;
tree.shellMesh.count = 0;
const start = new THREE.Vector3(
tree.position.x,
0.18,
tree.position.y
);
const trunkTip = {
id: tipCounter++,
position: start,
age: 0,
life: 999,
isTrunk: true,
blockedRounds: 0,
bias: new THREE.Vector3()
};
tree.trunkTip = trunkTip;
tree.tips.push(trunkTip);
addBranchSegment(
tree,
new THREE.Vector3(tree.position.x, 0, tree.position.y),
start,
true
);
}
updateAllUI();
}
function blockedAt(x, y, z, crownList) {
for (const crown of crownList) {
const dx = (x - crown.x) / crown.r;
const dz = (z - crown.z) / crown.r;
const dy = (y - crown.y) / crown.ry;
if (dx * dx + dy * dy + dz * dz < 1) return true;
}
return false;
}
function opennessAt(x, y, z, crownList = lightCrowns) {
const top = 9.2;
let openSamples = 0;
for (let i = 0; i < 10; i++) {
const sampleY = y + (top - y) * ((i + 0.5) / 10);
if (!blockedAt(x, sampleY, z, crownList)) openSamples++;
}
return openSamples / 10;
}
function shadeAt(x, y, z, crownList = lightCrowns) {
let shade = 0;
for (const crown of crownList) {
if (crown.y + crown.ry <= y) continue;
const distance = Math.hypot(x - crown.x, z - crown.z);
const reach = crown.r + 0.85;
if (distance >= reach) continue;
const horizontal = 1 - distance / reach;
const vertical = THREE.MathUtils.clamp(
(crown.y + crown.ry - y) / (crown.ry * 2 + 0.5),
0,
1
);
shade += horizontal * (0.22 + vertical * 0.78);
}
return shade;
}
function chooseDirection(tree, tip) {
const directions = [];
const best = { score: -Infinity, x: 0, z: 1 };
for (let i = 0; i < 8; i++) {
const angle = (i / 8) * Math.PI * 2;
const dx = Math.cos(angle);
const dz = Math.sin(angle);
const radius = tip.isTrunk ? 0.72 : 1.05;
const probe = tip.position.clone().add(new THREE.Vector3(
dx * radius,
tip.isTrunk ? 0.42 : 0.28,
dz * radius
));
const openness = opennessAt(probe.x, probe.y, probe.z);
const shade = shadeAt(probe.x, probe.y, probe.z);
let score = openness * 1.45 - shade * 0.72 + probe.y * 0.012;
if (!tip.isTrunk && tip.bias.lengthSq() > 0) {
score += (dx * tip.bias.x + dz * tip.bias.z) * 0.11;
}
score += (deterministicNoise(
simulationRound,
tree.index,
tip.id,
i
) - 0.5) * 0.045;
if (score > best.score) {
best.score = score;
best.x = dx;
best.z = dz;
}
}
const upward = tip.isTrunk ? 1.38 : 0.43;
const horizontal = tip.isTrunk ? 0.30 : 0.98;
const direction = new THREE.Vector3(
best.x * horizontal,
upward,
best.z * horizontal
);
if (!tip.isTrunk) {
direction.addScaledVector(tip.bias, 0.25);
}
if (direction.y < 0.06) direction.y = 0.06;
return direction.normalize();
}
function spawnBranches(tree, spawnIndex) {
const offsets = spawnIndex === 0
? [0, Math.PI]
: [Math.PI * 0.5, Math.PI * 1.5];
const origin = tree.trunkTip.position.clone();
origin.y -= 0.08;
offsets.forEach((offset, branchIndex) => {
const angle = tree.baseAngle + offset +
(deterministicNoise(tree.index, spawnIndex, branchIndex, 22) - 0.5) * 0.32;
const bias = new THREE.Vector3(Math.cos(angle), 0, Math.sin(angle)).normalize();
tree.tips.push({
id: tipCounter++,
position: origin.clone(),
age: 0,
life: 13 + tree.index % 3,
isTrunk: false,
blockedRounds: 0,
bias
});
tree.branchSerial++;
});
}
function stepSimulation() {
if (simulationRound >= MAX_ROUNDS) {
running = false;
updatePlayButton();
return;
}
simulationRound++;
// All tips read the same beginning-of-round light field, so processing
// order does not privilege one tree over another.
lightCrowns = crowns.map((crown) => ({ ...crown }));
for (const tree of trees) {
if (simulationRound === 12) spawnBranches(tree, 0);
if (simulationRound === 27) spawnBranches(tree, 1);
for (const tip of [...tree.tips]) {
tip.age++;
if (tip.age > tip.life) {
tip.dead = true;
continue;
}
const direction = chooseDirection(tree, tip);
const length = tip.isTrunk ? 0.16 : 0.24;
const destination = tip.position.clone().addScaledVector(direction, length);
if (tip.isTrunk) {
destination.y = Math.min(destination.y, tree.maxHeight);
} else {
destination.y = THREE.MathUtils.clamp(destination.y, 0.35, 8.2);
}
const openness = opennessAt(
destination.x,
destination.y,
destination.z,
lightCrowns
);
if (openness < 0.08) {
tip.blockedRounds++;
if (tip.blockedRounds >= 3) tip.dead = true;
continue;
}
tip.blockedRounds = 0;
addBranchSegment(tree, tip.position, destination, tip.isTrunk);
if (!tip.isTrunk || tree.segmentSerial % 3 === 0) {
addFoliage(tree, destination, !tip.isTrunk);
}
tip.position.copy(destination);
if (tip.isTrunk && tip.position.y >= tree.maxHeight - 0.02) {
tip.dead = true;
}
}
tree.tips = tree.tips.filter((tip) => !tip.dead);
updateTreeMetrics(tree);
}
lightCrowns = crowns.map((crown) => ({ ...crown }));
updateAllUI();
}
function updateTreeMetrics(tree) {
let height = 0;
let reach = 0;
for (const record of tree.foliageRecords) {
height = Math.max(height, record.y + record.ry);
reach = Math.max(
reach,
Math.hypot(record.x - tree.position.x, record.z - tree.position.y)
);
}
tree.metrics = {
height: Math.max(height, tree.maxY),
reach,
clusters: tree.foliageRecords.length
};
}
function buildTreeRows() {
const list = $("treeList");
list.innerHTML = "";
trees.forEach((tree, index) => {
const row = document.createElement("div");
row.className = "tree-row";
row.dataset.index = index;
row.innerHTML = `
<button class="tree-select" type="button" aria-label="Select tree ${index + 1}">
<span class="tree-dot" style="background:#${tree.color.toString(16).padStart(6, "0")}"></span>
T${index + 1}
</button>
<div class="coords">
<label>X<input type="number" step="0.1" data-axis="x" aria-label="Tree ${index + 1} X position"></label>
<label>Z<input type="number" step="0.1" data-axis="z" aria-label="Tree ${index + 1} Z position"></label>
</div>
<span class="metric"></span>
`;
row.querySelector(".tree-select").addEventListener("click", () => {
setSelectedTree(index);
});
row.querySelectorAll("input").forEach((input) => {
input.addEventListener("change", () => {
const value = Number.parseFloat(input.value);
if (!Number.isFinite(value)) return;
if (input.dataset.axis === "x") tree.position.x = value;
else tree.position.y = value;
constrainTreePosition(tree);
resetSimulation();
});
});
list.appendChild(row);
});
updateTreeRows();
}
function constrainTreePosition(tree) {
const radius = Math.hypot(tree.position.x, tree.position.y);
if (radius > 6.6) {
tree.position.multiplyScalar(6.6 / radius);
}
}
function setSelectedTree(index) {
selectedTree = THREE.MathUtils.clamp(index, 0, trees.length - 1);
updateTreeRows();
updateMarkerStyles();
updateLightOverlay();
}
function updateTreeRows() {
const rows = $("treeList").children;
trees.forEach((tree, index) => {
const row = rows[index];
if (!row) return;
row.classList.toggle("selected", index === selectedTree);
const xInput = row.querySelector('[data-axis="x"]');
const zInput = row.querySelector('[data-axis="z"]');
if (document.activeElement !== xInput) xInput.value = tree.position.x.toFixed(1);
if (document.activeElement !== zInput) zInput.value = tree.position.y.toFixed(1);
row.querySelector(".metric").innerHTML =
`H ${tree.metrics.height.toFixed(1)}<br>Ø ${tree.metrics.reach.toFixed(1)}`;
});
}
function updateMarkerStyles() {
trees.forEach((tree, index) => {
const selected = index === selectedTree;
tree.handle.material.color.set(selected ? 0xffc95b : tree.color);
tree.handle.scale.setScalar(selected ? 1.16 : 1);
tree.label.material.opacity = selected ? 1 : 0.78;
tree.label.position.set(tree.position.x, 0.52, tree.position.y);
tree.handle.position.set(tree.position.x, 0.08, tree.position.y);
});
}
function updateAllUI() {
updateTreeRows();
updateMarkerStyles();
updateStats();
updateLightOverlay();
}
function updateStats() {
let liveTips = 0;
let tallest = 0;
for (const tree of trees) {
liveTips += tree.tips.length;
tallest = Math.max(tallest, tree.metrics.height);
}
$("roundStat").textContent = String(simulationRound).padStart(2, "0");
$("tipsStat").textContent = liveTips;
$("heightStat").textContent = tallest.toFixed(1);
$("progressBar").style.width = `${simulationRound / MAX_ROUNDS * 100}%`;
}
// Light-probe overlay for the selected tree.
const probeGroup = new THREE.Group();
probeGroup.visible = $("showLight").checked;
scene.add(probeGroup);
const probeLines = [];
const probeDots = [];
const probeDotGeometry = new THREE.SphereGeometry(0.065, 8, 6);
for (let i = 0; i < 8; i++) {
const geometry = new THREE.BufferGeometry().setFromPoints([
new THREE.Vector3(),
new THREE.Vector3()
]);
const material = new THREE.LineBasicMaterial({
color: 0x5ca46b,
transparent: true,
opacity: 0.82,
depthTest: false,
depthWrite: false
});
const line = new THREE.Line(geometry, material);
line.renderOrder = 10;
probeGroup.add(line);
probeLines.push(line);
const dotMaterial = new THREE.MeshBasicMaterial({
color: 0x5ca46b,
depthTest: false,
depthWrite: false
});
const dot = new THREE.Mesh(probeDotGeometry, dotMaterial);
dot.renderOrder = 11;
probeGroup.add(dot);
probeDots.push(dot);
}
function updateLightOverlay() {
probeGroup.visible = $("showLight").checked;
if (!probeGroup.visible || !trees.length) return;
const tree = trees[selectedTree];
let origin = tree.trunkTip.position.clone();
if (tree.foliageRecords.length) {
origin = new THREE.Vector3();
for (const crown of tree.foliageRecords) origin.add(crown);
origin.multiplyScalar(1 / tree.foliageRecords.length);
}
for (let i = 0; i < 8; i++) {
const angle = (i / 8) * Math.PI * 2;
const dx = Math.cos(angle);
const dz = Math.sin(angle);
const base = origin.clone().add(new THREE.Vector3(dx * 1.05, 0, dz * 1.05));
const top = base.clone().add(new THREE.Vector3(0, 2.4, 0));
const openness = opennessAt(base.x, base.y + 0.08, base.z);
const line = probeLines[i];
const positions = line.geometry.attributes.position;
positions.setXYZ(0, base.x, base.y, base.z);
positions.setXYZ(1, top.x, top.y, top.z);
positions.needsUpdate = true;
colorScratch.set(0xd65d4c).lerp(new THREE.Color(0x68a96c), openness);
line.material.color.copy(colorScratch);
probeDots[i].position.copy(top);
probeDots[i].material.color.copy(colorScratch);
}
}
// Custom camera controls; no examples or addons are used.
const cameraState = {
azimuth: 0.63,
polar: 1.02,
distance: 17.5,
target: new THREE.Vector3(0, 2.1, 0)
};
function updateCamera() {
const spherical = new THREE.Spherical(
cameraState.distance,
cameraState.polar,
cameraState.azimuth
);
camera.position.setFromSpherical(spherical).add(cameraState.target);
camera.lookAt(cameraState.target);
camera.updateMatrixWorld();
}
function resetCamera(top = false) {
cameraState.azimuth = top ? 0 : 0.63;
cameraState.polar = top ? 0.08 : 1.02;
cameraState.distance = top ? 19 : 17.5;
cameraState.target.set(0, top ? 0.8 : 2.1, 0);
updateCamera();
}
const raycaster = new THREE.Raycaster();
const pointer = new THREE.Vector2();
const groundPlane = new THREE.Plane(new THREE.Vector3(0, 1, 0), 0);
const groundHit = new THREE.Vector3();
let pointerMode = null;
let draggedTree = null;
let dragOffset = new THREE.Vector2();
let lastPointerX = 0;
let lastPointerY = 0;
function updatePointer(event) {
const rect = renderer.domElement.getBoundingClientRect();
pointer.x = ((event.clientX - rect.left) / rect.width) * 2 - 1;
pointer.y = -((event.clientY - rect.top) / rect.height) * 2 + 1;
}
renderer.domElement.addEventListener("contextmenu", (event) => {
event.preventDefault();
});
renderer.domElement.addEventListener("pointerdown", (event) => {
updatePointer(event);
raycaster.setFromCamera(pointer, camera);
lastPointerX = event.clientX;
lastPointerY = event.clientY;
if (event.button === 2 || event.shiftKey) {
pointerMode = "pan";
} else {
const handles = trees.map((tree) => tree.handle);
const hit = raycaster.intersectObjects(handles, false)[0];
if (hit) {
draggedTree = trees[hit.object.userData.treeIndex];
setSelectedTree(draggedTree.index);
if (raycaster.ray.intersectPlane(groundPlane, groundHit)) {
dragOffset.set(
draggedTree.position.x - groundHit.x,
draggedTree.position.y - groundHit.z
);
} else {
dragOffset.set(0, 0);
}
pointerMode = "tree";
} else {
pointerMode = "orbit";
}
}
renderer.domElement.setPointerCapture(event.pointerId);
renderer.domElement.focus();
});
renderer.domElement.addEventListener("pointermove", (event) => {
if (!pointerMode) return;
const dx = event.clientX - lastPointerX;
const dy = event.clientY - lastPointerY;
lastPointerX = event.clientX;
lastPointerY = event.clientY;
if (pointerMode === "orbit") {
cameraState.azimuth -= dx * 0.006;
cameraState.polar = THREE.MathUtils.clamp(
cameraState.polar - dy * 0.005,
0.08,
1.43
);
updateCamera();
} else if (pointerMode === "pan") {
const forward = new THREE.Vector3();
camera.getWorldDirection(forward);
forward.y = 0;
forward.normalize();
const right = new THREE.Vector3().crossVectors(forward, up).normalize();
const scale = cameraState.distance * 0.0015;
cameraState.target.addScaledVector(right, -dx * scale);
cameraState.target.addScaledVector(forward, -dy * scale);
cameraState.target.x = THREE.MathUtils.clamp(cameraState.target.x, -8, 8);
cameraState.target.z = THREE.MathUtils.clamp(cameraState.target.z, -8, 8);
cameraState.target.y = THREE.MathUtils.clamp(cameraState.target.y, 0.3, 5);
updateCamera();
} else if (pointerMode === "tree" && draggedTree) {
updatePointer(event);
raycaster.setFromCamera(pointer, camera);
if (raycaster.ray.intersectPlane(groundPlane, groundHit)) {
draggedTree.position.set(
groundHit.x + dragOffset.x,
groundHit.y + dragOffset.y
);
constrainTreePosition(draggedTree);
resetSimulation();
}
}
});
function endPointer(event) {
pointerMode = null;
draggedTree = null;
if (renderer.domElement.hasPointerCapture(event.pointerId)) {
renderer.domElement.releasePointerCapture(event.pointerId);
}
}
renderer.domElement.addEventListener("pointerup", endPointer);
renderer.domElement.addEventListener("pointercancel", endPointer);
renderer.domElement.addEventListener("wheel", (event) => {
event.preventDefault();
cameraState.distance = THREE.MathUtils.clamp(
cameraState.distance * Math.exp(event.deltaY * 0.001),
8,
30
);
updateCamera();
}, { passive: false });
function updatePlayButton() {
$("play").textContent = running
? "Pause"
: simulationRound >= MAX_ROUNDS
? "Replay"
: "Play";
}
function togglePlay() {
if (simulationRound >= MAX_ROUNDS) resetSimulation();
running = !running;
lastStepTime = performance.now();
updatePlayButton();
}
$("play").addEventListener("click", togglePlay);
$("step").addEventListener("click", () => {
running = false;
updatePlayButton();
stepSimulation();
});
$("reset").addEventListener("click", () => {
running = false;
updatePlayButton();
resetSimulation();
});
$("randomize").addEventListener("click", () => {
layoutSeed += 97;
const positions = generatePositions(
trees.length,
Number($("spacing").value),
layoutSeed
);
trees.forEach((tree, index) => {
tree.position.copy(positions[index]);
});
running = false;
updatePlayButton();
resetSimulation();
});
$("treeCount").addEventListener("input", () => {
$("treeCountValue").textContent = $("treeCount").value;
buildTrees();
});
$("spacing").addEventListener("input", () => {
$("spacingValue").textContent = Number($("spacing").value).toFixed(1);
});
$("spacing").addEventListener("change", () => {
layoutSeed += 13;
buildTrees();
});
$("showCrowns").addEventListener("change", () => {
trees.forEach((tree) => {
tree.shellMesh.visible = $("showCrowns").checked;
});
});
$("showLight").addEventListener("change", updateLightOverlay);
$("isoView").addEventListener("click", () => resetCamera(false));
$("topView").addEventListener("click", () => resetCamera(true));
window.addEventListener("keydown", (event) => {
const tag = document.activeElement?.tagName;
if (tag === "INPUT" || tag === "SELECT" || tag === "TEXTAREA") return;
if (event.code === "Space") {
event.preventDefault();
togglePlay();
}
if (event.key.toLowerCase() === "r") {
running = false;
updatePlayButton();
resetSimulation();
}
});
window.addEventListener("resize", () => {
camera.aspect = innerWidth / innerHeight;
camera.updateProjectionMatrix();
renderer.setPixelRatio(Math.min(devicePixelRatio, 2));
renderer.setSize(innerWidth, innerHeight);
});
// Initial scene.
buildTrees();
resetCamera(false);
updatePlayButton();
function animate(time) {
requestAnimationFrame(animate);
if (running && simulationRound < MAX_ROUNDS) {
const interval = Number($("pace").value);
if (time - lastStepTime >= interval) {
stepSimulation();
lastStepTime = time;
}
}
renderer.render(scene, camera);
}
requestAnimationFrame(animate);
$("loading").remove();
</script>
</body>
</html>
```