Prompt specification
Build or customize the Three.js 3D scene "Planting-density exploration 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: Planting-density exploration sandbox
Category: Biology & Nature · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/planting-density-exploration-sandbox-x1108
Scene Description Prompt:
Build a self-contained HTML scene with Three.js from cdnjs featuring seed spacing. Create a toy garden with explicit growth-footprint rules; users vary spacing and compare overlap, unused ground, and reachable maintenance paths while agronomic limitations remain clearly stated. Low-poly.
Working Three.js Starter (planting-density-exploration-sandbox-x1108):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Seed Spacing Lab — Toy Garden</title>
<style>
:root {
--ink: #20352b;
--muted: #66756c;
--paper: #f6f3e8;
--panel: #fffdf7;
--line: #dcded2;
--green: #326a50;
--green-light: #dfeadf;
--mint: #53c6a5;
--coral: #e96e5b;
--amber: #dda64c;
--blue: #3a8ea8;
--shadow: 0 12px 34px rgba(39, 58, 45, 0.11);
}
* {
box-sizing: border-box;
}
html,
body {
margin: 0;
min-height: 100%;
background: var(--paper);
color: var(--ink);
font-family: Inter, ui-sans-serif, system-ui, -apple-system,
BlinkMacSystemFont, "Segoe UI", sans-serif;
}
body {
overflow: hidden;
}
button,
input {
font: inherit;
}
button {
color: inherit;
}
.app {
height: 100vh;
display: grid;
grid-template-rows: auto minmax(0, 1fr);
}
header {
min-height: 76px;
display: flex;
align-items: center;
justify-content: space-between;
gap: 24px;
padding: 14px 22px;
background: rgba(255, 253, 247, 0.94);
border-bottom: 1px solid var(--line);
z-index: 5;
}
.brand {
display: flex;
align-items: center;
gap: 13px;
min-width: 0;
}
.brand-mark {
width: 43px;
height: 43px;
flex: 0 0 auto;
display: grid;
place-items: center;
border-radius: 13px;
background: var(--green);
color: #f7f4d7;
box-shadow: inset 0 -5px 0 rgba(0, 0, 0, 0.12);
}
.brand-mark svg {
width: 26px;
height: 26px;
}
.eyebrow {
margin: 0 0 2px;
color: var(--green);
font-size: 0.69rem;
font-weight: 800;
letter-spacing: 0.14em;
text-transform: uppercase;
}
h1 {
margin: 0;
font-size: clamp(1.1rem, 2vw, 1.45rem);
line-height: 1.1;
letter-spacing: -0.025em;
}
.header-actions {
display: flex;
align-items: center;
gap: 12px;
}
.model-badge {
padding: 8px 11px;
border-radius: 999px;
color: #78532d;
background: #f4e6c9;
border: 1px solid #e9d4aa;
font-size: 0.76rem;
font-weight: 750;
}
.button {
border: 1px solid #cbd3c8;
background: #fffef9;
padding: 9px 13px;
border-radius: 10px;
font-weight: 750;
cursor: pointer;
transition: transform 120ms ease, background 120ms ease;
}
.button:hover {
transform: translateY(-1px);
background: #f2f6ee;
}
.button.primary {
color: white;
border-color: var(--green);
background: var(--green);
}
main {
min-height: 0;
display: grid;
grid-template-columns: minmax(0, 1fr) 400px;
}
.viewport {
position: relative;
min-width: 0;
min-height: 0;
overflow: hidden;
background:
radial-gradient(circle at 50% 34%, #f8faee 0, #e7eee1 58%, #dce6d7 100%);
}
#stage {
position: absolute;
inset: 0;
}
#stage canvas {
width: 100%;
height: 100%;
display: block;
cursor: grab;
touch-action: none;
outline: none;
}
#stage canvas:active {
cursor: grabbing;
}
.scene-heading {
position: absolute;
top: 20px;
left: 22px;
max-width: 340px;
padding: 13px 15px;
border: 1px solid rgba(255, 255, 255, 0.8);
border-radius: 14px;
background: rgba(255, 253, 247, 0.83);
box-shadow: var(--shadow);
backdrop-filter: blur(8px);
pointer-events: none;
}
.scene-heading strong {
display: block;
margin-bottom: 3px;
font-size: 0.96rem;
}
.scene-heading span {
color: var(--muted);
font-size: 0.78rem;
}
.scene-legend {
position: absolute;
left: 22px;
bottom: 22px;
display: flex;
flex-wrap: wrap;
gap: 8px 13px;
max-width: 480px;
padding: 11px 13px;
border: 1px solid rgba(255, 255, 255, 0.75);
border-radius: 13px;
background: rgba(255, 253, 247, 0.87);
box-shadow: var(--shadow);
backdrop-filter: blur(8px);
font-size: 0.73rem;
pointer-events: none;
}
.legend-item {
display: flex;
align-items: center;
gap: 6px;
white-space: nowrap;
}
.swatch {
width: 11px;
height: 11px;
border-radius: 50%;
border: 2px solid currentColor;
background: currentColor;
}
.swatch.footprint {
color: rgba(58, 142, 168, 0.38);
}
.swatch.overlap {
color: var(--coral);
background: transparent;
}
.swatch.reachable {
color: var(--mint);
}
.swatch.blocked {
color: var(--coral);
}
.camera-hint {
position: absolute;
right: 20px;
bottom: 20px;
padding: 8px 11px;
border-radius: 10px;
color: #536359;
background: rgba(255, 253, 247, 0.78);
font-size: 0.72rem;
pointer-events: none;
}
.loading {
position: absolute;
inset: 0;
display: grid;
place-items: center;
color: var(--green);
background: #e9f0e4;
font-weight: 800;
z-index: 3;
transition: opacity 250ms ease;
}
.loading.hidden {
opacity: 0;
pointer-events: none;
}
aside {
min-height: 0;
overflow-y: auto;
padding: 18px;
background: var(--panel);
border-left: 1px solid var(--line);
scrollbar-width: thin;
}
.panel-section {
padding-bottom: 18px;
margin-bottom: 18px;
border-bottom: 1px solid var(--line);
}
.panel-section:last-child {
margin-bottom: 0;
border-bottom: 0;
}
.section-title {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
margin: 0 0 12px;
font-size: 0.88rem;
letter-spacing: -0.01em;
}
.section-title small {
color: var(--muted);
font-size: 0.7rem;
font-weight: 650;
}
.control {
margin-bottom: 14px;
}
.control:last-child {
margin-bottom: 0;
}
.control-label {
display: flex;
align-items: baseline;
justify-content: space-between;
gap: 12px;
margin-bottom: 7px;
font-size: 0.78rem;
font-weight: 750;
}
output {
color: var(--green);
font-variant-numeric: tabular-nums;
}
input[type="range"] {
width: 100%;
margin: 0;
accent-color: var(--green);
cursor: pointer;
}
.range-ends {
display: flex;
justify-content: space-between;
color: #849087;
font-size: 0.64rem;
margin-top: 3px;
}
.toggles {
display: flex;
flex-wrap: wrap;
gap: 8px 14px;
margin-top: 14px;
font-size: 0.75rem;
color: #526158;
}
.toggles label {
display: flex;
align-items: center;
gap: 6px;
cursor: pointer;
}
.toggles input {
accent-color: var(--green);
}
.metrics {
display: grid;
grid-template-columns: repeat(3, minmax(0, 1fr));
gap: 8px;
}
.metric {
min-width: 0;
padding: 11px 9px;
border: 1px solid var(--line);
border-radius: 12px;
background: #faf9f1;
}
.metric-label {
display: block;
margin-bottom: 6px;
color: var(--muted);
font-size: 0.64rem;
font-weight: 800;
letter-spacing: 0.04em;
text-transform: uppercase;
}
.metric strong {
display: block;
font-size: 1.32rem;
line-height: 1;
letter-spacing: -0.04em;
font-variant-numeric: tabular-nums;
}
.metric small {
display: block;
margin-top: 6px;
color: var(--muted);
font-size: 0.62rem;
line-height: 1.3;
}
.metric.overlap strong {
color: var(--coral);
}
.metric.unused strong {
color: #9a6c30;
}
.metric.reach strong {
color: var(--green);
}
.insight {
margin-top: 10px;
padding: 10px 11px;
border-left: 3px solid var(--amber);
border-radius: 5px 9px 9px 5px;
color: #5e5948;
background: #f5edda;
font-size: 0.73rem;
line-height: 1.4;
}
table {
width: 100%;
border-collapse: collapse;
font-variant-numeric: tabular-nums;
}
th,
td {
padding: 8px 6px;
border-bottom: 1px solid #e7e8df;
text-align: right;
font-size: 0.73rem;
}
th:first-child,
td:first-child {
text-align: left;
}
th {
color: var(--muted);
font-size: 0.64rem;
font-weight: 800;
letter-spacing: 0.04em;
text-transform: uppercase;
}
.pin-table tbody tr:last-child td,
.preset-table tbody tr:last-child td {
border-bottom: 0;
}
.pin-table td:nth-child(2) {
color: var(--green);
font-weight: 800;
}
.preset-table tbody tr {
cursor: pointer;
transition: background 120ms ease;
}
.preset-table tbody tr:hover {
background: #f1f5ec;
}
.preset-table tbody tr.active {
background: #e5efe2;
outline: 2px solid rgba(50, 106, 80, 0.25);
outline-offset: -2px;
}
.preset-table .spacing-cell {
font-weight: 800;
}
.preset-table .active-dot {
display: inline-block;
width: 6px;
height: 6px;
margin-right: 5px;
border-radius: 50%;
background: var(--green);
vertical-align: 1px;
}
.micro-note {
margin: 8px 0 0;
color: var(--muted);
font-size: 0.67rem;
line-height: 1.45;
}
.rules {
margin: 0;
padding-left: 19px;
color: #59665d;
font-size: 0.72rem;
line-height: 1.48;
}
.rules li {
margin-bottom: 7px;
}
.rules strong {
color: var(--ink);
}
.limitations {
margin-top: 12px;
padding: 11px 12px;
border: 1px solid #e6c890;
border-radius: 10px;
color: #6c5837;
background: #fbf1d9;
font-size: 0.69rem;
line-height: 1.45;
}
.limitations strong {
display: block;
margin-bottom: 4px;
color: #71502b;
}
@media (max-width: 920px) {
body {
overflow: auto;
}
.app {
height: auto;
min-height: 100vh;
}
header {
align-items: flex-start;
}
.model-badge {
display: none;
}
main {
display: block;
}
.viewport {
height: 62vh;
min-height: 480px;
}
aside {
overflow: visible;
border-left: 0;
border-top: 1px solid var(--line);
}
.camera-hint {
display: none;
}
}
@media (max-width: 520px) {
header {
padding: 12px 14px;
}
.brand-mark {
width: 38px;
height: 38px;
}
.header-actions .button {
padding: 8px 10px;
font-size: 0.72rem;
}
.scene-heading {
top: 12px;
left: 12px;
right: 12px;
max-width: none;
}
.scene-legend {
left: 12px;
right: 12px;
bottom: 12px;
}
aside {
padding: 15px 12px;
}
}
</style>
</head>
<body>
<div class="app">
<header>
<div class="brand">
<div class="brand-mark" aria-hidden="true">
<svg viewBox="0 0 24 24" fill="none">
<path d="M12 20V8" stroke="currentColor" stroke-width="2" stroke-linecap="round"/>
<path d="M12 12C7 12 5 9 5 5C9 5 12 7 12 12Z" fill="currentColor"/>
<path d="M12 15C17 15 19 12 19 8C15 8 12 10 12 15Z" fill="currentColor"/>
<path d="M7 20H17" stroke="currentColor" stroke-width="2" stroke-linecap="round"/>
</svg>
</div>
<div>
<p class="eyebrow">Spatial toy model</p>
<h1>Seed Spacing Lab</h1>
</div>
</div>
<div class="header-actions">
<span class="model-badge">Illustrative geometry, not a planting prescription</span>
<button class="button" id="resetCamera" type="button">Reset camera</button>
</div>
</header>
<main>
<section class="viewport" aria-label="Interactive toy garden">
<div id="stage"></div>
<div class="scene-heading">
<strong>Mature-footprint garden</strong>
<span id="sceneSummary">Square grid · low-poly crop · geometric route test</span>
</div>
<div class="scene-legend" aria-label="Scene legend">
<span class="legend-item">
<span class="swatch footprint"></span>
Mature canopy
</span>
<span class="legend-item">
<span class="swatch overlap"></span>
Plant overlaps another
</span>
<span class="legend-item">
<span class="swatch reachable"></span>
Reachable path
</span>
<span class="legend-item">
<span class="swatch blocked"></span>
Unusable path
</span>
</div>
<div class="camera-hint">Drag to orbit · scroll to zoom · double-click to reset</div>
<div class="loading" id="loading">Growing the toy garden…</div>
</section>
<aside>
<section class="panel-section">
<h2 class="section-title">
Try a spacing
<small>Changes update the scene</small>
</h2>
<div class="control">
<label class="control-label" for="spacing">
Seed-to-seed spacing
<output id="spacingOutput" for="spacing">35 cm</output>
</label>
<input id="spacing" type="range" min="20" max="80" step="1" value="35">
<div class="range-ends">
<span>20 cm · dense</span>
<span>80 cm · open</span>
</div>
</div>
<div class="control">
<label class="control-label" for="radius">
Toy crop canopy radius
<output id="radiusOutput" for="radius">18 cm</output>
</label>
<input id="radius" type="range" min="10" max="28" step="1" value="18">
<div class="range-ends">
<span>small</span>
<span>large</span>
</div>
</div>
<div class="control">
<label class="control-label" for="pathWidth">
Required clear path width
<output id="pathOutput" for="pathWidth">25 cm</output>
</label>
<input id="pathWidth" type="range" min="20" max="50" step="1" value="25">
<div class="range-ends">
<span>20 cm</span>
<span>50 cm</span>
</div>
</div>
<div class="toggles">
<label>
<input id="showFootprints" type="checkbox" checked>
Show footprints
</label>
<label>
<input id="showPaths" type="checkbox" checked>
Show path grid
</label>
</div>
</section>
<section class="panel-section">
<h2 class="section-title">
Live garden metrics
<small id="plantCount">0 plants</small>
</h2>
<div class="metrics">
<article class="metric overlap">
<span class="metric-label">Overlap</span>
<strong id="overlapValue">—</strong>
<small id="overlapDetail">ground in 2+ canopies</small>
</article>
<article class="metric unused">
<span class="metric-label">Unused ground</span>
<strong id="unusedValue">—</strong>
<small id="unusedDetail">of the bed is uncovered</small>
</article>
<article class="metric reach">
<span class="metric-label">Path reach</span>
<strong id="reachValue">—</strong>
<small id="reachDetail">of candidate route length</small>
</article>
</div>
<div class="insight" id="insight">Adjust the sliders to compare the trade-offs.</div>
</section>
<section class="panel-section">
<h2 class="section-title">
Compare with a pinned snapshot
<button class="button" id="pinSnapshot" type="button">Pin current</button>
</h2>
<table class="pin-table">
<thead>
<tr>
<th>Metric</th>
<th>Live</th>
<th id="pinHeading">Pinned</th>
</tr>
</thead>
<tbody>
<tr>
<td>Overlap ground</td>
<td id="livePinnedOverlap">—</td>
<td id="pinnedOverlap">—</td>
</tr>
<tr>
<td>Unused ground</td>
<td id="livePinnedUnused">—</td>
<td id="pinnedUnused">—</td>
</tr>
<tr>
<td>Reachable paths</td>
<td id="livePinnedReach">—</td>
<td id="pinnedReach">—</td>
</tr>
</tbody>
</table>
<p class="micro-note">
Pin a result, change the spacing, then compare the live values in the same row.
</p>
</section>
<section class="panel-section">
<h2 class="section-title">
Spacing presets
<small>Click a row to apply</small>
</h2>
<table class="preset-table">
<thead>
<tr>
<th>Spacing</th>
<th>Overlap</th>
<th>Unused</th>
<th>Reach</th>
</tr>
</thead>
<tbody id="presetRows"></tbody>
</table>
<p class="micro-note">
Preset percentages use the current canopy radius and required path width.
</p>
</section>
<section class="panel-section">
<h2 class="section-title">Explicit model rules</h2>
<ol class="rules">
<li>
<strong>Bed:</strong> 4.8 m × 2.8 m, with one generic toy crop on a centered,
evenly spaced square grid. No random jitter.
</li>
<li>
<strong>Growth footprint:</strong> every mature plant occupies a circular
canopy of the selected radius. The circle is a planning proxy, not a prediction
of real leaf shape.
</li>
<li>
<strong>Overlap:</strong> percentage of 4 cm bed cells covered by at least two
canopy circles. A plant “touches” another when their circles intersect.
</li>
<li>
<strong>Unused ground:</strong> percentage of bed cells covered by no canopy.
</li>
<li>
<strong>Maintenance route:</strong> candidate alleys are the gaps between
rows and columns plus edge alleys. An alley is usable when its clear width meets
the selected minimum.
</li>
<li>
<strong>Reachability:</strong> an alley must be usable and connected to the
0.6 m south service lane. The reported percentage is connected candidate-route
length divided by all candidate-route length.
</li>
</ol>
<div class="limitations">
<strong>Agronomic limitations</strong>
This model does not account for sunlight, water, nutrients, soil, slope, yield,
disease, pests, cultivar differences, irrigation, compaction, turning radius,
hand/tool access, or local regulations. Path widths and accessibility are not
prescriptions. Consult local extension guidance and the actual seed supplier
before making planting or maintenance decisions.
</div>
</section>
</aside>
</main>
</div>
<script type="module">
import * as THREE from "https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
// ---------------------------------------------------------------------------
// Constants and state
// ---------------------------------------------------------------------------
const BED_WIDTH = 4.8;
const BED_DEPTH = 2.8;
const BED_X_MIN = -BED_WIDTH / 2;
const BED_X_MAX = BED_WIDTH / 2;
const BED_Z_MIN = -BED_DEPTH / 2;
const BED_Z_MAX = BED_DEPTH / 2;
const MAX_PLANT_SPAN_X = 4.3;
const MAX_PLANT_SPAN_Z = 2.3;
const SERVICE_LANE_WIDTH = 0.6;
const RASTER_CELL = 0.04;
const SOIL_TOP = 0.12;
const PRESET_SPACINGS = [20, 35, 50, 65, 80];
const state = {
spacing: 35,
radius: 18,
pathWidth: 25,
showFootprints: true,
showPaths: true,
pinned: null,
simulation: null
};
const dom = {
stage: document.getElementById("stage"),
loading: document.getElementById("loading"),
spacing: document.getElementById("spacing"),
radius: document.getElementById("radius"),
pathWidth: document.getElementById("pathWidth"),
spacingOutput: document.getElementById("spacingOutput"),
radiusOutput: document.getElementById("radiusOutput"),
pathOutput: document.getElementById("pathOutput"),
showFootprints: document.getElementById("showFootprints"),
showPaths: document.getElementById("showPaths"),
resetCamera: document.getElementById("resetCamera"),
pinSnapshot: document.getElementById("pinSnapshot"),
presetRows: document.getElementById("presetRows"),
plantCount: document.getElementById("plantCount"),
overlapValue: document.getElementById("overlapValue"),
overlapDetail: document.getElementById("overlapDetail"),
unusedValue: document.getElementById("unusedValue"),
unusedDetail: document.getElementById("unusedDetail"),
reachValue: document.getElementById("reachValue"),
reachDetail: document.getElementById("reachDetail"),
insight: document.getElementById("insight"),
sceneSummary: document.getElementById("sceneSummary"),
livePinnedOverlap: document.getElementById("livePinnedOverlap"),
livePinnedUnused: document.getElementById("livePinnedUnused"),
livePinnedReach: document.getElementById("livePinnedReach"),
pinnedOverlap: document.getElementById("pinnedOverlap"),
pinnedUnused: document.getElementById("pinnedUnused"),
pinnedReach: document.getElementById("pinnedReach"),
pinHeading: document.getElementById("pinHeading")
};
// ---------------------------------------------------------------------------
// Three.js scene
// ---------------------------------------------------------------------------
const scene = new THREE.Scene();
scene.background = new THREE.Color(0xe8efe3);
scene.fog = new THREE.Fog(0xe8efe3, 13, 25);
const camera = new THREE.PerspectiveCamera(
38,
dom.stage.clientWidth / Math.max(1, dom.stage.clientHeight),
0.1,
50
);
const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.05;
renderer.domElement.tabIndex = 0;
renderer.domElement.setAttribute(
"aria-label",
"Three-dimensional toy garden. Drag to orbit and use the mouse wheel to zoom."
);
dom.stage.appendChild(renderer.domElement);
const hemisphere = new THREE.HemisphereLight(0xfff8df, 0x6d876c, 2.1);
scene.add(hemisphere);
const sun = new THREE.DirectionalLight(0xfff3cf, 3.1);
sun.position.set(5.5, 9, 4.5);
sun.castShadow = true;
sun.shadow.mapSize.set(2048, 2048);
sun.shadow.camera.left = -6;
sun.shadow.camera.right = 6;
sun.shadow.camera.top = 6;
sun.shadow.camera.bottom = -6;
sun.shadow.camera.near = 0.5;
sun.shadow.camera.far = 22;
sun.shadow.bias = -0.0004;
scene.add(sun);
const fill = new THREE.DirectionalLight(0xcde7ff, 0.7);
fill.position.set(-5, 4, -4);
scene.add(fill);
const staticGroup = new THREE.Group();
const plantGroup = new THREE.Group();
const pathGroup = new THREE.Group();
scene.add(staticGroup, plantGroup, pathGroup);
const unitBox = new THREE.BoxGeometry(1, 1, 1);
const moundGeometry = new THREE.CylinderGeometry(1, 1, 1, 6);
const stemGeometry = new THREE.CylinderGeometry(0.018, 0.024, 0.22, 5);
const foliageGeometry = new THREE.ConeGeometry(1, 1, 5, 1);
const blossomGeometry = new THREE.IcosahedronGeometry(1, 0);
const footprintGeometry = new THREE.CircleGeometry(1, 28);
footprintGeometry.rotateX(-Math.PI / 2);
const ringGeometry = new THREE.TorusGeometry(1, 0.035, 4, 28);
ringGeometry.rotateX(Math.PI / 2);
const materials = {
ground: new THREE.MeshStandardMaterial({
color: 0xd9e4d4,
roughness: 1,
flatShading: true
}),
slab: new THREE.MeshStandardMaterial({
color: 0x637c5e,
roughness: 0.94,
flatShading: true
}),
walkway: new THREE.MeshStandardMaterial({
color: 0xd9d2b7,
roughness: 1,
flatShading: true
}),
soil: new THREE.MeshStandardMaterial({
color: 0x9c6b48,
roughness: 1,
flatShading: true
}),
soilDark: new THREE.MeshStandardMaterial({
color: 0x795039,
roughness: 1,
flatShading: true
}),
wood: new THREE.MeshStandardMaterial({
color: 0x705036,
roughness: 1,
flatShading: true
}),
stem: new THREE.MeshStandardMaterial({
color: 0x47734a,
roughness: 1,
flatShading: true
}),
mound: new THREE.MeshStandardMaterial({
color: 0x82553c,
roughness: 1,
flatShading: true
}),
blossom: new THREE.MeshStandardMaterial({
color: 0xf2c84b,
roughness: 0.9,
flatShading: true
}),
footprint: new THREE.MeshBasicMaterial({
color: 0xffffff,
transparent: true,
opacity: 0.16,
depthWrite: false,
side: THREE.DoubleSide
}),
ring: new THREE.MeshBasicMaterial({
color: 0xffffff,
transparent: true,
opacity: 0.72,
depthWrite: false
}),
servicePath: new THREE.MeshStandardMaterial({
color: 0xb8d9c8,
transparent: true,
opacity: 0.88,
roughness: 1
}),
reachablePath: new THREE.MeshBasicMaterial({
color: 0x43b990,
transparent: true,
opacity: 0.34,
depthWrite: false
}),
narrowPath: new THREE.MeshBasicMaterial({
color: 0xe96e5b,
transparent: true,
opacity: 0.24,
depthWrite: false
}),
disconnectedPath: new THREE.MeshBasicMaterial({
color: 0xe96e5b,
transparent: true,
opacity: 0.42,
depthWrite: false
}),
blockedLine: new THREE.LineDashedMaterial({
color: 0xd85f4e,
dashSize: 0.08,
gapSize: 0.055,
transparent: true,
opacity: 0.9
})
};
function addBox(group, width, height, depth, x, y, z, material, castShadow = false) {
const mesh = new THREE.Mesh(unitBox, material);
mesh.scale.set(width, height, depth);
mesh.position.set(x, y, z);
mesh.castShadow = castShadow;
mesh.receiveShadow = true;
group.add(mesh);
return mesh;
}
// Large surrounding ground.
const surroundings = new THREE.Mesh(
new THREE.PlaneGeometry(40, 40),
materials.ground
);
surroundings.rotation.x = -Math.PI / 2;
surroundings.position.y = -0.31;
surroundings.receiveShadow = true;
staticGroup.add(surroundings);
// Raised toy-garden slab.
addBox(staticGroup, 6.2, 0.28, 4.2, 0, -0.15, 0, materials.slab, true);
// Perimeter walkway surfaces.
addBox(staticGroup, 6.0, 0.08, 0.6, 0, 0.02, -1.7, materials.walkway);
addBox(staticGroup, 6.0, 0.08, 0.6, 0, 0.02, 1.7, materials.walkway);
addBox(staticGroup, 0.6, 0.08, 2.8, -2.7, 0.02, 0, materials.walkway);
addBox(staticGroup, 0.6, 0.08, 2.8, 2.7, 0.02, 0, materials.walkway);
// Soil bed and low wooden border.
addBox(staticGroup, BED_WIDTH, 0.14, BED_DEPTH, 0, 0.05, 0, materials.soil, true);
addBox(staticGroup, 4.96, 0.18, 0.08, 0, 0.14, -1.44, materials.wood, true);
addBox(staticGroup, 4.96, 0.18, 0.08, 0, 0.14, 1.44, materials.wood, true);
addBox(staticGroup, 0.08, 0.18, 2.8, -2.44, 0.14, 0, materials.wood, true);
addBox(staticGroup, 0.08, 0.18, 2.8, 2.44, 0.14, 0, materials.wood, true);
// A small sign and entrance marker.
const signPost = new THREE.Mesh(
new THREE.CylinderGeometry(0.025, 0.025, 0.5, 6),
materials.wood
);
signPost.position.set(2.62, 0.25, 1.67);
signPost.castShadow = true;
staticGroup.add(signPost);
const sign = addBox(
staticGroup,
0.38,
0.22,
0.045,
2.62,
0.48,
1.67,
materials.soilDark,
true
);
sign.rotation.y = -0.15;
// ---------------------------------------------------------------------------
// Direct camera controls — no addons
// ---------------------------------------------------------------------------
const cameraState = {
azimuth: 0.62,
polar: 0.88,
radius: 8.6,
target: new THREE.Vector3(0, 0.25, 0)
};
function updateCamera() {
const sinPolar = Math.sin(cameraState.polar);
camera.position.set(
cameraState.target.x + cameraState.radius * sinPolar * Math.sin(cameraState.azimuth),
cameraState.target.y + cameraState.radius * Math.cos(cameraState.polar),
cameraState.target.z + cameraState.radius * sinPolar * Math.cos(cameraState.azimuth)
);
camera.lookAt(cameraState.target);
}
function resetCamera() {
cameraState.azimuth = 0.62;
cameraState.polar = 0.88;
cameraState.radius = 8.6;
cameraState.target.set(0, 0.25, 0);
updateCamera();
}
let dragging = false;
let previousX = 0;
let previousY = 0;
renderer.domElement.addEventListener("pointerdown", (event) => {
if (event.button !== 0) return;
dragging = true;
previousX = event.clientX;
previousY = event.clientY;
renderer.domElement.setPointerCapture(event.pointerId);
});
renderer.domElement.addEventListener("pointermove", (event) => {
if (!dragging) return;
const dx = event.clientX - previousX;
const dy = event.clientY - previousY;
previousX = event.clientX;
previousY = event.clientY;
cameraState.azimuth -= dx * 0.006;
cameraState.polar = THREE.MathUtils.clamp(
cameraState.polar + dy * 0.005,
0.42,
1.28
);
updateCamera();
});
function stopDragging(event) {
dragging = false;
if (event.pointerId !== undefined && renderer.domElement.hasPointerCapture(event.pointerId)) {
renderer.domElement.releasePointerCapture(event.pointerId);
}
}
renderer.domElement.addEventListener("pointerup", stopDragging);
renderer.domElement.addEventListener("pointercancel", stopDragging);
renderer.domElement.addEventListener(
"wheel",
(event) => {
event.preventDefault();
cameraState.radius = THREE.MathUtils.clamp(
cameraState.radius * Math.exp(event.deltaY * 0.001),
6.1,
13.5
);
updateCamera();
},
{ passive: false }
);
renderer.domElement.addEventListener("dblclick", resetCamera);
renderer.domElement.addEventListener("keydown", (event) => {
const keyStep = 0.09;
if (event.key === "ArrowLeft") cameraState.azimuth -= keyStep;
else if (event.key === "ArrowRight") cameraState.azimuth += keyStep;
else if (event.key === "ArrowUp") cameraState.polar -= keyStep;
else if (event.key === "ArrowDown") cameraState.polar += keyStep;
else if (event.key === "+" || event.key === "=") cameraState.radius -= 0.35;
else if (event.key === "-") cameraState.radius += 0.35;
else return;
event.preventDefault();
cameraState.polar = THREE.MathUtils.clamp(cameraState.polar, 0.42, 1.28);
cameraState.radius = THREE.MathUtils.clamp(cameraState.radius, 6.1, 13.5);
updateCamera();
});
dom.resetCamera.addEventListener("click", resetCamera);
function resizeRenderer() {
const width = Math.max(1, dom.stage.clientWidth);
const height = Math.max(1, dom.stage.clientHeight);
renderer.setSize(width, height, false);
camera.aspect = width / height;
camera.updateProjectionMatrix();
}
new ResizeObserver(resizeRenderer).observe(dom.stage);
resizeRenderer();
resetCamera();
// ---------------------------------------------------------------------------
// Spatial calculations
// ---------------------------------------------------------------------------
function makeGridPositions(spacing, radius) {
const countX = Math.floor(MAX_PLANT_SPAN_X / spacing) + 1;
const countZ = Math.floor(MAX_PLANT_SPAN_Z / spacing) + 1;
const spanX = (countX - 1) * spacing;
const spanZ = (countZ - 1) * spacing;
const startX = -spanX / 2;
const startZ = -spanZ / 2;
const positions = [];
const columns = [];
const rows = [];
for (let z = 0; z < countZ; z++) {
const row = [];
const rowZ = startZ + z * spacing;
rows.push(rowZ);
for (let x = 0; x < countX; x++) {
const px = startX + x * spacing;
const pz = rowZ;
positions.push({ x: px, z: pz });
row.push(px);
}
columns.push(row);
}
return { positions, countX, countZ, columns, rows };
}
function findOverlappingPlants(positions, radius, countX) {
const flags = new Uint8Array(positions.length);
const touchingDistance = radius * 2;
function compare(a, b) {
if (b >= positions.length) return;
const dx = positions[a].x - positions[b].x;
const dz = positions[a].z - positions[b].z;
if (dx * dx + dz * dz < touchingDistance * touchingDistance) {
flags[a] = 1;
flags[b] = 1;
}
}
for (let i = 0; i < positions.length; i++) {
compare(i, i + 1); // Same row, right.
compare(i, i + countX); // Next row, same column.
compare(i, i + countX + 1); // Next row, right diagonal.
if (i % countX !== 0) {
compare(i, i + countX - 1); // Next row, left diagonal.
}
}
return flags;
}
function rasterizeGround(positions, radius) {
const nx = Math.round(BED_WIDTH / RASTER_CELL);
const nz = Math.round(BED_DEPTH / RASTER_CELL);
const coverage = new Uint16Array(nx * nz);
const radiusSquared = radius * radius;
for (const plant of positions) {
const minX = Math.max(
0,
Math.floor((plant.x - radius - BED_X_MIN) / RASTER_CELL)
);
const maxX = Math.min(
nx - 1,
Math.floor((plant.x + radius - BED_X_MIN) / RASTER_CELL)
);
const minZ = Math.max(
0,
Math.floor((plant.z - radius - BED_Z_MIN) / RASTER_CELL)
);
const maxZ = Math.min(
nz - 1,
Math.floor((plant.z + radius - BED_Z_MIN) / RASTER_CELL)
);
for (let iz = minZ; iz <= maxZ; iz++) {
const cz = BED_Z_MIN + (iz + 0.5) * RASTER_CELL;
const dz = cz - plant.z;
for (let ix = minX; ix <= maxX; ix++) {
const cx = BED_X_MIN + (ix + 0.5) * RASTER_CELL;
const dx = cx - plant.x;
if (dx * dx + dz * dz <= radiusSquared) {
coverage[iz * nx + ix]++;
}
}
}
}
let coveredCells = 0;
let overlapCells = 0;
for (const value of coverage) {
if (value >= 1) coveredCells++;
if (value >= 2) overlapCells++;
}
const totalCells = nx * nz;
const cellArea = RASTER_CELL * RASTER_CELL;
const bedArea = BED_WIDTH * BED_DEPTH;
return {
overlapPercent: overlapCells / totalCells * 100,
unusedPercent: (totalCells - coveredCells) / totalCells * 100,
overlapArea: overlapCells * cellArea,
uncoveredArea: (totalCells - coveredCells) * cellArea,
bedArea
};
}
function buildPathModel(columns, rows, spacing, radius, requiredWidth) {
const vWidths = [];
const vCoords = [];
const leftWidth = Math.max(
0,
columns[0][0] - radius - BED_X_MIN
);
const rightWidth = Math.max(
0,
BED_X_MAX - (columns[columns.length - 1][columns.length - 1] + radius)
);
vWidths.push(leftWidth);
vCoords.push(BED_X_MIN + leftWidth / 2);
for (let i = 1; i < columns.length; i++) {
vWidths.push(Math.max(0, spacing - radius * 2));
vCoords.push((columns[i - 1][0] + columns[i][0]) / 2);
}
vWidths.push(rightWidth);
vCoords.push(BED_X_MAX - rightWidth / 2);
const hWidths = [];
const hCoords = [];
const backWidth = Math.max(
0,
rows[0] - radius - BED_Z_MIN
);
const frontWidth = Math.max(
0,
BED_Z_MAX - (rows[rows.length - 1] + radius)
);
hWidths.push(backWidth);
hCoords.push(BED_Z_MIN + backWidth / 2);
for (let i = 1; i < rows.length; i++) {
hWidths.push(Math.max(0, spacing - radius * 2));
hCoords.push((rows[i - 1] + rows[i]) / 2);
}
hWidths.push(frontWidth);
hCoords.push(BED_Z_MAX - frontWidth / 2);
const horizontalEdges = [];
const verticalEdges = [];
const adjacency = new Map();
function nodeKey(i, j) {
return `${i},${j}`;
}
function addEdge(edge) {
const key = nodeKey(edge.a.i, edge.a.j);
if (!adjacency.has(key)) adjacency.set(key, []);
adjacency.get(key).push({ to: nodeKey(edge.b.i, edge.b.j), edge });
}
// Horizontal segments, one for each gap between neighboring vertical corridors.
for (let j = 0; j < hCoords.length; j++) {
for (let i = 1; i < vCoords.length; i++) {
const edge = {
kind: "h",
i,
j,
a: { i: i - 1, j },
b: { i, j },
width: hWidths[j],
length: vCoords[i] - vCoords[i - 1],
x1: vCoords[i - 1],
x2: vCoords[i],
z: hCoords[j],
reachable: false
};
horizontalEdges.push(edge);
addEdge(edge);
addEdge({
...edge,
a: edge.b,
b: edge.a
});
}
}
// Vertical segments, one for each gap between neighboring horizontal corridors.
for (let i = 0; i < vCoords.length; i++) {
for (let j = 1; j < hCoords.length; j++) {
const edge = {
kind: "v",
i,
j,
a: { i, j: j - 1 },
b: { i, j },
width: vWidths[i],
length: hCoords[j] - hCoords[j - 1],
z1: hCoords[j - 1],
z2: hCoords[j],
x: vCoords[i],
reachable: false
};
verticalEdges.push(edge);
addEdge(edge);
addEdge({
...edge,
a: edge.b,
b: edge.a
});
}
}
// The south service lane is continuous and connects to every front-edge node.
const visited = new Set();
const queue = [];
for (let i = 0; i < vCoords.length; i++) {
const key = nodeKey(i, hCoords.length - 1);
visited.add(key);
queue.push(key);
}
while (queue.length) {
const key = queue.shift();
const neighbors = adjacency.get(key) || [];
for (const neighbor of neighbors) {
if (neighbor.edge.width + 1e-8 < requiredWidth) continue;
if (visited.has(neighbor.to)) continue;
visited.add(neighbor.to);
queue.push(neighbor.to);
}
}
const allEdges = [...horizontalEdges, ...verticalEdges];
let totalLength = BED_WIDTH; // Continuous south service lane.
let reachableLength = BED_WIDTH;
for (const edge of allEdges) {
totalLength += edge.length;
const a = nodeKey(edge.a.i, edge.a.j);
const b = nodeKey(edge.b.i, edge.b.j);
edge.reachable =
edge.width + 1e-8 >= requiredWidth &&
visited.has(a) &&
visited.has(b);
if (edge.reachable) reachableLength += edge.length;
}
return {
vWidths,
vCoords,
hWidths,
hCoords,
edges: allEdges,
totalLength,
reachableLength,
reachPercent: reachableLength / totalLength * 100
};
}
function calculateSimulation(spacing, radiusCm, requiredWidthCm) {
const radius = radiusCm / 100;
const requiredWidth = requiredWidthCm / 100;
const spacingMeters = spacing / 100;
const grid = makeGridPositions(spacingMeters, radius);
const ground = rasterizeGround(grid.positions, radius);
const overlapFlags = findOverlappingPlants(grid.positions, radius, grid.countX);
const overlappingPlantCount = overlapFlags.reduce((sum, value) => sum + value, 0);
const path = buildPathModel(
grid.columns,
grid.rows,
spacingMeters,
radius,
requiredWidth
);
return {
spacing,
radius,
requiredWidth,
...grid,
ground,
overlapFlags,
overlappingPlantCount,
overlappingPlantPercent:
overlappingPlantCount / grid.positions.length * 100,
path
};
}
// ---------------------------------------------------------------------------
// Scene rendering
// ---------------------------------------------------------------------------
function clearGroup(group) {
while (group.children.length) {
group.remove(group.children[group.children.length - 1]);
}
}
function renderPlants(simulation) {
clearGroup(plantGroup);
const count = simulation.positions.length;
const radius = simulation.radius;
const moundMesh = new THREE.InstancedMesh(
moundGeometry,
materials.mound,
count
);
const stemMesh = new THREE.InstancedMesh(
stemGeometry,
materials.stem,
count
);
const foliageMesh = new THREE.InstancedMesh(
foliageGeometry,
materials.stem,
count
);
const blossomMesh = new THREE.InstancedMesh(
blossomGeometry,
materials.blossom,
count
);
const footprintMesh = new THREE.InstancedMesh(
footprintGeometry,
materials.footprint,
count
);
const ringMesh = new THREE.InstancedMesh(
ringGeometry,
materials.ring,
count
);
const dummy = new THREE.Object3D();
const color = new THREE.Color();
for (let i = 0; i < count; i++) {
const plant = simulation.positions[i];
const overlap = simulation.overlapFlags[i] === 1;
const foliageHeight = Math.max(0.16, radius * 1.6);
dummy.position.set(plant.x, SOIL_TOP + 0.03, plant.z);
dummy.rotation.set(0, 0, 0);
dummy.scale.set(radius * 0.66, 0.06, radius * 0.66);
dummy.updateMatrix();
moundMesh.setMatrixAt(i, dummy.matrix);
dummy.position.set(plant.x, SOIL_TOP + 0.11, plant.z);
dummy.scale.set(1, 1, 1);
dummy.updateMatrix();
stemMesh.setMatrixAt(i, dummy.matrix);
dummy.position.set(
plant.x,
SOIL_TOP + 0.07 + foliageHeight / 2,
plant.z
);
dummy.rotation.y = (i * 1.618) % (Math.PI * 2);
dummy.scale.set(radius * 0.72, foliageHeight, radius * 0.72);
dummy.updateMatrix();
foliageMesh.setMatrixAt(i, dummy.matrix);
color.setHSL(0.285 + ((i * 7) % 11) * 0.003, 0.38, 0.32 + (i % 3) * 0.035);
foliageMesh.setColorAt(i, color);
dummy.position.set(
plant.x,
SOIL_TOP + 0.07 + foliageHeight,
plant.z
);
dummy.rotation.set(0, (i * 0.77) % (Math.PI * 2), 0);
dummy.scale.setScalar(radius * 0.29);
dummy.updateMatrix();
blossomMesh.setMatrixAt(i, dummy.matrix);
color.set(i % 4 === 0 ? 0xe99442 : 0xf2ca4b);
blossomMesh.setColorAt(i, color);
dummy.position.set(plant.x, SOIL_TOP + 0.016, plant.z);
dummy.rotation.set(0, 0, 0);
dummy.scale.set(radius, radius, radius);
dummy.updateMatrix();
footprintMesh.setMatrixAt(i, dummy.matrix);
color.set(overlap ? 0xe96e5b : 0x3a8ea8);
footprintMesh.setColorAt(i, color);
dummy.position.set(plant.x, SOIL_TOP + 0.023, plant.z);
dummy.scale.set(radius, radius, radius);
dummy.updateMatrix();
ringMesh.setMatrixAt(i, dummy.matrix);
color.set(overlap ? 0xe96e5b : 0x3a8ea8);
ringMesh.setColorAt(i, color);
}
for (const mesh of [moundMesh, stemMesh, foliageMesh, blossomMesh]) {
mesh.castShadow = true;
mesh.receiveShadow = true;
mesh.frustumCulled = false;
plantGroup.add(mesh);
}
footprintMesh.frustumCulled = false;
footprintMesh.renderOrder = 2;
ringMesh.frustumCulled = false;
ringMesh.renderOrder = 3;
if (state.showFootprints) {
plantGroup.add(footprintMesh, ringMesh);
}
}
function renderPaths(pathModel) {
clearGroup(pathGroup);
if (!state.showPaths) return;
const serviceLane = addBox(
pathGroup,
BED_WIDTH,
0.018,
SERVICE_LANE_WIDTH,
0,
0.071,
BED_Z_MAX + SERVICE_LANE_WIDTH / 2,
materials.servicePath
);
serviceLane.renderOrder = 1;
const narrowLinePoints = [];
for (const edge of pathModel.edges) {
let material;
if (edge.width + 1e-8 < pathModel.requiredWidth) {
material = materials.narrowPath;
} else if (edge.reachable) {
material = materials.reachablePath;
} else {
material = materials.disconnectedPath;
}
if (edge.width > 0.005) {
const mesh = new THREE.Mesh(unitBox, material);
mesh.receiveShadow = false;
if (edge.kind === "h") {
mesh.scale.set(edge.length, 0.012, edge.width);
mesh.position.set(
(edge.x1 + edge.x2) / 2,
SOIL_TOP + 0.006,
edge.z
);
} else {
mesh.scale.set(edge.width, 0.012, edge.length);
mesh.position.set(
edge.x,
SOIL_TOP + 0.007,
(edge.z1 + edge.z2) / 2
);
}
mesh.renderOrder = 1;
pathGroup.add(mesh);
}
if (edge.width + 1e-8 < pathModel.requiredWidth) {
const y = SOIL_TOP + 0.026;
if (edge.kind === "h") {
narrowLinePoints.push(
new THREE.Vector3(edge.x1, y, edge.z),
new THREE.Vector3(edge.x2, y, edge.z)
);
} else {
narrowLinePoints.push(
new THREE.Vector3(edge.x, y, edge.z1),
new THREE.Vector3(edge.x, y, edge.z2)
);
}
}
}
if (narrowLinePoints.length) {
const geometry = new THREE.BufferGeometry().setFromPoints(narrowLinePoints);
const line = new THREE.LineSegments(geometry, materials.blockedLine);
line.computeLineDistances();
line.renderOrder = 4;
pathGroup.add(line);
}
}
// ---------------------------------------------------------------------------
// UI and comparison
// ---------------------------------------------------------------------------
function percent(value) {
return `${value.toFixed(1)}%`;
}
function updateMetricCards(simulation) {
const ground = simulation.ground;
const path = simulation.path;
dom.overlapValue.textContent = percent(ground.overlapPercent);
dom.overlapDetail.textContent =
`${simulation.overlappingPlantPercent.toFixed(0)}% of plants touch`;
dom.unusedValue.textContent = percent(ground.unusedPercent);
dom.unusedDetail.textContent =
`${ground.uncoveredArea.toFixed(1)} of ${ground.bedArea.toFixed(1)} m²`;
dom.reachValue.textContent = percent(path.reachPercent);
dom.reachDetail.textContent =
`${path.reachableLength.toFixed(1)} / ${path.totalLength.toFixed(1)} m`;
dom.plantCount.textContent = `${simulation.positions.length} plants`;
dom.sceneSummary.textContent =
`${simulation.positions.length} toy plants · ${simulation.countX} × ${simulation.countZ} grid · ${simulation.spacing} cm spacing`;
dom.livePinnedOverlap.textContent = percent(ground.overlapPercent);
dom.livePinnedUnused.textContent = percent(ground.unusedPercent);
dom.livePinnedReach.textContent = percent(path.reachPercent);
if (state.pinned) {
dom.pinnedOverlap.textContent = percent(state.pinned.overlap);
dom.pinnedUnused.textContent = percent(state.pinned.unused);
dom.pinnedReach.textContent = percent(state.pinned.reach);
dom.pinHeading.textContent = `${state.pinned.spacing} cm`;
} else {
dom.pinnedOverlap.textContent = "—";
dom.pinnedUnused.textContent = "—";
dom.pinnedReach.textContent = "—";
dom.pinHeading.textContent = "Pinned";
}
if (ground.overlapPercent > 1 && path.reachPercent < 50) {
dom.insight.textContent =
"Canopies collide while most internal alleys are too narrow or disconnected. " +
"More space may improve maintenance access, but it also leaves more unused ground.";
} else if (ground.overlapPercent <= 1 && path.reachPercent < 50) {
dom.insight.textContent =
"Canopies no longer overlap in this result, but the selected path width is still " +
"not met by enough connected alleys.";
} else if (path.reachPercent >= 50) {
dom.insight.textContent =
"Most candidate route length is usable and connected. The remaining trade-off " +
"is canopy area versus uncovered ground.";
} else {
dom.insight.textContent =
"The current spacing creates a narrow compromise between footprint overlap, " +
"ground use, and connected maintenance space.";
}
}
function refreshPresetTable() {
const rows = PRESET_SPACINGS.map((spacing) => {
const result = calculateSimulation(spacing, state.radius, state.pathWidth);
const active = Math.abs(spacing - state.spacing) < 0.5;
return `
<tr data-spacing="${spacing}" tabindex="0"
aria-label="Apply ${spacing} centimetre spacing"
class="${active ? "active" : ""}">
<td class="spacing-cell">
${active ? '<span class="active-dot"></span>' : ""}
${spacing} cm
</td>
<td>${result.ground.overlapPercent.toFixed(1)}%</td>
<td>${result.ground.unusedPercent.toFixed(1)}%</td>
<td>${result.path.reachPercent.toFixed(1)}%</td>
</tr>
`;
}).join("");
dom.presetRows.innerHTML = rows;
dom.presetRows.querySelectorAll("tr").forEach((row) => {
const apply = () => {
dom.spacing.value = row.dataset.spacing;
updateOutputs();
scheduleUpdate();
};
row.addEventListener("click", apply);
row.addEventListener("keydown", (event) => {
if (event.key === "Enter" || event.key === " ") {
event.preventDefault();
apply();
}
});
});
}
function updateOutputs() {
dom.spacingOutput.textContent = `${dom.spacing.value} cm`;
dom.radiusOutput.textContent = `${dom.radius.value} cm`;
dom.pathOutput.textContent = `${dom.pathWidth.value} cm`;
}
let updateFrame = 0;
function scheduleUpdate() {
cancelAnimationFrame(updateFrame);
updateFrame = requestAnimationFrame(() => {
state.spacing = Number(dom.spacing.value);
state.radius = Number(dom.radius.value);
state.pathWidth = Number(dom.pathWidth.value);
state.showFootprints = dom.showFootprints.checked;
state.showPaths = dom.showPaths.checked;
const simulation = calculateSimulation(
state.spacing,
state.radius,
state.pathWidth
);
state.simulation = simulation;
renderPlants(simulation);
renderPaths(simulation.path);
updateMetricCards(simulation);
refreshPresetTable();
});
}
dom.spacing.addEventListener("input", () => {
updateOutputs();
scheduleUpdate();
});
dom.radius.addEventListener("input", () => {
updateOutputs();
scheduleUpdate();
});
dom.pathWidth.addEventListener("input", () => {
updateOutputs();
scheduleUpdate();
});
dom.showFootprints.addEventListener("change", scheduleUpdate);
dom.showPaths.addEventListener("change", scheduleUpdate);
dom.pinSnapshot.addEventListener("click", () => {
if (!state.simulation) return;
state.pinned = {
spacing: state.simulation.spacing,
overlap: state.simulation.ground.overlapPercent,
unused: state.simulation.ground.unusedPercent,
reach: state.simulation.path.reachPercent
};
dom.pinSnapshot.textContent = "Update pin";
updateMetricCards(state.simulation);
});
updateOutputs();
scheduleUpdate();
// Render loop.
renderer.setAnimationLoop(() => {
renderer.render(scene, camera);
});
requestAnimationFrame(() => {
dom.loading.classList.add("hidden");
setTimeout(() => dom.loading.remove(), 300);
});
</script>
</body>
</html>
```