Prompt specification
Build or customize the Three.js 3D scene "Nutrient-source comparison classroom" 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: Nutrient-source comparison classroom
Category: Biology & Nature · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/nutrient-source-comparison-classroom-x0744
Scene Description Prompt:
Create a single self-contained HTML file using Three.js from cdnjs that shows a low-poly classroom crop-system model with tracked nitrogen tokens. Include soil, plant roots, nodules representing a schematic microbial partnership, and explicitly named input and output reservoirs. Give tokens persistent identities as they move along permitted transfer paths. Users can inspect a few predefined source scenarios, but no token should appear or disappear without a recorded transfer across the model boundary. Keep the rates synthetic and distinguish this accounting demonstration from a prediction for an actual field. Use a cutaway soil block and a small number of plants so the underground relationships remain as visible as the leaves above.
Working Three.js Starter (nutrient-source-comparison-classroom-x0744):
```html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Nitrogen Transfer Classroom</title>
<style>
:root {
--ink: #17251e;
--muted: #607068;
--line: #d8e0d9;
--panel: #f8faf7;
--paper: #ffffff;
--green: #285c3b;
--green-light: #dff0e4;
--mint: #8be2b0;
--amber: #d99136;
--blue: #4d9fc5;
--pink: #d66a75;
--shadow: 0 12px 32px rgba(33, 57, 43, 0.10);
}
* { box-sizing: border-box; }
html, body {
margin: 0;
width: 100%;
height: 100%;
color: var(--ink);
background: #eaf0e9;
font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
body { overflow: hidden; }
header {
height: 74px;
display: flex;
align-items: center;
justify-content: space-between;
gap: 20px;
padding: 0 24px;
background: var(--paper);
border-bottom: 1px solid var(--line);
}
.title-block {
display: flex;
align-items: center;
gap: 14px;
min-width: 0;
}
.title-mark {
width: 38px;
height: 38px;
flex: 0 0 auto;
display: grid;
place-items: center;
border-radius: 12px;
color: white;
background: var(--green);
font-weight: 800;
font-size: 20px;
}
h1 {
margin: 0;
font-size: 19px;
line-height: 1.15;
letter-spacing: -0.02em;
}
.subtitle {
margin-top: 4px;
color: var(--muted);
font-size: 12px;
}
.disclaimer-badge {
max-width: 440px;
padding: 9px 13px;
border: 1px solid #e6c58f;
border-radius: 999px;
color: #704a13;
background: #fff6df;
font-size: 11px;
font-weight: 750;
line-height: 1.25;
text-align: right;
}
#app {
height: calc(100vh - 74px);
display: grid;
grid-template-columns: 272px minmax(0, 1fr) 338px;
}
aside {
min-width: 0;
overflow: auto;
background: var(--panel);
}
.left-panel {
padding: 18px 16px 28px;
border-right: 1px solid var(--line);
}
.right-panel {
padding: 16px;
border-left: 1px solid var(--line);
}
.section {
margin-bottom: 20px;
}
.section-title {
margin: 0 0 9px;
color: #43574c;
font-size: 11px;
font-weight: 850;
letter-spacing: 0.12em;
text-transform: uppercase;
}
.intro {
margin: 0;
color: #526159;
font-size: 12px;
line-height: 1.55;
}
.scenario-list {
display: grid;
gap: 9px;
}
.scenario {
width: 100%;
padding: 12px;
border: 1px solid var(--line);
border-radius: 12px;
color: var(--ink);
background: white;
text-align: left;
cursor: pointer;
transition: border-color .15s, transform .15s, box-shadow .15s;
}
.scenario:hover {
transform: translateY(-1px);
border-color: #9abaa3;
box-shadow: 0 6px 16px rgba(42, 76, 55, .08);
}
.scenario.active {
border-color: var(--green);
box-shadow: inset 0 0 0 1px var(--green);
background: #f5fbf6;
}
.scenario strong {
display: block;
margin-bottom: 4px;
font-size: 13px;
}
.scenario .meta {
display: block;
margin-bottom: 6px;
color: var(--green);
font-size: 10px;
font-weight: 800;
letter-spacing: .05em;
text-transform: uppercase;
}
.scenario .detail {
display: block;
color: var(--muted);
font-size: 11px;
line-height: 1.45;
}
.scenario-note {
margin: 10px 2px 0;
color: #68776e;
font-size: 10.5px;
line-height: 1.45;
}
.boundary-list {
display: grid;
gap: 7px;
}
.boundary-row {
display: flex;
align-items: flex-start;
gap: 8px;
padding: 8px 9px;
border-radius: 9px;
background: white;
border: 1px solid var(--line);
font-size: 11px;
line-height: 1.35;
}
.dot {
width: 9px;
height: 9px;
flex: 0 0 auto;
margin-top: 3px;
border-radius: 50%;
background: var(--blue);
}
.dot.output { background: var(--amber); }
.dot.internal { background: var(--green); }
.boundary-row strong {
display: block;
font-size: 11px;
}
.boundary-row span {
color: var(--muted);
}
.small-note {
margin: 8px 2px 0;
color: #6c7971;
font-size: 10.5px;
line-height: 1.5;
}
#viewport {
position: relative;
min-width: 0;
min-height: 0;
overflow: hidden;
background:
radial-gradient(circle at 50% 38%, #f8fbf7 0%, #e6ede5 72%, #dbe5da 100%);
}
#canvasHost {
position: absolute;
inset: 0;
}
#canvasHost canvas {
display: block;
width: 100%;
height: 100%;
outline: none;
touch-action: none;
}
.viewport-top {
position: absolute;
z-index: 4;
top: 14px;
left: 14px;
right: 14px;
display: flex;
justify-content: space-between;
align-items: flex-start;
gap: 12px;
pointer-events: none;
}
.view-chip {
padding: 8px 11px;
border: 1px solid rgba(95, 118, 103, .20);
border-radius: 10px;
color: #42564a;
background: rgba(255, 255, 255, .84);
backdrop-filter: blur(8px);
box-shadow: 0 5px 18px rgba(43, 66, 50, .06);
font-size: 11px;
line-height: 1.35;
}
.view-chip strong {
display: block;
color: var(--green);
font-size: 12px;
}
.view-actions {
display: flex;
gap: 7px;
pointer-events: auto;
}
.view-actions button {
padding: 8px 10px;
border: 1px solid rgba(95, 118, 103, .22);
border-radius: 9px;
color: #344a3c;
background: rgba(255, 255, 255, .90);
cursor: pointer;
font: inherit;
font-size: 11px;
font-weight: 750;
}
.view-actions button:hover { background: white; }
.viewport-bottom {
position: absolute;
z-index: 4;
left: 14px;
right: 14px;
bottom: 13px;
display: flex;
justify-content: space-between;
align-items: flex-end;
gap: 10px;
pointer-events: none;
}
.view-hint {
max-width: 440px;
padding: 8px 11px;
border-radius: 9px;
color: #526359;
background: rgba(255, 255, 255, .84);
border: 1px solid rgba(95, 118, 103, .18);
font-size: 10.5px;
line-height: 1.4;
}
.boundary-badge {
padding: 8px 10px;
border-radius: 9px;
color: #28573a;
background: rgba(226, 244, 230, .92);
border: 1px solid #acd1b5;
font-size: 10.5px;
font-weight: 800;
}
#tokenTooltip {
position: absolute;
z-index: 10;
display: none;
padding: 6px 8px;
border-radius: 7px;
color: white;
background: rgba(22, 37, 29, .92);
font-size: 10px;
pointer-events: none;
white-space: nowrap;
}
.stats {
display: grid;
grid-template-columns: repeat(2, 1fr);
gap: 8px;
}
.stat {
padding: 10px;
border: 1px solid var(--line);
border-radius: 10px;
background: white;
}
.stat .value {
display: block;
font-size: 21px;
font-weight: 850;
line-height: 1;
color: var(--green);
}
.stat .label {
display: block;
margin-top: 5px;
color: var(--muted);
font-size: 9.5px;
line-height: 1.25;
}
.invariant {
margin-top: 8px;
padding: 10px;
border: 1px solid #b9d9c1;
border-radius: 10px;
color: #2a603b;
background: #eaf7ed;
font-size: 10.5px;
line-height: 1.45;
}
.token-inspector {
margin-top: 8px;
padding: 12px;
border: 1px solid var(--line);
border-radius: 11px;
background: white;
}
.token-id {
display: flex;
align-items: center;
justify-content: space-between;
gap: 8px;
margin-bottom: 9px;
}
.token-id strong {
font-size: 17px;
letter-spacing: .02em;
}
.token-id span {
color: var(--muted);
font-size: 9px;
}
.inspector-row {
display: grid;
grid-template-columns: 80px 1fr;
gap: 7px;
padding: 5px 0;
border-top: 1px solid #edf1ed;
font-size: 10.5px;
line-height: 1.35;
}
.inspector-row span:first-child {
color: var(--muted);
}
.route-line {
margin-top: 9px;
padding: 8px;
border-radius: 8px;
color: #516158;
background: #f3f6f2;
font-size: 9.5px;
line-height: 1.55;
word-break: break-word;
}
.history-title {
margin: 13px 0 6px;
color: #56665c;
font-size: 10px;
font-weight: 850;
letter-spacing: .09em;
text-transform: uppercase;
}
.history-row {
position: relative;
padding: 6px 0 6px 16px;
border-left: 2px solid #b9c8bd;
font-size: 9.5px;
line-height: 1.35;
}
.history-row::before {
content: "";
position: absolute;
left: -5px;
top: 9px;
width: 8px;
height: 8px;
border: 2px solid white;
border-radius: 50%;
background: var(--green);
box-shadow: 0 0 0 1px #9db3a2;
}
.ledger-head {
display: flex;
justify-content: space-between;
align-items: baseline;
margin-bottom: 7px;
}
.ledger-head small {
color: var(--muted);
font-size: 9px;
}
#ledgerList {
max-height: 360px;
overflow: auto;
border: 1px solid var(--line);
border-radius: 10px;
background: white;
}
.ledger-row {
width: 100%;
display: grid;
grid-template-columns: 34px 1fr;
gap: 7px;
padding: 9px;
border: 0;
border-bottom: 1px solid #edf1ed;
color: var(--ink);
background: white;
text-align: left;
cursor: pointer;
}
.ledger-row:hover,
.ledger-row.selected {
background: #f0f7f1;
}
.ledger-row:last-child { border-bottom: 0; }
.ledger-seq {
color: #7a887f;
font-size: 9px;
font-variant-numeric: tabular-nums;
}
.ledger-main {
min-width: 0;
}
.ledger-route {
display: block;
font-size: 10px;
font-weight: 750;
line-height: 1.3;
}
.ledger-meta {
display: flex;
align-items: center;
gap: 5px;
margin-top: 3px;
color: var(--muted);
font-size: 8.5px;
}
.kind {
padding: 2px 5px;
border-radius: 999px;
font-size: 7.5px;
font-weight: 850;
text-transform: uppercase;
letter-spacing: .05em;
}
.kind.boundary-input {
color: #245f7a;
background: #dff2fa;
}
.kind.internal {
color: #315d40;
background: #e1eee4;
}
.kind.boundary-output {
color: #7b5319;
background: #fbedcf;
}
.legend {
display: flex;
flex-wrap: wrap;
gap: 7px 10px;
color: #59685f;
font-size: 9.5px;
}
.legend-item {
display: flex;
align-items: center;
gap: 5px;
}
.legend-swatch {
width: 14px;
height: 3px;
border-radius: 2px;
background: var(--green);
}
@media (max-width: 1100px) {
#app { grid-template-columns: 235px minmax(0, 1fr) 285px; }
.left-panel, .right-panel { padding: 14px 12px; }
.disclaimer-badge { max-width: 320px; }
}
@media (max-width: 820px) {
body { overflow: auto; }
header {
height: auto;
min-height: 74px;
padding: 12px 14px;
}
.subtitle { display: none; }
.disclaimer-badge {
max-width: 220px;
font-size: 9px;
}
#app {
height: auto;
display: flex;
flex-direction: column;
}
#viewport {
order: -1;
height: 68vh;
min-height: 500px;
}
aside {
overflow: visible;
border: 0;
}
.left-panel { border-bottom: 1px solid var(--line); }
.right-panel { border-top: 1px solid var(--line); }
#ledgerList { max-height: 320px; }
}
@media (max-width: 520px) {
h1 { font-size: 15px; }
.title-mark { width: 32px; height: 32px; }
.disclaimer-badge { max-width: 145px; }
.view-hint { max-width: 240px; }
.boundary-badge { display: none; }
}
</style>
</head>
<body>
<header>
<div class="title-block">
<div class="title-mark" aria-hidden="true">N</div>
<div>
<h1>Nitrogen Transfer Classroom</h1>
<div class="subtitle">Persistent-token accounting in a low-poly crop–soil system</div>
</div>
</div>
<div class="disclaimer-badge">
Synthetic accounting demonstration — not a prediction for an actual field
</div>
</header>
<div id="app">
<aside class="left-panel">
<section class="section">
<h2 class="section-title">Predefined source scenarios</h2>
<p class="intro">
Running a scenario adds a new synthetic input batch. Earlier tokens and
ledger records remain in the model, so no identity is silently reset.
</p>
<div class="scenario-list" style="margin-top: 12px">
<button class="scenario" data-scenario="balanced">
<span class="meta">4 packets · 1.00× display pace</span>
<strong>Reference mixing</strong>
<span class="detail">
Fixation → uptake → residue return → soil solution → nitrate leaching.
</span>
</button>
<button class="scenario" data-scenario="dry">
<span class="meta">5 packets · 1.35× display pace</span>
<strong>Dry-soil shortcut</strong>
<span class="detail">
A shorter route emphasizes lower uptake and earlier nitrate leaching.
</span>
</button>
<button class="scenario" data-scenario="warm">
<span class="meta">4 packets · 0.72× display pace</span>
<strong>Warm pulse</strong>
<span class="detail">
Faster cycling, followed by a schematic denitrification exit.
</span>
</button>
</div>
<p class="scenario-note">
“Rate” means animation scheduling only. One token represents one
schematic nitrogen packet, with no conversion to kg N/ha.
</p>
</section>
<section class="section">
<h2 class="section-title">Named model reservoirs</h2>
<div class="boundary-list">
<div class="boundary-row">
<i class="dot"></i>
<div>
<strong>Atmospheric N₂ — input reservoir</strong>
<span>External nitrogen-fixation source</span>
</div>
</div>
<div class="boundary-row">
<i class="dot internal"></i>
<div>
<strong>Root nodule fixation</strong>
<span>Schematic rhizobial partnership</span>
</div>
</div>
<div class="boundary-row">
<i class="dot internal"></i>
<div>
<strong>Soil solution N</strong>
<span>NO₃⁻ available to roots</span>
</div>
</div>
<div class="boundary-row">
<i class="dot internal"></i>
<div>
<strong>Soil organic N</strong>
<span>Residue and microbial pool</span>
</div>
</div>
<div class="boundary-row">
<i class="dot internal"></i>
<div>
<strong>Plant tissue N</strong>
<span>Assimilated crop nitrogen</span>
</div>
</div>
<div class="boundary-row">
<i class="dot output"></i>
<div>
<strong>Nitrate leaching — output reservoir</strong>
<span>External boundary loss</span>
</div>
</div>
<div class="boundary-row">
<i class="dot output"></i>
<div>
<strong>Denitrification N₂ — output reservoir</strong>
<span>External boundary loss</span>
</div>
</div>
</div>
</section>
<section class="section">
<h2 class="section-title">Permitted transfer paths</h2>
<div class="legend">
<div class="legend-item"><i class="legend-swatch" style="background:#4d9fc5"></i>Boundary input</div>
<div class="legend-item"><i class="legend-swatch" style="background:#69b97e"></i>Fixation / uptake</div>
<div class="legend-item"><i class="legend-swatch" style="background:#a7783c"></i>Organic return</div>
<div class="legend-item"><i class="legend-swatch" style="background:#d99136"></i>Boundary output</div>
</div>
<p class="small-note">
Tokens follow only the displayed arrows. Click a token to inspect its
persistent ID and transfer history.
</p>
</section>
</aside>
<main id="viewport" aria-label="Interactive cutaway crop nitrogen model">
<div id="canvasHost"></div>
<div class="viewport-top">
<div class="view-chip">
<strong id="scenarioStatus">Reference mixing</strong>
<span id="scenarioStatusDetail">Preparing synthetic input batch…</span>
</div>
<div class="view-actions">
<button id="pauseButton" type="button">Pause</button>
<button id="resetCameraButton" type="button">Reset view</button>
</div>
</div>
<div class="viewport-bottom">
<div class="view-hint">
Drag to orbit · Shift-drag to pan · Wheel to zoom · Click a glowing token to inspect
</div>
<div class="boundary-badge">Every visible token has a recorded boundary input</div>
</div>
<div id="tokenTooltip"></div>
</main>
<aside class="right-panel">
<section class="section">
<h2 class="section-title">Identity accounting</h2>
<div class="stats">
<div class="stat">
<span class="value" id="tokenCount">0</span>
<span class="label">Persistent tokens</span>
</div>
<div class="stat">
<span class="value" id="inputCount">0</span>
<span class="label">Recorded inputs</span>
</div>
<div class="stat">
<span class="value" id="outputCount">0</span>
<span class="label">Recorded outputs</span>
</div>
<div class="stat">
<span class="value" id="inFlightCount">0</span>
<span class="label">Currently transferring</span>
</div>
</div>
<div class="invariant" id="invariantStatus">
Checking persistent token identities…
</div>
</section>
<section class="section">
<h2 class="section-title">Selected token</h2>
<div class="token-inspector" id="tokenInspector">
<div class="token-id">
<strong>No token selected</strong>
<span>Persistent identity</span>
</div>
<p class="small-note" style="margin:0">
Click a glowing token in the model to see its current reservoir,
route, and complete recorded history.
</p>
</div>
</section>
<section class="section">
<div class="ledger-head">
<h2 class="section-title" style="margin:0">Transfer ledger</h2>
<small id="ledgerCount">0 records</small>
</div>
<div id="ledgerList" aria-live="polite"></div>
<p class="small-note">
Newest entries first. Boundary output tokens remain visible in their
named reservoirs; the model never deletes a token.
</p>
</section>
</aside>
</div>
<script type="module">
import * as THREE from "https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
const $ = (selector) => document.querySelector(selector);
const viewport = $("#viewport");
const canvasHost = $("#canvasHost");
// -----------------------------------------------------------------------
// Scene and renderer
// -----------------------------------------------------------------------
const scene = new THREE.Scene();
scene.background = new THREE.Color(0xe9efe7);
scene.fog = new THREE.Fog(0xe9efe7, 28, 48);
let renderer;
try {
renderer = new THREE.WebGLRenderer({ antialias: true, alpha: true });
} catch (error) {
canvasHost.innerHTML = `
<div style="padding:30px;font:14px system-ui;color:#7c302e">
WebGL is unavailable. Please open this file in a browser with hardware-accelerated WebGL.
</div>`;
throw error;
}
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.08;
canvasHost.appendChild(renderer.domElement);
const camera = new THREE.PerspectiveCamera(42, 1, 0.1, 100);
const hemi = new THREE.HemisphereLight(0xf4fff4, 0x725e45, 2.15);
scene.add(hemi);
const sun = new THREE.DirectionalLight(0xfff4dc, 3.1);
sun.position.set(7, 13, 10);
sun.castShadow = true;
sun.shadow.mapSize.set(2048, 2048);
sun.shadow.camera.left = -15;
sun.shadow.camera.right = 15;
sun.shadow.camera.top = 14;
sun.shadow.camera.bottom = -12;
sun.shadow.camera.near = 1;
sun.shadow.camera.far = 40;
sun.shadow.bias = -0.0004;
scene.add(sun);
const fill = new THREE.DirectionalLight(0x9dd6e7, 1.1);
fill.position.set(-9, 5, -7);
scene.add(fill);
const standard = (color, options = {}) =>
new THREE.MeshStandardMaterial({
color,
roughness: 0.86,
metalness: 0,
flatShading: true,
...options
});
const soilMat = standard(0x755237);
const soilDarkMat = standard(0x60452f);
const soilTopMat = standard(0x80603d);
const rootMat = standard(0xb58a59);
const noduleMat = standard(0xe77668);
const stemMat = standard(0x477a3d);
const leafMats = [
standard(0x4f914e),
standard(0x65a957),
standard(0x3d7f49)
];
function box(w, h, d, material, x, y, z, cast = true) {
const mesh = new THREE.Mesh(new THREE.BoxGeometry(w, h, d), material);
mesh.position.set(x, y, z);
mesh.castShadow = cast;
mesh.receiveShadow = true;
scene.add(mesh);
return mesh;
}
function cylinderBetween(a, b, radius, material, radialSegments = 7) {
const direction = new THREE.Vector3().subVectors(b, a);
const length = direction.length();
const mesh = new THREE.Mesh(
new THREE.CylinderGeometry(radius * 0.72, radius, length, radialSegments),
material
);
mesh.position.copy(a).add(b).multiplyScalar(0.5);
mesh.quaternion.setFromUnitVectors(
new THREE.Vector3(0, 1, 0),
direction.normalize()
);
mesh.castShadow = true;
scene.add(mesh);
return mesh;
}
// -----------------------------------------------------------------------
// Low-poly cutaway soil block
// -----------------------------------------------------------------------
const ground = new THREE.Mesh(
new THREE.PlaneGeometry(70, 70),
standard(0xdbe6d8)
);
ground.rotation.x = -Math.PI / 2;
ground.position.y = -4.74;
ground.receiveShadow = true;
scene.add(ground);
// Rear and side walls form a block, while the front remains open.
box(12.2, 5.1, 0.55, soilMat, 0, -2.05, -2.82);
box(0.48, 5.1, 5.4, soilDarkMat, -6.05, -2.05, -0.35);
box(0.48, 5.1, 5.4, soilDarkMat, 6.05, -2.05, -0.35);
box(12.5, 0.48, 5.7, soilDarkMat, 0, -4.55, -0.25);
// Soil layers on the rear cut face.
box(12.0, 0.72, 0.08, standard(0x8b6741), 0, -0.85, -2.50);
box(12.0, 1.05, 0.08, standard(0x765237), 0, -2.05, -2.49);
box(12.0, 1.28, 0.08, standard(0x5d4934), 0, -3.58, -2.48);
// Thin surface lips; the center remains open for the roots.
box(12.2, 0.34, 0.72, soilTopMat, 0, 0.43, -2.45);
box(0.62, 0.34, 5.0, soilTopMat, -5.75, 0.43, -0.32);
box(0.62, 0.34, 5.0, soilTopMat, 5.75, 0.43, -0.32);
// Deterministic low-poly soil particles behind the visible root plane.
let seed = 9137;
function random() {
seed = (seed * 16807) % 2147483647;
return (seed - 1) / 2147483646;
}
const particleGeo = new THREE.IcosahedronGeometry(0.09, 0);
const particleMats = [
standard(0x5e442f),
standard(0x896540),
standard(0x735137),
standard(0x9a7448)
];
for (let i = 0; i < 95; i++) {
const particle = new THREE.Mesh(
particleGeo,
particleMats[i % particleMats.length]
);
particle.position.set(
-5.7 + random() * 11.4,
-4.25 + random() * 4.5,
-2.35 + random() * 2.45
);
const scale = 0.65 + random() * 1.25;
particle.scale.setScalar(scale);
particle.rotation.set(random() * 3, random() * 3, random() * 3);
particle.castShadow = true;
scene.add(particle);
}
// -----------------------------------------------------------------------
// Plants and visible roots
// -----------------------------------------------------------------------
function addPlant(x, plantIndex) {
const z = 1.25 + (plantIndex === 1 ? 0.22 : 0);
const stemTop = 2.75 + (plantIndex === 1 ? 0.35 : 0);
cylinderBetween(
new THREE.Vector3(x, 0.45, z),
new THREE.Vector3(x + 0.08, stemTop, z),
0.095,
stemMat,
7
);
const leafGeo = new THREE.IcosahedronGeometry(0.58, 0);
for (let i = 0; i < 7; i++) {
const leaf = new THREE.Mesh(leafGeo, leafMats[(i + plantIndex) % leafMats.length]);
const side = i % 2 === 0 ? 1 : -1;
const height = 1.05 + i * 0.27;
leaf.position.set(
x + side * (0.42 + (i % 3) * 0.08),
height,
z + (i % 3 - 1) * 0.09
);
leaf.scale.set(1.45, 0.43, 0.72);
leaf.rotation.z = side * (0.42 + i * 0.035);
leaf.rotation.y = (i - 3) * 0.22;
leaf.castShadow = true;
scene.add(leaf);
}
const mainRoot = [
new THREE.Vector3(x, 0.40, z),
new THREE.Vector3(x - 0.06, -0.95, z + 0.08),
new THREE.Vector3(x + 0.10, -2.25, z + 0.10),
new THREE.Vector3(x - 0.08, -3.45, z + 0.03),
new THREE.Vector3(x + 0.06, -4.33, z)
];
for (let i = 0; i < mainRoot.length - 1; i++) {
cylinderBetween(mainRoot[i], mainRoot[i + 1], 0.105 - i * 0.014, rootMat, 6);
}
const branchData = [
[-0.85, -1.15, 0.12, -1.75, 0.25],
[0.88, -1.42, 0.05, -2.15, 0.20],
[-1.05, -2.35, -0.05, -3.05, 0.12],
[0.95, -2.72, 0.00, -3.45, 0.18],
[-0.72, -3.30, -0.02, -4.12, 0.06]
];
branchData.forEach((b, i) => {
const start = new THREE.Vector3(
x + b[0] * 0.15,
b[1],
z + b[2]
);
const end = new THREE.Vector3(
x + b[0],
b[3],
z + b[4]
);
const mid = new THREE.Vector3(
x + b[0] * 0.62,
b[1] - 0.35,
z + b[4] * 0.45
);
cylinderBetween(start, mid, 0.055, rootMat, 6);
cylinderBetween(mid, end, 0.035, rootMat, 6);
const nodule = new THREE.Mesh(
new THREE.IcosahedronGeometry(0.16 + (i % 2) * 0.035, 0),
noduleMat
);
nodule.position.copy(mid).lerp(end, 0.55);
nodule.scale.set(1, 0.82, 1.15);
nodule.castShadow = true;
scene.add(nodule);
});
}
addPlant(-3.55, 0);
addPlant(0, 1);
addPlant(3.55, 2);
// -----------------------------------------------------------------------
// Named reservoirs and graph nodes
// -----------------------------------------------------------------------
const nodePositions = {
ATM: new THREE.Vector3(-7.45, 2.25, 0.45),
NOD: new THREE.Vector3(0, -0.72, 1.78),
SOL: new THREE.Vector3(0, -1.90, 1.92),
ORG: new THREE.Vector3(-4.05, -2.82, 0.82),
PLANT: new THREE.Vector3(0, 2.78, 0.75),
OUT_LEACH: new THREE.Vector3(7.45, -3.05, 1.00),
OUT_GAS: new THREE.Vector3(7.45, -0.50, -0.82)
};
const nodeNames = {
ATM: "Atmospheric N₂ input",
NOD: "Root nodule fixation",
SOL: "Soil solution N",
ORG: "Soil organic N",
PLANT: "Plant tissue N",
OUT_LEACH: "Nitrate leaching output",
OUT_GAS: "Denitrification N₂ output"
};
function reservoirShell(position, color, width = 1.8, height = 1.7) {
const group = new THREE.Group();
group.position.copy(position);
const shellMat = new THREE.MeshStandardMaterial({
color,
transparent: true,
opacity: 0.18,
roughness: 0.55,
depthWrite: false
});
const shell = new THREE.Mesh(
new THREE.BoxGeometry(width, height, 1.35),
shellMat
);
shell.castShadow = true;
group.add(shell);
const edges = new THREE.LineSegments(
new THREE.EdgesGeometry(shell.geometry),
new THREE.LineBasicMaterial({
color,
transparent: true,
opacity: 0.85
})
);
group.add(edges);
scene.add(group);
return group;
}
const atmTank = reservoirShell(nodePositions.ATM, 0x4d9fc5, 2.05, 1.75);
const leachTank = reservoirShell(nodePositions.OUT_LEACH, 0xd99136, 1.85, 1.55);
const gasTank = reservoirShell(nodePositions.OUT_GAS, 0xd99136, 1.85, 1.55);
function addTankMolecules(tank, color, count) {
for (let i = 0; i < count; i++) {
const molecule = new THREE.Mesh(
new THREE.IcosahedronGeometry(0.105, 0),
standard(color, { emissive: color, emissiveIntensity: 0.18 })
);
molecule.position.set(
-0.52 + (i % 3) * 0.52,
-0.42 + Math.floor(i / 3) * 0.56,
(i % 2) * 0.42 - 0.2
);
tank.add(molecule);
}
}
addTankMolecules(atmTank, 0x7cc7e3, 6);
addTankMolecules(leachTank, 0xe9b35f, 5);
addTankMolecules(gasTank, 0xe9b35f, 4);
const soilSolutionNode = new THREE.Mesh(
new THREE.IcosahedronGeometry(0.48, 1),
standard(0x65c8cc, {
transparent: true,
opacity: 0.62,
emissive: 0x255f62,
emissiveIntensity: 0.28,
depthWrite: false
})
);
soilSolutionNode.position.copy(nodePositions.SOL);
scene.add(soilSolutionNode);
const organicNode = new THREE.Mesh(
new THREE.DodecahedronGeometry(0.58, 0),
standard(0x9c713e)
);
organicNode.position.copy(nodePositions.ORG);
organicNode.scale.set(1.2, 0.8, 1);
organicNode.castShadow = true;
scene.add(organicNode);
const plantNode = new THREE.Mesh(
new THREE.IcosahedronGeometry(0.43, 0),
standard(0x79c75d, {
emissive: 0x2f6e31,
emissiveIntensity: 0.25
})
);
plantNode.position.copy(nodePositions.PLANT);
scene.add(plantNode);
const noduleNode = new THREE.Mesh(
new THREE.IcosahedronGeometry(0.39, 0),
standard(0xef7869, {
emissive: 0x8a2922,
emissiveIntensity: 0.25
})
);
noduleNode.position.copy(nodePositions.NOD);
scene.add(noduleNode);
// -----------------------------------------------------------------------
// Scene labels made with canvas textures
// -----------------------------------------------------------------------
function roundedRect(ctx, x, y, w, h, r) {
ctx.beginPath();
ctx.moveTo(x + r, y);
ctx.lineTo(x + w - r, y);
ctx.quadraticCurveTo(x + w, y, x + w, y + r);
ctx.lineTo(x + w, y + h - r);
ctx.quadraticCurveTo(x + w, y + h, x + w - r, y + h);
ctx.lineTo(x + r, y + h);
ctx.quadraticCurveTo(x, y + h, x, y + h - r);
ctx.lineTo(x, y + r);
ctx.quadraticCurveTo(x, y, x + r, y);
ctx.closePath();
}
function addLabel(title, subtitle, color, position, width = 3.55) {
const canvas = document.createElement("canvas");
canvas.width = 768;
canvas.height = 180;
const ctx = canvas.getContext("2d");
ctx.clearRect(0, 0, canvas.width, canvas.height);
roundedRect(ctx, 8, 8, 752, 164, 22);
ctx.fillStyle = "rgba(255,255,255,0.94)";
ctx.fill();
ctx.strokeStyle = "rgba(74,95,80,0.18)";
ctx.lineWidth = 3;
ctx.stroke();
ctx.fillStyle = color;
roundedRect(ctx, 24, 25, 11, 130, 5);
ctx.fill();
let titleSize = 42;
ctx.font = `800 ${titleSize}px system-ui`;
while (ctx.measureText(title).width > 700 && titleSize > 27) {
titleSize -= 1;
ctx.font = `800 ${titleSize}px system-ui`;
}
ctx.fillStyle = "#1c3025";
ctx.fillText(title, 54, 79);
ctx.font = "500 27px system-ui";
ctx.fillStyle = "#607068";
ctx.fillText(subtitle, 54, 127);
const texture = new THREE.CanvasTexture(canvas);
texture.colorSpace = THREE.SRGBColorSpace;
texture.minFilter = THREE.LinearFilter;
const sprite = new THREE.Sprite(
new THREE.SpriteMaterial({
map: texture,
transparent: true,
depthTest: false,
depthWrite: false
})
);
sprite.position.copy(position);
sprite.scale.set(width, width * 180 / 768, 1);
sprite.renderOrder = 20;
scene.add(sprite);
return sprite;
}
addLabel(
"INPUT · Atmospheric N₂",
"External nitrogen-fixation source",
"#4d9fc5",
new THREE.Vector3(-7.45, 3.78, 0.45),
3.85
);
addLabel(
"Root nodule fixation",
"Schematic rhizobial partnership",
"#d66a75",
new THREE.Vector3(0, -0.20, 2.02),
3.65
);
addLabel(
"Soil solution N",
"NO₃⁻ available to roots",
"#4d9fc5",
new THREE.Vector3(-0.95, -2.27, 2.02),
3.15
);
addLabel(
"Soil organic N",
"Residue and microbial pool",
"#a7783c",
new THREE.Vector3(-4.12, -3.86, 0.82),
3.25
);
addLabel(
"Plant tissue N",
"Assimilated crop nitrogen",
"#4f914e",
new THREE.Vector3(0, 3.78, 0.75),
3.25
);
addLabel(
"OUTPUT · Nitrate leaching",
"Boundary loss reservoir",
"#d99136",
new THREE.Vector3(7.45, -4.25, 1.00),
3.55
);
addLabel(
"OUTPUT · Denitrification N₂",
"Boundary loss reservoir",
"#d99136",
new THREE.Vector3(7.45, 0.48, -0.82),
3.65
);
// -----------------------------------------------------------------------
// Permitted transfer graph
// -----------------------------------------------------------------------
const edgeDefinitions = {
"ATM>NOD": {
color: 0x4d9fc5,
points: [
nodePositions.ATM,
new THREE.Vector3(-5.4, 2.7, 1.15),
new THREE.Vector3(-2.8, 0.5, 1.75),
nodePositions.NOD
]
},
"NOD>SOL": {
color: 0x69b97e,
points: [
nodePositions.NOD,
new THREE.Vector3(-0.75, -1.28, 2.0),
nodePositions.SOL
]
},
"SOL>PLANT": {
color: 0x69b97e,
points: [
nodePositions.SOL,
new THREE.Vector3(0, -0.25, 2.03),
new THREE.Vector3(0, 1.65, 1.28),
nodePositions.PLANT
]
},
"PLANT>ORG": {
color: 0xa7783c,
points: [
nodePositions.PLANT,
new THREE.Vector3(-1.7, 1.25, 1.38),
new THREE.Vector3(-3.25, -1.25, 1.12),
nodePositions.ORG
]
},
"ORG>SOL": {
color: 0xa7783c,
points: [
nodePositions.ORG,
new THREE.Vector3(-2.45, -3.02, 1.42),
nodePositions.SOL
]
},
"SOL>OUT_LEACH": {
color: 0xd99136,
points: [
nodePositions.SOL,
new THREE.Vector3(2.6, -2.55, 1.82),
new THREE.Vector3(5.55, -3.20, 1.35),
nodePositions.OUT_LEACH
]
},
"SOL>OUT_GAS": {
color: 0xd99136,
points: [
nodePositions.SOL,
new THREE.Vector3(2.7, -1.02, 0.65),
new THREE.Vector3(5.5, -0.55, -0.65),
nodePositions.OUT_GAS
]
}
};
const edgeCurves = {};
for (const [key, definition] of Object.entries(edgeDefinitions)) {
const curve = new THREE.CatmullRomCurve3(
definition.points,
false,
"centripetal",
0.45
);
edgeCurves[key] = curve;
const geometry = new THREE.BufferGeometry().setFromPoints(curve.getPoints(80));
const material = new THREE.LineDashedMaterial({
color: definition.color,
transparent: true,
opacity: 0.72,
dashSize: 0.22,
gapSize: 0.13,
depthWrite: false
});
const line = new THREE.Line(geometry, material);
line.computeLineDistances();
line.renderOrder = 2;
scene.add(line);
const arrow = new THREE.Mesh(
new THREE.ConeGeometry(0.13, 0.42, 6),
new THREE.MeshBasicMaterial({
color: definition.color,
transparent: true,
opacity: 0.9
})
);
arrow.position.copy(curve.getPoint(0.78));
arrow.quaternion.setFromUnitVectors(
new THREE.Vector3(0, 1, 0),
curve.getTangent(0.78).normalize()
);
arrow.renderOrder = 3;
scene.add(arrow);
}
// -----------------------------------------------------------------------
// Persistent token ledger
// -----------------------------------------------------------------------
const scenarios = {
balanced: {
name: "Reference mixing",
detail: "Fixation → uptake → residue return → soil solution → nitrate leaching.",
count: 4,
durationScale: 1.0,
route: ["ATM", "NOD", "SOL", "PLANT", "ORG", "SOL", "OUT_LEACH"]
},
dry: {
name: "Dry-soil shortcut",
detail: "Lower-uptake route ending in the nitrate-leaching output reservoir.",
count: 5,
durationScale: 1.35,
route: ["ATM", "NOD", "SOL", "OUT_LEACH"]
},
warm: {
name: "Warm pulse",
detail: "Faster cycling followed by the schematic denitrification output.",
count: 4,
durationScale: 0.72,
route: ["ATM", "NOD", "SOL", "PLANT", "ORG", "SOL", "OUT_GAS"]
}
};
const tokens = [];
const tokenCores = [];
const ledger = [];
const pendingStarts = [];
const settledOffsets = {};
let ledgerSequence = 0;
let tokenSequence = 0;
let simulationTime = 0;
let running = true;
let activeScenarioKey = null;
let selectedToken = null;
const edgeTimes = {
"ATM>NOD": 1.7,
"NOD>SOL": 1.15,
"SOL>PLANT": 1.45,
"PLANT>ORG": 1.70,
"ORG>SOL": 1.35,
"SOL>OUT_LEACH": 1.55,
"SOL>OUT_GAS": 1.55
};
function recordTransfer(token, from, to, kind) {
const entry = {
sequence: ++ledgerSequence,
time: simulationTime,
tokenId: token.id,
from,
to,
kind,
scenario: token.scenarioName
};
// The ledger entry is created before the token is made visible.
ledger.push(entry);
token.history.push(entry.sequence);
renderLedger();
return entry;
}
function transferKind(from, to, routeIndex) {
if (routeIndex === 0) return "boundary-input";
if (to.startsWith("OUT_")) return "boundary-output";
return "internal";
}
function startLeg(token) {
const from = token.route[token.routeIndex];
const to = token.route[token.routeIndex + 1];
const key = `${from}>${to}`;
const curve = edgeCurves[key];
if (!curve) {
throw new Error(`No permitted transfer path for ${key}`);
}
if (token.routeIndex > 0) {
recordTransfer(
token,
from,
to,
transferKind(from, to, token.routeIndex)
);
}
token.destination = to;
token.leg = {
curve,
elapsed: 0,
duration: edgeTimes[key] * token.durationScale
};
token.state = "moving";
}
function spawnToken(scenario, batchIndex) {
const id = `N-${String(++tokenSequence).padStart(3, "0")}`;
const coreMaterial = standard(0xd6ff72, {
emissive: 0x76e68a,
emissiveIntensity: 0.82,
roughness: 0.3
});
const group = new THREE.Group();
const core = new THREE.Mesh(
new THREE.IcosahedronGeometry(0.18, 1),
coreMaterial
);
core.castShadow = true;
group.add(core);
const halo = new THREE.Mesh(
new THREE.SphereGeometry(0.255, 12, 8),
new THREE.MeshBasicMaterial({
color: 0xffffff,
wireframe: true,
transparent: true,
opacity: 0.9,
depthTest: false,
depthWrite: false
})
);
halo.visible = false;
halo.renderOrder = 12;
group.add(halo);
const token = {
id,
group,
core,
halo,
route: [...scenario.route],
routeIndex: 0,
currentNode: "ATM",
destination: scenario.route[1],
state: "moving",
leg: null,
dwell: 0,
history: [],
scenarioName: scenario.name,
scenarioKey: activeScenarioKey,
durationScale: scenario.durationScale,
batchIndex
};
core.userData.token = token;
tokens.push(token);
tokenCores.push(core);
// Boundary-input record precedes visual creation.
recordTransfer(
token,
token.route[0],
token.route[1],
"boundary-input"
);
group.position.copy(nodePositions.ATM);
scene.add(group);
startLeg(token);
updateAccounting();
}
function settleToken(token) {
const node = token.currentNode;
const count = settledOffsets[node] || 0;
settledOffsets[node] = count + 1;
const angle = count * 2.399963;
const radius = node.startsWith("OUT_") ? 0.42 : 0.24;
token.group.position.copy(nodePositions[node]);
token.group.position.x += Math.cos(angle) * radius;
token.group.position.y += Math.sin(angle) * radius * 0.72;
token.group.position.z += ((count % 3) - 1) * 0.16;
}
function updateTokens(dt) {
for (const token of tokens) {
if (token.state === "moving") {
token.leg.elapsed += dt;
const t = Math.min(1, token.leg.elapsed / token.leg.duration);
token.group.position.copy(token.leg.curve.getPoint(t));
if (t >= 1) {
token.currentNode = token.destination;
token.routeIndex += 1;
if (token.routeIndex >= token.route.length - 1) {
token.state = "settled";
settleToken(token);
} else {
token.state = "dwell";
token.dwell = 0.28;
}
}
} else if (token.state === "dwell") {
token.dwell -= dt;
if (token.dwell <= 0) {
startLeg(token);
}
}
}
}
function updatePendingStarts() {
while (pendingStarts.length && pendingStarts[0].at <= simulationTime) {
const pending = pendingStarts.shift();
spawnToken(pending.scenario, pending.batchIndex);
}
}
function runScenario(key) {
const scenario = scenarios[key];
if (!scenario) return;
activeScenarioKey = key;
document.querySelectorAll(".scenario").forEach((button) => {
const active = button.dataset.scenario === key;
button.classList.toggle("active", active);
button.setAttribute("aria-pressed", String(active));
});
$("#scenarioStatus").textContent = scenario.name;
$("#scenarioStatusDetail").textContent =
`${scenario.count} synthetic packets · ${scenario.durationScale.toFixed(2)}× display pace`;
// The first packet begins immediately. Later packets are staggered.
spawnToken(scenario, 0);
for (let i = 1; i < scenario.count; i++) {
pendingStarts.push({
at: simulationTime + i * 0.42,
scenario,
batchIndex: i
});
}
updateAccounting();
}
// -----------------------------------------------------------------------
// Interface rendering
// -----------------------------------------------------------------------
function kindLabel(kind) {
if (kind === "boundary-input") return "boundary input";
if (kind === "boundary-output") return "boundary output";
return "internal";
}
function updateAccounting() {
const inputRecords = ledger.filter((entry) => entry.kind === "boundary-input");
const outputRecords = ledger.filter((entry) => entry.kind === "boundary-output");
const inFlight = tokens.filter(
(token) => token.state === "moving" || token.state === "dwell"
).length;
const uniqueIDs = new Set(tokens.map((token) => token.id)).size === tokens.length;
const allHaveInput = tokens.every((token) =>
token.history.some((sequence) =>
ledger.find((entry) => entry.sequence === sequence)?.kind === "boundary-input"
)
);
$("#tokenCount").textContent = tokens.length;
$("#inputCount").textContent = inputRecords.length;
$("#outputCount").textContent = outputRecords.length;
$("#inFlightCount").textContent = inFlight;
const pass = uniqueIDs && allHaveInput && inputRecords.length === tokens.length;
$("#invariantStatus").innerHTML = pass
? `<strong>PASS · ${tokens.length}/${tokens.length} identities accounted for.</strong><br>
Every token has one recorded boundary input. There are 0 token deletions;
output tokens remain in their named reservoirs.`
: `<strong>CHECK FAILED</strong><br>
A token identity lacks a corresponding recorded boundary input.`;
$("#ledgerCount").textContent =
`${ledger.length} record${ledger.length === 1 ? "" : "s"}`;
}
function renderLedger() {
const list = $("#ledgerList");
const newest = ledger.slice().reverse().slice(0, 120);
list.innerHTML = newest.map((entry) => `
<button
class="ledger-row ${selectedToken?.id === entry.tokenId ? "selected" : ""}"
data-token="${entry.tokenId}"
type="button"
>
<span class="ledger-seq">#${String(entry.sequence).padStart(3, "0")}</span>
<span class="ledger-main">
<span class="ledger-route">
${entry.tokenId} · ${entry.from} → ${entry.to}
</span>
<span class="ledger-meta">
<span class="kind ${entry.kind}">${kindLabel(entry.kind)}</span>
<span>${entry.scenario}</span>
<span>· ${entry.time.toFixed(1)} s</span>
</span>
</span>
</button>
`).join("");
if (ledger.length > 120) {
list.insertAdjacentHTML(
"beforeend",
`<div style="padding:8px;color:#6c7971;font-size:9px;text-align:center">
Showing newest 120 of ${ledger.length} records; all ${ledger.length} remain in memory.
</div>`
);
}
updateAccounting();
}
function renderInspector() {
const container = $("#tokenInspector");
if (!selectedToken) {
container.innerHTML = `
<div class="token-id">
<strong>No token selected</strong>
<span>Persistent identity</span>
</div>
<p class="small-note" style="margin:0">
Click a glowing token in the model to see its current reservoir,
route, and complete recorded history.
</p>`;
return;
}
const token = selectedToken;
const location = token.state === "moving"
? `In transfer: ${token.currentNode} → ${token.destination}`
: nodeNames[token.currentNode];
const routeText = token.route
.map((node, index) =>
index <= token.routeIndex
? `<strong>${node}</strong>`
: node
)
.join(" → ");
const history = ledger.filter((entry) => entry.tokenId === token.id);
container.innerHTML = `
<div class="token-id">
<strong>${token.id}</strong>
<span>${token.state.toUpperCase()}</span>
</div>
<div class="inspector-row">
<span>Current place</span><span>${location}</span>
</div>
<div class="inspector-row">
<span>Scenario</span><span>${token.scenarioName}</span>
</div>
<div class="inspector-row">
<span>Transfers</span><span>${history.length} recorded events</span>
</div>
<div class="route-line">
<strong>Permitted itinerary</strong><br>
${routeText}
</div>
<div class="history-title">Recorded history</div>
${history.map((entry) => `
<div class="history-row">
<strong>#${String(entry.sequence).padStart(3, "0")}</strong>
${entry.from} → ${entry.to}
<span style="color:#728078"> · ${kindLabel(entry.kind)}</span>
</div>
`).join("")}
`;
}
function selectToken(token) {
if (selectedToken) {
selectedToken.halo.visible = false;
selectedToken.core.scale.setScalar(1);
selectedToken.core.material.emissiveIntensity = 0.82;
}
selectedToken = token;
if (token) {
token.halo.visible = true;
token.core.scale.setScalar(1.32);
token.core.material.emissiveIntensity = 1.25;
}
renderInspector();
renderLedger();
}
// -----------------------------------------------------------------------
// Direct camera controls, implemented without Three.js addons
// -----------------------------------------------------------------------
const cameraState = {
target: new THREE.Vector3(0, -0.65, 0),
radius: 23.5,
theta: 0.64,
phi: 1.13
};
const cameraHome = { ...cameraState, target: cameraState.target.clone() };
function updateCamera() {
const offset = new THREE.Vector3().setFromSphericalCoords(
cameraState.radius,
cameraState.phi,
cameraState.theta
);
camera.position.copy(cameraState.target).add(offset);
camera.lookAt(cameraState.target);
}
function resetCamera() {
cameraState.target.copy(cameraHome.target);
cameraState.radius = cameraHome.radius;
cameraState.theta = cameraHome.theta;
cameraState.phi = cameraHome.phi;
}
let pointerDown = false;
let pointerMoved = false;
let pointerButton = 0;
let panMode = false;
let lastPointerX = 0;
let lastPointerY = 0;
const raycaster = new THREE.Raycaster();
const pointerNDC = new THREE.Vector2();
function tokenUnderPointer(event) {
const rect = renderer.domElement.getBoundingClientRect();
pointerNDC.x = ((event.clientX - rect.left) / rect.width) * 2 - 1;
pointerNDC.y = -((event.clientY - rect.top) / rect.height) * 2 + 1;
raycaster.setFromCamera(pointerNDC, camera);
const intersections = raycaster.intersectObjects(tokenCores, false);
return intersections.length ? intersections[0].object.userData.token : null;
}
renderer.domElement.addEventListener("pointerdown", (event) => {
if (event.button !== 0 && event.button !== 2) return;
pointerDown = true;
pointerMoved = false;
pointerButton = event.button;
panMode = event.shiftKey || event.button === 2;
lastPointerX = event.clientX;
lastPointerY = event.clientY;
renderer.domElement.setPointerCapture(event.pointerId);
});
renderer.domElement.addEventListener("pointermove", (event) => {
if (pointerDown) {
const dx = event.clientX - lastPointerX;
const dy = event.clientY - lastPointerY;
lastPointerX = event.clientX;
lastPointerY = event.clientY;
if (Math.abs(dx) + Math.abs(dy) > 1) pointerMoved = true;
if (panMode) {
const right = new THREE.Vector3().setFromMatrixColumn(camera.matrix, 0);
const up = new THREE.Vector3().setFromMatrixColumn(camera.matrix, 1);
const scale = cameraState.radius * 0.00125;
cameraState.target
.addScaledVector(right, -dx * scale)
.addScaledVector(up, dy * scale);
} else {
cameraState.theta -= dx * 0.006;
cameraState.phi = THREE.MathUtils.clamp(
cameraState.phi - dy * 0.005,
0.22,
1.48
);
}
} else {
const token = tokenUnderPointer(event);
const tooltip = $("#tokenTooltip");
if (token) {
const rect = viewport.getBoundingClientRect();
tooltip.style.display = "block";
tooltip.style.left = `${event.clientX - rect.left + 12}px`;
tooltip.style.top = `${event.clientY - rect.top + 12}px`;
tooltip.textContent = `${token.id} · ${nodeNames[token.currentNode]}`;
renderer.domElement.style.cursor = "pointer";
} else {
tooltip.style.display = "none";
renderer.domElement.style.cursor = "grab";
}
}
});
renderer.domElement.addEventListener("pointerup", (event) => {
if (pointerDown && !pointerMoved && pointerButton === 0) {
selectToken(tokenUnderPointer(event));
}
pointerDown = false;
panMode = false;
$("#tokenTooltip").style.display = "none";
if (renderer.domElement.hasPointerCapture(event.pointerId)) {
renderer.domElement.releasePointerCapture(event.pointerId);
}
});
renderer.domElement.addEventListener("pointercancel", () => {
pointerDown = false;
panMode = false;
});
renderer.domElement.addEventListener("pointerleave", () => {
if (!pointerDown) $("#tokenTooltip").style.display = "none";
});
renderer.domElement.addEventListener("wheel", (event) => {
event.preventDefault();
cameraState.radius = THREE.MathUtils.clamp(
cameraState.radius * Math.exp(event.deltaY * 0.001),
11,
36
);
}, { passive: false });
renderer.domElement.addEventListener("contextmenu", (event) => {
event.preventDefault();
});
// -----------------------------------------------------------------------
// UI events
// -----------------------------------------------------------------------
document.querySelectorAll(".scenario").forEach((button) => {
button.addEventListener("click", () => {
runScenario(button.dataset.scenario);
});
});
$("#pauseButton").addEventListener("click", () => {
running = !running;
$("#pauseButton").textContent = running ? "Pause" : "Resume";
$("#scenarioStatusDetail").textContent = running
? `${scenarios[activeScenarioKey].count} synthetic packets · ${scenarios[activeScenarioKey].durationScale.toFixed(2)}× display pace`
: "Animation paused; ledger and identities remain intact";
});
$("#resetCameraButton").addEventListener("click", resetCamera);
$("#ledgerList").addEventListener("click", (event) => {
const row = event.target.closest("[data-token]");
if (!row) return;
const token = tokens.find((item) => item.id === row.dataset.token);
if (token) selectToken(token);
});
window.addEventListener("keydown", (event) => {
if (event.code === "Space" && event.target === document.body) {
event.preventDefault();
$("#pauseButton").click();
}
if (event.key.toLowerCase() === "r" && event.target === document.body) {
resetCamera();
}
});
// -----------------------------------------------------------------------
// Resize and animation loop
// -----------------------------------------------------------------------
function resize() {
const width = Math.max(1, viewport.clientWidth);
const height = Math.max(1, viewport.clientHeight);
renderer.setSize(width, height, false);
camera.aspect = width / height;
camera.updateProjectionMatrix();
}
const resizeObserver = new ResizeObserver(resize);
resizeObserver.observe(viewport);
resize();
updateCamera();
// Load one initial synthetic batch after the ledger system is ready.
runScenario("balanced");
renderLedger();
renderInspector();
let previousTime = performance.now();
function animate(now) {
requestAnimationFrame(animate);
const dt = Math.max(0, Math.min(0.05, (now - previousTime) / 1000));
previousTime = now;
if (running) {
simulationTime += dt;
updatePendingStarts();
updateTokens(dt);
}
updateCamera();
renderer.render(scene, camera);
}
requestAnimationFrame(animate);
</script>
</body>
</html>
```