Prompt specification
Build or customize the Three.js 3D scene "Three-neighbor flocking diagram" 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: Three-neighbor flocking diagram
Category: Voxel Worlds · Style: Voxel 3D
License: MIT · Reference: https://three3d.app/scene/three-neighbor-flocking-diagram-x0685
Scene Description Prompt:
Make a voxel Three.js scene in a self-contained HTML file using cdnjs: three-neighbor flocking diagram. Show one bird-like agent with nearby neighbors and separate alignment, cohesion, and separation arrows; keep the vectors distinct from the animals' physical wings.
Working Three.js Starter (three-neighbor-flocking-diagram-x0685):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Voxel Flocking — Three Neighbors</title>
<style>
:root {
color-scheme: dark;
--bg: #07111f;
--panel: rgba(8, 19, 34, 0.82);
--line: rgba(139, 176, 211, 0.22);
--text: #edf7ff;
--muted: #91a9c1;
--alignment: #58dcff;
--cohesion: #cb8cff;
--separation: #ffc857;
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: var(--bg);
font-family:
Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
color: var(--text);
}
#scene {
display: block;
width: 100%;
height: 100%;
touch-action: none;
}
.hud {
position: fixed;
inset: 0;
pointer-events: none;
}
.brand {
position: absolute;
top: 28px;
left: 30px;
max-width: 520px;
text-shadow: 0 2px 20px rgba(0, 0, 0, 0.45);
}
.eyebrow {
display: flex;
align-items: center;
gap: 9px;
margin-bottom: 10px;
color: #79ddff;
font: 700 11px/1.2 ui-monospace, SFMono-Regular, Menlo, monospace;
letter-spacing: 0.16em;
text-transform: uppercase;
}
.eyebrow::before {
content: "";
width: 26px;
height: 3px;
background: #58dcff;
box-shadow: 0 0 14px rgba(88, 220, 255, 0.7);
}
h1 {
margin: 0;
font-size: clamp(30px, 4.2vw, 58px);
line-height: 0.98;
letter-spacing: -0.055em;
}
.brand p {
max-width: 440px;
margin: 14px 0 0;
color: #b7c9dc;
font-size: 14px;
line-height: 1.55;
}
.panel {
position: absolute;
top: 26px;
right: 26px;
width: min(330px, calc(100vw - 52px));
padding: 18px;
border: 1px solid var(--line);
border-radius: 16px;
background: var(--panel);
box-shadow:
0 18px 60px rgba(0, 0, 0, 0.28),
inset 0 1px rgba(255, 255, 255, 0.04);
backdrop-filter: blur(16px);
-webkit-backdrop-filter: blur(16px);
pointer-events: auto;
}
.panel-heading {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 14px;
padding-bottom: 12px;
border-bottom: 1px solid var(--line);
font: 700 11px/1 ui-monospace, SFMono-Regular, Menlo, monospace;
letter-spacing: 0.13em;
text-transform: uppercase;
}
.count {
color: #8ba3bb;
letter-spacing: 0.06em;
}
.force-row {
display: grid;
grid-template-columns: 11px 1fr;
gap: 11px;
padding: 11px 0;
}
.force-row + .force-row {
border-top: 1px solid rgba(139, 176, 211, 0.11);
}
.swatch {
width: 9px;
height: 9px;
margin-top: 4px;
border-radius: 2px;
box-shadow: 0 0 12px currentColor;
}
.swatch.alignment {
color: var(--alignment);
background: var(--alignment);
}
.swatch.cohesion {
color: var(--cohesion);
background: var(--cohesion);
}
.swatch.separation {
color: var(--separation);
background: var(--separation);
}
.force-name {
display: block;
margin-bottom: 5px;
font: 800 12px/1.2 ui-monospace, SFMono-Regular, Menlo, monospace;
letter-spacing: 0.08em;
}
.alignment-text {
color: var(--alignment);
}
.cohesion-text {
color: var(--cohesion);
}
.separation-text {
color: var(--separation);
}
.formula {
display: block;
color: #a9bbce;
font: 11px/1.4 ui-monospace, SFMono-Regular, Menlo, monospace;
white-space: nowrap;
}
.panel-note {
margin: 13px 0 0;
padding-top: 13px;
border-top: 1px solid var(--line);
color: #839bb3;
font-size: 11px;
line-height: 1.5;
}
.status {
position: absolute;
left: 30px;
bottom: 27px;
display: flex;
flex-wrap: wrap;
gap: 9px;
align-items: center;
}
.chip {
display: flex;
align-items: center;
gap: 8px;
min-height: 34px;
padding: 0 12px;
border: 1px solid var(--line);
border-radius: 9px;
background: rgba(8, 19, 34, 0.76);
color: #b7c9dc;
font: 700 10px/1 ui-monospace, SFMono-Regular, Menlo, monospace;
letter-spacing: 0.08em;
text-transform: uppercase;
backdrop-filter: blur(10px);
}
.chip strong {
color: #ffffff;
font-size: 12px;
}
.dot {
width: 6px;
height: 6px;
border-radius: 50%;
background: #ff9a4d;
box-shadow: 0 0 10px rgba(255, 154, 77, 0.8);
}
.controls {
position: absolute;
right: 26px;
bottom: 27px;
display: flex;
align-items: center;
gap: 12px;
color: #829bb4;
font: 600 10px/1 ui-monospace, SFMono-Regular, Menlo, monospace;
letter-spacing: 0.06em;
text-transform: uppercase;
}
button {
border: 1px solid var(--line);
border-radius: 8px;
padding: 9px 11px;
background: rgba(8, 19, 34, 0.8);
color: #dcecff;
font: 700 10px/1 ui-monospace, SFMono-Regular, Menlo, monospace;
letter-spacing: 0.08em;
text-transform: uppercase;
cursor: pointer;
pointer-events: auto;
}
button:hover {
border-color: rgba(88, 220, 255, 0.55);
color: #ffffff;
background: rgba(17, 43, 67, 0.9);
}
@media (max-width: 760px) {
.brand {
top: 20px;
left: 20px;
right: 20px;
}
.brand p {
display: none;
}
.panel {
top: auto;
right: 12px;
bottom: 72px;
width: calc(100vw - 24px);
padding: 13px 15px;
}
.force-row {
display: inline-grid;
width: 32%;
vertical-align: top;
padding: 8px 4px;
}
.force-row + .force-row {
border-top: 0;
}
.formula {
white-space: normal;
font-size: 9px;
}
.panel-note {
display: none;
}
.status {
left: 12px;
bottom: 15px;
}
.controls {
display: none;
}
}
</style>
</head>
<body>
<canvas id="scene" aria-label="Interactive voxel flocking diagram with three neighboring birds"></canvas>
<div class="hud">
<header class="brand">
<div class="eyebrow">Voxel boids / local neighborhood</div>
<h1>Three neighbors.<br>Three forces.</h1>
<p>
The orange bird is the focal agent. Its three nearby neighbors produce
independent alignment, cohesion, and separation vectors on the elevated
analysis plane.
</p>
</header>
<aside class="panel">
<div class="panel-heading">
<span>Local force stack</span>
<span class="count">03 neighbors</span>
</div>
<div class="force-row">
<span class="swatch alignment"></span>
<div>
<span class="force-name alignment-text">Alignment</span>
<span class="formula">mean(v₁, v₂, v₃) − v₀</span>
</div>
</div>
<div class="force-row">
<span class="swatch cohesion"></span>
<div>
<span class="force-name cohesion-text">Cohesion</span>
<span class="formula">mean(p₁, p₂, p₃) − p₀</span>
</div>
</div>
<div class="force-row">
<span class="swatch separation"></span>
<div>
<span class="force-name separation-text">Separation</span>
<span class="formula">Σ normalize(p₀ − pᵢ)</span>
</div>
</div>
<p class="panel-note">
Colored vector blocks are lifted above the flock on a separate diagram
plane. The birds’ physical wings remain dark, broad voxel geometry.
Directions are calculated; arrow lengths are illustrative.
</p>
</aside>
<div class="status">
<div class="chip"><span class="dot"></span><strong>03</strong> agents in radius</div>
<div class="chip">4.2 m neighborhood</div>
<div class="chip">Focal agent selected</div>
</div>
<div class="controls">
<span>Drag: orbit · Wheel: zoom · Shift/right drag: pan</span>
<button id="reset-view" type="button">Reset view</button>
</div>
</div>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
// ---------------------------------------------------------------------
// Renderer and scene
// ---------------------------------------------------------------------
const canvas = document.querySelector("#scene");
const renderer = new THREE.WebGLRenderer({
canvas,
antialias: true,
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.12;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x07111f);
scene.fog = new THREE.Fog(0x07111f, 18, 36);
const camera = new THREE.PerspectiveCamera(
43,
window.innerWidth / window.innerHeight,
0.1,
100
);
const cameraState = {
theta: 0.72,
phi: 0.83,
radius: 14.5,
target: new THREE.Vector3(0, 0.9, 0)
};
function updateCamera() {
const { theta, phi, radius, target } = cameraState;
const horizontal = Math.sin(phi) * radius;
camera.position.set(
target.x + horizontal * Math.sin(theta),
target.y + Math.cos(phi) * radius,
target.z + horizontal * Math.cos(theta)
);
camera.lookAt(target);
}
updateCamera();
// ---------------------------------------------------------------------
// Lighting
// ---------------------------------------------------------------------
scene.add(new THREE.HemisphereLight(0x9ed5ff, 0x142137, 1.8));
const keyLight = new THREE.DirectionalLight(0xffffff, 3.1);
keyLight.position.set(6, 12, 8);
keyLight.castShadow = true;
keyLight.shadow.mapSize.set(2048, 2048);
keyLight.shadow.camera.left = -12;
keyLight.shadow.camera.right = 12;
keyLight.shadow.camera.top = 12;
keyLight.shadow.camera.bottom = -12;
keyLight.shadow.camera.near = 1;
keyLight.shadow.camera.far = 35;
keyLight.shadow.bias = -0.0003;
scene.add(keyLight);
const warmLight = new THREE.PointLight(0xff8a42, 26, 12, 2);
warmLight.position.set(-4, 4.5, 1);
scene.add(warmLight);
const coolLight = new THREE.PointLight(0x45cfff, 22, 14, 2);
coolLight.position.set(5, 5, -5);
scene.add(coolLight);
// ---------------------------------------------------------------------
// Shared geometry and materials
// ---------------------------------------------------------------------
const unitBox = new THREE.BoxGeometry(1, 1, 1);
const wingMaterial = new THREE.MeshStandardMaterial({
color: 0x17263a,
roughness: 0.82,
metalness: 0.04
});
const wingTipMaterial = new THREE.MeshStandardMaterial({
color: 0x3c526c,
roughness: 0.76,
metalness: 0.05
});
const beakMaterial = new THREE.MeshStandardMaterial({
color: 0xffcf67,
roughness: 0.66
});
const eyeMaterial = new THREE.MeshStandardMaterial({
color: 0xf5fbff,
roughness: 0.52
});
const pupilMaterial = new THREE.MeshStandardMaterial({
color: 0x06101d,
roughness: 0.4
});
function addBlock(
parent,
material,
sizeX,
sizeY,
sizeZ,
x = 0,
y = 0,
z = 0
) {
const mesh = new THREE.Mesh(unitBox, material);
mesh.scale.set(sizeX, sizeY, sizeZ);
mesh.position.set(x, y, z);
mesh.castShadow = true;
mesh.receiveShadow = true;
parent.add(mesh);
return mesh;
}
// ---------------------------------------------------------------------
// Voxel ground
// ---------------------------------------------------------------------
const floor = new THREE.Mesh(
new THREE.PlaneGeometry(80, 80),
new THREE.MeshStandardMaterial({
color: 0x06101c,
roughness: 1
})
);
floor.rotation.x = -Math.PI / 2;
floor.position.y = -0.14;
floor.receiveShadow = true;
scene.add(floor);
const tileCount = 17 * 17;
const tileMaterial = new THREE.MeshStandardMaterial({
color: 0xffffff,
roughness: 0.94,
metalness: 0.02
});
const tiles = new THREE.InstancedMesh(unitBox, tileMaterial, tileCount);
tiles.receiveShadow = true;
const dummy = new THREE.Object3D();
const tileColor = new THREE.Color();
let tileIndex = 0;
for (let x = -8; x <= 8; x++) {
for (let z = -8; z <= 8; z++) {
dummy.position.set(x, -0.06, z);
dummy.scale.set(0.94, 0.12, 0.94);
dummy.rotation.set(0, 0, 0);
dummy.updateMatrix();
tiles.setMatrixAt(tileIndex, dummy.matrix);
const variation = ((x * 17 + z * 31 + 10000) % 9) / 9;
tileColor.setHSL(
0.585,
0.34,
0.052 + variation * 0.017
);
tiles.setColorAt(tileIndex, tileColor);
tileIndex++;
}
}
tiles.instanceMatrix.needsUpdate = true;
tiles.instanceColor.needsUpdate = true;
scene.add(tiles);
// ---------------------------------------------------------------------
// Canvas texture labels
// ---------------------------------------------------------------------
function roundedRect(context, x, y, width, height, radius) {
const r = Math.min(radius, width / 2, height / 2);
context.beginPath();
context.moveTo(x + r, y);
context.lineTo(x + width - r, y);
context.quadraticCurveTo(x + width, y, x + width, y + r);
context.lineTo(x + width, y + height - r);
context.quadraticCurveTo(
x + width,
y + height,
x + width - r,
y + height
);
context.lineTo(x + r, y + height);
context.quadraticCurveTo(x, y + height, x, y + height - r);
context.lineTo(x, y + r);
context.quadraticCurveTo(x, y, x + r, y);
context.closePath();
}
function makeTextSprite(
text,
color = "#ffffff",
width = 2.4,
height = 0.58
) {
const labelCanvas = document.createElement("canvas");
labelCanvas.width = 512;
labelCanvas.height = 128;
const context = labelCanvas.getContext("2d");
context.clearRect(0, 0, 512, 128);
roundedRect(context, 8, 12, 496, 104, 18);
context.fillStyle = "rgba(6, 15, 28, 0.90)";
context.fill();
context.lineWidth = 4;
context.strokeStyle = color;
context.stroke();
context.fillStyle = color;
context.font =
'700 40px ui-monospace, SFMono-Regular, Menlo, Consolas, monospace';
context.textAlign = "center";
context.textBaseline = "middle";
context.fillText(text, 256, 66);
const texture = new THREE.CanvasTexture(labelCanvas);
texture.colorSpace = THREE.SRGBColorSpace;
texture.minFilter = THREE.LinearFilter;
texture.generateMipmaps = false;
const material = new THREE.SpriteMaterial({
map: texture,
transparent: true,
depthTest: false,
depthWrite: false
});
const sprite = new THREE.Sprite(material);
sprite.scale.set(width, height, 1);
sprite.renderOrder = 20;
return sprite;
}
// ---------------------------------------------------------------------
// Pixel rings and neighbor links
// ---------------------------------------------------------------------
function makePixelRing(
radius,
color,
opacity = 0.35,
count = 72,
tileWidth = 0.055,
tileDepth = 0.16
) {
const material = new THREE.MeshBasicMaterial({
color,
transparent: true,
opacity,
depthWrite: false
});
const ring = new THREE.InstancedMesh(unitBox, material, count);
const object = new THREE.Object3D();
for (let i = 0; i < count; i++) {
const angle = (i / count) * Math.PI * 2;
object.position.set(
Math.cos(angle) * radius,
0.055,
Math.sin(angle) * radius
);
object.scale.set(tileWidth, 0.025, tileDepth);
object.rotation.set(0, angle, 0);
object.updateMatrix();
ring.setMatrixAt(i, object.matrix);
}
ring.instanceMatrix.needsUpdate = true;
ring.frustumCulled = false;
scene.add(ring);
return ring;
}
const NEIGHBOR_RADIUS = 4.2;
makePixelRing(NEIGHBOR_RADIUS, 0x58dcff, 0.31, 84);
makePixelRing(1.03, 0xff9a4d, 0.76, 36, 0.065, 0.19);
// ---------------------------------------------------------------------
// Flocking data
// ---------------------------------------------------------------------
const focal = {
position: new THREE.Vector3(0, 0, 0),
heading: new THREE.Vector3(1, 0, 0)
};
const neighborDefinitions = [
{
position: new THREE.Vector3(-2.8, 0, -1.7),
heading: new THREE.Vector3(0.35, 0, 0.94),
color: 0x3f8cff
},
{
position: new THREE.Vector3(-2.4, 0, 2.2),
heading: new THREE.Vector3(0.25, 0, 0.97),
color: 0x497fe6
},
{
position: new THREE.Vector3(-0.9, 0, -2.8),
heading: new THREE.Vector3(0.42, 0, 0.91),
color: 0x5ba4e8
}
];
const averageHeading = new THREE.Vector3();
const averagePosition = new THREE.Vector3();
const separation = new THREE.Vector3();
for (const neighbor of neighborDefinitions) {
averageHeading.add(neighbor.heading);
averagePosition.add(neighbor.position);
const away = focal.position.clone().sub(neighbor.position);
away.y = 0;
away.normalize();
separation.add(away);
const linkGeometry = new THREE.BufferGeometry().setFromPoints([
new THREE.Vector3(focal.position.x, 0.17, focal.position.z),
new THREE.Vector3(neighbor.position.x, 0.17, neighbor.position.z)
]);
const link = new THREE.Line(
linkGeometry,
new THREE.LineDashedMaterial({
color: 0x7897b8,
dashSize: 0.18,
gapSize: 0.13,
transparent: true,
opacity: 0.48
})
);
link.computeLineDistances();
scene.add(link);
}
averageHeading.multiplyScalar(1 / neighborDefinitions.length);
averagePosition.multiplyScalar(1 / neighborDefinitions.length);
// Alignment: average neighbor heading minus the focal heading.
const alignmentDirection = averageHeading
.clone()
.sub(focal.heading)
.normalize();
// Cohesion: direction from the focal agent to the neighbor centroid.
const cohesionDirection = averagePosition
.clone()
.sub(focal.position)
.normalize();
// Separation: sum of normalized directions away from each neighbor.
const separationDirection = separation.normalize();
// ---------------------------------------------------------------------
// Voxel bird construction
// ---------------------------------------------------------------------
const birds = [];
function createBird(definition, index, isFocal = false) {
const root = new THREE.Group();
root.position.copy(definition.position);
root.rotation.y = Math.atan2(
definition.heading.x,
definition.heading.z
);
const bodyMaterial = new THREE.MeshStandardMaterial({
color: definition.color,
roughness: 0.7,
metalness: 0.04
});
// Torso, head, beak, and tail are all rectangular voxel pieces.
addBlock(root, bodyMaterial, 0.82, 0.56, 0.92, 0, 0.53, 0);
addBlock(root, bodyMaterial, 0.62, 0.58, 0.58, 0, 0.72, 0.65);
addBlock(root, beakMaterial, 0.25, 0.19, 0.35, 0, 0.68, 1.10);
addBlock(root, wingMaterial, 0.48, 0.42, 0.52, 0, 0.52, -0.72);
addBlock(root, wingMaterial, 0.18, 0.32, 0.42, -0.27, 0.54, -0.74);
addBlock(root, wingMaterial, 0.18, 0.32, 0.42, 0.27, 0.54, -0.74);
// Broad, dark physical wings.
const leftWing = new THREE.Group();
const rightWing = new THREE.Group();
leftWing.position.set(-0.43, 0.64, -0.02);
rightWing.position.set(0.43, 0.64, -0.02);
addBlock(leftWing, wingMaterial, 0.52, 0.12, 0.68, -0.27, 0, 0);
addBlock(leftWing, wingTipMaterial, 0.18, 0.13, 0.56, -0.55, 0, -0.02);
addBlock(rightWing, wingMaterial, 0.52, 0.12, 0.68, 0.27, 0, 0);
addBlock(rightWing, wingTipMaterial, 0.18, 0.13, 0.56, 0.55, 0, -0.02);
root.add(leftWing, rightWing);
// Small square eyes.
addBlock(root, eyeMaterial, 0.09, 0.09, 0.05, -0.16, 0.82, 0.946);
addBlock(root, eyeMaterial, 0.09, 0.09, 0.05, 0.16, 0.82, 0.946);
addBlock(root, pupilMaterial, 0.045, 0.045, 0.025, -0.16, 0.82, 0.978);
addBlock(root, pupilMaterial, 0.045, 0.045, 0.025, 0.16, 0.82, 0.978);
scene.add(root);
const label = makeTextSprite(
isFocal ? "FOCAL" : `NEIGHBOR ${index + 1}`,
isFocal ? "#ff9a4d" : "#8dc6ff",
isFocal ? 1.65 : 2.15,
isFocal ? 0.4 : 0.46
);
label.position.set(
definition.position.x,
isFocal ? 1.42 : 1.38,
definition.position.z
);
scene.add(label);
return {
root,
leftWing,
rightWing,
phase: index * 1.7,
isFocal
};
}
birds.push(
createBird(
{
position: focal.position,
heading: focal.heading,
color: 0xff8a3d
},
0,
true
)
);
neighborDefinitions.forEach((neighbor, index) => {
birds.push(createBird(neighbor, index, false));
});
// ---------------------------------------------------------------------
// Elevated force-analysis plane
// ---------------------------------------------------------------------
const FORCE_PLANE_Y = 2.32;
const ARROW_Y = 2.47;
const forceGrid = new THREE.GridHelper(
8,
8,
0x476986,
0x22384e
);
forceGrid.position.y = FORCE_PLANE_Y;
forceGrid.material.transparent = true;
forceGrid.material.opacity = 0.28;
forceGrid.material.depthWrite = false;
scene.add(forceGrid);
// A dashed vertical guide makes the separation between the animal layer
// and the analytical vector plane explicit.
const verticalGuide = new THREE.Line(
new THREE.BufferGeometry().setFromPoints([
new THREE.Vector3(0, 1.1, 0),
new THREE.Vector3(0, FORCE_PLANE_Y, 0)
]),
new THREE.LineDashedMaterial({
color: 0x8aa5bd,
dashSize: 0.08,
gapSize: 0.08,
transparent: true,
opacity: 0.5
})
);
verticalGuide.computeLineDistances();
scene.add(verticalGuide);
const planeLabel = makeTextSprite(
"FORCE PLANE",
"#839db6",
1.85,
0.38
);
planeLabel.position.set(0, 3.32, 0);
scene.add(planeLabel);
// ---------------------------------------------------------------------
// Blocky force arrows
// ---------------------------------------------------------------------
const forceArrows = [];
function createVoxelArrow(direction, length, color, labelText) {
const group = new THREE.Group();
group.position.set(0, ARROW_Y, 0);
const material = new THREE.MeshStandardMaterial({
color,
emissive: color,
emissiveIntensity: 0.58,
roughness: 0.42,
metalness: 0.04
});
const shaftLength = length - 0.43;
addBlock(
group,
material,
0.075,
0.075,
shaftLength,
0,
0,
shaftLength / 2
);
// Stepped cube arrowhead.
addBlock(group, material, 0.14, 0.14, 0.14, 0, 0, length - 0.07);
addBlock(group, material, 0.26, 0.26, 0.20, 0, 0, length - 0.21);
addBlock(group, material, 0.40, 0.40, 0.20, 0, 0, length - 0.37);
const direction3D = new THREE.Vector3(
direction.x,
0,
direction.z
).normalize();
group.quaternion.setFromUnitVectors(
new THREE.Vector3(0, 0, 1),
direction3D
);
scene.add(group);
const label = makeTextSprite(labelText, color, 2.35, 0.55);
label.position.set(
direction3D.x * (length + 0.43),
ARROW_Y + 0.38,
direction3D.z * (length + 0.43)
);
scene.add(label);
forceArrows.push({ group, material });
return group;
}
createVoxelArrow(
alignmentDirection,
3.45,
0x58dcff,
"ALIGNMENT"
);
createVoxelArrow(
cohesionDirection,
2.85,
0xcb8cff,
"COHESION"
);
createVoxelArrow(
separationDirection,
3.15,
0xffc857,
"SEPARATION"
);
// Central vector origin marker.
const originMaterial = new THREE.MeshBasicMaterial({
color: 0xeaf8ff
});
addBlock(scene, originMaterial, 0.13, 0.11, 0.13, 0, ARROW_Y, 0);
const alignmentOriginMaterial = new THREE.MeshBasicMaterial({
color: 0x58dcff
});
const cohesionOriginMaterial = new THREE.MeshBasicMaterial({
color: 0xcb8cff
});
const separationOriginMaterial = new THREE.MeshBasicMaterial({
color: 0xffc857
});
addBlock(
scene,
alignmentOriginMaterial,
0.09,
0.08,
0.09,
-0.17,
ARROW_Y,
0
);
addBlock(
scene,
cohesionOriginMaterial,
0.09,
0.08,
0.09,
0.17,
ARROW_Y,
0
);
addBlock(
scene,
separationOriginMaterial,
0.09,
0.08,
0.09,
0,
ARROW_Y,
0.17
);
// ---------------------------------------------------------------------
// Direct camera controls: orbit, zoom, and pan
// ---------------------------------------------------------------------
let dragging = false;
let dragButton = 0;
let lastX = 0;
let lastY = 0;
canvas.addEventListener("contextmenu", event => {
event.preventDefault();
});
canvas.addEventListener("pointerdown", event => {
dragging = true;
dragButton = event.button;
lastX = event.clientX;
lastY = event.clientY;
canvas.setPointerCapture(event.pointerId);
});
canvas.addEventListener("pointermove", event => {
if (!dragging) return;
const dx = event.clientX - lastX;
const dy = event.clientY - lastY;
lastX = event.clientX;
lastY = event.clientY;
const wantsPan =
dragButton === 2 ||
dragButton === 1 ||
event.shiftKey;
if (wantsPan) {
const forward = new THREE.Vector3();
camera.getWorldDirection(forward);
const right = new THREE.Vector3()
.crossVectors(forward, camera.up)
.normalize();
const up = new THREE.Vector3()
.crossVectors(right, forward)
.normalize();
const panScale = cameraState.radius * 0.0012;
cameraState.target
.addScaledVector(right, -dx * panScale)
.addScaledVector(up, dy * panScale);
cameraState.target.y = THREE.MathUtils.clamp(
cameraState.target.y,
-0.5,
4
);
} else {
cameraState.theta -= dx * 0.006;
cameraState.phi = THREE.MathUtils.clamp(
cameraState.phi - dy * 0.005,
0.25,
1.45
);
}
});
function stopDragging(event) {
dragging = false;
if (event && canvas.hasPointerCapture(event.pointerId)) {
canvas.releasePointerCapture(event.pointerId);
}
}
canvas.addEventListener("pointerup", stopDragging);
canvas.addEventListener("pointercancel", stopDragging);
canvas.addEventListener(
"wheel",
event => {
event.preventDefault();
cameraState.radius = THREE.MathUtils.clamp(
cameraState.radius * Math.exp(event.deltaY * 0.001),
7.5,
25
);
},
{ passive: false }
);
function resetCamera() {
cameraState.theta = 0.72;
cameraState.phi = 0.83;
cameraState.radius = 14.5;
cameraState.target.set(0, 0.9, 0);
}
document.querySelector("#reset-view").addEventListener("click", resetCamera);
canvas.addEventListener("dblclick", resetCamera);
// ---------------------------------------------------------------------
// Animation and resize
// ---------------------------------------------------------------------
const clock = new THREE.Clock();
function animate() {
const time = clock.getElapsedTime();
birds.forEach((bird, index) => {
bird.root.position.y =
Math.sin(time * 1.7 + bird.phase) * 0.035;
const flap =
0.14 + Math.sin(time * 5.1 + bird.phase) * 0.14;
bird.leftWing.rotation.z = -flap;
bird.rightWing.rotation.z = flap;
// A nearly imperceptible body roll adds life without changing the
// neighbor positions used by the flocking calculations.
bird.root.rotation.z =
Math.sin(time * 1.25 + bird.phase) * 0.012;
});
forceArrows.forEach((arrow, index) => {
arrow.material.emissiveIntensity =
0.54 + Math.sin(time * 2.4 + index * 1.3) * 0.12;
});
updateCamera();
renderer.render(scene, camera);
requestAnimationFrame(animate);
}
window.addEventListener("resize", () => {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
});
animate();
</script>
</body>
</html>
```