Prompt specification
Build or customize the Three.js 3D scene "Local-rule flock formation" 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: Local-rule flock formation
Category: Biology & Nature · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/local-rule-flock-formation-x0686
Scene Description Prompt:
A low-poly flock with separate toggles for neighbor-based separation, alignment, and cohesion rules. One HTML file using Three.js from cdnjs.
Working Three.js Starter (local-rule-flock-formation-x0686):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Low-Poly Flock</title>
<style>
:root {
color-scheme: dark;
--bg: #07131d;
--panel: rgba(10, 23, 34, 0.78);
--line: rgba(255, 255, 255, 0.11);
--text: #eef8ff;
--muted: #8fa7b8;
--cyan: #58e1dc;
--orange: #ff9d5c;
--violet: #b69cff;
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background:
radial-gradient(circle at 25% 15%, rgba(44, 102, 120, 0.22), transparent 38%),
radial-gradient(circle at 78% 80%, rgba(92, 61, 130, 0.18), transparent 42%),
var(--bg);
color: var(--text);
font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
button,
input {
font: inherit;
}
#stage {
position: fixed;
inset: 0;
}
#stage canvas {
display: block;
width: 100%;
height: 100%;
cursor: grab;
touch-action: none;
}
#stage canvas:active {
cursor: grabbing;
}
.brand {
position: fixed;
top: 28px;
left: 30px;
z-index: 2;
pointer-events: none;
user-select: none;
}
.eyebrow {
margin-bottom: 8px;
color: var(--cyan);
font-size: 10px;
font-weight: 800;
letter-spacing: 0.22em;
text-transform: uppercase;
}
h1 {
margin: 0;
font-size: clamp(30px, 4vw, 56px);
font-weight: 720;
letter-spacing: -0.055em;
line-height: 0.95;
}
.subtitle {
max-width: 360px;
margin: 13px 0 0;
color: var(--muted);
font-size: 13px;
line-height: 1.55;
}
.panel {
position: fixed;
top: 24px;
right: 24px;
z-index: 3;
width: min(330px, calc(100vw - 32px));
padding: 18px;
border: 1px solid var(--line);
border-radius: 18px;
background: var(--panel);
box-shadow: 0 20px 60px rgba(0, 0, 0, 0.25);
backdrop-filter: blur(18px) saturate(130%);
-webkit-backdrop-filter: blur(18px) saturate(130%);
}
.panel-heading {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 10px;
}
.panel-heading h2 {
margin: 0;
font-size: 13px;
font-weight: 750;
letter-spacing: 0.02em;
}
.rule-count {
color: var(--muted);
font-size: 10px;
font-weight: 700;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.rule {
--accent: var(--cyan);
display: grid;
grid-template-columns: 36px 1fr auto;
align-items: center;
gap: 11px;
min-height: 66px;
border-bottom: 1px solid var(--line);
cursor: pointer;
}
.rule:last-of-type {
border-bottom: 0;
}
.rule[data-rule="alignment"] {
--accent: var(--orange);
}
.rule[data-rule="cohesion"] {
--accent: var(--violet);
}
.rule-icon {
position: relative;
width: 32px;
height: 32px;
border: 1px solid color-mix(in srgb, var(--accent) 48%, transparent);
border-radius: 9px;
background: color-mix(in srgb, var(--accent) 10%, transparent);
}
.rule-icon::before,
.rule-icon::after {
content: "";
position: absolute;
border-radius: 50%;
background: var(--accent);
}
.rule-icon::before {
width: 5px;
height: 5px;
top: 8px;
left: 8px;
box-shadow:
9px 3px 0 -1px var(--accent),
3px 11px 0 -1px var(--accent),
12px 13px 0 -1px var(--accent);
}
.rule-icon::after {
width: 17px;
height: 17px;
right: 4px;
bottom: 4px;
border: 1px solid var(--accent);
background: transparent;
opacity: 0.55;
}
.rule-copy strong {
display: block;
margin-bottom: 3px;
font-size: 12px;
font-weight: 700;
}
.rule-copy span {
display: block;
color: var(--muted);
font-size: 10px;
line-height: 1.35;
}
.rule input {
position: absolute;
width: 1px;
height: 1px;
opacity: 0;
pointer-events: none;
}
.switch {
position: relative;
display: block;
width: 38px;
height: 22px;
border: 1px solid rgba(255, 255, 255, 0.14);
border-radius: 999px;
background: rgba(255, 255, 255, 0.08);
transition: background 180ms ease, border-color 180ms ease;
}
.switch::after {
content: "";
position: absolute;
top: 3px;
left: 3px;
width: 14px;
height: 14px;
border-radius: 50%;
background: #8497a5;
box-shadow: 0 2px 5px rgba(0, 0, 0, 0.35);
transition: transform 180ms ease, background 180ms ease;
}
.rule input:checked + .switch {
border-color: var(--accent);
background: color-mix(in srgb, var(--accent) 34%, transparent);
}
.rule input:checked + .switch::after {
transform: translateX(16px);
background: var(--accent);
}
.rule input:focus-visible + .switch {
outline: 2px solid var(--accent);
outline-offset: 3px;
}
.stats {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 7px;
margin: 15px 0;
}
.stat {
padding: 10px 8px;
border: 1px solid var(--line);
border-radius: 10px;
background: rgba(255, 255, 255, 0.035);
text-align: center;
}
.stat strong {
display: block;
font-size: 14px;
font-variant-numeric: tabular-nums;
}
.stat span {
display: block;
margin-top: 3px;
color: var(--muted);
font-size: 8px;
font-weight: 700;
letter-spacing: 0.1em;
text-transform: uppercase;
}
.actions {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 8px;
}
.action {
min-height: 38px;
border: 1px solid var(--line);
border-radius: 10px;
background: rgba(255, 255, 255, 0.055);
color: var(--text);
font-size: 11px;
font-weight: 700;
cursor: pointer;
transition: transform 140ms ease, background 140ms ease, border-color 140ms ease;
}
.action:hover {
transform: translateY(-1px);
border-color: rgba(255, 255, 255, 0.23);
background: rgba(255, 255, 255, 0.1);
}
.action:active {
transform: translateY(0);
}
.action.primary {
border-color: rgba(88, 225, 220, 0.35);
background: rgba(88, 225, 220, 0.12);
color: #b9fffb;
}
.hint {
position: fixed;
bottom: 24px;
left: 30px;
z-index: 2;
display: flex;
align-items: center;
gap: 9px;
color: var(--muted);
font-size: 10px;
font-weight: 650;
letter-spacing: 0.06em;
text-transform: uppercase;
pointer-events: none;
}
.mouse {
position: relative;
width: 17px;
height: 24px;
border: 1px solid rgba(255, 255, 255, 0.4);
border-radius: 8px;
}
.mouse::before {
content: "";
position: absolute;
top: 4px;
left: 7px;
width: 2px;
height: 5px;
border-radius: 2px;
background: var(--cyan);
}
@media (max-width: 700px) {
.brand {
top: 20px;
left: 20px;
}
.subtitle {
display: none;
}
.panel {
top: auto;
right: 16px;
bottom: 16px;
left: 16px;
width: auto;
padding: 14px;
}
.rule {
min-height: 56px;
}
.hint {
display: none;
}
}
</style>
</head>
<body>
<div id="stage" aria-label="Interactive low-poly flock simulation"></div>
<header class="brand">
<div class="eyebrow">Swarm simulation / 01</div>
<h1>Murmuration</h1>
<p class="subtitle">
A real-time low-poly flock driven by three independent behavioral rules.
Toggle each force and watch the collective shape change.
</p>
</header>
<aside class="panel">
<div class="panel-heading">
<h2>Behavior rules</h2>
<div class="rule-count" id="ruleCount">3 / 3 active</div>
</div>
<label class="rule" data-rule="separation">
<span class="rule-icon" aria-hidden="true"></span>
<span class="rule-copy">
<strong>Separation</strong>
<span>Avoid crowding nearby neighbors</span>
</span>
<input id="separation" type="checkbox" checked />
<span class="switch" aria-hidden="true"></span>
</label>
<label class="rule" data-rule="alignment">
<span class="rule-icon" aria-hidden="true"></span>
<span class="rule-copy">
<strong>Alignment</strong>
<span>Match the direction of the flock</span>
</span>
<input id="alignment" type="checkbox" checked />
<span class="switch" aria-hidden="true"></span>
</label>
<label class="rule" data-rule="cohesion">
<span class="rule-icon" aria-hidden="true"></span>
<span class="rule-copy">
<strong>Cohesion</strong>
<span>Move toward the local group center</span>
</span>
<input id="cohesion" type="checkbox" checked />
<span class="switch" aria-hidden="true"></span>
</label>
<div class="stats">
<div class="stat">
<strong id="boidCount">0</strong>
<span>Birds</span>
</div>
<div class="stat">
<strong id="fps">60</strong>
<span>FPS</span>
</div>
<div class="stat">
<strong id="state">Live</strong>
<span>State</span>
</div>
</div>
<div class="actions">
<button class="action primary" id="pauseButton" type="button">Pause</button>
<button class="action" id="resetButton" type="button">Re-seed</button>
</div>
</aside>
<div class="hint">
<span class="mouse"></span>
Drag to orbit · Scroll to zoom · Space to pause
</div>
<script type="module">
import * as THREE from "https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
const stage = document.getElementById("stage");
const scene = new THREE.Scene();
scene.fog = new THREE.Fog(0x07131d, 48, 125);
const camera = new THREE.PerspectiveCamera(
45,
window.innerWidth / window.innerHeight,
0.1,
180
);
const renderer = new THREE.WebGLRenderer({
antialias: true,
alpha: true,
powerPreference: "high-performance"
});
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.setClearColor(0x07131d, 0);
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.12;
stage.appendChild(renderer.domElement);
scene.add(new THREE.HemisphereLight(0xbcecff, 0x172033, 2.1));
const keyLight = new THREE.DirectionalLight(0xffffff, 2.6);
keyLight.position.set(-18, 26, 14);
scene.add(keyLight);
const rimLight = new THREE.DirectionalLight(0x58e1dc, 1.5);
rimLight.position.set(18, 4, -22);
scene.add(rimLight);
const warmLight = new THREE.PointLight(0xff9164, 45, 65, 2);
warmLight.position.set(-20, -2, 10);
scene.add(warmLight);
// Ground and grid.
const ground = new THREE.Mesh(
new THREE.CircleGeometry(62, 64),
new THREE.MeshStandardMaterial({
color: 0x091721,
roughness: 0.95,
metalness: 0.05
})
);
ground.rotation.x = -Math.PI / 2;
ground.position.y = -15;
scene.add(ground);
const grid = new THREE.GridHelper(110, 22, 0x214151, 0x142b38);
grid.position.y = -14.95;
grid.material.transparent = true;
grid.material.opacity = 0.34;
scene.add(grid);
// Sparse atmospheric particles.
const dustGeometry = new THREE.BufferGeometry();
const dustPositions = new Float32Array(480 * 3);
for (let i = 0; i < 480; i++) {
dustPositions[i * 3] = (Math.random() - 0.5) * 95;
dustPositions[i * 3 + 1] = (Math.random() - 0.5) * 50;
dustPositions[i * 3 + 2] = (Math.random() - 0.5) * 95;
}
dustGeometry.setAttribute(
"position",
new THREE.BufferAttribute(dustPositions, 3)
);
const dust = new THREE.Points(
dustGeometry,
new THREE.PointsMaterial({
color: 0x8ab6c9,
size: 0.09,
transparent: true,
opacity: 0.36,
depthWrite: false
})
);
scene.add(dust);
// Shared low-poly bird geometry.
function createBodyGeometry() {
const geometry = new THREE.BufferGeometry();
const positions = new Float32Array([
0.00, 0.00, 1.05, // nose
0.00, 0.32, 0.12, // top
-0.24, 0.00, 0.08, // left
0.24, 0.00, 0.08, // right
0.00, -0.24, 0.08, // bottom
0.00, 0.02, -0.72 // tail
]);
const indices = [
0, 2, 1,
0, 1, 3,
0, 3, 4,
0, 4, 2,
5, 2, 1,
5, 1, 3,
5, 3, 4,
5, 4, 2
];
geometry.setAttribute("position", new THREE.BufferAttribute(positions, 3));
geometry.setIndex(indices);
geometry.computeVertexNormals();
return geometry;
}
function createWingGeometry(side) {
const geometry = new THREE.BufferGeometry();
const positions = new Float32Array([
0, 0, 0.28,
0, 0, -0.38,
side * 1.18, 0, -0.16
]);
geometry.setAttribute("position", new THREE.BufferAttribute(positions, 3));
geometry.computeVertexNormals();
return geometry;
}
const bodyGeometry = createBodyGeometry();
const leftWingGeometry = createWingGeometry(-1);
const rightWingGeometry = createWingGeometry(1);
const palette = [0xffa15f, 0x5fe0d4, 0xa88cff, 0xf4d35e, 0xef7c92];
const bodyMaterials = palette.map(
(color) =>
new THREE.MeshStandardMaterial({
color,
roughness: 0.76,
metalness: 0.05,
flatShading: true,
side: THREE.DoubleSide
})
);
const wingMaterials = palette.map(
(color) =>
new THREE.MeshStandardMaterial({
color: new THREE.Color(color).multiplyScalar(0.78),
roughness: 0.82,
metalness: 0.03,
flatShading: true,
side: THREE.DoubleSide
})
);
const BOID_COUNT = 84;
const MAX_SPEED = 7.2;
const MIN_SPEED = 2.8;
const MAX_FORCE = 2.6;
const SEPARATION_RADIUS = 3.4;
const ALIGNMENT_RADIUS = 8.5;
const COHESION_RADIUS = 11;
const bounds = {
x: 36,
y: 13,
z: 36
};
const boids = [];
function randomDirection() {
const vector = new THREE.Vector3(
Math.random() * 2 - 1,
Math.random() * 2 - 1,
Math.random() * 2 - 1
);
if (vector.lengthSq() < 0.001) {
vector.set(0, 0, 1);
}
return vector.normalize();
}
function createBird() {
const colorIndex = Math.floor(Math.random() * palette.length);
const group = new THREE.Group();
const body = new THREE.Mesh(bodyGeometry, bodyMaterials[colorIndex]);
group.add(body);
const leftPivot = new THREE.Group();
const rightPivot = new THREE.Group();
const leftWing = new THREE.Mesh(leftWingGeometry, wingMaterials[colorIndex]);
const rightWing = new THREE.Mesh(rightWingGeometry, wingMaterials[colorIndex]);
leftPivot.add(leftWing);
rightPivot.add(rightWing);
group.add(leftPivot, rightPivot);
const scale = 0.65 + Math.random() * 0.48;
group.scale.setScalar(scale);
const position = new THREE.Vector3(
(Math.random() - 0.5) * bounds.x * 1.35,
(Math.random() - 0.5) * bounds.y * 1.35,
(Math.random() - 0.5) * bounds.z * 1.35
);
const velocity = randomDirection().multiplyScalar(3.5 + Math.random() * 2);
group.position.copy(position);
scene.add(group);
return {
group,
position,
velocity,
leftPivot,
rightPivot,
phase: Math.random() * Math.PI * 2,
flapSpeed: 7.5 + Math.random() * 3.5,
wanderPhase: Math.random() * Math.PI * 2,
bank: 0
};
}
function seedFlock() {
for (const boid of boids) {
scene.remove(boid.group);
}
boids.length = 0;
for (let i = 0; i < BOID_COUNT; i++) {
boids.push(createBird());
}
document.getElementById("boidCount").textContent = BOID_COUNT;
}
seedFlock();
const rules = {
separation: true,
alignment: true,
cohesion: true
};
function syncRuleInputs() {
for (const name of Object.keys(rules)) {
document.getElementById(name).checked = rules[name];
}
const active = Object.values(rules).filter(Boolean).length;
document.getElementById("ruleCount").textContent = `${active} / 3 active`;
}
for (const name of Object.keys(rules)) {
document.getElementById(name).addEventListener("change", (event) => {
rules[name] = event.target.checked;
syncRuleInputs();
});
}
syncRuleInputs();
function clampVectorLength(x, y, z, maximum) {
const lengthSquared = x * x + y * y + z * z;
if (lengthSquared > maximum * maximum) {
const scale = maximum / Math.sqrt(lengthSquared);
return [x * scale, y * scale, z * scale];
}
return [x, y, z];
}
function updateBoid(boid, delta, time) {
let separationX = 0;
let separationY = 0;
let separationZ = 0;
let separationCount = 0;
let alignmentX = 0;
let alignmentY = 0;
let alignmentZ = 0;
let alignmentCount = 0;
let cohesionX = 0;
let cohesionY = 0;
let cohesionZ = 0;
let cohesionCount = 0;
for (let j = 0; j < boids.length; j++) {
if (boid === boids[j]) continue;
const other = boids[j];
const dx = boid.position.x - other.position.x;
const dy = boid.position.y - other.position.y;
const dz = boid.position.z - other.position.z;
const distanceSquared = dx * dx + dy * dy + dz * dz;
if (rules.separation && distanceSquared < SEPARATION_RADIUS ** 2) {
const inverse = 1 / (distanceSquared + 0.08);
separationX -= dx * inverse;
separationY -= dy * inverse;
separationZ -= dz * inverse;
separationCount++;
}
if (rules.alignment && distanceSquared < ALIGNMENT_RADIUS ** 2) {
alignmentX += other.velocity.x;
alignmentY += other.velocity.y;
alignmentZ += other.velocity.z;
alignmentCount++;
}
if (rules.cohesion && distanceSquared < COHESION_RADIUS ** 2) {
cohesionX += other.position.x;
cohesionY += other.position.y;
cohesionZ += other.position.z;
cohesionCount++;
}
}
let forceX = 0;
let forceY = 0;
let forceZ = 0;
if (rules.separation && separationCount > 0) {
const length = Math.hypot(separationX, separationY, separationZ) || 1;
let [steerX, steerY, steerZ] = clampVectorLength(
(separationX / length) * MAX_SPEED - boid.velocity.x,
(separationY / length) * MAX_SPEED - boid.velocity.y,
(separationZ / length) * MAX_SPEED - boid.velocity.z,
MAX_FORCE
);
forceX += steerX * 2.15;
forceY += steerY * 2.15;
forceZ += steerZ * 2.15;
}
if (rules.alignment && alignmentCount > 0) {
const length = Math.hypot(alignmentX, alignmentY, alignmentZ) || 1;
let [steerX, steerY, steerZ] = clampVectorLength(
(alignmentX / length) * MAX_SPEED - boid.velocity.x,
(alignmentY / length) * MAX_SPEED - boid.velocity.y,
(alignmentZ / length) * MAX_SPEED - boid.velocity.z,
MAX_FORCE
);
forceX += steerX * 0.95;
forceY += steerY * 0.95;
forceZ += steerZ * 0.95;
}
if (rules.cohesion && cohesionCount > 0) {
cohesionX = cohesionX / cohesionCount - boid.position.x;
cohesionY = cohesionY / cohesionCount - boid.position.y;
cohesionZ = cohesionZ / cohesionCount - boid.position.z;
const length = Math.hypot(cohesionX, cohesionY, cohesionZ) || 1;
let [steerX, steerY, steerZ] = clampVectorLength(
(cohesionX / length) * MAX_SPEED - boid.velocity.x,
(cohesionY / length) * MAX_SPEED - boid.velocity.y,
(cohesionZ / length) * MAX_SPEED - boid.velocity.z,
MAX_FORCE
);
forceX += steerX * 0.62;
forceY += steerY * 0.62;
forceZ += steerZ * 0.62;
}
// Soft containment keeps the flock inside the visible volume.
const softX = bounds.x * 0.76;
const softY = bounds.y * 0.76;
const softZ = bounds.z * 0.76;
if (Math.abs(boid.position.x) > softX) {
forceX += -Math.sign(boid.position.x) * 2.4;
}
if (Math.abs(boid.position.y) > softY) {
forceY += -Math.sign(boid.position.y) * 2.8;
}
if (Math.abs(boid.position.z) > softZ) {
forceZ += -Math.sign(boid.position.z) * 2.4;
}
// Gentle individual wander prevents perfectly uniform motion.
const wander = time * 0.7 + boid.wanderPhase;
forceX += Math.sin(wander * 1.13) * 0.22;
forceY += Math.sin(wander * 0.73 + 1.8) * 0.17;
forceZ += Math.cos(wander * 0.91 + 0.6) * 0.22;
boid.velocity.x += forceX * delta;
boid.velocity.y += forceY * delta;
boid.velocity.z += forceZ * delta;
const speed = boid.velocity.length();
if (speed > MAX_SPEED) {
boid.velocity.multiplyScalar(MAX_SPEED / speed);
} else if (speed < MIN_SPEED) {
if (speed > 0.001) {
boid.velocity.multiplyScalar(MIN_SPEED / speed);
} else {
boid.velocity.copy(randomDirection()).multiplyScalar(MIN_SPEED);
}
}
boid.position.addScaledVector(boid.velocity, delta);
// Hard limits as a final safety net.
for (const axis of ["x", "y", "z"]) {
const limit = bounds[axis];
if (boid.position[axis] > limit) {
boid.position[axis] = limit;
boid.velocity[axis] *= -0.8;
} else if (boid.position[axis] < -limit) {
boid.position[axis] = -limit;
boid.velocity[axis] *= -0.8;
}
}
boid.group.position.copy(boid.position);
const lookTarget = new THREE.Vector3().copy(boid.position).add(boid.velocity);
boid.group.lookAt(lookTarget);
const lateralMotion = boid.velocity.x * Math.cos(boid.group.rotation.y) -
boid.velocity.z * Math.sin(boid.group.rotation.y);
const targetBank = THREE.MathUtils.clamp(-lateralMotion * 0.035, -0.42, 0.42);
boid.bank += (targetBank - boid.bank) * Math.min(1, delta * 5);
boid.group.rotateZ(boid.bank);
boid.phase += delta * boid.flapSpeed;
const flap = Math.sin(boid.phase) * 0.55;
boid.leftPivot.rotation.z = flap;
boid.rightPivot.rotation.z = -flap;
}
// Camera controls implemented directly, without Three.js addons.
const cameraTarget = new THREE.Vector3(0, 0, 0);
const cameraState = {
radius: 48,
theta: 0.62,
phi: 1.08
};
let dragging = false;
let previousX = 0;
let previousY = 0;
function updateCamera() {
const sinPhi = Math.sin(cameraState.phi);
camera.position.set(
cameraTarget.x + cameraState.radius * sinPhi * Math.sin(cameraState.theta),
cameraTarget.y + cameraState.radius * Math.cos(cameraState.phi),
cameraTarget.z + cameraState.radius * sinPhi * Math.cos(cameraState.theta)
);
camera.lookAt(cameraTarget);
}
renderer.domElement.addEventListener("pointerdown", (event) => {
dragging = true;
previousX = event.clientX;
previousY = event.clientY;
renderer.domElement.setPointerCapture(event.pointerId);
});
renderer.domElement.addEventListener("pointermove", (event) => {
if (!dragging) return;
const deltaX = event.clientX - previousX;
const deltaY = event.clientY - previousY;
cameraState.theta -= deltaX * 0.005;
cameraState.phi = THREE.MathUtils.clamp(
cameraState.phi - deltaY * 0.005,
0.22,
Math.PI - 0.22
);
previousX = event.clientX;
previousY = event.clientY;
});
function endDrag(event) {
dragging = false;
if (renderer.domElement.hasPointerCapture(event.pointerId)) {
renderer.domElement.releasePointerCapture(event.pointerId);
}
}
renderer.domElement.addEventListener("pointerup", endDrag);
renderer.domElement.addEventListener("pointercancel", endDrag);
renderer.domElement.addEventListener(
"wheel",
(event) => {
event.preventDefault();
cameraState.radius = THREE.MathUtils.clamp(
cameraState.radius + event.deltaY * 0.035,
18,
88
);
},
{ passive: false }
);
window.addEventListener("resize", () => {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
});
let paused = false;
const pauseButton = document.getElementById("pauseButton");
const stateLabel = document.getElementById("state");
function setPaused(value) {
paused = value;
pauseButton.textContent = paused ? "Resume" : "Pause";
stateLabel.textContent = paused ? "Paused" : "Live";
}
pauseButton.addEventListener("click", () => setPaused(!paused));
document.getElementById("resetButton").addEventListener("click", () => {
seedFlock();
});
window.addEventListener("keydown", (event) => {
if (event.target instanceof HTMLInputElement) return;
if (event.code === "Space") {
event.preventDefault();
setPaused(!paused);
}
if (event.key.toLowerCase() === "r") {
seedFlock();
}
if (event.key === "1") {
rules.separation = !rules.separation;
syncRuleInputs();
}
if (event.key === "2") {
rules.alignment = !rules.alignment;
syncRuleInputs();
}
if (event.key === "3") {
rules.cohesion = !rules.cohesion;
syncRuleInputs();
}
});
const clock = new THREE.Clock();
let elapsed = 0;
let fpsElapsed = 0;
let fpsFrames = 0;
let displayedFPS = 60;
function animate() {
const delta = Math.min(clock.getDelta(), 0.033);
elapsed += delta;
if (!paused) {
for (const boid of boids) {
updateBoid(boid, delta, elapsed);
}
}
dust.rotation.y += delta * 0.008;
dust.position.y = Math.sin(elapsed * 0.08) * 0.7;
updateCamera();
renderer.render(scene, camera);
fpsElapsed += delta;
fpsFrames++;
if (fpsElapsed >= 0.5) {
displayedFPS = Math.round(fpsFrames / fpsElapsed);
document.getElementById("fps").textContent = displayedFPS;
fpsElapsed = 0;
fpsFrames = 0;
}
}
renderer.setAnimationLoop(animate);
</script>
</body>
</html>
```