Prompt specification
Build or customize the Three.js 3D scene "Colony detection threshold explorer" 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: Colony detection threshold explorer
Category: Voxel Worlds · Style: Voxel 3D
License: MIT · Reference: https://three3d.app/scene/colony-detection-threshold-explorer-x0832
Scene Description Prompt:
Adjust the detection threshold on a synthetic voxel colony pattern and watch counted regions change. Make one HTML file with Three.js from cdnjs.
Working Three.js Starter (colony-detection-threshold-explorer-x0832):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>ColonyScan — Voxel Threshold Explorer</title>
<style>
:root {
color-scheme: dark;
--bg: #071019;
--panel: #0b1722;
--panel-2: #0e1d29;
--border: #1b3040;
--text: #e8f4fa;
--muted: #7891a3;
--accent: #45e3f2;
--accent-2: #8b7cf6;
--warning: #f4a742;
--success: #66e6a6;
}
* {
box-sizing: border-box;
}
html,
body {
margin: 0;
min-height: 100%;
background: var(--bg);
color: var(--text);
font-family:
Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
body {
overflow: hidden;
}
button,
input {
font: inherit;
}
button {
color: inherit;
}
.app {
display: grid;
grid-template-rows: 68px minmax(0, 1fr);
height: 100vh;
}
.topbar {
z-index: 10;
display: flex;
align-items: center;
justify-content: space-between;
gap: 20px;
padding: 0 24px;
border-bottom: 1px solid var(--border);
background: rgba(7, 16, 25, 0.92);
backdrop-filter: blur(16px);
}
.brand {
display: flex;
align-items: center;
gap: 12px;
min-width: 0;
}
.logo {
position: relative;
width: 34px;
height: 34px;
flex: 0 0 auto;
border: 1px solid rgba(69, 227, 242, 0.45);
border-radius: 10px;
background:
linear-gradient(135deg, rgba(69, 227, 242, 0.18), rgba(139, 124, 246, 0.16));
box-shadow: 0 0 24px rgba(69, 227, 242, 0.08);
}
.logo::before,
.logo::after {
content: "";
position: absolute;
border-radius: 2px;
background: var(--accent);
box-shadow: 0 0 10px rgba(69, 227, 242, 0.55);
}
.logo::before {
width: 7px;
height: 7px;
top: 8px;
left: 8px;
}
.logo::after {
width: 9px;
height: 9px;
right: 6px;
bottom: 6px;
background: var(--accent-2);
box-shadow: 0 0 10px rgba(139, 124, 246, 0.55);
}
.brand h1 {
margin: 0;
font-size: 16px;
font-weight: 700;
letter-spacing: 0.01em;
}
.brand p {
margin: 3px 0 0;
color: var(--muted);
font-size: 11px;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.top-actions {
display: flex;
align-items: center;
gap: 10px;
}
.live-pill,
.seed-pill {
display: inline-flex;
align-items: center;
gap: 7px;
height: 32px;
padding: 0 11px;
border: 1px solid var(--border);
border-radius: 999px;
color: #9db1bf;
background: rgba(14, 29, 41, 0.7);
font-size: 10px;
font-weight: 700;
letter-spacing: 0.08em;
}
.live-dot {
width: 7px;
height: 7px;
border-radius: 50%;
background: var(--success);
box-shadow: 0 0 10px rgba(102, 230, 166, 0.8);
}
.button {
height: 34px;
padding: 0 13px;
border: 1px solid #294454;
border-radius: 9px;
background: #102330;
cursor: pointer;
font-size: 12px;
font-weight: 650;
transition:
border-color 160ms ease,
background 160ms ease,
transform 160ms ease;
}
.button:hover {
border-color: rgba(69, 227, 242, 0.55);
background: #142c39;
}
.button:active {
transform: translateY(1px);
}
.button.primary {
color: #031014;
border-color: transparent;
background: var(--accent);
}
.button.primary:hover {
background: #7aedf7;
}
main {
display: grid;
grid-template-columns: 330px minmax(0, 1fr);
min-height: 0;
}
aside {
z-index: 5;
min-height: 0;
overflow-y: auto;
padding: 18px;
border-right: 1px solid var(--border);
background:
linear-gradient(180deg, rgba(12, 26, 37, 0.98), rgba(8, 19, 29, 0.98));
scrollbar-color: #294454 transparent;
scrollbar-width: thin;
}
.section {
padding: 0 0 18px;
margin-bottom: 18px;
border-bottom: 1px solid var(--border);
}
.section:last-child {
margin-bottom: 0;
border-bottom: 0;
}
.section-title {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 14px;
}
.section-title h2 {
margin: 0;
color: #b9cbd6;
font-size: 10px;
font-weight: 750;
letter-spacing: 0.13em;
text-transform: uppercase;
}
.control-label {
display: flex;
align-items: baseline;
justify-content: space-between;
gap: 16px;
margin-bottom: 11px;
}
.control-label label {
color: #dceaf1;
font-size: 13px;
font-weight: 650;
}
output {
color: var(--accent);
font-family: "SFMono-Regular", Consolas, monospace;
font-size: 13px;
font-weight: 700;
}
input[type="range"] {
--pct: 50%;
width: 100%;
height: 4px;
margin: 0;
border-radius: 999px;
outline: none;
appearance: none;
background: linear-gradient(
to right,
var(--accent) 0,
var(--accent) var(--pct),
#213746 var(--pct),
#213746 100%
);
cursor: pointer;
}
input[type="range"]::-webkit-slider-thumb {
width: 16px;
height: 16px;
border: 3px solid #d9fbff;
border-radius: 50%;
appearance: none;
background: #20bfd0;
box-shadow: 0 0 0 4px rgba(69, 227, 242, 0.12);
}
input[type="range"]::-moz-range-thumb {
width: 11px;
height: 11px;
border: 3px solid #d9fbff;
border-radius: 50%;
background: #20bfd0;
box-shadow: 0 0 0 4px rgba(69, 227, 242, 0.12);
}
.range-notes {
display: flex;
justify-content: space-between;
gap: 10px;
margin-top: 9px;
color: #617b8c;
font-size: 10px;
}
.signal-note {
margin-top: 13px;
padding: 10px 11px;
border: 1px solid rgba(69, 227, 242, 0.12);
border-radius: 9px;
color: #8fa8b7;
background: rgba(69, 227, 242, 0.045);
font-size: 11px;
line-height: 1.5;
}
.signal-note strong {
color: #cdebf0;
font-weight: 650;
}
.chart-wrap {
position: relative;
height: 108px;
overflow: hidden;
border: 1px solid var(--border);
border-radius: 10px;
background: #08131d;
}
#histogram {
display: block;
width: 100%;
height: 100%;
}
.chart-caption {
display: flex;
justify-content: space-between;
margin-top: 7px;
color: #617b8c;
font-size: 10px;
}
.stats {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 8px;
}
.stat {
min-height: 74px;
padding: 12px;
border: 1px solid var(--border);
border-radius: 10px;
background: rgba(13, 29, 40, 0.72);
}
.stat-label {
color: #6f899a;
font-size: 9px;
font-weight: 700;
letter-spacing: 0.09em;
text-transform: uppercase;
}
.stat-value {
margin-top: 8px;
color: #edf9ff;
font-family: "SFMono-Regular", Consolas, monospace;
font-size: 21px;
font-weight: 750;
}
.stat-value.accent {
color: var(--accent);
}
.seed-controls {
display: grid;
grid-template-columns: minmax(0, 1fr) auto;
gap: 8px;
}
.seed-controls input {
width: 100%;
min-width: 0;
height: 34px;
padding: 0 10px;
border: 1px solid #294454;
border-radius: 8px;
outline: none;
color: #d9eaf2;
background: #0b1923;
font-family: "SFMono-Regular", Consolas, monospace;
font-size: 12px;
}
.seed-controls input:focus {
border-color: rgba(69, 227, 242, 0.6);
}
.toggle-row {
display: flex;
align-items: center;
justify-content: space-between;
margin-top: 12px;
color: #91a8b6;
font-size: 11px;
}
.toggle-row input {
accent-color: var(--accent);
}
.region-list {
display: grid;
gap: 6px;
max-height: 250px;
overflow-y: auto;
scrollbar-width: thin;
}
.region-row {
display: grid;
grid-template-columns: 10px minmax(0, 1fr) auto;
align-items: center;
gap: 9px;
min-height: 39px;
padding: 7px 9px;
border: 1px solid rgba(36, 59, 74, 0.72);
border-radius: 8px;
background: rgba(12, 28, 39, 0.65);
}
.swatch {
width: 8px;
height: 8px;
border-radius: 3px;
box-shadow: 0 0 9px currentColor;
}
.region-main {
min-width: 0;
}
.region-name {
display: flex;
justify-content: space-between;
gap: 8px;
color: #bfd1dc;
font-size: 10px;
}
.region-bar {
height: 3px;
margin-top: 6px;
overflow: hidden;
border-radius: 999px;
background: #172d3a;
}
.region-bar > span {
display: block;
height: 100%;
border-radius: inherit;
}
.region-size {
color: #7894a4;
font-family: "SFMono-Regular", Consolas, monospace;
font-size: 9px;
}
.empty-state {
padding: 18px 12px;
border: 1px dashed #284252;
border-radius: 9px;
color: #668090;
text-align: center;
font-size: 11px;
line-height: 1.5;
}
#viewport {
position: relative;
min-width: 0;
min-height: 0;
overflow: hidden;
background: #071019;
}
#viewport > canvas {
position: absolute;
inset: 0;
display: block;
outline: none;
touch-action: none;
}
.stage-hud {
position: absolute;
z-index: 3;
top: 18px;
left: 18px;
min-width: 215px;
padding: 13px 15px;
border: 1px solid rgba(54, 84, 103, 0.75);
border-radius: 12px;
background: rgba(7, 17, 26, 0.78);
box-shadow: 0 12px 40px rgba(0, 0, 0, 0.18);
backdrop-filter: blur(12px);
pointer-events: none;
}
.eyebrow {
color: #668596;
font-size: 9px;
font-weight: 750;
letter-spacing: 0.13em;
text-transform: uppercase;
}
#stageCount {
display: block;
margin-top: 6px;
color: #f0fbff;
font-size: 21px;
font-weight: 740;
}
#stageDetail {
display: block;
margin-top: 5px;
color: #7892a2;
font-size: 10px;
}
.stage-meta {
position: absolute;
z-index: 3;
top: 18px;
right: 18px;
display: flex;
gap: 8px;
pointer-events: none;
}
.meta-chip {
padding: 8px 10px;
border: 1px solid rgba(54, 84, 103, 0.72);
border-radius: 8px;
color: #83a0b1;
background: rgba(7, 17, 26, 0.72);
font-size: 9px;
font-weight: 650;
letter-spacing: 0.06em;
text-transform: uppercase;
backdrop-filter: blur(10px);
}
.stage-bottom {
position: absolute;
z-index: 3;
right: 18px;
bottom: 18px;
left: 18px;
display: flex;
align-items: flex-end;
justify-content: space-between;
gap: 20px;
pointer-events: none;
}
.legend {
display: flex;
flex-wrap: wrap;
gap: 13px;
padding: 9px 12px;
border: 1px solid rgba(54, 84, 103, 0.65);
border-radius: 9px;
background: rgba(7, 17, 26, 0.72);
backdrop-filter: blur(10px);
}
.legend-item {
display: flex;
align-items: center;
gap: 7px;
color: #7892a2;
font-size: 9px;
}
.legend-dot {
width: 8px;
height: 8px;
border-radius: 3px;
}
.legend-dot.detected {
background: var(--accent);
box-shadow: 0 0 8px rgba(69, 227, 242, 0.55);
}
.legend-dot.excluded {
background: var(--warning);
}
.legend-dot.ghost {
border: 1px solid #496879;
background: #1e3a49;
}
.camera-help {
color: #627c8d;
font-size: 10px;
text-align: right;
line-height: 1.6;
}
.camera-help strong {
color: #9bb1be;
font-weight: 600;
}
#resetView {
position: absolute;
z-index: 5;
right: 18px;
top: 62px;
}
#loading {
position: absolute;
z-index: 20;
inset: 0;
display: grid;
place-items: center;
color: #8ca6b5;
background: #071019;
font-size: 12px;
letter-spacing: 0.08em;
text-transform: uppercase;
transition: opacity 250ms ease;
}
#loading.hidden {
opacity: 0;
pointer-events: none;
}
@media (max-width: 860px) {
body {
overflow: auto;
}
.app {
display: block;
height: auto;
min-height: 100vh;
}
.topbar {
height: 68px;
padding: 0 14px;
}
.brand p,
.live-pill,
.seed-pill {
display: none;
}
main {
display: flex;
flex-direction: column;
}
#viewport {
order: -1;
height: 62vh;
min-height: 430px;
}
aside {
overflow: visible;
border-top: 1px solid var(--border);
border-right: 0;
}
.stage-meta {
display: none;
}
.camera-help {
display: none;
}
}
</style>
</head>
<body>
<div class="app">
<header class="topbar">
<div class="brand">
<div class="logo" aria-hidden="true"></div>
<div>
<h1>ColonyScan</h1>
<p>Synthetic voxel morphology</p>
</div>
</div>
<div class="top-actions">
<div class="live-pill">
<span class="live-dot"></span>
Live field
</div>
<div class="seed-pill" id="seedPill">Seed 8421</div>
<button class="button primary" id="newSeedButton">New pattern</button>
</div>
</header>
<main>
<aside>
<section class="section">
<div class="section-title">
<h2>Detection controls</h2>
</div>
<div class="control-label">
<label for="threshold">Signal threshold</label>
<output id="thresholdValue" for="threshold">0.46</output>
</div>
<input
id="threshold"
type="range"
min="0.18"
max="0.90"
step="0.01"
value="0.46"
/>
<div class="range-notes">
<span>More sensitive</span>
<span>More selective</span>
</div>
<div class="signal-note">
Voxels at or above the threshold are selected.
<strong id="retainedText">—</strong>
</div>
</section>
<section class="section">
<div class="control-label">
<label for="minVolume">Minimum region size</label>
<output id="minVolumeValue" for="minVolume">8 voxels</output>
</div>
<input
id="minVolume"
type="range"
min="1"
max="80"
step="1"
value="8"
/>
<div class="range-notes">
<span>Include small fragments</span>
<span>Exclude noise</span>
</div>
</section>
<section class="section">
<div class="section-title">
<h2>Signal distribution</h2>
</div>
<div class="chart-wrap">
<canvas id="histogram" aria-label="Signal value histogram"></canvas>
</div>
<div class="chart-caption">
<span>Voxel signal</span>
<span id="histogramCaption">Threshold marker</span>
</div>
</section>
<section class="section">
<div class="section-title">
<h2>Detection summary</h2>
</div>
<div class="stats">
<div class="stat">
<div class="stat-label">Regions</div>
<div class="stat-value accent" id="regionCount">0</div>
</div>
<div class="stat">
<div class="stat-label">Selected</div>
<div class="stat-value" id="selectedCount">0</div>
</div>
<div class="stat">
<div class="stat-label">Largest</div>
<div class="stat-value" id="largestRegion">0</div>
</div>
<div class="stat">
<div class="stat-label">Coverage</div>
<div class="stat-value" id="coverage">0%</div>
</div>
</div>
</section>
<section class="section">
<div class="section-title">
<h2>Counted regions</h2>
<span class="seed-pill" id="regionCountPill">0 found</span>
</div>
<div class="region-list" id="regionList" aria-live="polite"></div>
</section>
<section class="section">
<div class="section-title">
<h2>Pattern seed</h2>
</div>
<div class="seed-controls">
<input
id="seedInput"
type="number"
value="8421"
min="1"
max="999999"
aria-label="Pattern seed"
/>
<button class="button" id="applySeed">Apply</button>
</div>
<div class="toggle-row">
<label for="orbitToggle">Slow automatic orbit</label>
<input id="orbitToggle" type="checkbox" />
</div>
</section>
</aside>
<section id="viewport" aria-label="Interactive three-dimensional voxel colony">
<div id="loading">Initializing voxel field…</div>
<div class="stage-hud">
<span class="eyebrow">Detection result</span>
<strong id="stageCount">0 counted regions</strong>
<span id="stageDetail">Waiting for analysis</span>
</div>
<div class="stage-meta">
<div class="meta-chip">36 × 26 × 12</div>
<div class="meta-chip">26-neighbor connectivity</div>
</div>
<button class="button" id="resetView">Reset camera</button>
<div class="stage-bottom">
<div class="legend">
<div class="legend-item">
<span class="legend-dot detected"></span>
Counted region
</div>
<div class="legend-item">
<span class="legend-dot excluded"></span>
Below minimum size
</div>
<div class="legend-item">
<span class="legend-dot ghost"></span>
Unselected voxel
</div>
</div>
<div class="camera-help">
<strong>Drag</strong> orbit · <strong>Scroll</strong> zoom<br />
<strong>Shift-drag</strong> or <strong>right-drag</strong> pan
</div>
</div>
</section>
</main>
</div>
<script type="module">
import * as THREE from "https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
// ---------------------------------------------------------------------
// Configuration and utility functions
// ---------------------------------------------------------------------
const GRID = Object.freeze({
nx: 36,
ny: 26,
nz: 12,
spacing: 0.34
});
const TOTAL = GRID.nx * GRID.ny * GRID.nz;
const HISTOGRAM_BINS = 48;
const COLORS = [
0x45e3f2,
0x9a83ff,
0x66e6a6,
0xff78b7,
0xffc857,
0x6ea8ff,
0xff9366,
0xa7ec62,
0x55d6bd,
0xe58cff
].map((hex) => new THREE.Color(hex));
const $ = (id) => document.getElementById(id);
const viewport = $("viewport");
const thresholdInput = $("threshold");
const minVolumeInput = $("minVolume");
const seedInput = $("seedInput");
const histogramCanvas = $("histogram");
let threshold = Number(thresholdInput.value);
let minVolume = Number(minVolumeInput.value);
let seed = Number(seedInput.value);
let field = new Float32Array(TOTAL);
let histogram = new Uint32Array(HISTOGRAM_BINS);
let regions = [];
let selectedVoxels = [];
let excludedVoxels = [];
let activeCount = 0;
let excludedComponentCount = 0;
let detectionScheduled = false;
function mulberry32(value) {
let state = value >>> 0;
return function random() {
state += 0x6d2b79f5;
let result = state;
result = Math.imul(result ^ (result >>> 15), result | 1);
result ^= result + Math.imul(result ^ (result >>> 7), result | 61);
return ((result ^ (result >>> 14)) >>> 0) / 4294967296;
};
}
function voxelIndex(x, y, z) {
return x + GRID.nx * (y + GRID.ny * z);
}
function decodeIndex(index) {
const x = index % GRID.nx;
const y = Math.floor(index / GRID.nx) % GRID.ny;
const z = Math.floor(index / (GRID.nx * GRID.ny));
return { x, y, z };
}
function gridToWorld(x, y, z) {
return new THREE.Vector3(
(x - (GRID.nx - 1) * 0.5) * GRID.spacing,
(y - (GRID.ny - 1) * 0.5) * GRID.spacing,
(z - (GRID.nz - 1) * 0.5) * GRID.spacing
);
}
function clamp(value, minimum, maximum) {
return Math.max(minimum, Math.min(maximum, value));
}
function formatNumber(value) {
return new Intl.NumberFormat("en-US").format(value);
}
// ---------------------------------------------------------------------
// Three.js scene
// ---------------------------------------------------------------------
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x071019);
scene.fog = new THREE.Fog(0x071019, 18, 39);
const camera = new THREE.PerspectiveCamera(
45,
viewport.clientWidth / viewport.clientHeight,
0.1,
100
);
const renderer = new THREE.WebGLRenderer({
antialias: true,
powerPreference: "high-performance"
});
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(viewport.clientWidth, viewport.clientHeight, false);
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.15;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.domElement.tabIndex = 0;
renderer.domElement.setAttribute(
"aria-label",
"Three-dimensional synthetic voxel colony. Drag to rotate."
);
viewport.appendChild(renderer.domElement);
const hemisphere = new THREE.HemisphereLight(0x9ce7ff, 0x071019, 1.7);
scene.add(hemisphere);
const keyLight = new THREE.DirectionalLight(0xd9f7ff, 2.6);
keyLight.position.set(8, 12, 9);
keyLight.castShadow = true;
keyLight.shadow.mapSize.set(1024, 1024);
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;
scene.add(keyLight);
const fillLight = new THREE.DirectionalLight(0x8875ff, 1.25);
fillLight.position.set(-8, 4, -7);
scene.add(fillLight);
const floorY = -(GRID.ny * GRID.spacing) / 2 - 0.48;
const floor = new THREE.Mesh(
new THREE.PlaneGeometry(50, 50),
new THREE.MeshStandardMaterial({
color: 0x08131d,
roughness: 0.95,
metalness: 0.04
})
);
floor.rotation.x = -Math.PI / 2;
floor.position.y = floorY;
floor.receiveShadow = true;
scene.add(floor);
const floorGrid = new THREE.GridHelper(
28,
56,
0x245064,
0x102b39
);
floorGrid.position.y = floorY + 0.012;
floorGrid.material.transparent = true;
floorGrid.material.opacity = 0.34;
scene.add(floorGrid);
const volumeWidth = GRID.nx * GRID.spacing;
const volumeHeight = GRID.ny * GRID.spacing;
const volumeDepth = GRID.nz * GRID.spacing;
const boundary = new THREE.LineSegments(
new THREE.EdgesGeometry(
new THREE.BoxGeometry(volumeWidth, volumeHeight, volumeDepth)
),
new THREE.LineBasicMaterial({
color: 0x2b7185,
transparent: true,
opacity: 0.35
})
);
scene.add(boundary);
// Every voxel is represented by a small, faint point.
const ghostPositions = new Float32Array(TOTAL * 3);
for (let z = 0; z < GRID.nz; z++) {
for (let y = 0; y < GRID.ny; y++) {
for (let x = 0; x < GRID.nx; x++) {
const index = voxelIndex(x, y, z);
const position = gridToWorld(x, y, z);
const offset = index * 3;
ghostPositions[offset] = position.x;
ghostPositions[offset + 1] = position.y;
ghostPositions[offset + 2] = position.z;
}
}
}
const ghostGeometry = new THREE.BufferGeometry();
ghostGeometry.setAttribute(
"position",
new THREE.BufferAttribute(ghostPositions, 3)
);
const ghostPoints = new THREE.Points(
ghostGeometry,
new THREE.PointsMaterial({
color: 0x3e687d,
size: 0.055,
transparent: true,
opacity: 0.38,
depthWrite: false,
sizeAttenuation: true
})
);
scene.add(ghostPoints);
const voxelGeometry = new THREE.BoxGeometry(
GRID.spacing * 0.76,
GRID.spacing * 0.76,
GRID.spacing * 0.76
);
const regionMaterial = new THREE.MeshStandardMaterial({
color: 0xffffff,
roughness: 0.28,
metalness: 0.18,
emissive: 0x04121a,
emissiveIntensity: 0.85
});
const excludedMaterial = new THREE.MeshStandardMaterial({
color: 0xf4a742,
roughness: 0.42,
metalness: 0.08,
emissive: 0x281304,
emissiveIntensity: 0.55
});
const regionMesh = new THREE.InstancedMesh(
voxelGeometry,
regionMaterial,
TOTAL
);
regionMesh.count = 0;
regionMesh.castShadow = true;
regionMesh.receiveShadow = true;
regionMesh.frustumCulled = false;
regionMesh.instanceMatrix.setUsage(THREE.DynamicDrawUsage);
scene.add(regionMesh);
const excludedMesh = new THREE.InstancedMesh(
voxelGeometry,
excludedMaterial,
TOTAL
);
excludedMesh.count = 0;
excludedMesh.castShadow = true;
excludedMesh.frustumCulled = false;
excludedMesh.instanceMatrix.setUsage(THREE.DynamicDrawUsage);
scene.add(excludedMesh);
const dummy = new THREE.Object3D();
// ---------------------------------------------------------------------
// Synthetic signal field
// ---------------------------------------------------------------------
function generatePattern(nextSeed) {
seed = Math.max(1, Math.floor(Number(nextSeed) || 1));
seedInput.value = seed;
$("seedPill").textContent = `Seed ${seed}`;
const random = mulberry32(seed ^ 0x9e3779b9);
const colonies = [];
const colonyCount = 7 + Math.floor(random() * 3);
for (let i = 0; i < colonyCount; i++) {
let x = 0;
let y = 0;
let z = 0;
let accepted = false;
// Try to keep the main colonies spatially separated.
for (let attempt = 0; attempt < 40; attempt++) {
x = 2.5 + random() * (GRID.nx - 5);
y = 2.5 + random() * (GRID.ny - 5);
z = 1.3 + random() * (GRID.nz - 2.6);
accepted = colonies.every((other) => {
const distance = Math.hypot(
(x - other.x) / 2.2,
(y - other.y) / 2.2,
(z - other.z) / 1.5
);
return distance > 3.25;
});
if (accepted) break;
}
const parent = {
x,
y,
z,
rx: 1.8 + random() * 1.1,
ry: 1.7 + random() * 1.0,
rz: 1.05 + random() * 0.7,
amplitude: 0.76 + random() * 0.22
};
const lobes = [parent];
const satelliteCount = random() > 0.22 ? 1 + Math.floor(random() * 2) : 0;
for (let lobe = 0; lobe < satelliteCount; lobe++) {
const angle = random() * Math.PI * 2;
const distance = 1.8 + random() * 1.6;
lobes.push({
x: clamp(x + Math.cos(angle) * distance, 1, GRID.nx - 2),
y: clamp(y + Math.sin(angle) * distance, 1, GRID.ny - 2),
z: clamp(z + (random() - 0.5) * 2.2, 1, GRID.nz - 2),
rx: 0.9 + random() * 0.55,
ry: 0.9 + random() * 0.55,
rz: 0.75 + random() * 0.45,
amplitude: 0.46 + random() * 0.25
});
}
colonies.push(...lobes);
}
for (let z = 0; z < GRID.nz; z++) {
for (let y = 0; y < GRID.ny; y++) {
for (let x = 0; x < GRID.nx; x++) {
let value = 0.075 + random() * 0.075;
for (const colony of colonies) {
const dx = (x - colony.x) / colony.rx;
const dy = (y - colony.y) / colony.ry;
const dz = (z - colony.z) / colony.rz;
const distanceSquared = dx * dx + dy * dy + dz * dz;
value +=
colony.amplitude *
Math.exp(-0.55 * distanceSquared);
}
field[voxelIndex(x, y, z)] = Math.min(0.99, value);
}
}
}
histogram.fill(0);
for (let i = 0; i < field.length; i++) {
const bin = Math.min(
HISTOGRAM_BINS - 1,
Math.max(0, Math.floor(field[i] * HISTOGRAM_BINS))
);
histogram[bin]++;
}
applyDetection();
}
// ---------------------------------------------------------------------
// Connected-component detection
// ---------------------------------------------------------------------
function detectComponents() {
const active = new Uint8Array(TOTAL);
const visited = new Uint8Array(TOTAL);
const queue = new Int32Array(TOTAL);
const components = [];
activeCount = 0;
for (let i = 0; i < TOTAL; i++) {
if (field[i] >= threshold) {
active[i] = 1;
activeCount++;
}
}
for (let start = 0; start < TOTAL; start++) {
if (!active[start] || visited[start]) continue;
let head = 0;
let tail = 0;
queue[tail++] = start;
visited[start] = 1;
const component = [];
while (head < tail) {
const current = queue[head++];
component.push(current);
const { x, y, z } = decodeIndex(current);
// 26-neighbor connectivity in three dimensions.
for (let dz = -1; dz <= 1; dz++) {
for (let dy = -1; dy <= 1; dy++) {
for (let dx = -1; dx <= 1; dx++) {
if (dx === 0 && dy === 0 && dz === 0) continue;
const nx = x + dx;
const ny = y + dy;
const nz = z + dz;
if (
nx < 0 ||
nx >= GRID.nx ||
ny < 0 ||
ny >= GRID.ny ||
nz < 0 ||
nz >= GRID.nz
) {
continue;
}
const neighbor = voxelIndex(nx, ny, nz);
if (active[neighbor] && !visited[neighbor]) {
visited[neighbor] = 1;
queue[tail++] = neighbor;
}
}
}
}
}
components.push(component);
}
return components;
}
function applyDetection() {
const components = detectComponents();
regions = [];
selectedVoxels = [];
excludedVoxels = [];
excludedComponentCount = 0;
for (const component of components) {
if (component.length < minVolume) {
excludedComponentCount++;
excludedVoxels.push(...component);
continue;
}
const center = new THREE.Vector3();
for (const voxel of component) {
const { x, y, z } = decodeIndex(voxel);
center.add(gridToWorld(x, y, z));
}
center.multiplyScalar(1 / component.length);
regions.push({
id: regions.length,
size: component.length,
voxels: component,
center,
color: COLORS[regions.length % COLORS.length].clone()
});
selectedVoxels.push(...component);
}
updateVoxelMeshes();
updateInterface();
drawHistogram();
}
function updateVoxelMeshes() {
let regionInstance = 0;
for (const region of regions) {
for (const voxel of region.voxels) {
const { x, y, z } = decodeIndex(voxel);
const position = gridToWorld(x, y, z);
dummy.position.copy(position);
dummy.scale.setScalar(1);
dummy.updateMatrix();
regionMesh.setMatrixAt(regionInstance, dummy.matrix);
regionMesh.setColorAt(regionInstance, region.color);
regionInstance++;
}
}
regionMesh.count = regionInstance;
regionMesh.instanceMatrix.needsUpdate = true;
if (regionMesh.instanceColor) {
regionMesh.instanceColor.needsUpdate = true;
}
let excludedInstance = 0;
const excludedColor = new THREE.Color(0xf4a742);
for (const voxel of excludedVoxels) {
const { x, y, z } = decodeIndex(voxel);
const position = gridToWorld(x, y, z);
dummy.position.copy(position);
dummy.scale.setScalar(0.66);
dummy.updateMatrix();
excludedMesh.setMatrixAt(excludedInstance, dummy.matrix);
excludedMesh.setColorAt(excludedInstance, excludedColor);
excludedInstance++;
}
excludedMesh.count = excludedInstance;
excludedMesh.instanceMatrix.needsUpdate = true;
if (excludedMesh.instanceColor) {
excludedMesh.instanceColor.needsUpdate = true;
}
}
// ---------------------------------------------------------------------
// Interface and histogram
// ---------------------------------------------------------------------
function updateInterface() {
const largest = regions.reduce(
(maximum, region) => Math.max(maximum, region.size),
0
);
const retainedPercent = (activeCount / TOTAL) * 100;
$("thresholdValue").textContent = threshold.toFixed(2);
$("minVolumeValue").textContent = `${minVolume} voxel${minVolume === 1 ? "" : "s"}`;
$("retainedText").textContent =
`${retainedPercent.toFixed(1)}% of the volume is retained.`;
$("regionCount").textContent = formatNumber(regions.length);
$("selectedCount").textContent = formatNumber(activeCount);
$("largestRegion").textContent = formatNumber(largest);
$("coverage").textContent = `${retainedPercent.toFixed(1)}%`;
$("regionCountPill").textContent = `${regions.length} found`;
$("stageCount").textContent =
`${regions.length} counted region${regions.length === 1 ? "" : "s"}`;
$("stageDetail").textContent =
`${formatNumber(activeCount)} selected · ${excludedComponentCount} component` +
`${excludedComponentCount === 1 ? "" : "s"} below minimum size`;
if (typeof $("stageCount").animate === "function") {
$("stageCount").animate(
[
{ transform: "scale(1)", color: "#f0fbff" },
{ transform: "scale(1.1)", color: "#45e3f2" },
{ transform: "scale(1)", color: "#f0fbff" }
],
{ duration: 280, easing: "ease-out" }
);
}
const sortedRegions = [...regions].sort((a, b) => b.size - a.size);
if (sortedRegions.length === 0) {
$("regionList").innerHTML = `
<div class="empty-state">
No components meet the current threshold and minimum-size rules.
Lower the threshold or reduce the minimum region size.
</div>
`;
return;
}
$("regionList").innerHTML = sortedRegions
.map((region) => {
const percentage = largest ? (region.size / largest) * 100 : 0;
const color = `#${region.color.getHexString()}`;
return `
<div class="region-row">
<span class="swatch" style="color:${color};background:${color}"></span>
<div class="region-main">
<div class="region-name">
<span>Region ${String(region.id + 1).padStart(2, "0")}</span>
</div>
<div class="region-bar">
<span style="width:${percentage}%;background:${color}"></span>
</div>
</div>
<span class="region-size">${formatNumber(region.size)} vox</span>
</div>
`;
})
.join("");
}
function drawHistogram() {
const rect = histogramCanvas.getBoundingClientRect();
if (!rect.width || !rect.height) return;
const dpr = Math.min(window.devicePixelRatio, 2);
const targetWidth = Math.round(rect.width * dpr);
const targetHeight = Math.round(rect.height * dpr);
if (
histogramCanvas.width !== targetWidth ||
histogramCanvas.height !== targetHeight
) {
histogramCanvas.width = targetWidth;
histogramCanvas.height = targetHeight;
}
const context = histogramCanvas.getContext("2d");
context.setTransform(dpr, 0, 0, dpr, 0, 0);
context.clearRect(0, 0, rect.width, rect.height);
const width = rect.width;
const height = rect.height;
const bottom = height - 17;
const chartHeight = bottom - 8;
const maximum = Math.max(...histogram);
const gradient = context.createLinearGradient(0, 0, 0, bottom);
gradient.addColorStop(0, "rgba(69, 227, 242, 0.9)");
gradient.addColorStop(1, "rgba(69, 227, 242, 0.15)");
context.fillStyle = gradient;
for (let i = 0; i < HISTOGRAM_BINS; i++) {
const x = (i / HISTOGRAM_BINS) * width;
const barWidth = Math.max(1, width / HISTOGRAM_BINS - 1);
const barHeight = (histogram[i] / maximum) * chartHeight;
context.fillRect(
x,
bottom - barHeight,
barWidth,
barHeight
);
}
const thresholdX = threshold * width;
context.strokeStyle = "#ffcd6b";
context.lineWidth = 1.5;
context.beginPath();
context.moveTo(thresholdX, 3);
context.lineTo(thresholdX, bottom);
context.stroke();
context.fillStyle = "#ffcd6b";
context.beginPath();
context.arc(thresholdX, 5, 3, 0, Math.PI * 2);
context.fill();
context.font = "9px ui-monospace, monospace";
context.fillStyle = "#587283";
context.fillText("0.0", 3, height - 3);
context.fillText("0.5", width / 2 - 6, height - 3);
context.fillText("1.0", width - 18, height - 3);
$("histogramCaption").textContent =
`Marker at ${threshold.toFixed(2)}`;
}
function syncRange(input) {
const minimum = Number(input.min);
const maximum = Number(input.max);
const value = Number(input.value);
const percentage = ((value - minimum) / (maximum - minimum)) * 100;
input.style.setProperty("--pct", `${percentage}%`);
}
function scheduleDetection() {
if (detectionScheduled) return;
detectionScheduled = true;
requestAnimationFrame(() => {
detectionScheduled = false;
applyDetection();
});
}
thresholdInput.addEventListener("input", () => {
threshold = Number(thresholdInput.value);
syncRange(thresholdInput);
$("thresholdValue").textContent = threshold.toFixed(2);
scheduleDetection();
});
minVolumeInput.addEventListener("input", () => {
minVolume = Number(minVolumeInput.value);
syncRange(minVolumeInput);
$("minVolumeValue").textContent =
`${minVolume} voxel${minVolume === 1 ? "" : "s"}`;
scheduleDetection();
});
$("applySeed").addEventListener("click", () => {
generatePattern(Number(seedInput.value));
});
seedInput.addEventListener("keydown", (event) => {
if (event.key === "Enter") {
generatePattern(Number(seedInput.value));
seedInput.blur();
}
});
$("newSeedButton").addEventListener("click", () => {
const nextSeed = 100000 + Math.floor(Math.random() * 899999);
generatePattern(nextSeed);
});
// ---------------------------------------------------------------------
// Camera controls implemented directly without external add-ons
// ---------------------------------------------------------------------
const cameraState = {
yaw: 0.68,
pitch: 0.38,
distance: 17.5,
target: new THREE.Vector3(0, 0, 0)
};
const pointerState = {
down: false,
mode: "orbit",
x: 0,
y: 0,
pointerId: null
};
function updateCamera() {
const { yaw, pitch, distance, target } = cameraState;
const horizontal = Math.cos(pitch) * distance;
camera.position.set(
target.x + Math.sin(yaw) * horizontal,
target.y + Math.sin(pitch) * distance,
target.z + Math.cos(yaw) * horizontal
);
camera.lookAt(target);
}
function resetCamera() {
cameraState.yaw = 0.68;
cameraState.pitch = 0.38;
cameraState.distance = 17.5;
cameraState.target.set(0, 0, 0);
updateCamera();
}
renderer.domElement.addEventListener("pointerdown", (event) => {
if (
event.pointerType === "mouse" &&
event.button !== 0 &&
event.button !== 2
) {
return;
}
pointerState.down = true;
pointerState.mode =
event.shiftKey || event.button === 2 ? "pan" : "orbit";
pointerState.x = event.clientX;
pointerState.y = event.clientY;
pointerState.pointerId = event.pointerId;
renderer.domElement.setPointerCapture(event.pointerId);
});
renderer.domElement.addEventListener("pointermove", (event) => {
if (!pointerState.down || event.pointerId !== pointerState.pointerId) {
return;
}
const deltaX = event.clientX - pointerState.x;
const deltaY = event.clientY - pointerState.y;
pointerState.x = event.clientX;
pointerState.y = event.clientY;
if (pointerState.mode === "orbit") {
cameraState.yaw -= deltaX * 0.006;
cameraState.pitch = clamp(
cameraState.pitch + deltaY * 0.006,
-1.35,
1.35
);
} else {
camera.updateMatrixWorld();
const right = new THREE.Vector3().setFromMatrixColumn(
camera.matrix,
0
);
const up = new THREE.Vector3().setFromMatrixColumn(
camera.matrix,
1
);
const panScale = cameraState.distance * 0.00125;
cameraState.target.addScaledVector(
right,
-deltaX * panScale
);
cameraState.target.addScaledVector(
up,
deltaY * panScale
);
}
});
function endPointer(event) {
if (event.pointerId !== pointerState.pointerId) return;
pointerState.down = false;
pointerState.pointerId = null;
if (renderer.domElement.hasPointerCapture(event.pointerId)) {
renderer.domElement.releasePointerCapture(event.pointerId);
}
}
renderer.domElement.addEventListener("pointerup", endPointer);
renderer.domElement.addEventListener("pointercancel", endPointer);
renderer.domElement.addEventListener("contextmenu", (event) => {
event.preventDefault();
});
renderer.domElement.addEventListener(
"wheel",
(event) => {
event.preventDefault();
cameraState.distance = clamp(
cameraState.distance * Math.exp(event.deltaY * 0.001),
6.5,
32
);
},
{ passive: false }
);
renderer.domElement.addEventListener("dblclick", resetCamera);
$("resetView").addEventListener("click", resetCamera);
renderer.domElement.addEventListener("keydown", (event) => {
let handled = true;
switch (event.key) {
case "ArrowLeft":
cameraState.yaw += 0.1;
break;
case "ArrowRight":
cameraState.yaw -= 0.1;
break;
case "ArrowUp":
cameraState.pitch = clamp(cameraState.pitch + 0.08, -1.35, 1.35);
break;
case "ArrowDown":
cameraState.pitch = clamp(cameraState.pitch - 0.08, -1.35, 1.35);
break;
case "+":
case "=":
cameraState.distance = clamp(cameraState.distance - 0.7, 6.5, 32);
break;
case "-":
cameraState.distance = clamp(cameraState.distance + 0.7, 6.5, 32);
break;
default:
handled = false;
}
if (handled) event.preventDefault();
});
// ---------------------------------------------------------------------
// Resize and render loop
// ---------------------------------------------------------------------
function resizeRenderer() {
const width = Math.max(1, viewport.clientWidth);
const height = Math.max(1, viewport.clientHeight);
renderer.setSize(width, height, false);
camera.aspect = width / height;
camera.updateProjectionMatrix();
drawHistogram();
}
const resizeObserver = new ResizeObserver(resizeRenderer);
resizeObserver.observe(viewport);
syncRange(thresholdInput);
syncRange(minVolumeInput);
resetCamera();
generatePattern(seed);
$("loading").classList.add("hidden");
let previousTime = performance.now();
renderer.setAnimationLoop((time) => {
const delta = Math.min((time - previousTime) / 1000, 0.05);
previousTime = time;
if ($("orbitToggle").checked && !pointerState.down) {
cameraState.yaw += delta * 0.12;
}
updateCamera();
renderer.render(scene, camera);
});
</script>
</body>
</html>
```