Prompt specification
Build or customize the Three.js 3D scene "Microbe navigating a porous environment" 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: Microbe navigating a porous environment
Category: Voxel Worlds · Style: Voxel 3D
License: MIT · Reference: https://three3d.app/scene/microbe-navigating-a-porous-environment-x0851
Scene Description Prompt:
Please create one self-contained HTML file with Three.js from cdnjs showing flagellated microbes. Compose a transparent microhabitat with passages, obstacles, and several swimming cells; keep bodies clear of walls and distinguish prescribed motion from a fluid simulation. Voxel style.
Working Three.js Starter (microbe-navigating-a-porous-environment-x0851):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Voxel Microhabitat</title>
<style>
:root {
color-scheme: dark;
--ink: #e8f8ff;
--muted: #8ca8b7;
--panel: rgba(7, 17, 29, 0.78);
--line: rgba(126, 221, 235, 0.22);
--amber: #ffc46a;
--cyan: #59f0e2;
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: #050a12;
font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
canvas {
display: block;
width: 100%;
height: 100%;
touch-action: none;
}
#hud {
position: fixed;
inset: 0;
pointer-events: none;
color: var(--ink);
}
.panel {
position: absolute;
top: 22px;
left: 22px;
width: min(340px, calc(100vw - 44px));
padding: 18px 18px 16px;
border: 1px solid var(--line);
border-radius: 14px;
background: var(--panel);
box-shadow:
0 18px 50px rgba(0, 0, 0, 0.35),
inset 0 1px rgba(255, 255, 255, 0.04);
backdrop-filter: blur(14px);
-webkit-backdrop-filter: blur(14px);
}
.eyebrow {
margin-bottom: 7px;
color: #70dce8;
font-size: 10px;
font-weight: 800;
letter-spacing: 0.22em;
text-transform: uppercase;
}
h1 {
margin: 0;
font-size: 23px;
line-height: 1.05;
letter-spacing: -0.035em;
}
.subtitle {
margin: 8px 0 16px;
color: var(--muted);
font-size: 12px;
line-height: 1.45;
}
.legend {
display: grid;
gap: 9px;
padding: 13px 0;
border-top: 1px solid var(--line);
border-bottom: 1px solid var(--line);
}
.legend-row {
display: grid;
grid-template-columns: 30px 1fr;
align-items: center;
gap: 9px;
font-size: 11px;
line-height: 1.3;
}
.symbol {
position: relative;
width: 24px;
height: 24px;
}
.symbol.script {
border: 1px solid var(--amber);
clip-path: polygon(
0 0, 36% 0, 36% 8%, 8% 8%, 8% 36%, 0 36%,
0 64%, 8% 64%, 8% 92%, 36% 92%, 36% 100%, 0 100%,
100% 100%, 64% 100%, 64% 92%, 92% 92%, 92% 64%, 100% 64%,
100% 36%, 92% 36%, 92% 8%, 64% 8%, 64% 0, 100% 0
);
background: rgba(255, 196, 106, 0.45);
}
.symbol.fluid {
border: 2px dotted var(--cyan);
border-radius: 50%;
background: rgba(89, 240, 226, 0.2);
box-shadow: 0 0 14px rgba(89, 240, 226, 0.24);
}
.legend strong {
display: block;
color: #f2fbff;
font-size: 11px;
letter-spacing: 0.04em;
}
.legend span {
color: var(--muted);
}
.controls {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 8px;
margin-top: 14px;
pointer-events: auto;
}
button {
min-height: 34px;
border: 1px solid rgba(111, 216, 228, 0.24);
border-radius: 8px;
color: #dffbff;
background: rgba(30, 65, 78, 0.46);
font: inherit;
font-size: 10px;
font-weight: 750;
letter-spacing: 0.08em;
text-transform: uppercase;
cursor: pointer;
transition:
background 150ms ease,
border-color 150ms ease,
transform 150ms ease;
}
button:hover {
border-color: rgba(111, 216, 228, 0.55);
background: rgba(42, 94, 106, 0.62);
}
button:active {
transform: translateY(1px);
}
button.active {
color: #061216;
background: #6cdddc;
border-color: #6cdddc;
}
.solver {
margin-top: 14px;
padding: 10px 11px;
border: 1px solid rgba(89, 240, 226, 0.13);
border-radius: 8px;
color: var(--muted);
background: rgba(3, 11, 18, 0.35);
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 9px;
line-height: 1.55;
}
.solver b {
color: #8ceee7;
font-weight: 600;
}
#hint {
position: absolute;
right: 22px;
bottom: 20px;
padding: 9px 12px;
border: 1px solid rgba(118, 207, 220, 0.16);
border-radius: 9px;
color: rgba(211, 238, 244, 0.66);
background: rgba(6, 15, 24, 0.58);
font-size: 10px;
letter-spacing: 0.06em;
backdrop-filter: blur(8px);
}
#credit {
position: absolute;
left: 24px;
bottom: 20px;
color: rgba(181, 216, 226, 0.42);
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 9px;
letter-spacing: 0.12em;
text-transform: uppercase;
}
#loading {
position: fixed;
inset: 0;
z-index: 10;
display: grid;
place-items: center;
color: #bceff3;
background: #050a12;
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 11px;
letter-spacing: 0.18em;
text-transform: uppercase;
}
@media (max-width: 620px) {
.panel {
top: 12px;
left: 12px;
width: calc(100vw - 24px);
padding: 14px;
}
.subtitle {
margin-bottom: 11px;
}
.solver {
display: none;
}
#hint {
right: 12px;
bottom: 12px;
}
#credit {
display: none;
}
}
</style>
</head>
<body>
<div id="loading">Building voxel microhabitat…</div>
<div id="hud">
<section class="panel">
<div class="eyebrow">Microscopic ecology / 01</div>
<h1>Voxel Microhabitat</h1>
<p class="subtitle">
A transparent, navigable lattice containing 18 flagellated microbes.
Two motion systems are intentionally color-coded.
</p>
<div class="legend">
<div class="legend-row">
<div class="symbol script"></div>
<div>
<strong>AMBER · Prescribed motion</strong>
<span>Square markers follow collision-free scripted waypoint loops.</span>
</div>
</div>
<div class="legend-row">
<div class="symbol fluid"></div>
<div>
<strong>CYAN · Fluid response</strong>
<span>Ring markers move through a projected Eulerian velocity field.</span>
</div>
</div>
</div>
<div class="controls">
<button id="pauseButton">Pause</button>
<button id="resetButton">Reset</button>
<button id="guideButton" class="active">Guides</button>
<button id="tracerButton" class="active">Flow</button>
</div>
<div class="solver">
<b>33 × 23 lattice</b> · semi-Lagrangian advection<br>
pressure projection · 10 Jacobi passes<br>
solid voxel boundaries · sampled collision envelope
</div>
</section>
<div id="hint">DRAG TO ORBIT · WHEEL TO ZOOM · DOUBLE-CLICK TO RESET VIEW</div>
<div id="credit">Three.js core / procedural habitat / no external assets</div>
</div>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
// -------------------------------------------------------------------------
// Constants and deterministic random utilities
// -------------------------------------------------------------------------
const NX = 33;
const NZ = 23;
const CELL = 1;
const ORIGIN_X = -16;
const ORIGIN_Z = -11;
const TOTAL = NX * NZ;
const SCRIPT_COUNT = 9;
const FLUID_COUNT = 9;
const TRACER_COUNT = 150;
let seed = 0x1a2b3c4d;
function random() {
seed |= 0;
seed = (seed + 0x6d2b79f5) | 0;
let t = Math.imul(seed ^ (seed >>> 15), 1 | seed);
t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
}
function clamp(v, min, max) {
return Math.max(min, Math.min(max, v));
}
function gridToWorld(gx, gz) {
return {
x: ORIGIN_X + gx + 0.5,
z: ORIGIN_Z + gz + 0.5
};
}
function worldToGrid(x, z) {
return {
gx: Math.floor(x - ORIGIN_X),
gz: Math.floor(z - ORIGIN_Z)
};
}
// -------------------------------------------------------------------------
// Renderer, scene, lighting
// -------------------------------------------------------------------------
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x050a12);
scene.fog = new THREE.FogExp2(0x050a12, 0.0115);
const renderer = new THREE.WebGLRenderer({
antialias: true,
alpha: false,
powerPreference: "high-performance"
});
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 1.8));
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.18;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
document.body.prepend(renderer.domElement);
const camera = new THREE.PerspectiveCamera(
42,
window.innerWidth / window.innerHeight,
0.1,
180
);
scene.add(new THREE.HemisphereLight(0x9addeb, 0x07101b, 1.7));
const keyLight = new THREE.DirectionalLight(0xc7f5ff, 2.4);
keyLight.position.set(8, 18, 12);
keyLight.castShadow = true;
keyLight.shadow.mapSize.set(2048, 2048);
keyLight.shadow.camera.left = -25;
keyLight.shadow.camera.right = 25;
keyLight.shadow.camera.top = 22;
keyLight.shadow.camera.bottom = -22;
keyLight.shadow.camera.near = 1;
keyLight.shadow.camera.far = 55;
keyLight.shadow.bias = -0.0004;
scene.add(keyLight);
const cyanLight = new THREE.PointLight(0x38d9e0, 42, 35, 2);
cyanLight.position.set(-12, 7, -7);
scene.add(cyanLight);
const amberLight = new THREE.PointLight(0xffa24b, 32, 28, 2);
amberLight.position.set(12, 5, 9);
scene.add(amberLight);
// -------------------------------------------------------------------------
// Habitat occupancy
// -------------------------------------------------------------------------
const occupancy = new Uint8Array(TOTAL);
const obstacleSet = new Set();
function cellIndex(gx, gz) {
return gz * NX + gx;
}
function markWall(gx, gz) {
if (gx >= 0 && gx < NX && gz >= 0 && gz < NZ) {
occupancy[cellIndex(gx, gz)] = 1;
}
}
function markObstacle(gx, gz) {
if (gx >= 0 && gx < NX && gz >= 0 && gz < NZ) {
occupancy[cellIndex(gx, gz)] = 1;
obstacleSet.add(cellIndex(gx, gz));
}
}
// Outer voxel boundary.
for (let gx = 0; gx < NX; gx++) {
markWall(gx, 0);
markWall(gx, NZ - 1);
}
for (let gz = 0; gz < NZ; gz++) {
markWall(0, gz);
markWall(NX - 1, gz);
}
function verticalWall(gx, start, end, gaps) {
for (let gz = start; gz <= end; gz++) {
if (!gaps.includes(gz)) markWall(gx, gz);
}
}
function horizontalWall(gz, start, end, gaps) {
for (let gx = start; gx <= end; gx++) {
if (!gaps.includes(gx)) markWall(gx, gz);
}
}
// Vertical partitions, including deliberate passage gaps.
verticalWall(7, 2, 20, [5, 10, 15]);
verticalWall(16, 1, 21, [4, 8, 13, 18]);
verticalWall(25, 2, 20, [5, 10, 15]);
// Horizontal partitions.
horizontalWall(6, 2, 30, [4, 10, 18, 26]);
horizontalWall(16, 2, 30, [3, 11, 19, 28]);
// Solid obstacle clusters, visually distinct from transparent partitions.
[
[3, 13], [4, 13],
[11, 3], [11, 4],
[20, 18], [21, 18],
[22, 9], [23, 9],
[28, 4], [29, 4],
[14, 12], [14, 13]
].forEach(([gx, gz]) => markObstacle(gx, gz));
const openCells = [];
for (let gz = 0; gz < NZ; gz++) {
for (let gx = 0; gx < NX; gx++) {
if (!occupancy[cellIndex(gx, gz)]) openCells.push({ gx, gz });
}
}
// -------------------------------------------------------------------------
// Habitat geometry: tiled floor, transparent voxel walls, solid obstacles
// -------------------------------------------------------------------------
const unitBox = new THREE.BoxGeometry(1, 1, 1);
const dummy = new THREE.Object3D();
function writeInstance(mesh, index, x, y, z, sx, sy, sz, ry = 0) {
dummy.position.set(x, y, z);
dummy.rotation.set(0, ry, 0);
dummy.scale.set(sx, sy, sz);
dummy.updateMatrix();
mesh.setMatrixAt(index, dummy.matrix);
}
const floorMaterial = new THREE.MeshStandardMaterial({
color: 0xffffff,
roughness: 0.94,
metalness: 0.04
});
const floor = new THREE.InstancedMesh(
unitBox,
floorMaterial,
NX * NZ
);
floor.receiveShadow = true;
let floorIndex = 0;
const tileColor = new THREE.Color();
for (let gz = 0; gz < NZ; gz++) {
for (let gx = 0; gx < NX; gx++) {
const p = gridToWorld(gx, gz);
writeInstance(floor, floorIndex, p.x, -0.47, p.z, 0.94, 0.09, 0.94);
const variation = 0.018 + random() * 0.025;
tileColor.setRGB(
0.025 + variation * 0.25,
0.065 + variation,
0.095 + variation * 1.4
);
floor.setColorAt(floorIndex, tileColor);
floorIndex++;
}
}
floor.instanceColor.needsUpdate = true;
scene.add(floor);
const baseMaterial = new THREE.MeshStandardMaterial({
color: 0x08121d,
roughness: 0.7,
metalness: 0.2
});
const base = new THREE.Mesh(
new THREE.BoxGeometry(NX * CELL + 0.3, 0.18, NZ * CELL + 0.3),
baseMaterial
);
base.position.set(0.5, -0.61, 0.5);
base.receiveShadow = true;
scene.add(base);
const barrierCells = [];
const obstacleCells = [];
for (let gz = 0; gz < NZ; gz++) {
for (let gx = 0; gx < NX; gx++) {
const index = cellIndex(gx, gz);
if (!occupancy[index]) continue;
if (obstacleSet.has(index)) {
obstacleCells.push({ gx, gz });
} else {
barrierCells.push({ gx, gz });
}
}
}
const barrierMaterial = new THREE.MeshStandardMaterial({
color: 0x69dce5,
emissive: 0x0b4c59,
emissiveIntensity: 0.5,
transparent: true,
opacity: 0.18,
depthWrite: false,
roughness: 0.28,
metalness: 0.06,
side: THREE.DoubleSide
});
const barriers = new THREE.InstancedMesh(
unitBox,
barrierMaterial,
barrierCells.length
);
barrierCells.forEach(({ gx, gz }, i) => {
const p = gridToWorld(gx, gz);
writeInstance(barriers, i, p.x, 0.49, p.z, 0.92, 1.86, 0.92);
});
barriers.instanceMatrix.needsUpdate = true;
barriers.renderOrder = 2;
scene.add(barriers);
const capMaterial = new THREE.MeshStandardMaterial({
color: 0x8cebf1,
emissive: 0x166875,
emissiveIntensity: 0.65,
transparent: true,
opacity: 0.38,
depthWrite: false,
roughness: 0.35
});
const barrierCaps = new THREE.InstancedMesh(
unitBox,
capMaterial,
barrierCells.length
);
barrierCells.forEach(({ gx, gz }, i) => {
const p = gridToWorld(gx, gz);
writeInstance(barrierCaps, i, p.x, 1.44, p.z, 0.94, 0.055, 0.94);
});
barrierCaps.instanceMatrix.needsUpdate = true;
barrierCaps.renderOrder = 3;
scene.add(barrierCaps);
const obstacleMaterial = new THREE.MeshStandardMaterial({
color: 0xbc5b72,
emissive: 0x41101f,
emissiveIntensity: 0.42,
roughness: 0.42,
metalness: 0.12
});
const obstacles = new THREE.InstancedMesh(
unitBox,
obstacleMaterial,
obstacleCells.length
);
obstacleCells.forEach(({ gx, gz }, i) => {
const p = gridToWorld(gx, gz);
writeInstance(obstacles, i, p.x, 0.23, p.z, 0.88, 1.28, 0.88);
});
obstacles.instanceMatrix.needsUpdate = true;
obstacles.castShadow = true;
obstacles.receiveShadow = true;
scene.add(obstacles);
const obstacleTopMaterial = new THREE.MeshStandardMaterial({
color: 0xffb184,
emissive: 0x6a241f,
emissiveIntensity: 0.55,
roughness: 0.45
});
const obstacleTops = new THREE.InstancedMesh(
unitBox,
obstacleTopMaterial,
obstacleCells.length
);
obstacleCells.forEach(({ gx, gz }, i) => {
const p = gridToWorld(gx, gz);
writeInstance(obstacleTops, i, p.x, 0.9, p.z, 0.58, 0.08, 0.58);
});
obstacleTops.instanceMatrix.needsUpdate = true;
scene.add(obstacleTops);
// Thin outer glass panels make the entire habitat read as a transparent tank.
const glassMaterial = new THREE.MeshBasicMaterial({
color: 0x8ee9f1,
transparent: true,
opacity: 0.035,
depthWrite: false,
side: THREE.DoubleSide
});
function glassPanel(width, height, depth, x, y, z) {
const panel = new THREE.Mesh(
new THREE.BoxGeometry(width, height, depth),
glassMaterial
);
panel.position.set(x, y, z);
scene.add(panel);
}
glassPanel(33.25, 2.8, 0.05, 0.5, 0.55, -11.1);
glassPanel(33.25, 2.8, 0.05, 0.5, 0.55, 12.1);
glassPanel(0.05, 2.8, 23.25, -16.1, 0.55, 0.5);
glassPanel(0.05, 2.8, 23.25, 17.1, 0.55, 0.5);
const rimMaterial = new THREE.MeshStandardMaterial({
color: 0x4aa7b3,
emissive: 0x0d3b43,
emissiveIntensity: 0.5,
transparent: true,
opacity: 0.32,
depthWrite: false
});
function rim(width, depth, x, z) {
const mesh = new THREE.Mesh(
new THREE.BoxGeometry(width, 0.08, depth),
rimMaterial
);
mesh.position.set(x, 1.58, z);
scene.add(mesh);
}
rim(33.25, 0.1, 0.5, -11.12);
rim(33.25, 0.1, 0.5, 12.12);
rim(0.1, 23.25, -16.12, 0.5);
rim(0.1, 23.25, 17.12, 0.5);
// -------------------------------------------------------------------------
// A* pathfinding on the occupied lattice
// -------------------------------------------------------------------------
function nearestOpen(gx, gz) {
if (
gx >= 0 && gx < NX && gz >= 0 && gz < NZ &&
!occupancy[cellIndex(gx, gz)]
) {
return { gx, gz };
}
let best = null;
let bestDistance = Infinity;
for (const cell of openCells) {
const distance =
Math.abs(cell.gx - gx) + Math.abs(cell.gz - gz);
if (distance < bestDistance) {
bestDistance = distance;
best = cell;
}
}
return best;
}
function aStar(start, goal) {
const startIndex = cellIndex(start.gx, start.gz);
const goalIndex = cellIndex(goal.gx, goal.gz);
if (startIndex === goalIndex) return [start];
const gScore = new Float32Array(TOTAL);
gScore.fill(Infinity);
const fScore = new Float32Array(TOTAL);
fScore.fill(Infinity);
const cameFrom = new Int32Array(TOTAL);
cameFrom.fill(-1);
const closed = new Uint8Array(TOTAL);
const inOpen = new Uint8Array(TOTAL);
const open = [];
const heuristic = (gx, gz) =>
Math.abs(gx - goal.gx) + Math.abs(gz - goal.gz);
gScore[startIndex] = 0;
fScore[startIndex] = heuristic(start.gx, start.gz);
open.push(startIndex);
inOpen[startIndex] = 1;
while (open.length) {
let bestOpen = 0;
for (let i = 1; i < open.length; i++) {
if (fScore[open[i]] < fScore[open[bestOpen]]) {
bestOpen = i;
}
}
const current = open.splice(bestOpen, 1)[0];
inOpen[current] = 0;
if (current === goalIndex) {
const path = [];
let cursor = current;
while (cursor !== -1) {
path.push({
gx: cursor % NX,
gz: Math.floor(cursor / NX)
});
cursor = cameFrom[cursor];
}
path.reverse();
return path;
}
closed[current] = 1;
const gx = current % NX;
const gz = Math.floor(current / NX);
const neighbors = [
[gx + 1, gz],
[gx - 1, gz],
[gx, gz + 1],
[gx, gz - 1]
];
for (const [nx, nz] of neighbors) {
if (
nx < 0 || nx >= NX || nz < 0 || nz >= NZ ||
occupancy[cellIndex(nx, nz)]
) {
continue;
}
const nextIndex = cellIndex(nx, nz);
if (closed[nextIndex]) continue;
const tentative = gScore[current] + 1;
if (tentative < gScore[nextIndex]) {
cameFrom[nextIndex] = current;
gScore[nextIndex] = tentative;
fScore[nextIndex] =
tentative + heuristic(nx, nz);
if (!inOpen[nextIndex]) {
open.push(nextIndex);
inOpen[nextIndex] = 1;
}
}
}
}
return [];
}
function makeCycle(rawWaypoints) {
const waypoints = rawWaypoints.map(([gx, gz]) =>
nearestOpen(gx, gz)
);
const cycle = [];
for (let i = 0; i < waypoints.length; i++) {
const a = waypoints[i];
const b = waypoints[(i + 1) % waypoints.length];
const segment = aStar(a, b);
for (const point of segment) {
const last = cycle[cycle.length - 1];
if (
!last ||
last.gx !== point.gx ||
last.gz !== point.gz
) {
cycle.push(point);
}
}
}
// The closing segment appended the first point again.
if (
cycle.length > 1 &&
cycle[0].gx === cycle[cycle.length - 1].gx &&
cycle[0].gz === cycle[cycle.length - 1].gz
) {
cycle.pop();
}
return cycle;
}
const routeDefinitions = [
[
[2, 3], [6, 3], [6, 5], [10, 5],
[10, 10], [3, 10], [3, 5], [2, 5]
],
[
[20, 3], [20, 4], [14, 4], [14, 8],
[20, 8], [20, 13], [22, 13], [22, 10],
[28, 10], [30, 10], [30, 18], [28, 18],
[28, 16], [28, 15], [22, 15], [22, 13],
[20, 13]
],
[
[2, 13], [2, 11], [6, 11], [6, 15],
[11, 15], [11, 18], [11, 16], [11, 13],
[6, 13], [2, 13]
]
];
const routes = routeDefinitions.map(makeCycle);
// Dotted amber voxel guides make the prescribed paths explicit.
const guideMeshes = [];
const guideMaterials = [
new THREE.MeshStandardMaterial({
color: 0xffbf62,
emissive: 0x63300d,
emissiveIntensity: 0.7,
transparent: true,
opacity: 0.42,
depthWrite: false
}),
new THREE.MeshStandardMaterial({
color: 0xffd18a,
emissive: 0x63300d,
emissiveIntensity: 0.55,
transparent: true,
opacity: 0.34,
depthWrite: false
}),
new THREE.MeshStandardMaterial({
color: 0xe9a54c,
emissive: 0x52260a,
emissiveIntensity: 0.65,
transparent: true,
opacity: 0.38,
depthWrite: false
})
];
routes.forEach((route, routeIndex) => {
const guidePoints = [];
for (let i = 0; i < route.length; i += 2) {
guidePoints.push(route[i]);
}
guidePoints.push(route[0]);
const mesh = new THREE.InstancedMesh(
new THREE.BoxGeometry(0.11, 0.11, 0.11),
guideMaterials[routeIndex],
guidePoints.length
);
guidePoints.forEach((point, i) => {
const p = gridToWorld(point.gx, point.gz);
writeInstance(mesh, i, p.x, -0.36, p.z, 1, 1, 1);
});
mesh.instanceMatrix.needsUpdate = true;
mesh.renderOrder = 4;
scene.add(mesh);
guideMeshes.push(mesh);
});
// -------------------------------------------------------------------------
// Voxel microbes
// -------------------------------------------------------------------------
const amberCoreMaterial = new THREE.MeshStandardMaterial({
color: 0xffbe5b,
emissive: 0x8b3c0c,
emissiveIntensity: 0.8,
roughness: 0.38,
metalness: 0.08
});
const cyanCoreMaterial = new THREE.MeshStandardMaterial({
color: 0x4be2d7,
emissive: 0x07575a,
emissiveIntensity: 0.85,
roughness: 0.34,
metalness: 0.08
});
const amberMarkerMaterial = new THREE.MeshStandardMaterial({
color: 0xffe0a2,
emissive: 0x70400e,
emissiveIntensity: 0.75,
transparent: true,
opacity: 0.9,
depthWrite: false
});
const cyanMarkerMaterial = new THREE.MeshStandardMaterial({
color: 0xa4fff4,
emissive: 0x126c69,
emissiveIntensity: 0.8,
transparent: true,
opacity: 0.85,
depthWrite: false
});
const eyeMaterial = new THREE.MeshStandardMaterial({
color: 0x08131a,
emissive: 0x102b31,
emissiveIntensity: 0.3,
roughness: 0.25
});
const coreTransforms = [
[0.00, 0.00, 0.00, 0.30, 0.24, 0.24],
[0.16, 0.00, 0.00, 0.18, 0.20, 0.22],
[-0.15, 0.00, 0.00, 0.18, 0.18, 0.20],
[0.00, 0.11, 0.00, 0.20, 0.14, 0.20],
[0.00, -0.10, 0.00, 0.20, 0.12, 0.20],
[0.00, 0.00, 0.11, 0.20, 0.20, 0.10],
[0.00, 0.00, -0.11, 0.20, 0.20, 0.10],
[0.12, 0.11, 0.00, 0.12, 0.10, 0.12],
[0.12, -0.11, 0.00, 0.12, 0.10, 0.12]
];
const FLAGELLA_PER_CHAIN = 5;
const FLAGELLA_CHAINS = 3;
const FLAGELLA_COUNT = FLAGELLA_PER_CHAIN * FLAGELLA_CHAINS;
function createMarkerTransforms(type) {
const transforms = [];
if (type === "script") {
// Angular corner brackets.
for (const sx of [-1, 1]) {
for (const sz of [-1, 1]) {
transforms.push([sx * 0.38, 0, sz * 0.24, 0.065]);
transforms.push([sx * 0.33, 0, sz * 0.24, 0.065]);
transforms.push([sx * 0.38, 0, sz * 0.19, 0.065]);
}
}
} else {
// Discrete circular halo.
for (let i = 0; i < 12; i++) {
const angle = (i / 12) * Math.PI * 2;
transforms.push([
Math.cos(angle) * 0.40,
0,
Math.sin(angle) * 0.29,
0.062
]);
}
}
return transforms;
}
const microbes = [];
function createMicrobe(type, id) {
const group = new THREE.Group();
group.position.y = 0.45;
scene.add(group);
const coreMaterial = type === "script"
? amberCoreMaterial
: cyanCoreMaterial;
const markerMaterial = type === "script"
? amberMarkerMaterial
: cyanMarkerMaterial;
const core = new THREE.InstancedMesh(
unitBox,
coreMaterial,
coreTransforms.length
);
coreTransforms.forEach((t, i) => {
writeInstance(core, i, ...t);
});
core.instanceMatrix.needsUpdate = true;
core.castShadow = true;
group.add(core);
const eyes = new THREE.InstancedMesh(
unitBox,
eyeMaterial,
2
);
writeInstance(eyes, 0, 0.285, 0.055, 0.095, 0.06, 0.06, 0.06);
writeInstance(eyes, 1, 0.285, 0.055, -0.095, 0.06, 0.06, 0.06);
eyes.instanceMatrix.needsUpdate = true;
group.add(eyes);
const markerTransforms = createMarkerTransforms(type);
const marker = new THREE.InstancedMesh(
unitBox,
markerMaterial,
markerTransforms.length
);
markerTransforms.forEach((t, i) => {
writeInstance(marker, i, ...t);
});
marker.instanceMatrix.needsUpdate = true;
marker.renderOrder = 6;
group.add(marker);
const flagella = new THREE.InstancedMesh(
unitBox,
coreMaterial,
FLAGELLA_COUNT
);
flagella.instanceMatrix.setUsage(THREE.DynamicDrawUsage);
flagella.frustumCulled = false;
group.add(flagella);
const microbe = {
id,
type,
group,
core,
marker,
flagella,
phase: random() * Math.PI * 2,
heading: new THREE.Vector2(1, 0),
baseY: 0.45 + (random() - 0.5) * 0.05
};
microbes.push(microbe);
return microbe;
}
const scriptCells = [];
const fluidCells = [];
for (let i = 0; i < SCRIPT_COUNT; i++) {
const cell = createMicrobe("script", i);
const route = routes[i % routes.length];
const start = gridToWorld(route[0].gx, route[0].gz);
cell.route = route;
cell.routeIndex = Math.floor(i / 3) *
Math.max(1, Math.floor(route.length / 3));
cell.group.position.set(start.x, cell.baseY, start.z);
scriptCells.push(cell);
}
function randomOpenCell() {
return openCells[Math.floor(random() * openCells.length)];
}
for (let i = 0; i < FLUID_COUNT; i++) {
const cell = createMicrobe("fluid", SCRIPT_COUNT + i);
const spawn = randomOpenCell();
const p = gridToWorld(spawn.gx, spawn.gz);
const angle = random() * Math.PI * 2;
cell.group.position.set(p.x, cell.baseY, p.z);
cell.heading.set(Math.cos(angle), Math.sin(angle));
fluidCells.push(cell);
}
// -------------------------------------------------------------------------
// Coarse 2D Eulerian fluid solver
//
// Semi-Lagrangian velocity advection followed by a Jacobi pressure solve
// and gradient subtraction. Solid lattice cells impose no-slip boundaries.
// -------------------------------------------------------------------------
const fluid = {
u: new Float32Array(TOTAL),
v: new Float32Array(TOTAL),
u0: new Float32Array(TOTAL),
v0: new Float32Array(TOTAL),
pressure: new Float32Array(TOTAL),
pressureNext: new Float32Array(TOTAL),
divergence: new Float32Array(TOTAL)
};
function initializeFluid() {
fluid.u.fill(0);
fluid.v.fill(0);
for (let gz = 0; gz < NZ; gz++) {
for (let gx = 0; gx < NX; gx++) {
const index = cellIndex(gx, gz);
if (occupancy[index]) continue;
fluid.u[index] =
1.7 * Math.sin((gz + 1) * 0.43) +
0.7 * Math.cos(gz * 0.17);
fluid.v[index] =
1.35 * Math.cos((gx - 5) * 0.31) +
0.55 * Math.sin(gx * 0.21);
const vortex =
Math.exp(
-(
(gx - 19) * (gx - 19) +
(gz - 10) * (gz - 10)
) / 34
);
fluid.v[index] += vortex * 1.4;
}
}
projectFluid(18);
}
function sampleField(field, gx, gz) {
const x = clamp(gx, 0, NX - 1.001);
const z = clamp(gz, 0, NZ - 1.001);
const x0 = Math.floor(x);
const z0 = Math.floor(z);
const x1 = Math.min(x0 + 1, NX - 1);
const z1 = Math.min(z0 + 1, NZ - 1);
const tx = x - x0;
const tz = z - z0;
const a = field[cellIndex(x0, z0)];
const b = field[cellIndex(x1, z0)];
const c = field[cellIndex(x0, z1)];
const d = field[cellIndex(x1, z1)];
return (
a * (1 - tx) * (1 - tz) +
b * tx * (1 - tz) +
c * (1 - tx) * tz +
d * tx * tz
);
}
function projectFluid(iterations) {
fluid.pressure.fill(0);
fluid.pressureNext.fill(0);
for (let gz = 0; gz < NZ; gz++) {
for (let gx = 0; gx < NX; gx++) {
const index = cellIndex(gx, gz);
if (occupancy[index]) continue;
const leftIndex = cellIndex(Math.max(0, gx - 1), gz);
const rightIndex = cellIndex(Math.min(NX - 1, gx + 1), gz);
const upIndex = cellIndex(gx, Math.max(0, gz - 1));
const downIndex = cellIndex(gx, Math.min(NZ - 1, gz + 1));
const leftSolid = occupancy[leftIndex];
const rightSolid = occupancy[rightIndex];
const upSolid = occupancy[upIndex];
const downSolid = occupancy[downIndex];
const uLeft = leftSolid ? fluid.u[index] : fluid.u[leftIndex];
const uRight = rightSolid ? fluid.u[index] : fluid.u[rightIndex];
const vUp = upSolid ? fluid.v[index] : fluid.v[upIndex];
const vDown = downSolid ? fluid.v[index] : fluid.v[downIndex];
fluid.divergence[index] =
-0.5 * (uRight - uLeft + vDown - vUp);
}
}
for (let iteration = 0; iteration < iterations; iteration++) {
for (let gz = 0; gz < NZ; gz++) {
for (let gx = 0; gx < NX; gx++) {
const index = cellIndex(gx, gz);
if (occupancy[index]) {
fluid.pressureNext[index] = 0;
continue;
}
const left = cellIndex(Math.max(0, gx - 1), gz);
const right = cellIndex(Math.min(NX - 1, gx + 1), gz);
const up = cellIndex(gx, Math.max(0, gz - 1));
const down = cellIndex(gx, Math.min(NZ - 1, gz + 1));
fluid.pressureNext[index] = (
fluid.divergence[index] +
fluid.pressure[left] +
fluid.pressure[right] +
fluid.pressure[up] +
fluid.pressure[down]
) * 0.25;
}
}
fluid.pressure.set(fluid.pressureNext);
}
for (let gz = 0; gz < NZ; gz++) {
for (let gx = 0; gx < NX; gx++) {
const index = cellIndex(gx, gz);
if (occupancy[index]) {
fluid.u[index] = 0;
fluid.v[index] = 0;
continue;
}
const left = cellIndex(Math.max(0, gx - 1), gz);
const right = cellIndex(Math.min(NX - 1, gx + 1), gz);
const up = cellIndex(gx, Math.max(0, gz - 1));
const down = cellIndex(gx, Math.min(NZ - 1, gz + 1));
fluid.u[index] -= 0.5 * (
fluid.pressure[right] - fluid.pressure[left]
);
fluid.v[index] -= 0.5 * (
fluid.pressure[down] - fluid.pressure[up]
);
}
}
}
function stepFluid(dt, time) {
fluid.u0.set(fluid.u);
fluid.v0.set(fluid.v);
for (let gz = 0; gz < NZ; gz++) {
for (let gx = 0; gx < NX; gx++) {
const index = cellIndex(gx, gz);
if (occupancy[index]) {
fluid.u[index] = 0;
fluid.v[index] = 0;
continue;
}
// A gentle, smooth forcing keeps the projected field evolving.
fluid.u[index] +=
dt * 0.22 * Math.sin(gz * 0.47 + time * 0.35);
fluid.v[index] +=
dt * 0.22 * Math.cos(gx * 0.38 - time * 0.31);
const sourceX = gx - dt * fluid.u0[index];
const sourceZ = gz - dt * fluid.v0[index];
const sourceIndex = cellIndex(
clamp(Math.floor(sourceX), 0, NX - 1),
clamp(Math.floor(sourceZ), 0, NZ - 1)
);
if (!occupancy[sourceIndex]) {
fluid.u[index] = sampleField(fluid.u0, sourceX, sourceZ);
fluid.v[index] = sampleField(fluid.v0, sourceX, sourceZ);
}
}
}
projectFluid(10);
}
// -------------------------------------------------------------------------
// Collision-safe movement
// -------------------------------------------------------------------------
const collisionOffsets = [];
for (let i = 0; i < 12; i++) {
const angle = (i / 12) * Math.PI * 2;
collisionOffsets.push([
Math.cos(angle) * 0.37,
Math.sin(angle) * 0.37
]);
}
function isClear(x, z) {
for (const [ox, oz] of collisionOffsets) {
const { gx, gz } = worldToGrid(x + ox, z + oz);
if (gx < 0 || gx >= NX || gz < 0 || gz >= NZ) {
return false;
}
if (occupancy[cellIndex(gx, gz)]) {
return false;
}
}
return true;
}
function angleLerp(current, target, amount) {
const difference = Math.atan2(
Math.sin(target - current),
Math.cos(target - current)
);
return current + difference * amount;
}
function updateScriptCell(cell, dt, time) {
const route = cell.route;
const nextIndex = (cell.routeIndex + 1) % route.length;
const current = gridToWorld(
route[cell.routeIndex].gx,
route[cell.routeIndex].gz
);
const target = gridToWorld(
route[nextIndex].gx,
route[nextIndex].gz
);
const dx = target.x - current.x;
const dz = target.z - current.z;
const distance = Math.hypot(dx, dz);
const speed = 1.18 + (cell.id % 3) * 0.08;
if (distance <= speed * dt) {
cell.group.position.x = target.x;
cell.group.position.z = target.z;
cell.routeIndex = nextIndex;
} else {
cell.group.position.x += dx / distance * speed * dt;
cell.group.position.z += dz / distance * speed * dt;
}
if (distance > 0.0001) {
const targetAngle = Math.atan2(-dz, dx);
cell.group.rotation.y = angleLerp(
cell.group.rotation.y,
targetAngle,
0.18
);
}
cell.group.position.y =
cell.baseY + Math.sin(time * 1.7 + cell.phase) * 0.035;
}
function updateFluidCell(cell, dt, time) {
const position = cell.group.position;
const grid = worldToGrid(position.x, position.z);
const flowU = sampleField(
fluid.u,
position.x - ORIGIN_X - 0.5,
position.z - ORIGIN_Z - 0.5
);
const flowV = sampleField(
fluid.v,
position.x - ORIGIN_X - 0.5,
position.z - ORIGIN_Z - 0.5
);
const wiggle = Math.sin(time * 3.2 + cell.phase) * 0.22;
let desiredX =
cell.heading.x * 1.42 +
flowU * 0.62 -
cell.heading.y * wiggle;
let desiredY =
cell.heading.y * 1.42 +
flowV * 0.62 +
cell.heading.x * wiggle;
const desiredLength = Math.hypot(desiredX, desiredY) || 1;
desiredX /= desiredLength;
desiredY /= desiredLength;
cell.heading.x += (desiredX - cell.heading.x) * 0.075;
cell.heading.y += (desiredY - cell.heading.y) * 0.075;
const headingLength =
Math.hypot(cell.heading.x, cell.heading.y) || 1;
cell.heading.x /= headingLength;
cell.heading.y /= headingLength;
const speed = 1.28 + (cell.id % 4) * 0.06;
const nextX = position.x + cell.heading.x * speed * dt;
const nextZ = position.z + cell.heading.y * speed * dt;
if (isClear(nextX, nextZ)) {
position.x = nextX;
position.z = nextZ;
} else if (isClear(nextX, position.z)) {
position.x = nextX;
} else if (isClear(position.x, nextZ)) {
position.z = nextZ;
} else {
cell.heading.set(-cell.heading.y, cell.heading.x);
}
position.y =
cell.baseY + Math.sin(time * 1.8 + cell.phase) * 0.045;
const targetAngle = Math.atan2(-cell.heading.y, cell.heading.x);
cell.group.rotation.y = angleLerp(
cell.group.rotation.y,
targetAngle,
0.12
);
}
function updateFlagella(cell, time) {
let instance = 0;
for (let chain = 0; chain < FLAGELLA_CHAINS; chain++) {
for (let segment = 0; segment < FLAGELLA_PER_CHAIN; segment++) {
const wave = Math.sin(
time * 8.2 +
segment * 0.78 +
chain * 1.9 +
cell.phase
);
const x = -0.27 - segment * 0.105;
const z =
(chain - 1) * 0.085 +
wave * (0.015 + segment * 0.009);
const y =
-0.025 +
Math.cos(time * 7.4 + segment * 0.66 + cell.phase) *
0.012;
writeInstance(
cell.flagella,
instance,
x,
y,
z,
0.11,
0.052,
0.052
);
instance++;
}
}
cell.flagella.instanceMatrix.needsUpdate = true;
}
// -------------------------------------------------------------------------
// Flow tracer voxels
// -------------------------------------------------------------------------
const tracerMaterial = new THREE.MeshStandardMaterial({
color: 0x67e9e2,
emissive: 0x0a7774,
emissiveIntensity: 0.8,
transparent: true,
opacity: 0.5,
depthWrite: false
});
const tracerMesh = new THREE.InstancedMesh(
new THREE.BoxGeometry(0.075, 0.075, 0.075),
tracerMaterial,
TRACER_COUNT
);
tracerMesh.instanceMatrix.setUsage(THREE.DynamicDrawUsage);
tracerMesh.frustumCulled = false;
tracerMesh.renderOrder = 5;
scene.add(tracerMesh);
const tracers = [];
function resetTracer(tracer) {
const cell = randomOpenCell();
const p = gridToWorld(cell.gx, cell.gz);
tracer.x = p.x;
tracer.z = p.z;
tracer.life = random() * 9;
tracer.phase = random() * Math.PI * 2;
}
for (let i = 0; i < TRACER_COUNT; i++) {
const tracer = {};
resetTracer(tracer);
tracers.push(tracer);
}
function updateTracers(dt, time) {
tracers.forEach((tracer, i) => {
const flowU = sampleField(
fluid.u,
tracer.x - ORIGIN_X - 0.5,
tracer.z - ORIGIN_Z - 0.5
);
const flowV = sampleField(
fluid.v,
tracer.x - ORIGIN_X - 0.5,
tracer.z - ORIGIN_Z - 0.5
);
const nextX = tracer.x + flowU * dt * 0.72;
const nextZ = tracer.z + flowV * dt * 0.72;
tracer.life += dt;
if (
!isClear(nextX, nextZ) ||
tracer.life > 13 ||
!Number.isFinite(nextX) ||
!Number.isFinite(nextZ)
) {
resetTracer(tracer);
} else {
tracer.x = nextX;
tracer.z = nextZ;
}
writeInstance(
tracerMesh,
i,
tracer.x,
-0.31 + Math.sin(time * 2 + tracer.phase) * 0.025,
tracer.z,
1,
1,
1
);
});
tracerMesh.instanceMatrix.needsUpdate = true;
}
initializeFluid();
// -------------------------------------------------------------------------
// Direct camera controls: orbit, zoom, double-click reset
// -------------------------------------------------------------------------
const orbit = {
theta: 0.77,
phi: 0.86,
radius: 42,
target: new THREE.Vector3(0.5, 0.15, 0.5)
};
let dragging = false;
let previousX = 0;
let previousY = 0;
function updateCamera() {
const sinPhi = Math.sin(orbit.phi);
camera.position.set(
orbit.target.x + orbit.radius * sinPhi * Math.cos(orbit.theta),
orbit.target.y + orbit.radius * Math.cos(orbit.phi),
orbit.target.z + orbit.radius * sinPhi * Math.sin(orbit.theta)
);
camera.lookAt(orbit.target);
}
function resetCamera() {
orbit.theta = 0.77;
orbit.phi = 0.86;
orbit.radius = 42;
}
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 dx = event.clientX - previousX;
const dy = event.clientY - previousY;
previousX = event.clientX;
previousY = event.clientY;
orbit.theta -= dx * 0.006;
orbit.phi = clamp(orbit.phi + dy * 0.005, 0.34, 1.43);
});
function endDrag(event) {
dragging = false;
if (
event.pointerId !== undefined &&
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();
orbit.radius = clamp(
orbit.radius * Math.exp(event.deltaY * 0.001),
24,
64
);
},
{ passive: false }
);
renderer.domElement.addEventListener("dblclick", resetCamera);
// -------------------------------------------------------------------------
// UI and reset
// -------------------------------------------------------------------------
let paused = false;
let guidesVisible = true;
let tracersVisible = true;
const pauseButton = document.getElementById("pauseButton");
const resetButton = document.getElementById("resetButton");
const guideButton = document.getElementById("guideButton");
const tracerButton = document.getElementById("tracerButton");
pauseButton.addEventListener("click", () => {
paused = !paused;
pauseButton.textContent = paused ? "Resume" : "Pause";
pauseButton.classList.toggle("active", paused);
});
guideButton.addEventListener("click", () => {
guidesVisible = !guidesVisible;
guideMeshes.forEach((mesh) => {
mesh.visible = guidesVisible;
});
guideButton.classList.toggle("active", guidesVisible);
});
tracerButton.addEventListener("click", () => {
tracersVisible = !tracersVisible;
tracerMesh.visible = tracersVisible;
tracerButton.classList.toggle("active", tracersVisible);
});
resetButton.addEventListener("click", () => {
initializeFluid();
scriptCells.forEach((cell) => {
const route = cell.route;
const start = gridToWorld(route[0].gx, route[0].gz);
cell.routeIndex = 0;
cell.group.position.set(start.x, cell.baseY, start.z);
cell.group.rotation.set(0, 0, 0);
});
fluidCells.forEach((cell) => {
const spawn = randomOpenCell();
const p = gridToWorld(spawn.gx, spawn.gz);
const angle = random() * Math.PI * 2;
cell.group.position.set(p.x, cell.baseY, p.z);
cell.heading.set(Math.cos(angle), Math.sin(angle));
});
tracers.forEach(resetTracer);
});
// -------------------------------------------------------------------------
// Main loop
// -------------------------------------------------------------------------
const clock = new THREE.Clock();
let simulationTime = 0;
function animate() {
requestAnimationFrame(animate);
const dt = Math.min(clock.getDelta(), 0.033);
if (!paused) {
simulationTime += dt;
stepFluid(dt, simulationTime);
scriptCells.forEach((cell) => {
updateScriptCell(cell, dt, simulationTime);
});
fluidCells.forEach((cell) => {
updateFluidCell(cell, dt, simulationTime);
});
microbes.forEach((cell) => {
updateFlagella(cell, simulationTime);
});
if (tracersVisible) {
updateTracers(dt, simulationTime);
}
}
updateCamera();
renderer.render(scene, camera);
}
window.addEventListener("resize", () => {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 1.8));
});
updateCamera();
animate();
document.getElementById("loading").remove();
</script>
</body>
</html>
```