Prompt specification
Build or customize the Three.js 3D scene "Two-route ant foraging model" 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: Two-route ant foraging model
Category: Biology & Nature · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/two-route-ant-foraging-model-x0642
Scene Description Prompt:
Build a self-contained HTML scene with Three.js from cdnjs featuring ant foraging trails. Animate ants choosing between two food routes under an explicit toy pheromone rule; successful return trips strengthen visible trail markers while unused markers fade. Low-poly.
Working Three.js Starter (two-route-ant-foraging-model-x0642):
```html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Pheromone Trail — Ant Foraging Lab</title>
<style>
:root {
color-scheme: light;
--ink: #26352c;
--muted: #637268;
--paper: rgba(249, 247, 237, 0.92);
--line: rgba(48, 70, 54, 0.16);
--green: #476b50;
--amber: #dc8f16;
--upper: #729783;
--lower: #b27c59;
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: #dce6d4;
color: var(--ink);
font-family:
Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
#app {
position: fixed;
inset: 0;
}
canvas {
display: block;
width: 100%;
height: 100%;
touch-action: none;
cursor: grab;
}
canvas:active {
cursor: grabbing;
}
.panel {
position: fixed;
z-index: 10;
border: 1px solid var(--line);
border-radius: 16px;
background: var(--paper);
box-shadow: 0 14px 40px rgba(38, 54, 42, 0.12);
backdrop-filter: blur(14px);
-webkit-backdrop-filter: blur(14px);
}
.intro {
top: 18px;
left: 18px;
width: min(340px, calc(100vw - 36px));
padding: 18px 19px 17px;
}
.eyebrow {
margin-bottom: 6px;
color: var(--green);
font-size: 10px;
font-weight: 800;
letter-spacing: 0.18em;
text-transform: uppercase;
}
h1 {
margin: 0;
font-size: clamp(22px, 2.4vw, 31px);
line-height: 1.03;
letter-spacing: -0.04em;
}
.intro p {
margin: 10px 0 0;
color: var(--muted);
font-size: 12px;
line-height: 1.55;
}
.pill-row {
display: flex;
flex-wrap: wrap;
gap: 7px;
margin-top: 13px;
}
.pill {
padding: 6px 9px;
border: 1px solid rgba(71, 107, 80, 0.15);
border-radius: 999px;
background: rgba(255, 255, 255, 0.55);
color: #46604d;
font-size: 10px;
font-weight: 700;
letter-spacing: 0.02em;
}
.stats {
top: 18px;
right: 18px;
width: 220px;
padding: 13px;
}
.stat-grid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 8px;
}
.stat {
min-height: 62px;
padding: 10px;
border: 1px solid rgba(54, 79, 60, 0.1);
border-radius: 11px;
background: rgba(255, 255, 255, 0.52);
}
.stat-label {
display: block;
margin-bottom: 5px;
color: var(--muted);
font-size: 9px;
font-weight: 750;
letter-spacing: 0.09em;
text-transform: uppercase;
}
.stat-value {
display: block;
font-size: 20px;
font-weight: 800;
letter-spacing: -0.035em;
}
.stat small {
display: block;
margin-top: 2px;
color: var(--muted);
font-size: 9px;
}
.route-meter {
margin-top: 11px;
}
.meter-label {
display: flex;
justify-content: space-between;
margin-bottom: 6px;
color: var(--muted);
font-size: 9px;
font-weight: 750;
letter-spacing: 0.05em;
text-transform: uppercase;
}
.meter-track {
display: flex;
height: 7px;
overflow: hidden;
border-radius: 999px;
background: #e3e5db;
}
.meter-upper {
width: 50%;
background: var(--upper);
transition: width 180ms ease-out;
}
.meter-lower {
width: 50%;
background: var(--lower);
transition: width 180ms ease-out;
}
.rule {
bottom: 18px;
left: 18px;
width: min(440px, calc(100vw - 36px));
padding: 16px 18px;
}
.rule h2 {
margin: 0 0 9px;
font-size: 13px;
letter-spacing: -0.01em;
}
.formula {
margin: 8px 0;
padding: 10px 11px;
border-radius: 10px;
background: rgba(71, 107, 80, 0.075);
color: #354c3c;
font-family: "SFMono-Regular", Consolas, "Liberation Mono", monospace;
font-size: 11px;
line-height: 1.55;
}
.rule p {
margin: 6px 0 0;
color: var(--muted);
font-size: 10px;
line-height: 1.55;
}
.legend {
display: flex;
gap: 13px;
margin-top: 11px;
color: var(--muted);
font-size: 10px;
}
.legend-item {
display: flex;
align-items: center;
gap: 6px;
}
.swatch {
width: 9px;
height: 9px;
border-radius: 50%;
background: var(--upper);
}
.swatch.lower {
background: var(--lower);
}
.swatch.pheromone {
border-radius: 2px;
background: #f2a51c;
transform: rotate(45deg);
}
.controls {
right: 18px;
bottom: 18px;
width: 250px;
padding: 14px;
}
.button-row {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 8px;
}
button {
min-height: 37px;
border: 1px solid rgba(49, 78, 57, 0.15);
border-radius: 10px;
background: #fffef8;
color: var(--ink);
font: inherit;
font-size: 10px;
font-weight: 750;
cursor: pointer;
transition:
transform 120ms ease,
background 120ms ease;
}
button:hover {
transform: translateY(-1px);
background: #f2f4e9;
}
button.primary {
border-color: transparent;
background: var(--green);
color: white;
}
button.primary:hover {
background: #3b5e44;
}
.slider-label {
display: flex;
justify-content: space-between;
margin: 13px 0 6px;
color: var(--muted);
font-size: 9px;
font-weight: 750;
letter-spacing: 0.06em;
text-transform: uppercase;
}
input[type="range"] {
width: 100%;
accent-color: var(--green);
cursor: pointer;
}
.hint {
position: fixed;
z-index: 8;
right: 288px;
bottom: 23px;
color: rgba(38, 53, 44, 0.62);
font-size: 10px;
font-weight: 650;
pointer-events: none;
}
@media (max-width: 760px) {
.intro {
top: 10px;
left: 10px;
width: calc(100vw - 20px);
padding: 13px 15px;
}
.intro p {
display: none;
}
.pill-row {
margin-top: 9px;
}
.stats {
top: 125px;
right: 10px;
width: 180px;
padding: 9px;
}
.stat {
min-height: 51px;
padding: 8px;
}
.stat-value {
font-size: 16px;
}
.rule {
left: 10px;
bottom: 10px;
width: calc(100vw - 20px);
padding: 12px 14px;
}
.rule h2 {
margin-bottom: 5px;
}
.rule p,
.legend {
display: none;
}
.formula {
margin: 6px 0 0;
padding: 8px;
font-size: 9px;
}
.controls {
right: 10px;
bottom: 153px;
width: 180px;
padding: 10px;
}
.hint {
display: none;
}
}
</style>
</head>
<body>
<div id="app"></div>
<section class="panel intro">
<div class="eyebrow">Ant foraging laboratory</div>
<h1>Pheromone Trail</h1>
<p>
Watch a colony discover two routes to the same food source. Ants choose
a branch from route-level pheromone, then reinforce only the route they
successfully carry food back along.
</p>
<div class="pill-row">
<span class="pill">42 foragers</span>
<span class="pill">2 routes</span>
<span class="pill">Live pheromone</span>
</div>
</section>
<section class="panel stats">
<div class="stat-grid">
<div class="stat">
<span class="stat-label">Returns</span>
<span class="stat-value" id="returnCount">0</span>
<small>successful trips</small>
</div>
<div class="stat">
<span class="stat-label">Next choice</span>
<span class="stat-value" id="choiceValue">50%</span>
<small>upper route</small>
</div>
<div class="stat">
<span class="stat-label">Trail A</span>
<span class="stat-value" id="trailAValue">0%</span>
<small>mean pheromone</small>
</div>
<div class="stat">
<span class="stat-label">Trail B</span>
<span class="stat-value" id="trailBValue">0%</span>
<small>mean pheromone</small>
</div>
</div>
<div class="route-meter">
<div class="meter-label">
<span>Route A</span>
<span>Route B</span>
</div>
<div class="meter-track">
<div class="meter-upper" id="upperMeter"></div>
<div class="meter-lower" id="lowerMeter"></div>
</div>
</div>
</section>
<section class="panel rule">
<h2>Explicit toy pheromone rule</h2>
<div class="formula">
qA = mean(pheromone on A)<br />
qB = mean(pheromone on B)<br />
P(A) = ε + (1−2ε)·e<sup>βqA</sup> /
(e<sup>βqA</sup> + e<sup>βqB</sup>)
</div>
<p>
At the fork, each ant samples this probability. After a complete return
to the nest, every segment of the chosen route gains
<strong>+0.27 pheromone</strong>. All segments decay continuously, so
unused trails become faint and disappear.
</p>
<div class="legend">
<span class="legend-item"><i class="swatch"></i>Route A</span>
<span class="legend-item"><i class="swatch lower"></i>Route B</span>
<span class="legend-item"><i class="swatch pheromone"></i>Pheromone</span>
</div>
</section>
<section class="panel controls">
<div class="button-row">
<button class="primary" id="pauseButton">Pause</button>
<button id="clearButton">Clear trails</button>
<button id="resetButton">Restart ants</button>
<button id="resetView">Reset view</button>
</div>
<label class="slider-label" for="decaySlider">
<span>Trail decay λ</span>
<span id="decayValue">0.018 / s</span>
</label>
<input
id="decaySlider"
type="range"
min="0"
max="0.050"
step="0.001"
value="0.018"
/>
</section>
<div class="hint">Drag to orbit · wheel/pinch to zoom · shift/right-drag to pan</div>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
// -------------------------------------------------------------------------
// Scene
// -------------------------------------------------------------------------
const app = document.querySelector("#app");
const renderer = new THREE.WebGLRenderer({
antialias: true,
alpha: false,
powerPreference: "high-performance"
});
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.05;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
app.appendChild(renderer.domElement);
const scene = new THREE.Scene();
scene.background = new THREE.Color(0xdce6d4);
scene.fog = new THREE.Fog(0xdce6d4, 30, 58);
const camera = new THREE.PerspectiveCamera(
42,
window.innerWidth / window.innerHeight,
0.1,
100
);
const cameraState = {
target: new THREE.Vector3(-0.2, 0, 0),
radius: window.innerWidth < 700 ? 30 : 25,
azimuth: 0.48,
elevation: 0.72
};
function updateCamera() {
const c = Math.cos(cameraState.elevation);
const s = Math.sin(cameraState.elevation);
camera.position.set(
cameraState.target.x +
cameraState.radius * c * Math.sin(cameraState.azimuth),
cameraState.target.y + cameraState.radius * s,
cameraState.target.z +
cameraState.radius * c * Math.cos(cameraState.azimuth)
);
camera.lookAt(cameraState.target);
}
updateCamera();
// -------------------------------------------------------------------------
// Lights and low-poly environment
// -------------------------------------------------------------------------
scene.add(new THREE.HemisphereLight(0xfff7dc, 0x49634d, 2.15));
const sun = new THREE.DirectionalLight(0xffedc7, 2.6);
sun.position.set(-9, 15, 8);
sun.castShadow = true;
sun.shadow.mapSize.set(2048, 2048);
sun.shadow.camera.left = -18;
sun.shadow.camera.right = 18;
sun.shadow.camera.top = 14;
sun.shadow.camera.bottom = -14;
sun.shadow.camera.near = 1;
sun.shadow.camera.far = 42;
sun.shadow.bias = -0.00035;
scene.add(sun);
const fill = new THREE.DirectionalLight(0xb7d2e4, 0.65);
fill.position.set(10, 8, -10);
scene.add(fill);
function mulberry32(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;
};
}
const decorRandom = mulberry32(24191);
const decorRange = (a, b) => a + (b - a) * decorRandom();
const groundGeometry = new THREE.PlaneGeometry(30, 20, 15, 10);
const groundPositions = groundGeometry.attributes.position;
const groundColors = [];
for (let i = 0; i < groundPositions.count; i++) {
const x = groundPositions.getX(i);
const y = groundPositions.getY(i);
const height =
0.025 +
0.025 * Math.sin(x * 1.35 + y * 0.7) +
0.018 * Math.cos(y * 1.8 - x * 0.35);
groundPositions.setZ(i, height);
const color = new THREE.Color();
color.setHSL(
0.245 + decorRandom() * 0.025,
0.20 + decorRandom() * 0.08,
0.69 + decorRandom() * 0.07
);
groundColors.push(color.r, color.g, color.b);
}
groundGeometry.setAttribute(
"color",
new THREE.Float32BufferAttribute(groundColors, 3)
);
groundGeometry.computeVertexNormals();
groundGeometry.rotateX(-Math.PI / 2);
const ground = new THREE.Mesh(
groundGeometry,
new THREE.MeshStandardMaterial({
vertexColors: true,
roughness: 0.96,
flatShading: true
})
);
ground.receiveShadow = true;
scene.add(ground);
const base = new THREE.Mesh(
new THREE.BoxGeometry(30.4, 0.46, 20.4),
new THREE.MeshStandardMaterial({
color: 0x71836d,
roughness: 1,
flatShading: true
})
);
base.position.y = -0.28;
base.receiveShadow = true;
scene.add(base);
const nodes = {
nest: new THREE.Vector3(-9.1, 0, 0),
fork: new THREE.Vector3(-5.4, 0, 0),
upperA: new THREE.Vector3(-2.5, 0, 4.35),
upperB: new THREE.Vector3(2.7, 0, 4.35),
food: new THREE.Vector3(8.25, 0, 0),
lowerA: new THREE.Vector3(-2.5, 0, -4.35),
lowerB: new THREE.Vector3(2.7, 0, -4.35)
};
const edgeDefinitions = {
stem: { a: "nest", b: "fork" },
upperA: { a: "fork", b: "upperA" },
upperB: { a: "upperA", b: "upperB" },
upperC: { a: "upperB", b: "food" },
lowerA: { a: "fork", b: "lowerA" },
lowerB: { a: "lowerA", b: "lowerB" },
lowerC: { a: "lowerB", b: "food" }
};
const routeEdges = {
upper: ["upperA", "upperB", "upperC"],
lower: ["lowerA", "lowerB", "lowerC"]
};
const edges = {};
for (const [id, definition] of Object.entries(edgeDefinitions)) {
const a = nodes[definition.a];
const b = nodes[definition.b];
const delta = new THREE.Vector3().subVectors(b, a);
const length = delta.length();
const direction = delta.clone().normalize();
const perpendicular = new THREE.Vector3(-direction.z, 0, direction.x);
edges[id] = {
id,
a,
b,
length,
direction,
perpendicular
};
}
function addRouteRibbon(id, color) {
const edge = edges[id];
const ribbon = new THREE.Mesh(
new THREE.BoxGeometry(edge.length, 0.035, 0.34),
new THREE.MeshStandardMaterial({
color,
roughness: 0.93,
flatShading: true
})
);
ribbon.position.copy(edge.a).add(edge.b).multiplyScalar(0.5);
ribbon.position.y = 0.105;
ribbon.rotation.y = Math.atan2(
-edge.direction.z,
edge.direction.x
);
ribbon.receiveShadow = true;
scene.add(ribbon);
}
addRouteRibbon("stem", 0x9c9c83);
routeEdges.upper.forEach((id) => addRouteRibbon(id, 0x729783));
routeEdges.lower.forEach((id) => addRouteRibbon(id, 0xb27c59));
const forkMarker = new THREE.Mesh(
new THREE.CylinderGeometry(0.33, 0.43, 0.16, 8),
new THREE.MeshStandardMaterial({
color: 0x7a806f,
roughness: 0.9,
flatShading: true
})
);
forkMarker.position.copy(nodes.fork);
forkMarker.position.y = 0.1;
forkMarker.castShadow = true;
scene.add(forkMarker);
// Central obstacle makes the two routes visually distinct.
const centralRock = new THREE.Mesh(
new THREE.DodecahedronGeometry(1.65, 0),
new THREE.MeshStandardMaterial({
color: 0x7f8d78,
roughness: 0.95,
flatShading: true
})
);
centralRock.position.set(0.55, 0.72, 0);
centralRock.scale.set(1.35, 0.85, 0.95);
centralRock.rotation.set(0.15, 0.35, -0.1);
centralRock.castShadow = true;
centralRock.receiveShadow = true;
scene.add(centralRock);
// Nest.
const nestMound = new THREE.Mesh(
new THREE.ConeGeometry(1.35, 0.7, 9),
new THREE.MeshStandardMaterial({
color: 0x76533b,
roughness: 1,
flatShading: true
})
);
nestMound.position.copy(nodes.nest);
nestMound.position.y = 0.3;
nestMound.castShadow = true;
nestMound.receiveShadow = true;
scene.add(nestMound);
const nestHole = new THREE.Mesh(
new THREE.CircleGeometry(0.54, 12),
new THREE.MeshBasicMaterial({ color: 0x251e19 })
);
nestHole.rotation.x = -Math.PI / 2;
nestHole.position.copy(nodes.nest);
nestHole.position.y = 0.655;
scene.add(nestHole);
// Food: a small low-poly berry bush.
const stemMaterial = new THREE.MeshStandardMaterial({
color: 0x536b3c,
roughness: 0.9,
flatShading: true
});
for (let i = 0; i < 5; i++) {
const stem = new THREE.Mesh(
new THREE.CylinderGeometry(0.07, 0.11, 1.0, 5),
stemMaterial
);
stem.position.set(
nodes.food.x + 0.55 + decorRange(-0.24, 0.24),
0.46,
nodes.food.z + decorRange(-0.26, 0.26)
);
stem.rotation.z = decorRange(-0.18, 0.18);
stem.castShadow = true;
scene.add(stem);
}
const berryMaterial = new THREE.MeshStandardMaterial({
color: 0xc94935,
roughness: 0.67,
flatShading: true
});
for (let i = 0; i < 9; i++) {
const berry = new THREE.Mesh(
new THREE.DodecahedronGeometry(0.22, 0),
berryMaterial
);
berry.position.set(
nodes.food.x + 0.55 + decorRange(-0.42, 0.42),
decorRange(0.68, 1.12),
nodes.food.z + decorRange(-0.42, 0.42)
);
berry.rotation.set(
decorRange(0, Math.PI),
decorRange(0, Math.PI),
decorRange(0, Math.PI)
);
berry.castShadow = true;
scene.add(berry);
}
function distanceToSegmentXZ(point, a, b) {
const abx = b.x - a.x;
const abz = b.z - a.z;
const apx = point.x - a.x;
const apz = point.z - a.z;
const denominator = abx * abx + abz * abz;
const t = denominator
? THREE.MathUtils.clamp(
(apx * abx + apz * abz) / denominator,
0,
1
)
: 0;
const dx = point.x - (a.x + abx * t);
const dz = point.z - (a.z + abz * t);
return Math.hypot(dx, dz);
}
function isClearDecoration(x, z, clearance = 1) {
if (Math.hypot(x - nodes.nest.x, z - nodes.nest.z) < 2.2) {
return false;
}
if (Math.hypot(x - nodes.food.x, z - nodes.food.z) < 2.0) {
return false;
}
if (Math.hypot(x - 0.55, z) < 2.7) {
return false;
}
for (const edge of Object.values(edges)) {
if (
distanceToSegmentXZ(
new THREE.Vector3(x, 0, z),
edge.a,
edge.b
) < clearance
) {
return false;
}
}
return true;
}
// Instanced rocks.
const rockGeometry = new THREE.DodecahedronGeometry(1, 0);
const rockMaterial = new THREE.MeshStandardMaterial({
color: 0xffffff,
roughness: 0.96,
flatShading: true
});
const rockCount = 22;
const rocks = new THREE.InstancedMesh(
rockGeometry,
rockMaterial,
rockCount
);
rocks.castShadow = true;
rocks.receiveShadow = true;
rocks.frustumCulled = false;
const decorDummy = new THREE.Object3D();
const decorColor = new THREE.Color();
for (let i = 0; i < rockCount; i++) {
let x = 0;
let z = 0;
let attempts = 0;
do {
x = decorRange(-13.7, 13.7);
z = decorRange(-8.5, 8.5);
attempts++;
} while (!isClearDecoration(x, z, 0.95) && attempts < 100);
const scale = decorRange(0.18, 0.62);
decorDummy.position.set(x, scale * 0.36, z);
decorDummy.rotation.set(
decorRange(0, Math.PI),
decorRange(0, Math.PI),
decorRange(0, Math.PI)
);
decorDummy.scale.set(
scale * decorRange(0.8, 1.45),
scale * decorRange(0.55, 0.95),
scale * decorRange(0.8, 1.35)
);
decorDummy.updateMatrix();
rocks.setMatrixAt(i, decorDummy.matrix);
decorColor.setHSL(
decorRange(0.22, 0.31),
decorRange(0.08, 0.16),
decorRange(0.42, 0.61)
);
rocks.setColorAt(i, decorColor);
}
rocks.instanceMatrix.needsUpdate = true;
if (rocks.instanceColor) rocks.instanceColor.needsUpdate = true;
scene.add(rocks);
// Instanced triangular grass.
const grassCount = 105;
const grass = new THREE.InstancedMesh(
new THREE.ConeGeometry(0.12, 0.58, 3),
new THREE.MeshStandardMaterial({
color: 0xffffff,
roughness: 1,
flatShading: true
}),
grassCount
);
grass.castShadow = true;
grass.frustumCulled = false;
for (let i = 0; i < grassCount; i++) {
let x = 0;
let z = 0;
let attempts = 0;
do {
x = decorRange(-14.2, 14.2);
z = decorRange(-9.2, 9.2);
attempts++;
} while (!isClearDecoration(x, z, 0.72) && attempts < 100);
const height = decorRange(0.7, 1.35);
decorDummy.position.set(x, 0.27 * height, z);
decorDummy.rotation.set(
decorRange(-0.16, 0.16),
decorRange(0, Math.PI * 2),
decorRange(-0.16, 0.16)
);
decorDummy.scale.set(
decorRange(0.7, 1.2),
height,
decorRange(0.7, 1.2)
);
decorDummy.updateMatrix();
grass.setMatrixAt(i, decorDummy.matrix);
decorColor.setHSL(
decorRange(0.25, 0.34),
decorRange(0.24, 0.38),
decorRange(0.32, 0.46)
);
grass.setColorAt(i, decorColor);
}
grass.instanceMatrix.needsUpdate = true;
if (grass.instanceColor) grass.instanceColor.needsUpdate = true;
scene.add(grass);
// Canvas-generated labels are still self-contained; no font asset is needed.
function makeLabel(text, color, width = 512, height = 128) {
const canvas = document.createElement("canvas");
canvas.width = width;
canvas.height = height;
const context = canvas.getContext("2d");
context.clearRect(0, 0, width, height);
const x = 10;
const y = 10;
const w = width - 20;
const h = height - 20;
const radius = 22;
context.beginPath();
context.moveTo(x + radius, y);
context.lineTo(x + w - radius, y);
context.quadraticCurveTo(x + w, y, x + w, y + radius);
context.lineTo(x + w, y + h - radius);
context.quadraticCurveTo(x + w, y + h, x + w - radius, y + h);
context.lineTo(x + radius, y + h);
context.quadraticCurveTo(x, y + h, x, y + h - radius);
context.lineTo(x, y + radius);
context.quadraticCurveTo(x, y, x + radius, y);
context.closePath();
context.fillStyle = "rgba(249,247,237,0.93)";
context.fill();
context.lineWidth = 4;
context.strokeStyle = color;
context.stroke();
context.fillStyle = "#34483a";
context.font = "700 48px system-ui, sans-serif";
context.textAlign = "center";
context.textBaseline = "middle";
context.fillText(text, width / 2, height / 2 + 2);
const texture = new THREE.CanvasTexture(canvas);
texture.colorSpace = THREE.SRGBColorSpace;
const sprite = new THREE.Sprite(
new THREE.SpriteMaterial({
map: texture,
transparent: true,
depthTest: false,
depthWrite: false
})
);
sprite.renderOrder = 20;
return sprite;
}
const nestLabel = makeLabel("NEST", "#76533b");
nestLabel.position.set(nodes.nest.x, 1.38, nodes.nest.z);
nestLabel.scale.set(2.2, 0.55, 1);
scene.add(nestLabel);
const foodLabel = makeLabel("FOOD", "#c94935");
foodLabel.position.set(nodes.food.x + 0.45, 1.85, nodes.food.z);
foodLabel.scale.set(2.25, 0.56, 1);
scene.add(foodLabel);
const upperLabel = makeLabel("ROUTE A", "#729783", 384, 96);
upperLabel.position.set(0.1, 0.72, 4.35);
upperLabel.scale.set(1.85, 0.46, 1);
scene.add(upperLabel);
const lowerLabel = makeLabel("ROUTE B", "#b27c59", 384, 96);
lowerLabel.position.set(0.1, 0.72, -4.35);
lowerLabel.scale.set(1.85, 0.46, 1);
scene.add(lowerLabel);
// -------------------------------------------------------------------------
// Pheromone state and visible markers
// -------------------------------------------------------------------------
const pheromone = {};
for (const id of Object.keys(edges)) pheromone[id] = 0.015;
pheromone.stem = 0.12;
const markerData = [];
for (const edge of Object.values(edges)) {
const markerCount = Math.max(10, Math.round(edge.length * 1.55));
for (let i = 0; i < markerCount; i++) {
const t = (i + 0.5) / markerCount;
const position = new THREE.Vector3()
.lerpVectors(edge.a, edge.b, t)
.addScaledVector(
edge.perpendicular,
decorRange(-0.095, 0.095)
);
position.y = 0.22;
markerData.push({
edgeId: edge.id,
position,
phase: decorRange(0, Math.PI * 2)
});
}
}
const markerBaseGeometry = new THREE.OctahedronGeometry(1, 0);
const markerGeometry = new THREE.InstancedBufferGeometry();
markerGeometry.index = markerBaseGeometry.index;
markerGeometry.setAttribute(
"position",
markerBaseGeometry.getAttribute("position")
);
markerGeometry.setAttribute(
"normal",
markerBaseGeometry.getAttribute("normal")
);
markerGeometry.instanceCount = markerData.length;
const markerMatrices = new Float32Array(markerData.length * 16);
const markerAlphas = new Float32Array(markerData.length);
const markerStrengths = new Float32Array(markerData.length);
const markerMatrixAttribute = new THREE.InstancedBufferAttribute(
markerMatrices,
16
);
markerMatrixAttribute.setUsage(THREE.DynamicDrawUsage);
const markerAlphaAttribute = new THREE.InstancedBufferAttribute(
markerAlphas,
1
);
markerAlphaAttribute.setUsage(THREE.DynamicDrawUsage);
const markerStrengthAttribute = new THREE.InstancedBufferAttribute(
markerStrengths,
1
);
markerStrengthAttribute.setUsage(THREE.DynamicDrawUsage);
markerGeometry.setAttribute(
"instanceMatrix",
markerMatrixAttribute
);
markerGeometry.setAttribute("aAlpha", markerAlphaAttribute);
markerGeometry.setAttribute("aStrength", markerStrengthAttribute);
const markerMaterial = new THREE.ShaderMaterial({
transparent: true,
depthWrite: false,
vertexShader: `
attribute mat4 instanceMatrix;
attribute float aAlpha;
attribute float aStrength;
varying float vAlpha;
varying float vStrength;
void main() {
vAlpha = aAlpha;
vStrength = aStrength;
vec4 worldPosition = instanceMatrix * vec4(position, 1.0);
gl_Position = projectionMatrix * modelViewMatrix * worldPosition;
}
`,
fragmentShader: `
precision highp float;
varying float vAlpha;
varying float vStrength;
void main() {
vec3 weakColor = vec3(0.62, 0.34, 0.08);
vec3 strongColor = vec3(1.0, 0.62, 0.08);
vec3 color = mix(weakColor, strongColor, clamp(vStrength, 0.0, 1.0));
gl_FragColor = vec4(color, vAlpha);
}
`
});
const markerMesh = new THREE.Mesh(markerGeometry, markerMaterial);
markerMesh.frustumCulled = false;
markerMesh.renderOrder = 3;
scene.add(markerMesh);
const markerDummy = new THREE.Object3D();
function updateMarkerInstances(time) {
for (let i = 0; i < markerData.length; i++) {
const data = markerData[i];
const strength = pheromone[data.edgeId];
const alpha = Math.min(1, strength / 0.30) * 0.94;
const scale = 0.052 + 0.105 * Math.sqrt(Math.max(0, strength));
markerDummy.position.copy(data.position);
markerDummy.rotation.set(
time * 0.42 + data.phase,
time * 0.68 + data.phase * 0.5,
data.phase
);
markerDummy.scale.setScalar(scale);
markerDummy.updateMatrix();
markerMatrices.set(
markerDummy.matrix.elements,
i * 16
);
markerAlphas[i] = alpha;
markerStrengths[i] = strength;
}
markerMatrixAttribute.needsUpdate = true;
markerAlphaAttribute.needsUpdate = true;
markerStrengthAttribute.needsUpdate = true;
}
// -------------------------------------------------------------------------
// Ant colony: instanced low-poly bodies, dynamic legs, and carried berries
// -------------------------------------------------------------------------
const antCount = 42;
const antMaterial = new THREE.MeshStandardMaterial({
color: 0xffffff,
roughness: 0.76,
metalness: 0.02,
flatShading: true
});
const sphereGeometry = new THREE.SphereGeometry(1, 6, 4);
const abdomenMesh = new THREE.InstancedMesh(
sphereGeometry,
antMaterial,
antCount
);
const thoraxMesh = new THREE.InstancedMesh(
sphereGeometry,
antMaterial,
antCount
);
const headMesh = new THREE.InstancedMesh(
sphereGeometry,
antMaterial,
antCount
);
for (const mesh of [abdomenMesh, thoraxMesh, headMesh]) {
mesh.instanceMatrix.setUsage(THREE.DynamicDrawUsage);
mesh.castShadow = true;
mesh.frustumCulled = false;
scene.add(mesh);
}
const berryCarryMesh = new THREE.InstancedMesh(
new THREE.DodecahedronGeometry(1, 0),
new THREE.MeshStandardMaterial({
color: 0xd34b36,
roughness: 0.7,
flatShading: true
}),
antCount
);
berryCarryMesh.instanceMatrix.setUsage(THREE.DynamicDrawUsage);
berryCarryMesh.castShadow = true;
berryCarryMesh.frustumCulled = false;
scene.add(berryCarryMesh);
// Six legs plus two antennae: 16 line vertices per ant.
const antLinePositions = new Float32Array(antCount * 16 * 3);
const antLineGeometry = new THREE.BufferGeometry();
const antLinePositionAttribute = new THREE.BufferAttribute(
antLinePositions,
3
);
antLinePositionAttribute.setUsage(THREE.DynamicDrawUsage);
antLineGeometry.setAttribute("position", antLinePositionAttribute);
const antLines = new THREE.LineSegments(
antLineGeometry,
new THREE.LineBasicMaterial({
color: 0x33251d,
transparent: true,
opacity: 0.95
})
);
antLines.frustumCulled = false;
scene.add(antLines);
const ants = [];
function makeLeg(edgeId, reverse = false) {
const edge = edges[edgeId];
return {
edgeId,
from: reverse ? edge.b.clone() : edge.a.clone(),
to: reverse ? edge.a.clone() : edge.b.clone()
};
}
function randomRange(a, b) {
return a + Math.random() * (b - a);
}
function beginOutbound(ant) {
ant.phase = "out";
ant.route = null;
ant.legs = [makeLeg("stem")];
ant.legIndex = 0;
ant.legT = 0;
ant.position.copy(nodes.nest);
ant.carry = false;
}
function resetAnt(ant, delay = 0) {
ant.position = nodes.nest.clone();
ant.yaw = 0;
ant.speed = randomRange(1.9, 2.5);
ant.gait = randomRange(0, Math.PI * 2);
ant.route = null;
ant.legs = [makeLeg("stem")];
ant.legIndex = 0;
ant.legT = 0;
ant.carry = false;
ant.timer = delay;
if (delay > 0) {
ant.phase = "rest";
} else {
ant.phase = "out";
}
}
for (let i = 0; i < antCount; i++) {
const ant = {
position: new THREE.Vector3(),
yaw: 0,
speed: 2,
gait: 0,
phase: "rest",
route: null,
legs: [],
legIndex: 0,
legT: 0,
timer: 0,
carry: false
};
resetAnt(ant, i < 5 ? 0 : randomRange(0.2, 11));
ants.push(ant);
const antColor = new THREE.Color();
antColor.setHSL(
randomRange(0.065, 0.095),
randomRange(0.30, 0.48),
randomRange(0.15, 0.23)
);
abdomenMesh.setColorAt(i, antColor);
thoraxMesh.setColorAt(i, antColor);
headMesh.setColorAt(i, antColor);
}
for (const mesh of [abdomenMesh, thoraxMesh, headMesh]) {
if (mesh.instanceColor) mesh.instanceColor.needsUpdate = true;
}
const rootDummy = new THREE.Object3D();
const partDummy = new THREE.Object3D();
const berryDummy = new THREE.Object3D();
const finalMatrix = new THREE.Matrix4();
function setAntPartMatrix(mesh, index, rootMatrix, position, scale) {
partDummy.position.set(...position);
partDummy.rotation.set(0, 0, 0);
partDummy.scale.set(...scale);
partDummy.updateMatrix();
finalMatrix.multiplyMatrices(rootMatrix, partDummy.matrix);
mesh.setMatrixAt(index, finalMatrix);
}
function updateAntVisuals() {
for (let i = 0; i < ants.length; i++) {
const ant = ants[i];
const cosine = Math.cos(ant.yaw);
const sine = Math.sin(ant.yaw);
// Tiny side-to-side motion, applied only to the rendered position.
const sideOffset = Math.sin(ant.gait * 1.8) * 0.025;
rootDummy.position.set(
ant.position.x + sine * sideOffset,
ant.position.y,
ant.position.z + cosine * sideOffset
);
rootDummy.rotation.set(0, ant.yaw, 0);
rootDummy.scale.setScalar(1.18);
rootDummy.updateMatrix();
setAntPartMatrix(
abdomenMesh,
i,
rootDummy.matrix,
[-0.21, 0.16, 0],
[0.19, 0.135, 0.22]
);
setAntPartMatrix(
thoraxMesh,
i,
rootDummy.matrix,
[0.015, 0.16, 0],
[0.145, 0.12, 0.13]
);
setAntPartMatrix(
headMesh,
i,
rootDummy.matrix,
[0.205, 0.16, 0],
[0.14, 0.115, 0.13]
);
if (ant.carry) {
berryDummy.position.set(0.31, 0.32, 0);
berryDummy.rotation.set(0.4, ant.gait * 0.15, 0.2);
berryDummy.scale.setScalar(0.105);
} else {
berryDummy.position.set(0, -10, 0);
berryDummy.scale.setScalar(0.001);
}
berryDummy.updateMatrix();
finalMatrix.multiplyMatrices(
rootDummy.matrix,
berryDummy.matrix
);
berryCarryMesh.setMatrixAt(i, finalMatrix);
}
abdomenMesh.instanceMatrix.needsUpdate = true;
thoraxMesh.instanceMatrix.needsUpdate = true;
headMesh.instanceMatrix.needsUpdate = true;
berryCarryMesh.instanceMatrix.needsUpdate = true;
updateAntLines();
}
function updateAntLines() {
let offset = 0;
function writeVertex(worldX, worldY, worldZ) {
antLinePositions[offset++] = worldX;
antLinePositions[offset++] = worldY;
antLinePositions[offset++] = worldZ;
}
function writeLocalSegment(ant, a, b) {
const cosine = Math.cos(ant.yaw);
const sine = Math.sin(ant.yaw);
writeVertex(
ant.position.x + a[0] * cosine + a[2] * sine,
a[1],
ant.position.z - a[0] * sine + a[2] * cosine
);
writeVertex(
ant.position.x + b[0] * cosine + b[2] * sine,
b[1],
ant.position.z - b[0] * sine + b[2] * cosine
);
}
for (const ant of ants) {
const hipX = [-0.075, 0.015, 0.10];
for (let leg = 0; leg < 6; leg++) {
const side = leg < 3 ? -1 : 1;
const index = leg % 3;
const alternating = leg === 0 || leg === 3 || leg === 4;
const gait =
Math.sin(ant.gait * 1.7 + index * 1.7) *
(alternating ? 1 : -1);
const hip = [hipX[index], 0.11, side * 0.085];
const knee = [
hipX[index] + 0.065 + gait * 0.035,
0.075,
side * (0.19 + Math.abs(gait) * 0.018)
];
const foot = [
hipX[index] + 0.13 + gait * 0.065,
0.035,
side * (0.27 + Math.abs(gait) * 0.025)
];
writeLocalSegment(ant, hip, knee);
writeLocalSegment(ant, knee, foot);
}
const antennaMotion = Math.sin(ant.gait * 1.2) * 0.025;
writeLocalSegment(
ant,
[0.29, 0.19, -0.055],
[0.41 + antennaMotion, 0.18, -0.15]
);
writeLocalSegment(
ant,
[0.29, 0.19, 0.055],
[0.41 - antennaMotion, 0.18, 0.15]
);
}
antLinePositionAttribute.needsUpdate = true;
}
// -------------------------------------------------------------------------
// Choice rule, decay, and successful returns
// -------------------------------------------------------------------------
const EXPLORATION = 0.08;
const SENSITIVITY = 4.5;
const DEPOSIT = 0.27;
let decayRate = 0.018;
let paused = false;
let successfulReturns = 0;
const successfulByRoute = { upper: 0, lower: 0 };
function routeStrength(route) {
const ids = routeEdges[route];
let total = 0;
for (const id of ids) total += pheromone[id];
return total / ids.length;
}
function upperChoiceProbability() {
const qA = routeStrength("upper");
const qB = routeStrength("lower");
const numerator = Math.exp(SENSITIVITY * qA);
const denominator =
numerator + Math.exp(SENSITIVITY * qB);
return (
EXPLORATION +
(1 - 2 * EXPLORATION) * (numerator / denominator)
);
}
function chooseRoute() {
return Math.random() < upperChoiceProbability()
? "upper"
: "lower";
}
function depositPheromone(route) {
const reinforced = ["stem", ...routeEdges[route]];
for (const id of reinforced) {
pheromone[id] = Math.min(1, pheromone[id] + DEPOSIT);
}
}
// Small expanding rings provide feedback for successful returns.
const pulseGeometry = new THREE.TorusGeometry(0.45, 0.035, 4, 18);
const pulses = [];
for (let i = 0; i < 12; i++) {
const material = new THREE.MeshBasicMaterial({
color: 0xf2a51c,
transparent: true,
opacity: 0,
depthWrite: false
});
const mesh = new THREE.Mesh(pulseGeometry, material);
mesh.rotation.x = Math.PI / 2;
mesh.position.copy(nodes.nest);
mesh.position.y = 0.25;
mesh.visible = false;
scene.add(mesh);
pulses.push({ mesh, life: 1 });
}
function spawnPulse() {
const pulse = pulses.find((item) => item.life >= 1) || pulses[0];
pulse.life = 0;
pulse.mesh.visible = true;
pulse.mesh.scale.setScalar(1);
pulse.mesh.material.opacity = 0.85;
}
function updatePulses(dt) {
for (const pulse of pulses) {
if (pulse.life >= 1) continue;
pulse.life += dt / 0.9;
const t = Math.min(1, pulse.life);
pulse.mesh.scale.setScalar(1 + t * 2.6);
pulse.mesh.material.opacity = Math.max(0, 0.85 * (1 - t));
if (pulse.life >= 1) {
pulse.mesh.visible = false;
}
}
}
function updateAnt(ant, dt) {
if (ant.phase === "rest") {
ant.timer -= dt;
if (ant.timer <= 0) {
beginOutbound(ant);
}
return;
}
if (ant.phase === "pickup") {
ant.timer -= dt;
if (ant.timer <= 0) {
ant.phase = "return";
ant.legs = [
...routeEdges[ant.route]
.slice()
.reverse()
.map((id) => makeLeg(id, true)),
makeLeg("stem", true)
];
ant.legIndex = 0;
ant.legT = 0;
}
return;
}
ant.gait += dt * ant.speed * 5.6;
const leg = ant.legs[ant.legIndex];
if (!leg) return;
const legLength = leg.from.distanceTo(leg.to);
ant.legT += (ant.speed * dt) / legLength;
if (ant.legT >= 1) {
ant.position.copy(leg.to);
ant.legT = 0;
ant.legIndex++;
const completedEdge = leg.edgeId;
// The route is sampled once, at the fork.
if (
ant.phase === "out" &&
completedEdge === "stem" &&
!ant.route
) {
ant.route = chooseRoute();
ant.legs = routeEdges[ant.route].map((id) =>
makeLeg(id, false)
);
ant.legIndex = 0;
} else if (
ant.phase === "out" &&
ant.legIndex >= ant.legs.length
) {
ant.phase = "pickup";
ant.timer = randomRange(0.65, 1.35);
ant.carry = true;
} else if (
ant.phase === "return" &&
ant.legIndex >= ant.legs.length
) {
depositPheromone(ant.route);
successfulReturns++;
successfulByRoute[ant.route]++;
spawnPulse();
ant.phase = "rest";
ant.timer = randomRange(0.2, 1.0);
ant.carry = false;
ant.legs = [];
ant.legIndex = 0;
}
return;
}
ant.position.lerpVectors(leg.from, leg.to, ant.legT);
const dx = leg.to.x - leg.from.x;
const dz = leg.to.z - leg.from.z;
ant.yaw = Math.atan2(-dz, dx);
}
function updateAnts(dt) {
for (const ant of ants) updateAnt(ant, dt);
}
function updatePheromone(dt) {
for (const id of Object.keys(pheromone)) {
pheromone[id] = Math.max(
0,
pheromone[id] - decayRate * dt
);
}
}
// -------------------------------------------------------------------------
// UI
// -------------------------------------------------------------------------
const returnCountElement = document.querySelector("#returnCount");
const choiceValueElement = document.querySelector("#choiceValue");
const trailAValueElement = document.querySelector("#trailAValue");
const trailBValueElement = document.querySelector("#trailBValue");
const upperMeterElement = document.querySelector("#upperMeter");
const lowerMeterElement = document.querySelector("#lowerMeter");
const pauseButton = document.querySelector("#pauseButton");
const clearButton = document.querySelector("#clearButton");
const resetButton = document.querySelector("#resetButton");
const resetViewButton = document.querySelector("#resetView");
const decaySlider = document.querySelector("#decaySlider");
const decayValueElement = document.querySelector("#decayValue");
let statsTimer = 0;
function updateStats() {
const probability = upperChoiceProbability();
const qA = routeStrength("upper");
const qB = routeStrength("lower");
returnCountElement.textContent = successfulReturns;
choiceValueElement.textContent = `${Math.round(probability * 100)}%`;
trailAValueElement.textContent = `${Math.round(qA * 100)}%`;
trailBValueElement.textContent = `${Math.round(qB * 100)}%`;
upperMeterElement.style.width = `${probability * 100}%`;
lowerMeterElement.style.width = `${(1 - probability) * 100}%`;
}
pauseButton.addEventListener("click", () => {
paused = !paused;
pauseButton.textContent = paused ? "Resume" : "Pause";
});
clearButton.addEventListener("click", () => {
for (const id of Object.keys(pheromone)) {
pheromone[id] = 0.015;
}
pheromone.stem = 0.05;
});
resetButton.addEventListener("click", () => {
successfulReturns = 0;
successfulByRoute.upper = 0;
successfulByRoute.lower = 0;
for (let i = 0; i < ants.length; i++) {
resetAnt(ants[i], i < 5 ? 0 : randomRange(0.2, 11));
}
});
resetViewButton.addEventListener("click", () => {
cameraState.target.set(-0.2, 0, 0);
cameraState.radius = window.innerWidth < 700 ? 30 : 25;
cameraState.azimuth = 0.48;
cameraState.elevation = 0.72;
updateCamera();
});
decaySlider.addEventListener("input", () => {
decayRate = Number(decaySlider.value);
decayValueElement.textContent = `${decayRate.toFixed(3)} / s`;
});
// -------------------------------------------------------------------------
// Direct camera controls: orbit, pan, wheel zoom, and touch pinch
// -------------------------------------------------------------------------
const canvas = renderer.domElement;
const pointers = new Map();
let lastPinchDistance = 0;
let lastPinchCenter = null;
function currentPinchData() {
const values = [...pointers.values()];
if (values.length < 2) return null;
const dx = values[0].x - values[1].x;
const dy = values[0].y - values[1].y;
return {
distance: Math.hypot(dx, dy),
center: {
x: (values[0].x + values[1].x) / 2,
y: (values[0].y + values[1].y) / 2
}
};
}
function panCamera(dx, dy) {
const right = new THREE.Vector3(
Math.cos(cameraState.azimuth),
0,
-Math.sin(cameraState.azimuth)
);
const forward = new THREE.Vector3(
-Math.sin(cameraState.azimuth),
0,
-Math.cos(cameraState.azimuth)
);
const scale = cameraState.radius * 0.00145;
cameraState.target.addScaledVector(right, -dx * scale);
cameraState.target.addScaledVector(forward, -dy * scale);
}
canvas.addEventListener("contextmenu", (event) => {
event.preventDefault();
});
canvas.addEventListener("pointerdown", (event) => {
canvas.setPointerCapture(event.pointerId);
pointers.set(event.pointerId, {
x: event.clientX,
y: event.clientY
});
if (pointers.size === 2) {
const pinch = currentPinchData();
lastPinchDistance = pinch.distance;
lastPinchCenter = pinch.center;
}
});
canvas.addEventListener("pointermove", (event) => {
const previous = pointers.get(event.pointerId);
if (!previous) return;
const dx = event.clientX - previous.x;
const dy = event.clientY - previous.y;
pointers.set(event.pointerId, {
x: event.clientX,
y: event.clientY
});
if (pointers.size === 1) {
if (event.shiftKey || event.buttons === 2) {
panCamera(dx, dy);
} else {
cameraState.azimuth -= dx * 0.006;
cameraState.elevation = THREE.MathUtils.clamp(
cameraState.elevation + dy * 0.005,
0.25,
1.38
);
}
} else if (pointers.size === 2) {
const pinch = currentPinchData();
if (lastPinchDistance > 0) {
cameraState.radius = THREE.MathUtils.clamp(
cameraState.radius *
(lastPinchDistance / pinch.distance),
12,
43
);
}
if (lastPinchCenter) {
panCamera(
pinch.center.x - lastPinchCenter.x,
pinch.center.y - lastPinchCenter.y
);
}
lastPinchDistance = pinch.distance;
lastPinchCenter = pinch.center;
}
});
function releasePointer(event) {
pointers.delete(event.pointerId);
if (pointers.size < 2) {
lastPinchDistance = 0;
lastPinchCenter = null;
}
}
canvas.addEventListener("pointerup", releasePointer);
canvas.addEventListener("pointercancel", releasePointer);
canvas.addEventListener("lostpointercapture", releasePointer);
canvas.addEventListener(
"wheel",
(event) => {
event.preventDefault();
cameraState.radius = THREE.MathUtils.clamp(
cameraState.radius * Math.exp(event.deltaY * 0.001),
12,
43
);
},
{ passive: false }
);
window.addEventListener("resize", () => {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
});
// -------------------------------------------------------------------------
// Animation loop
// -------------------------------------------------------------------------
const clock = new THREE.Clock();
let simulationTime = 0;
updateMarkerInstances(0);
updateAntVisuals();
updateStats();
function animate() {
requestAnimationFrame(animate);
const dt = Math.min(clock.getDelta(), 0.05);
if (!paused) {
simulationTime += dt;
updatePheromone(dt);
updateAnts(dt);
updatePulses(dt);
}
updateMarkerInstances(simulationTime);
updateAntVisuals();
updateCamera();
statsTimer += dt;
if (statsTimer > 0.1) {
updateStats();
statsTimer = 0;
}
renderer.render(scene, camera);
}
animate();
</script>
</body>
</html>
```