Prompt specification
Build or customize the Three.js 3D scene "Diffusion distance comparison 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: Diffusion distance comparison explorer
Category: Voxel Worlds · Style: Voxel 3D
License: MIT · Reference: https://three3d.app/scene/diffusion-distance-comparison-explorer-x0840
Scene Description Prompt:
Compare arrival-time distributions for identical random walkers crossing short and long distances in a voxel diffusion model. Label it illustrative. Three.js from cdnjs; HTML.
Working Three.js Starter (diffusion-distance-comparison-explorer-x0840):
```html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Illustrative Voxel Diffusion — Arrival-Time Distributions</title>
<style>
:root {
color-scheme: dark;
--bg: #071019;
--panel: #0d1824;
--panel-2: #111f2d;
--border: #22364a;
--text: #e9f0f7;
--muted: #91a5b8;
--short: #ffb454;
--long: #42d6c8;
--grid: #263a4e;
}
* { box-sizing: border-box; }
body {
margin: 0;
background:
radial-gradient(circle at 15% 0%, #132a3d 0, transparent 35%),
var(--bg);
color: var(--text);
font-family: Inter, ui-sans-serif, system-ui, -apple-system,
BlinkMacSystemFont, "Segoe UI", sans-serif;
line-height: 1.45;
}
button, input { font: inherit; }
.app {
width: min(1540px, 100%);
margin: 0 auto;
padding: 24px;
}
header {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 24px;
margin-bottom: 20px;
}
h1 {
margin: 5px 0 6px;
font-size: clamp(1.55rem, 3vw, 2.35rem);
line-height: 1.12;
letter-spacing: -0.035em;
}
h2, h3 { margin: 0; }
.subtitle {
max-width: 850px;
color: var(--muted);
margin: 0;
}
.badge {
display: inline-flex;
align-items: center;
gap: 7px;
border: 1px solid #8c642a;
background: #2a1e0d;
color: #ffd18a;
border-radius: 999px;
padding: 5px 10px;
font-size: 0.72rem;
font-weight: 800;
letter-spacing: 0.13em;
white-space: nowrap;
}
.badge::before {
content: "";
width: 7px;
height: 7px;
border-radius: 50%;
background: var(--short);
box-shadow: 0 0 12px rgba(255, 180, 84, 0.75);
}
.header-badge {
margin-top: 5px;
background: #111f2d;
border-color: var(--border);
color: var(--muted);
}
.header-badge::before {
background: var(--long);
box-shadow: 0 0 12px rgba(66, 214, 200, 0.65);
}
.layout {
display: grid;
grid-template-columns: 300px minmax(0, 1fr);
gap: 18px;
align-items: start;
}
.panel,
.card {
background: linear-gradient(180deg, rgba(17, 31, 45, 0.96), rgba(11, 23, 34, 0.96));
border: 1px solid var(--border);
border-radius: 15px;
box-shadow: 0 14px 40px rgba(0, 0, 0, 0.18);
}
.panel {
padding: 19px;
position: sticky;
top: 16px;
}
.panel h2 {
font-size: 1rem;
margin-bottom: 4px;
}
.panel-intro {
color: var(--muted);
font-size: 0.83rem;
margin: 0 0 19px;
}
.control {
margin: 0 0 17px;
}
.control-head {
display: flex;
justify-content: space-between;
align-items: baseline;
gap: 12px;
margin-bottom: 7px;
font-size: 0.86rem;
}
.control output {
color: var(--text);
font-variant-numeric: tabular-nums;
font-weight: 700;
}
input[type="range"] {
width: 100%;
margin: 0;
accent-color: var(--long);
cursor: pointer;
}
.control small {
display: block;
margin-top: 4px;
color: #71869a;
font-size: 0.72rem;
}
.buttons {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 8px;
margin: 18px 0;
}
button {
border: 1px solid #34506a;
border-radius: 9px;
color: var(--text);
background: #15283a;
padding: 9px 10px;
cursor: pointer;
transition: background 120ms ease, transform 120ms ease;
font-size: 0.82rem;
font-weight: 650;
}
button:hover { background: #1c354b; }
button:active { transform: translateY(1px); }
button:disabled { opacity: 0.5; cursor: wait; }
button.primary {
color: #06201e;
background: var(--long);
border-color: var(--long);
}
button.primary:hover { background: #62e3d7; }
.legend {
border-top: 1px solid var(--border);
margin-top: 18px;
padding-top: 16px;
}
.legend-row {
display: flex;
align-items: center;
gap: 9px;
margin: 8px 0;
font-size: 0.82rem;
color: #bdcad6;
}
.swatch {
width: 22px;
height: 4px;
border-radius: 3px;
}
.swatch.short { background: var(--short); }
.swatch.long { background: var(--long); }
.model-note {
margin-top: 15px;
padding: 12px;
border-radius: 10px;
color: var(--muted);
background: rgba(4, 11, 17, 0.45);
font-size: 0.76rem;
border: 1px solid rgba(71, 97, 119, 0.45);
}
.content {
min-width: 0;
display: grid;
gap: 18px;
}
.scene-card {
overflow: hidden;
position: relative;
}
.card-head {
min-height: 61px;
padding: 13px 17px;
display: flex;
align-items: center;
justify-content: space-between;
gap: 14px;
border-bottom: 1px solid var(--border);
}
.card-head h2 {
font-size: 0.98rem;
}
.card-head p {
margin: 2px 0 0;
color: var(--muted);
font-size: 0.75rem;
}
.status {
color: #a8b9c9;
font-size: 0.75rem;
text-align: right;
font-variant-numeric: tabular-nums;
}
#scene {
height: 475px;
position: relative;
background:
radial-gradient(circle at 50% 45%, rgba(35, 73, 95, 0.28), transparent 55%),
#08121c;
overflow: hidden;
touch-action: none;
}
#scene > canvas {
width: 100%;
height: 100%;
display: block;
cursor: grab;
}
#scene > canvas:active { cursor: grabbing; }
.scene-label {
position: absolute;
z-index: 4;
left: 0;
top: 0;
pointer-events: none;
padding: 5px 9px;
border-radius: 6px;
border: 1px solid currentColor;
background: rgba(5, 13, 21, 0.84);
font-size: 0.7rem;
font-weight: 750;
letter-spacing: 0.03em;
white-space: nowrap;
transform: translate(-50%, -100%);
}
#labelShort { color: var(--short); }
#labelLong { color: var(--long); }
.scene-help {
position: absolute;
left: 13px;
bottom: 12px;
z-index: 3;
color: #8197aa;
font-size: 0.7rem;
pointer-events: none;
background: rgba(5, 12, 19, 0.65);
padding: 5px 8px;
border-radius: 6px;
}
.busy {
position: absolute;
inset: 0;
z-index: 8;
display: grid;
place-items: center;
background: rgba(5, 12, 19, 0.58);
backdrop-filter: blur(2px);
color: var(--muted);
font-size: 0.86rem;
transition: opacity 140ms ease;
}
.busy.hidden {
opacity: 0;
pointer-events: none;
}
.stats-grid {
display: grid;
grid-template-columns: repeat(4, minmax(0, 1fr));
gap: 12px;
}
.stat {
padding: 14px 15px;
min-height: 103px;
}
.stat-label {
display: block;
color: var(--muted);
font-size: 0.72rem;
text-transform: uppercase;
letter-spacing: 0.07em;
}
.stat strong {
display: block;
margin: 4px 0 2px;
font-size: 1.55rem;
line-height: 1.15;
font-variant-numeric: tabular-nums;
}
.stat small {
color: #8398aa;
font-size: 0.72rem;
}
.stat.short strong { color: var(--short); }
.stat.long strong { color: var(--long); }
.charts-grid {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 14px;
}
.chart-card {
padding: 12px 12px 8px;
min-width: 0;
}
.chart-card.wide { grid-column: 1 / -1; }
.chart-card canvas {
display: block;
width: 100%;
height: 265px;
}
.method {
padding: 16px 18px;
color: var(--muted);
font-size: 0.78rem;
}
.method strong { color: #c9d5df; }
.method-grid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 20px;
}
.method p { margin: 7px 0; }
code {
color: #c9e8e3;
background: rgba(65, 210, 194, 0.08);
padding: 1px 5px;
border-radius: 4px;
}
footer {
margin-top: 17px;
text-align: center;
color: #72879a;
font-size: 0.72rem;
}
@media (max-width: 1050px) {
.layout { grid-template-columns: 1fr; }
.panel { position: static; }
.controls-grid {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 0 24px;
}
.buttons { grid-template-columns: repeat(4, minmax(0, 1fr)); }
}
@media (max-width: 720px) {
.app { padding: 13px; }
header { flex-direction: column; gap: 8px; }
.controls-grid, .method-grid { grid-template-columns: 1fr; }
.buttons { grid-template-columns: 1fr 1fr; }
.stats-grid { grid-template-columns: 1fr 1fr; }
.charts-grid { grid-template-columns: 1fr; }
.chart-card.wide { grid-column: auto; }
#scene { height: 390px; }
.card-head { align-items: flex-start; }
.status { max-width: 145px; }
}
</style>
</head>
<body>
<div class="app">
<header>
<div>
<div class="badge">ILLUSTRATIVE</div>
<h1>Voxel diffusion: arrival-time distributions</h1>
<p class="subtitle">
Paired random walkers cross a short and a long absorbing gate in the same
voxel lattice. Each trajectory uses one shared random stream, so the
comparison isolates the effect of crossing distance.
</p>
</div>
<div class="badge header-badge">SYNTHETIC MODEL</div>
</header>
<main class="layout">
<aside class="panel">
<h2>Model controls</h2>
<p class="panel-intro">
Six-neighbor lattice steps, reflecting side walls, absorbing x-direction gates.
</p>
<div class="controls-grid">
<div class="control">
<div class="control-head">
<label for="walkers">Paired walkers</label>
<output id="walkersOut">360</output>
</div>
<input id="walkers" type="range" min="120" max="900" step="20" value="360">
</div>
<div class="control">
<div class="control-head">
<label for="shortDistance">Short distance</label>
<output id="shortOut">6 voxels</output>
</div>
<input id="shortDistance" type="range" min="3" max="12" step="1" value="6">
</div>
<div class="control">
<div class="control-head">
<label for="longDistance">Long distance</label>
<output id="longOut">18 voxels</output>
</div>
<input id="longDistance" type="range" min="8" max="26" step="1" value="18">
</div>
<div class="control">
<div class="control-head">
<label for="speed">Animation speed</label>
<output id="speedOut">18 steps/s</output>
</div>
<input id="speed" type="range" min="4" max="120" step="2" value="18">
<small>Visual playback only; it does not affect sampling.</small>
</div>
</div>
<div class="buttons">
<button id="playButton" class="primary" type="button">Pause paths</button>
<button id="replayButton" type="button">Replay paths</button>
<button id="reseedButton" type="button">New seed</button>
<button id="cameraButton" type="button">Reset camera</button>
</div>
<div class="legend">
<div class="legend-row">
<span class="swatch short"></span>
<span>Short absorbing gate and first arrival</span>
</div>
<div class="legend-row">
<span class="swatch long"></span>
<span>Long absorbing gate and first arrival</span>
</div>
</div>
<div class="model-note">
<strong>Interpretation:</strong> longer crossings generally arrive later
and show a wider spread. The scaled chart tests whether the arrival-time
shapes approximately collapse when time is divided by distance squared.
</div>
</aside>
<section class="content">
<div class="card scene-card">
<div class="card-head">
<div>
<h2>3D voxel random walk</h2>
<p>Representative paired trajectories · illustrative playback</p>
</div>
<div id="status" class="status">Preparing simulation…</div>
</div>
<div id="scene">
<div id="labelShort" class="scene-label">Short gate</div>
<div id="labelLong" class="scene-label">Long gate</div>
<div class="scene-help">Drag to orbit · wheel to zoom · double-click to reset</div>
<div id="busy" class="busy">Sampling paired arrival times…</div>
</div>
</div>
<div class="stats-grid">
<div class="card stat short">
<span class="stat-label">Short median arrival</span>
<strong id="shortMedian">—</strong>
<small id="shortP90">p90 —</small>
</div>
<div class="card stat long">
<span class="stat-label">Long median arrival</span>
<strong id="longMedian">—</strong>
<small id="longP90">p90 —</small>
</div>
<div class="card stat">
<span class="stat-label">Median ratio</span>
<strong id="medianRatio">—</strong>
<small id="ratioReference">distance-squared reference —</small>
</div>
<div class="card stat">
<span class="stat-label">Paired sample</span>
<strong id="sampleCount">—</strong>
<small id="seedLabel">seed —</small>
</div>
</div>
<div class="charts-grid">
<div class="card chart-card">
<canvas id="rawChart" aria-label="Raw arrival-time density chart"></canvas>
</div>
<div class="card chart-card">
<canvas id="scaledChart" aria-label="Distance-scaled arrival-time density chart"></canvas>
</div>
<div class="card chart-card wide">
<canvas id="survivalChart" aria-label="Arrival-time survival curves"></canvas>
</div>
</div>
<div class="card method">
<div class="method-grid">
<div>
<strong>Illustrative model</strong>
<p>
Walkers begin at the origin of a cubic voxel lattice. At every step,
one of the six nearest-neighbor voxels is selected uniformly.
Transverse walls reflect, while planes at
<code>x = Lshort</code> and <code>x = Llong</code> are absorbing targets.
</p>
<p>
For each walker, the short and long arrival times come from the
<em>same sequence</em> of random choices. The long gate necessarily
occurs after the short gate because the lattice steps are nearest-neighbor.
</p>
</div>
<div>
<strong>Scaling interpretation</strong>
<p>
Diffusive motion suggests a time scale proportional to
<code>t ∝ L²</code>. Accordingly, the scaled panel uses
<code>t / L²</code>. Similar curves there indicate approximate
distance-squared scaling.
</p>
<p>
Medians and quantiles are emphasized because first-passage times
in three dimensions can have heavy upper tails. This synthetic
visualization is not calibrated to experimental data and is not
intended for prediction.
</p>
</div>
</div>
</div>
</section>
</main>
<footer>
ILLUSTRATIVE ONLY · synthetic voxel random walks · no experimental calibration
</footer>
</div>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
const $ = id => document.getElementById(id);
const COLORS = {
short: "#ffb454",
long: "#42d6c8",
grid: "#2a4055",
text: "#dce7f0",
muted: "#8da2b5"
};
const state = {
seed: 0x4a31c9e2,
shortTimes: [],
longTimes: [],
traces: [],
playing: true,
animationStep: 0,
maxAnimationStep: 1,
simulationToken: 0
};
// ---------------------------------------------------------------------
// Three.js scene
// ---------------------------------------------------------------------
const sceneHost = $("scene");
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x08121c);
scene.fog = new THREE.FogExp2(0x08121c, 0.015);
const camera = new THREE.PerspectiveCamera(
43,
1,
0.1,
250
);
const renderer = new THREE.WebGLRenderer({
antialias: true,
alpha: false,
powerPreference: "high-performance"
});
renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 2));
renderer.outputColorSpace = THREE.SRGBColorSpace;
sceneHost.prepend(renderer.domElement);
const ambient = new THREE.AmbientLight(0x9dc8df, 1.3);
scene.add(ambient);
const keyLight = new THREE.DirectionalLight(0xffffff, 2.2);
keyLight.position.set(-8, 16, 12);
scene.add(keyLight);
const cameraState = {
yaw: 0.72,
pitch: 0.43,
radius: 30,
target: new THREE.Vector3(7, 0, 0)
};
let latticeMesh = null;
let shortGate = null;
let longGate = null;
let directionArrow = null;
let traceObjects = [];
function disposeMaterial(material) {
if (Array.isArray(material)) {
material.forEach(disposeMaterial);
} else if (material) {
material.dispose();
}
}
function disposeObject(object) {
if (!object) return;
scene.remove(object);
object.traverse(child => {
if (child.geometry) child.geometry.dispose();
if (child.material) disposeMaterial(child.material);
});
}
function makeGate(color, xPosition) {
const group = new THREE.Group();
const geometry = new THREE.BoxGeometry(0.09, 11.3, 11.3);
const material = new THREE.MeshBasicMaterial({
color,
transparent: true,
opacity: 0.17,
depthWrite: false,
side: THREE.DoubleSide
});
const panel = new THREE.Mesh(geometry, material);
group.add(panel);
const edges = new THREE.LineSegments(
new THREE.EdgesGeometry(geometry),
new THREE.LineBasicMaterial({
color,
transparent: true,
opacity: 0.72
})
);
group.add(edges);
group.position.x = xPosition;
scene.add(group);
return { group, panel, edges, x: xPosition };
}
function rebuildScene() {
if (latticeMesh) disposeObject(latticeMesh);
if (shortGate) disposeObject(shortGate.group);
if (longGate) disposeObject(longGate.group);
if (directionArrow) disposeObject(directionArrow);
clearTraces();
const shortDistance = Number($("shortDistance").value);
const longDistance = Number($("longDistance").value);
const xMin = -4;
const xMax = longDistance + 2;
const side = 5;
const count =
(xMax - xMin + 1) *
(side * 2 + 1) *
(side * 2 + 1);
const geometry = new THREE.BoxGeometry(0.86, 0.86, 0.86);
const material = new THREE.MeshBasicMaterial({
color: 0x2c536c,
transparent: true,
opacity: 0.105,
depthWrite: false
});
latticeMesh = new THREE.InstancedMesh(geometry, material, count);
const matrix = new THREE.Matrix4();
let instance = 0;
for (let x = xMin; x <= xMax; x++) {
for (let y = -side; y <= side; y++) {
for (let z = -side; z <= side; z++) {
matrix.makeTranslation(x, y, z);
latticeMesh.setMatrixAt(instance++, matrix);
}
}
}
latticeMesh.instanceMatrix.needsUpdate = true;
latticeMesh.frustumCulled = false;
scene.add(latticeMesh);
shortGate = makeGate(COLORS.short, shortDistance);
longGate = makeGate(COLORS.long, longDistance);
// Origin marker.
const origin = new THREE.Mesh(
new THREE.SphereGeometry(0.22, 16, 12),
new THREE.MeshBasicMaterial({ color: 0xf4f8fb })
);
scene.add(origin);
const originRing = new THREE.Mesh(
new THREE.TorusGeometry(0.43, 0.025, 8, 40),
new THREE.MeshBasicMaterial({ color: 0xffffff, transparent: true, opacity: 0.8 })
);
originRing.rotation.y = Math.PI / 2;
scene.add(originRing);
directionArrow = new THREE.ArrowHelper(
new THREE.Vector3(1, 0, 0),
new THREE.Vector3(xMin, -6.2, 0),
xMax - xMin,
0x688096,
0.7,
0.42
);
scene.add(directionArrow);
cameraState.target.set((xMin + xMax) / 2, 0, 0);
cameraState.radius = Math.max(23, (xMax - xMin) * 1.45);
$("labelShort").textContent = `Short gate · L=${shortDistance}`;
$("labelLong").textContent = `Long gate · L=${longDistance}`;
}
function clearTraces() {
for (const object of traceObjects) {
scene.remove(object.group);
object.group.traverse(child => {
if (child.geometry) child.geometry.dispose();
if (child.material) disposeMaterial(child.material);
});
}
traceObjects = [];
}
function buildTraces() {
clearTraces();
const shortColor = new THREE.Color(COLORS.short);
const longColor = new THREE.Color(COLORS.long);
state.traces.forEach(trace => {
const group = new THREE.Group();
const points = trace.path.map(
p => new THREE.Vector3(p[0], p[1], p[2])
);
const shortGeometry = new THREE.BufferGeometry().setFromPoints(points);
const longGeometry = new THREE.BufferGeometry().setFromPoints(points);
const shortLine = new THREE.Line(
shortGeometry,
new THREE.LineBasicMaterial({
color: COLORS.short,
transparent: true,
opacity: 0.43
})
);
const longLine = new THREE.Line(
longGeometry,
new THREE.LineBasicMaterial({
color: COLORS.long,
transparent: true,
opacity: 0.48
})
);
shortGeometry.setDrawRange(0, 0);
longGeometry.setDrawRange(trace.shortHit, 0);
group.add(shortLine, longLine);
const walker = new THREE.Mesh(
new THREE.SphereGeometry(0.13, 12, 8),
new THREE.MeshBasicMaterial({ color: COLORS.short })
);
group.add(walker);
const shortMarker = new THREE.Mesh(
new THREE.SphereGeometry(0.18, 12, 8),
new THREE.MeshBasicMaterial({
color: shortColor,
transparent: true,
opacity: 0.9
})
);
shortMarker.position.fromArray(trace.path[trace.shortHit]);
shortMarker.visible = false;
group.add(shortMarker);
const longMarker = new THREE.Mesh(
new THREE.SphereGeometry(0.2, 12, 8),
new THREE.MeshBasicMaterial({
color: longColor,
transparent: true,
opacity: 0.95
})
);
longMarker.position.fromArray(trace.path[trace.longHit]);
longMarker.visible = false;
group.add(longMarker);
scene.add(group);
traceObjects.push({
group,
shortLine,
longLine,
walker,
shortMarker,
longMarker,
trace
});
});
state.maxAnimationStep = state.traces.length
? Math.max(...state.traces.map(t => t.longHit)) + 18
: 1;
}
function updateTraces(step) {
for (const object of traceObjects) {
const { trace, walker, shortMarker, longMarker } = object;
const path = trace.path;
const currentIndex = Math.min(
Math.max(step, 0),
path.length - 1
);
walker.position.fromArray(path[currentIndex]);
walker.material.color.set(
step >= trace.shortHit ? COLORS.long : COLORS.short
);
shortMarker.visible = step >= trace.shortHit;
longMarker.visible = step >= trace.longHit;
const shortCount = Math.min(
step + 1,
trace.shortHit + 1
);
object.shortLine.geometry.setDrawRange(
0,
Math.max(0, shortCount)
);
const longCount = Math.max(
0,
Math.min(
step - trace.shortHit + 1,
path.length - trace.shortHit
)
);
object.longLine.geometry.setDrawRange(
trace.shortHit,
longCount
);
const pulse = 1 + 0.18 * Math.sin(step * 0.25);
shortMarker.scale.setScalar(step >= trace.shortHit ? pulse : 1);
}
}
// Direct camera controls; no examples or addon modules are used.
function resetCamera() {
const longDistance = Number($("longDistance").value);
cameraState.yaw = 0.72;
cameraState.pitch = 0.43;
cameraState.radius = Math.max(23, (longDistance + 6) * 1.45);
cameraState.target.set((longDistance - 2) / 2, 0, 0);
}
let pointerDown = false;
let pointerX = 0;
let pointerY = 0;
renderer.domElement.addEventListener("pointerdown", event => {
pointerDown = true;
pointerX = event.clientX;
pointerY = event.clientY;
renderer.domElement.setPointerCapture(event.pointerId);
});
renderer.domElement.addEventListener("pointermove", event => {
if (!pointerDown) return;
const dx = event.clientX - pointerX;
const dy = event.clientY - pointerY;
pointerX = event.clientX;
pointerY = event.clientY;
cameraState.yaw -= dx * 0.006;
cameraState.pitch = THREE.MathUtils.clamp(
cameraState.pitch + dy * 0.005,
-0.15,
1.25
);
});
function endPointer(event) {
pointerDown = false;
if (renderer.domElement.hasPointerCapture(event.pointerId)) {
renderer.domElement.releasePointerCapture(event.pointerId);
}
}
renderer.domElement.addEventListener("pointerup", endPointer);
renderer.domElement.addEventListener("pointercancel", endPointer);
renderer.domElement.addEventListener("wheel", event => {
event.preventDefault();
cameraState.radius = THREE.MathUtils.clamp(
cameraState.radius * Math.exp(event.deltaY * 0.001),
11,
90
);
}, { passive: false });
renderer.domElement.addEventListener("dblclick", resetCamera);
const projected = new THREE.Vector3();
function positionSceneLabel(element, x, y, z) {
projected.set(x, y, z).project(camera);
const width = sceneHost.clientWidth;
const height = sceneHost.clientHeight;
const visible = projected.z > -1 && projected.z < 1;
element.style.display = visible ? "block" : "none";
const screenX = (projected.x * 0.5 + 0.5) * width;
const screenY = (-projected.y * 0.5 + 0.5) * height;
element.style.left = `${screenX}px`;
element.style.top = `${screenY}px`;
}
function resizeRenderer() {
const width = sceneHost.clientWidth;
const height = sceneHost.clientHeight;
if (!width || !height) return;
renderer.setSize(width, height, false);
camera.aspect = width / height;
camera.updateProjectionMatrix();
}
new ResizeObserver(resizeRenderer).observe(sceneHost);
// ---------------------------------------------------------------------
// Monte Carlo first-passage simulation
// ---------------------------------------------------------------------
function mulberry32(seed) {
return function random() {
let value = seed += 0x6D2B79F5;
value = Math.imul(value ^ value >>> 15, value | 1);
value ^= value + Math.imul(value ^ value >>> 7, value | 61);
return ((value ^ value >>> 14) >>> 0) / 4294967296;
};
}
function reflect(value, minimum, maximum) {
if (value < minimum) return 2 * minimum + 1 - value;
if (value > maximum) return 2 * maximum - 1 - value;
return value;
}
function scheduleSimulation() {
clearTimeout(scheduleSimulation.timer);
scheduleSimulation.timer = setTimeout(runSimulation, 180);
}
async function runSimulation() {
const token = ++state.simulationToken;
const walkerCount = Number($("walkers").value);
const shortDistance = Number($("shortDistance").value);
const longDistance = Number($("longDistance").value);
const shortTimes = [];
const longTimes = [];
const traces = [];
const traceCount = Math.min(9, walkerCount);
const traceIndices = new Set();
for (let i = 0; i < traceCount; i++) {
traceIndices.add(
Math.floor(i * (walkerCount - 1) / Math.max(1, traceCount - 1))
);
}
const random = mulberry32(state.seed);
const maximumSteps = 60000;
const side = 5;
const xMinimum = -4;
const xMaximum = longDistance + 2;
$("busy").classList.remove("hidden");
$("status").textContent = "Sampling paired trajectories…";
$("playButton").disabled = true;
$("reseedButton").disabled = true;
let walkerIndex = 0;
while (walkerIndex < walkerCount) {
const chunkEnd = Math.min(walkerIndex + 35, walkerCount);
for (; walkerIndex < chunkEnd; walkerIndex++) {
let x = 0;
let y = 0;
let z = 0;
let shortHit = -1;
let longHit = -1;
const capturePath = traceIndices.has(walkerIndex);
const path = capturePath ? [[0, 0, 0]] : null;
for (let step = 1; step <= maximumSteps; step++) {
const axis = Math.floor(random() * 3);
const direction = random() < 0.5 ? -1 : 1;
if (axis === 0) {
x = reflect(x + direction, xMinimum, xMaximum);
} else if (axis === 1) {
y = reflect(y + direction, -side, side);
} else {
z = reflect(z + direction, -side, side);
}
if (shortHit < 0 && x === shortDistance) {
shortHit = step;
}
if (capturePath) path.push([x, y, z]);
if (x === longDistance) {
longHit = step;
break;
}
}
// This is extraordinarily unlikely at the chosen upper bound, but
// preserve a finite censoring value if it occurs.
if (shortHit < 0) shortHit = maximumSteps;
if (longHit < 0) longHit = maximumSteps;
shortTimes.push(shortHit);
longTimes.push(longHit);
if (capturePath) {
traces.push({
path,
shortHit,
longHit
});
}
}
$("status").textContent =
`Sampling ${walkerIndex} / ${walkerCount}`;
await new Promise(resolve => requestAnimationFrame(resolve));
if (token !== state.simulationToken) return;
}
state.shortTimes = shortTimes;
state.longTimes = longTimes;
state.traces = traces;
state.animationStep = 0;
buildTraces();
updateStats();
drawCharts();
$("busy").classList.add("hidden");
$("playButton").disabled = false;
$("reseedButton").disabled = false;
$("status").textContent =
`${walkerCount} paired walks · seed ${state.seed}`;
}
// ---------------------------------------------------------------------
// Statistics
// ---------------------------------------------------------------------
function quantile(values, probability) {
const sorted = [...values].sort((a, b) => a - b);
const position = (sorted.length - 1) * probability;
const lower = Math.floor(position);
const upper = Math.ceil(position);
const fraction = position - lower;
return sorted[lower] +
(sorted[upper] - sorted[lower]) * fraction;
}
function integer(value) {
return Math.round(value).toLocaleString();
}
function updateStats() {
if (!state.shortTimes.length) return;
const shortMedian = quantile(state.shortTimes, 0.5);
const longMedian = quantile(state.longTimes, 0.5);
const shortP90 = quantile(state.shortTimes, 0.9);
const longP90 = quantile(state.longTimes, 0.9);
const shortDistance = Number($("shortDistance").value);
const longDistance = Number($("longDistance").value);
const observedRatio = longMedian / shortMedian;
const referenceRatio = Math.pow(longDistance / shortDistance, 2);
$("shortMedian").textContent = `${integer(shortMedian)} steps`;
$("longMedian").textContent = `${integer(longMedian)} steps`;
$("shortP90").textContent = `p90 ${integer(shortP90)} steps`;
$("longP90").textContent = `p90 ${integer(longP90)} steps`;
$("medianRatio").textContent = `${observedRatio.toFixed(2)}×`;
$("ratioReference").textContent =
`${referenceRatio.toFixed(2)}× distance-squared reference`;
$("sampleCount").textContent = `${state.shortTimes.length} walkers`;
$("seedLabel").textContent = `seed ${state.seed}`;
}
// ---------------------------------------------------------------------
// Canvas charts
// ---------------------------------------------------------------------
function prepareCanvas(canvas) {
const rect = canvas.getBoundingClientRect();
const dpr = Math.min(window.devicePixelRatio || 1, 2);
const width = Math.max(1, rect.width);
const height = Math.max(1, rect.height);
if (
canvas.width !== Math.round(width * dpr) ||
canvas.height !== Math.round(height * dpr)
) {
canvas.width = Math.round(width * dpr);
canvas.height = Math.round(height * dpr);
}
const context = canvas.getContext("2d");
context.setTransform(dpr, 0, 0, dpr, 0, 0);
context.clearRect(0, 0, width, height);
return { context, width, height };
}
function drawFrame(context, width, height, title, subtitle, yLabel) {
const margin = {
left: 58,
right: 18,
top: 48,
bottom: 48
};
const plotWidth = width - margin.left - margin.right;
const plotHeight = height - margin.top - margin.bottom;
context.fillStyle = COLORS.text;
context.font = "600 13px system-ui, sans-serif";
context.textAlign = "left";
context.fillText(title, margin.left, 18);
context.fillStyle = COLORS.muted;
context.font = "11px system-ui, sans-serif";
context.fillText(subtitle, margin.left, 35);
context.save();
context.translate(15, margin.top + plotHeight / 2);
context.rotate(-Math.PI / 2);
context.textAlign = "center";
context.fillText(yLabel, 0, 0);
context.restore();
return { margin, plotWidth, plotHeight };
}
function drawGrid(context, frame, maximumY, formatterY) {
const { margin, plotWidth, plotHeight } = frame;
context.font = "10px system-ui, sans-serif";
context.lineWidth = 1;
for (let i = 0; i <= 5; i++) {
const value = maximumY * i / 5;
const y = margin.top + plotHeight - plotHeight * i / 5;
context.strokeStyle = COLORS.grid;
context.globalAlpha = 0.55;
context.beginPath();
context.moveTo(margin.left, y);
context.lineTo(margin.left + plotWidth, y);
context.stroke();
context.globalAlpha = 1;
context.fillStyle = COLORS.muted;
context.textAlign = "right";
context.fillText(
formatterY(value),
margin.left - 8,
y + 3
);
}
}
function drawXAxis(context, frame, tickValues, inverse, formatter) {
const { margin, plotWidth, plotHeight } = frame;
const minimum = 0;
const maximum = tickValues.length - 1;
context.font = "10px system-ui, sans-serif";
context.textAlign = "center";
tickValues.forEach((value, index) => {
const x = margin.left + plotWidth * index / maximum;
const display = formatter(inverse(value));
context.strokeStyle = COLORS.grid;
context.beginPath();
context.moveTo(x, margin.top + plotHeight);
context.lineTo(x, margin.top + plotHeight + 4);
context.stroke();
context.fillStyle = COLORS.muted;
context.fillText(
display,
x,
margin.top + plotHeight + 17
);
});
}
function drawLegend(context, frame, entries) {
let x = frame.margin.left + frame.plotWidth - 112;
const y = 22;
entries.forEach(entry => {
context.fillStyle = entry.color;
context.fillRect(x, y - 7, 13, 4);
context.fillStyle = COLORS.muted;
context.font = "10px system-ui, sans-serif";
context.textAlign = "left";
context.fillText(entry.label, x + 18, y);
x += 77;
});
}
function drawHistogram(
canvas,
datasets,
title,
subtitle,
xLabel,
transform,
inverse,
xFormatter
) {
const { context, width, height } = prepareCanvas(canvas);
const frame = drawFrame(
context,
width,
height,
title,
subtitle,
"Relative density"
);
const { margin, plotWidth, plotHeight } = frame;
const transformed = datasets.map(dataset => ({
...dataset,
values: dataset.values.map(transform)
}));
const maximumU = Math.max(
0.001,
...transformed.flatMap(dataset => dataset.values)
);
const binCount = 42;
const binWidth = maximumU / binCount;
let maximumY = 0;
const bins = transformed.map(dataset => {
const counts = new Uint32Array(binCount);
dataset.values.forEach(value => {
const index = Math.min(
binCount - 1,
Math.max(0, Math.floor(value / binWidth))
);
counts[index]++;
});
const densities = Array.from(counts, count =>
count / (dataset.values.length * binWidth)
);
maximumY = Math.max(maximumY, ...densities);
return densities;
});
drawGrid(context, frame, maximumY, value =>
value >= 10 ? value.toFixed(0) : value.toFixed(2)
);
datasets.forEach((dataset, datasetIndex) => {
const densities = bins[datasetIndex];
context.fillStyle = dataset.color;
context.globalAlpha = 0.48;
densities.forEach((density, index) => {
const x0 = margin.left + plotWidth * index / binCount;
const x1 = margin.left + plotWidth * (index + 1) / binCount;
const barHeight = plotHeight * density / maximumY;
context.fillRect(
x0 + 0.5,
margin.top + plotHeight - barHeight,
Math.max(1, x1 - x0 - 1),
barHeight
);
});
context.globalAlpha = 1;
});
const tickValues = Array.from(
{ length: 6 },
(_, index) => maximumU * index / 5
);
drawXAxis(
context,
frame,
tickValues,
inverse,
xFormatter
);
context.fillStyle = COLORS.muted;
context.font = "10px system-ui, sans-serif";
context.textAlign = "center";
context.fillText(
xLabel,
margin.left + plotWidth / 2,
height - 8
);
drawLegend(context, frame, datasets.map(dataset => ({
color: dataset.color,
label: dataset.label
})));
}
function drawSurvival(canvas) {
const { context, width, height } = prepareCanvas(canvas);
const frame = drawFrame(
context,
width,
height,
"Arrival-time survival curves",
"ILLUSTRATIVE · fraction of walkers not yet arrived · logarithmic time axis",
"Survival probability"
);
const { margin, plotWidth, plotHeight } = frame;
const datasets = [
{
label: "Short",
color: COLORS.short,
values: state.shortTimes
},
{
label: "Long",
color: COLORS.long,
values: state.longTimes
}
];
let maximumU = 0.001;
const sorted = datasets.map(dataset => {
const values = [...dataset.values].sort((a, b) => a - b);
maximumU = Math.max(
maximumU,
...values.map(value => Math.log1p(value))
);
return values;
});
drawGrid(context, frame, 1, value => value.toFixed(2));
datasets.forEach((dataset, datasetIndex) => {
context.strokeStyle = dataset.color;
context.lineWidth = 2.1;
context.beginPath();
sorted[datasetIndex].forEach((value, index) => {
const u = Math.log1p(value);
const x = margin.left + plotWidth * u / maximumU;
const y = margin.top + plotHeight * (1 - index / dataset.values.length);
if (index === 0) context.moveTo(x, y);
else context.lineTo(x, y);
});
context.stroke();
});
const tickValues = Array.from(
{ length: 7 },
(_, index) => maximumU * index / 6
);
drawXAxis(
context,
frame,
tickValues,
u => Math.expm1(u),
value => integer(value)
);
context.fillStyle = COLORS.muted;
context.font = "10px system-ui, sans-serif";
context.textAlign = "center";
context.fillText(
"Arrival time (steps; logarithmic axis)",
margin.left + plotWidth / 2,
height - 8
);
drawLegend(context, frame, datasets.map(dataset => ({
color: dataset.color,
label: dataset.label
})));
}
function drawCharts() {
if (!state.shortTimes.length) return;
const shortDistance = Number($("shortDistance").value);
const longDistance = Number($("longDistance").value);
const rawDatasets = [
{
label: "Short",
color: COLORS.short,
values: state.shortTimes
},
{
label: "Long",
color: COLORS.long,
values: state.longTimes
}
];
const scaledDatasets = [
{
label: "Short",
color: COLORS.short,
values: state.shortTimes.map(value => value / shortDistance ** 2)
},
{
label: "Long",
color: COLORS.long,
values: state.longTimes.map(value => value / longDistance ** 2)
}
];
drawHistogram(
$("rawChart"),
rawDatasets,
"Arrival-time distributions",
"ILLUSTRATIVE · density on logarithmic time bins",
"Arrival time t (steps; logarithmic axis)",
value => Math.log1p(value),
u => Math.expm1(u),
value => integer(value)
);
drawHistogram(
$("scaledChart"),
scaledDatasets,
"Distance-scaled distributions",
"ILLUSTRATIVE · normalized by the distance-squared time scale",
"Scaled time t / L² (logarithmic axis)",
value => Math.log1p(value),
u => Math.expm1(u),
value => value.toFixed(value < 1 ? 2 : 1)
);
drawSurvival($("survivalChart"));
}
let chartResizeTimer = null;
window.addEventListener("resize", () => {
clearTimeout(chartResizeTimer);
chartResizeTimer = setTimeout(drawCharts, 80);
});
// ---------------------------------------------------------------------
// UI wiring
// ---------------------------------------------------------------------
function updateControlLabels() {
const walkers = Number($("walkers").value);
const shortDistance = Number($("shortDistance").value);
const longDistance = Number($("longDistance").value);
const speed = Number($("speed").value);
$("walkersOut").textContent = walkers;
$("shortOut").textContent = `${shortDistance} voxels`;
$("longOut").textContent = `${longDistance} voxels`;
$("speedOut").textContent = `${speed} steps/s`;
$("longDistance").min = Math.max(8, shortDistance + 4);
if (longDistance <= shortDistance) {
$("longDistance").value = shortDistance + 4;
$("longOut").textContent = `${shortDistance + 4} voxels`;
}
}
$("walkers").addEventListener("input", () => {
updateControlLabels();
scheduleSimulation();
});
$("shortDistance").addEventListener("input", () => {
updateControlLabels();
scheduleSimulation();
});
$("longDistance").addEventListener("input", () => {
updateControlLabels();
scheduleSimulation();
});
$("speed").addEventListener("input", updateControlLabels);
$("playButton").addEventListener("click", () => {
state.playing = !state.playing;
$("playButton").textContent = state.playing
? "Pause paths"
: "Play paths";
});
$("replayButton").addEventListener("click", () => {
state.animationStep = 0;
});
$("reseedButton").addEventListener("click", () => {
state.seed = (state.seed + 0x9e3779b9) >>> 0;
state.animationStep = 0;
runSimulation();
});
$("cameraButton").addEventListener("click", resetCamera);
// ---------------------------------------------------------------------
// Animation loop
// ---------------------------------------------------------------------
const clock = new THREE.Clock();
function animate() {
requestAnimationFrame(animate);
const delta = Math.min(clock.getDelta(), 0.08);
const speed = Number($("speed").value);
if (
state.playing &&
state.traces.length &&
state.animationStep <= state.maxAnimationStep
) {
state.animationStep += delta * speed;
}
if (state.animationStep > state.maxAnimationStep) {
state.animationStep = 0;
}
updateTraces(Math.floor(state.animationStep));
const cp = Math.cos(cameraState.pitch);
camera.position.set(
cameraState.target.x +
cameraState.radius * Math.sin(cameraState.yaw) * cp,
cameraState.radius * Math.sin(cameraState.pitch),
cameraState.target.z +
cameraState.radius * Math.cos(cameraState.yaw) * cp
);
camera.lookAt(cameraState.target);
if (shortGate) {
shortGate.panel.material.opacity =
0.13 + 0.06 * (0.5 + 0.5 * Math.sin(state.animationStep * 0.12));
}
if (longGate) {
longGate.panel.material.opacity =
0.13 + 0.06 * (0.5 + 0.5 * Math.sin(state.animationStep * 0.09 + 1.4));
}
camera.updateMatrixWorld();
renderer.render(scene, camera);
if (shortGate) {
positionSceneLabel(
$("labelShort"),
shortGate.x,
5.9,
0
);
}
if (longGate) {
positionSceneLabel(
$("labelLong"),
longGate.x,
5.9,
0
);
}
}
updateControlLabels();
rebuildScene();
resizeRenderer();
animate();
runSimulation();
</script>
</body>
</html>
```