Prompt specification
Build or customize the Three.js 3D scene "Rare-event token calendar" 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: Rare-event token calendar
Category: Algorithms & Systems · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/rare-event-token-calendar-x1821
Scene Description Prompt:
Please create one self-contained HTML file with Three.js from cdnjs showing rare events across repeated opportunities. Build a long sequence of synthetic daily trials with occasional marked events; show per-trial probability separately from the chance of at least one event across the sequence. Low-poly.
Working Three.js Starter (rare-event-token-calendar-x1821):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta name="theme-color" content="#07121b" />
<title>The Long Shot — Rare Events Over Time</title>
<style>
:root {
--bg: #07121b;
--panel: rgba(8, 22, 31, 0.84);
--panel-strong: rgba(9, 27, 37, 0.94);
--line: rgba(148, 206, 219, 0.18);
--text: #edf8fa;
--muted: #91aeb8;
--cyan: #75e7f4;
--cyan-soft: rgba(117, 231, 244, 0.13);
--orange: #ff9b52;
--orange-soft: rgba(255, 155, 82, 0.13);
--lime: #d8ff83;
--violet: #b7a6ff;
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background:
radial-gradient(circle at 24% 12%, rgba(31, 83, 103, 0.24), transparent 33%),
radial-gradient(circle at 80% 78%, rgba(66, 36, 31, 0.15), transparent 32%),
linear-gradient(150deg, #0a1c27 0%, #07121b 48%, #050d14 100%);
color: var(--text);
font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
button,
input {
font: inherit;
}
#scene {
position: fixed;
inset: 0;
width: 100%;
height: 100%;
display: block;
touch-action: none;
cursor: grab;
}
#scene:active {
cursor: grabbing;
}
.hud {
position: fixed;
inset: 0;
z-index: 2;
pointer-events: none;
}
.brand {
position: absolute;
top: 26px;
left: 30px;
max-width: 430px;
text-shadow: 0 2px 18px rgba(0, 0, 0, 0.6);
}
.eyebrow {
color: var(--cyan);
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 10px;
font-weight: 800;
letter-spacing: 0.19em;
text-transform: uppercase;
}
.brand h1 {
margin: 7px 0 5px;
font-size: clamp(30px, 4vw, 54px);
line-height: 0.92;
letter-spacing: -0.055em;
font-weight: 850;
}
.brand h1 span {
color: var(--orange);
}
.brand p {
margin: 10px 0 0;
color: var(--muted);
font-size: 13px;
line-height: 1.5;
}
.stats {
position: absolute;
top: 24px;
right: 24px;
display: grid;
grid-template-columns: repeat(3, minmax(150px, 1fr));
gap: 9px;
width: min(590px, calc(100vw - 48px));
}
.stat {
position: relative;
min-height: 128px;
padding: 15px 16px 13px;
overflow: hidden;
background: var(--panel);
border: 1px solid var(--line);
clip-path: polygon(0 0, calc(100% - 12px) 0, 100% 12px, 100% 100%, 0 100%);
backdrop-filter: blur(14px);
-webkit-backdrop-filter: blur(14px);
}
.stat::before {
content: "";
position: absolute;
inset: 0 auto 0 0;
width: 3px;
background: var(--accent, var(--cyan));
}
.stat.daily {
--accent: var(--cyan);
}
.stat.sequence {
--accent: var(--orange);
}
.stat.observed {
--accent: var(--violet);
}
.stat-label {
color: var(--accent);
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 9px;
font-weight: 800;
letter-spacing: 0.13em;
text-transform: uppercase;
}
.stat-value {
margin-top: 8px;
color: var(--accent);
font-size: clamp(26px, 3vw, 38px);
font-weight: 800;
line-height: 1;
letter-spacing: -0.055em;
font-variant-numeric: tabular-nums;
}
.stat-description {
margin-top: 7px;
color: var(--muted);
font-size: 10px;
line-height: 1.4;
}
.formula {
margin-top: 8px;
color: rgba(237, 248, 250, 0.72);
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 9px;
line-height: 1.35;
white-space: nowrap;
}
.formula sup {
font-size: 7px;
}
.legend {
position: absolute;
left: 30px;
bottom: 166px;
display: flex;
flex-wrap: wrap;
gap: 8px 15px;
max-width: min(600px, calc(100vw - 60px));
padding: 10px 13px;
color: var(--muted);
background: rgba(7, 18, 27, 0.64);
border: 1px solid rgba(148, 206, 219, 0.12);
backdrop-filter: blur(10px);
-webkit-backdrop-filter: blur(10px);
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 9px;
letter-spacing: 0.025em;
}
.legend-item {
display: flex;
align-items: center;
gap: 7px;
white-space: nowrap;
}
.legend-mark {
width: 9px;
height: 9px;
transform: rotate(45deg);
background: var(--cyan);
box-shadow: 0 0 10px rgba(117, 231, 244, 0.5);
}
.legend-mark.event {
background: var(--orange);
box-shadow: 0 0 10px rgba(255, 155, 82, 0.5);
}
.legend-mark.span {
width: 19px;
height: 2px;
transform: none;
background: var(--orange);
box-shadow: none;
}
.controls {
position: absolute;
right: 24px;
bottom: 22px;
left: 24px;
display: grid;
grid-template-columns: 1.2fr 1.2fr 0.8fr auto;
gap: 18px;
align-items: end;
width: min(1080px, calc(100vw - 48px));
margin: 0 auto;
padding: 16px 18px;
pointer-events: auto;
background: var(--panel-strong);
border: 1px solid var(--line);
clip-path: polygon(0 0, calc(100% - 17px) 0, 100% 17px, 100% 100%, 0 100%);
box-shadow: 0 18px 55px rgba(0, 0, 0, 0.34);
backdrop-filter: blur(18px);
-webkit-backdrop-filter: blur(18px);
}
.control {
min-width: 0;
}
.control-head {
display: flex;
justify-content: space-between;
align-items: baseline;
gap: 10px;
margin-bottom: 9px;
}
.control label,
.control-title {
color: var(--muted);
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 9px;
font-weight: 800;
letter-spacing: 0.13em;
text-transform: uppercase;
}
.control output {
color: var(--text);
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 11px;
font-weight: 700;
white-space: nowrap;
}
input[type="range"] {
width: 100%;
height: 4px;
margin: 0;
appearance: none;
-webkit-appearance: none;
border-radius: 0;
background: rgba(151, 201, 214, 0.18);
outline: none;
cursor: pointer;
}
input[type="range"]::-webkit-slider-thumb {
width: 13px;
height: 13px;
appearance: none;
-webkit-appearance: none;
border: 2px solid #081821;
border-radius: 0;
background: var(--cyan);
box-shadow: 0 0 0 1px var(--cyan);
transform: rotate(45deg);
}
input[type="range"]::-moz-range-thumb {
width: 11px;
height: 11px;
border: 2px solid #081821;
border-radius: 0;
background: var(--cyan);
box-shadow: 0 0 0 1px var(--cyan);
transform: rotate(45deg);
}
#probability::-webkit-slider-thumb {
background: var(--orange);
box-shadow: 0 0 0 1px var(--orange);
}
#probability::-moz-range-thumb {
background: var(--orange);
box-shadow: 0 0 0 1px var(--orange);
}
.seed-row {
display: flex;
gap: 7px;
}
#seed {
width: 100%;
min-width: 0;
height: 35px;
padding: 0 10px;
color: var(--text);
background: rgba(1, 9, 14, 0.52);
border: 1px solid var(--line);
border-radius: 0;
outline: none;
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 12px;
}
#seed:focus {
border-color: rgba(117, 231, 244, 0.65);
}
.button-row {
display: flex;
gap: 8px;
}
button {
height: 35px;
padding: 0 14px;
color: #07131a;
background: var(--cyan);
border: 0;
border-radius: 0;
clip-path: polygon(0 0, calc(100% - 8px) 0, 100% 8px, 100% 100%, 0 100%);
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 9px;
font-weight: 900;
letter-spacing: 0.09em;
text-transform: uppercase;
cursor: pointer;
transition: transform 150ms ease, filter 150ms ease;
}
button:hover {
filter: brightness(1.12);
transform: translateY(-1px);
}
button:active {
transform: translateY(0);
}
button.secondary {
color: var(--text);
background: rgba(117, 231, 244, 0.1);
border: 1px solid rgba(117, 231, 244, 0.25);
}
.hint {
position: absolute;
right: 28px;
bottom: 145px;
color: rgba(145, 174, 184, 0.75);
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 9px;
letter-spacing: 0.04em;
text-align: right;
}
.reset-view {
position: absolute;
right: 24px;
top: 166px;
pointer-events: auto;
height: 29px;
padding: 0 10px;
color: var(--muted);
background: rgba(7, 18, 27, 0.68);
border: 1px solid var(--line);
clip-path: none;
font-size: 8px;
}
.loading {
position: fixed;
inset: 0;
z-index: 10;
display: grid;
place-items: center;
background: #07121b;
color: var(--cyan);
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 11px;
letter-spacing: 0.16em;
text-transform: uppercase;
transition: opacity 350ms ease, visibility 350ms ease;
}
.loading.hidden {
opacity: 0;
visibility: hidden;
}
@media (max-width: 980px) {
.brand {
top: 18px;
left: 18px;
}
.brand h1 {
font-size: 35px;
}
.brand p {
display: none;
}
.stats {
top: 91px;
right: 16px;
left: 16px;
width: auto;
grid-template-columns: repeat(3, 1fr);
}
.stat {
min-height: 112px;
padding: 12px 13px;
}
.stat-value {
font-size: 27px;
}
.reset-view {
top: 216px;
right: 17px;
}
.legend {
left: 18px;
bottom: 181px;
}
.hint {
display: none;
}
.controls {
right: 14px;
bottom: 14px;
left: 14px;
grid-template-columns: 1fr 1fr;
gap: 13px 18px;
width: auto;
}
.button-row {
justify-content: flex-end;
}
}
@media (max-width: 590px) {
.brand h1 {
font-size: 30px;
}
.stats {
grid-template-columns: 1fr 1fr;
}
.stat.observed {
grid-column: 1 / -1;
min-height: 82px;
}
.stat.observed .stat-value {
display: inline-block;
margin-right: 8px;
}
.stat.observed .stat-description {
display: inline-block;
}
.formula {
display: none;
}
.reset-view {
top: 286px;
}
.legend {
display: none;
}
.controls {
grid-template-columns: 1fr;
padding: 14px;
}
.button-row {
justify-content: stretch;
}
.button-row button {
flex: 1;
}
}
</style>
</head>
<body>
<canvas id="scene" aria-label="Interactive 3D visualization of rare events over repeated daily trials"></canvas>
<div class="hud">
<header class="brand">
<div class="eyebrow" id="runLabel">Bernoulli field / 240 opportunities</div>
<h1>THE LONG <span>SHOT</span></h1>
<p>One rare day becomes a likely story when opportunity repeats.</p>
</header>
<section class="stats" aria-live="polite">
<article class="stat daily">
<div class="stat-label">Per trial</div>
<div class="stat-value" id="dailyValue">1.50%</div>
<div class="stat-description">Chance of a marked event on any one day</div>
<div class="formula" id="dailyFormula">p = 0.0150</div>
</article>
<article class="stat sequence">
<div class="stat-label" id="sequenceLabel">Across 240 trials</div>
<div class="stat-value" id="sequenceValue">97.34%</div>
<div class="stat-description">Chance of at least one event in the sequence</div>
<div class="formula" id="sequenceFormula">1 − (1 − 0.0150)<sup>240</sup></div>
</article>
<article class="stat observed">
<div class="stat-label">Synthetic run</div>
<div class="stat-value" id="observedValue">0</div>
<div class="stat-description" id="observedDescription">marked events / 240 trials</div>
</article>
</section>
<button class="reset-view" id="resetView" type="button">Reset view</button>
<div class="legend">
<div class="legend-item">
<span class="legend-mark"></span>
one daily opportunity
</div>
<div class="legend-item">
<span class="legend-mark event"></span>
marked event in this seeded run
</div>
<div class="legend-item">
<span class="legend-mark span"></span>
at-least-one probability across the whole run
</div>
</div>
<div class="hint">
DRAG TO ORBIT · WHEEL TO ZOOM<br />
SHIFT / RIGHT-DRAG TO PAN · R TO RESET
</div>
<section class="controls" aria-label="Simulation controls">
<div class="control">
<div class="control-head">
<label for="days">Sequence length</label>
<output id="daysOutput" for="days">240 days</output>
</div>
<input id="days" type="range" min="30" max="365" step="5" value="240" />
</div>
<div class="control">
<div class="control-head">
<label for="probability">Per-trial probability</label>
<output id="probabilityOutput" for="probability">1.50%</output>
</div>
<input id="probability" type="range" min="0.2" max="10" step="0.1" value="1.5" />
</div>
<div class="control">
<div class="control-head">
<span class="control-title">Random seed</span>
</div>
<div class="seed-row">
<input id="seed" type="number" min="0" max="999999" value="137" aria-label="Random seed" />
</div>
</div>
<div class="button-row">
<button id="replay" type="button" class="secondary" title="Regenerate with the current seed">Replay</button>
<button id="newRun" type="button">New run</button>
</div>
</section>
</div>
<div class="loading" id="loading">Building probability field…</div>
<script type="module">
import * as THREE from "https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
const canvas = document.querySelector("#scene");
const loading = document.querySelector("#loading");
const ui = {
days: document.querySelector("#days"),
probability: document.querySelector("#probability"),
seed: document.querySelector("#seed"),
daysOutput: document.querySelector("#daysOutput"),
probabilityOutput: document.querySelector("#probabilityOutput"),
dailyValue: document.querySelector("#dailyValue"),
dailyFormula: document.querySelector("#dailyFormula"),
sequenceLabel: document.querySelector("#sequenceLabel"),
sequenceValue: document.querySelector("#sequenceValue"),
sequenceFormula: document.querySelector("#sequenceFormula"),
observedValue: document.querySelector("#observedValue"),
observedDescription: document.querySelector("#observedDescription"),
runLabel: document.querySelector("#runLabel"),
replay: document.querySelector("#replay"),
newRun: document.querySelector("#newRun"),
resetView: document.querySelector("#resetView")
};
const COLORS = {
cyan: 0x75e7f4,
orange: 0xff9b52,
violet: 0xb7a6ff,
bg: 0x07121b
};
const renderer = new THREE.WebGLRenderer({
canvas,
antialias: true,
alpha: true,
powerPreference: "high-performance"
});
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.08;
const scene = new THREE.Scene();
scene.fog = new THREE.Fog(COLORS.bg, 350, 1400);
const camera = new THREE.PerspectiveCamera(
42,
window.innerWidth / window.innerHeight,
0.1,
3000
);
scene.add(new THREE.HemisphereLight(0x9adcf0, 0x071018, 1.55));
const keyLight = new THREE.DirectionalLight(0xd9f5ff, 2.3);
keyLight.position.set(-20, 70, -40);
scene.add(keyLight);
const rimLight = new THREE.DirectionalLight(0xff8750, 1.0);
rimLight.position.set(80, 25, 80);
scene.add(rimLight);
const fillLight = new THREE.PointLight(0x4ac9e1, 18, 180, 2);
fillLight.position.set(-50, 24, 30);
scene.add(fillLight);
// Static, square-shaped atmospheric particles.
{
const count = 650;
const positions = new Float32Array(count * 3);
const random = mulberry32(9147);
for (let i = 0; i < count; i++) {
positions[i * 3] = (random() - 0.5) * 1300;
positions[i * 3 + 1] = random() * 170 - 15;
positions[i * 3 + 2] = (random() - 0.5) * 1100;
}
const geometry = new THREE.BufferGeometry();
geometry.setAttribute("position", new THREE.BufferAttribute(positions, 3));
const material = new THREE.PointsMaterial({
color: 0x93c4d2,
size: 0.34,
transparent: true,
opacity: 0.38,
depthWrite: false,
sizeAttenuation: true
});
scene.add(new THREE.Points(geometry, material));
}
let world = null;
let eventAnimations = [];
let playhead = null;
let playheadActive = true;
let playheadIndex = 0;
let currentEventDays = [];
let buildFrame = 0;
let pendingFit = false;
const clock = new THREE.Clock();
// Camera orbit state.
const desiredCamera = {
theta: -1.38,
phi: 0.96,
radius: 180,
target: new THREE.Vector3(0, 0.1, 0)
};
const currentCamera = {
theta: desiredCamera.theta,
phi: desiredCamera.phi,
radius: desiredCamera.radius,
target: desiredCamera.target.clone()
};
function mulberry32(seed) {
let value = seed >>> 0;
return function () {
value += 0x6D2B79F5;
let result = value;
result = Math.imul(result ^ (result >>> 15), result | 1);
result ^= result + Math.imul(result ^ (result >>> 7), result | 61);
return ((result ^ (result >>> 14)) >>> 0) / 4294967296;
};
}
function getSettings() {
return {
days: Number(ui.days.value),
probability: Number(ui.probability.value) / 100,
seed: Math.max(0, Math.min(999999, Math.floor(Number(ui.seed.value) || 0)))
};
}
function simulate(settings) {
const random = mulberry32(settings.seed);
const events = [];
for (let day = 0; day < settings.days; day++) {
if (random() < settings.probability) {
events.push(day);
}
}
return events;
}
function formatSequenceProbability(value) {
if (value >= 0.999995) return ">99.999%";
if (value >= 0.9999) return `${(value * 100).toFixed(4)}%`;
if (value >= 0.999) return `${(value * 100).toFixed(3)}%`;
return `${(value * 100).toFixed(2)}%`;
}
function updateStats() {
const settings = getSettings();
const atLeastOne = 1 - Math.pow(1 - settings.probability, settings.days);
const perTrialPercent = settings.probability * 100;
ui.daysOutput.textContent = `${settings.days} days`;
ui.probabilityOutput.textContent = `${perTrialPercent.toFixed(2)}%`;
ui.dailyValue.textContent = `${perTrialPercent.toFixed(2)}%`;
ui.dailyFormula.textContent = `p = ${settings.probability.toFixed(4)}`;
ui.sequenceLabel.textContent = `Across ${settings.days} trials`;
ui.sequenceValue.textContent = formatSequenceProbability(atLeastOne);
ui.sequenceFormula.innerHTML =
`1 − (1 − ${settings.probability.toFixed(4)})<sup>${settings.days}</sup>`;
ui.observedValue.textContent = String(currentEventDays.length);
ui.observedDescription.textContent =
`marked events / ${settings.days} trials`;
ui.runLabel.textContent =
`Bernoulli field / ${settings.days} opportunities`;
}
function disposeGroup(group) {
const geometries = new Set();
const materials = new Set();
const textures = new Set();
group.traverse((object) => {
if (object.geometry) geometries.add(object.geometry);
const objectMaterials = Array.isArray(object.material)
? object.material
: object.material
? [object.material]
: [];
for (const material of objectMaterials) {
materials.add(material);
if (material.map) textures.add(material.map);
}
});
for (const geometry of geometries) geometry.dispose();
for (const texture of textures) texture.dispose();
for (const material of materials) material.dispose();
}
function pathPosition(index, days, spacing) {
const x = (index - (days - 1) / 2) * spacing;
const z =
Math.sin(index * 0.045) * 1.35 +
Math.sin(index * 0.012 + 0.7) * 2.65;
return { x, z };
}
function roundedRect(context, x, y, width, height, radius) {
context.beginPath();
context.moveTo(x + radius, y);
context.lineTo(x + width - radius, y);
context.quadraticCurveTo(x + width, y, x + width, y + radius);
context.lineTo(x + width, y + height - radius);
context.quadraticCurveTo(x + width, y + height, x + width - radius, y + height);
context.lineTo(x + radius, y + height);
context.quadraticCurveTo(x, y + height, x, y + height - radius);
context.lineTo(x, y + radius);
context.quadraticCurveTo(x, y, x + radius, y);
context.closePath();
}
function makeTextSprite(text, color = "#d9f6fb", worldWidth = 5) {
const canvas = document.createElement("canvas");
canvas.width = 1024;
canvas.height = 192;
const context = canvas.getContext("2d");
context.clearRect(0, 0, canvas.width, canvas.height);
roundedRect(context, 8, 24, 1008, 144, 12);
context.fillStyle = "rgba(4, 14, 21, 0.88)";
context.fill();
context.strokeStyle = "rgba(150, 220, 235, 0.24)";
context.lineWidth = 3;
context.stroke();
context.fillStyle = color;
context.font = "800 56px ui-monospace, SFMono-Regular, Menlo, Consolas, monospace";
context.textAlign = "center";
context.textBaseline = "middle";
context.fillText(text, 512, 98);
const texture = new THREE.CanvasTexture(canvas);
texture.colorSpace = THREE.SRGBColorSpace;
texture.minFilter = THREE.LinearFilter;
texture.magFilter = THREE.LinearFilter;
const material = new THREE.SpriteMaterial({
map: texture,
transparent: true,
depthTest: false,
depthWrite: false,
toneMapped: false
});
const sprite = new THREE.Sprite(material);
sprite.scale.set(worldWidth, worldWidth * 192 / 1024, 1);
sprite.renderOrder = 10;
return sprite;
}
function buildGround(group, length, days) {
const segments = Math.min(110, Math.max(28, Math.floor(days / 3)));
let geometry = new THREE.PlaneGeometry(length + 18, 34, segments, 5);
geometry.rotateX(-Math.PI / 2);
const positions = geometry.attributes.position;
const random = mulberry32(404);
for (let i = 0; i < positions.count; i++) {
const x = positions.getX(i);
const z = positions.getZ(i);
const height =
-0.62 +
Math.sin(x * 0.035) * 0.12 +
Math.cos(z * 0.18 + x * 0.012) * 0.07 +
(random() - 0.5) * 0.035;
positions.setY(i, height);
}
const nonIndexed = geometry.toNonIndexed();
geometry.dispose();
const colors = new Float32Array(nonIndexed.attributes.position.count * 3);
const color = new THREE.Color();
for (let i = 0; i < nonIndexed.attributes.position.count; i += 3) {
color.setHSL(
0.535 + (random() - 0.5) * 0.025,
0.27 + random() * 0.08,
0.045 + random() * 0.035
);
for (let vertex = 0; vertex < 3; vertex++) {
color.toArray(colors, (i + vertex) * 3);
}
}
nonIndexed.setAttribute("color", new THREE.BufferAttribute(colors, 3));
const material = new THREE.MeshStandardMaterial({
color: 0xffffff,
vertexColors: true,
roughness: 1,
metalness: 0,
flatShading: true,
side: THREE.DoubleSide
});
const ground = new THREE.Mesh(nonIndexed, material);
group.add(ground);
}
function buildWorld() {
if (world) {
scene.remove(world);
disposeGroup(world);
}
eventAnimations = [];
const settings = getSettings();
const { days } = settings;
const spacing = days > 300 ? 0.81 : 0.91;
const length = (days - 1) * spacing;
world = new THREE.Group();
scene.add(world);
buildGround(world, length, days);
// Daily opportunity tiles.
const tileGeometry = new THREE.CylinderGeometry(0.39, 0.47, 0.17, 6);
const tileMaterial = new THREE.MeshStandardMaterial({
color: 0xffffff,
roughness: 0.72,
metalness: 0.12,
flatShading: true
});
const tiles = new THREE.InstancedMesh(tileGeometry, tileMaterial, days);
tiles.instanceMatrix.setUsage(THREE.StaticDrawUsage);
const dummy = new THREE.Object3D();
const tileColor = new THREE.Color();
for (let i = 0; i < days; i++) {
const { x, z } = pathPosition(i, days, spacing);
dummy.position.set(x, 0, z);
dummy.rotation.set(0, i * 0.19, 0);
dummy.scale.setScalar(1);
dummy.updateMatrix();
tiles.setMatrixAt(i, dummy.matrix);
const progress = i / Math.max(1, days - 1);
tileColor.setHSL(
0.525 + progress * 0.025,
0.31,
0.21 + progress * 0.055
);
tiles.setColorAt(i, tileColor);
}
tiles.instanceMatrix.needsUpdate = true;
if (tiles.instanceColor) tiles.instanceColor.needsUpdate = true;
world.add(tiles);
// The path through all opportunities.
const pathPoints = [];
for (let i = 0; i < days; i++) {
const { x, z } = pathPosition(i, days, spacing);
pathPoints.push(new THREE.Vector3(x, 0.025, z));
}
const pathGeometry = new THREE.BufferGeometry().setFromPoints(pathPoints);
const pathMaterial = new THREE.LineDashedMaterial({
color: COLORS.cyan,
dashSize: 0.42,
gapSize: 0.24,
transparent: true,
opacity: 0.34
});
const pathLine = new THREE.Line(pathGeometry, pathMaterial);
pathLine.computeLineDistances();
world.add(pathLine);
// Small cyan diamonds represent the daily probability opportunity.
const eventSet = new Set(currentEventDays);
const ordinaryDays = [];
for (let i = 0; i < days; i++) {
if (!eventSet.has(i)) ordinaryDays.push(i);
}
const opportunityGeometry = new THREE.OctahedronGeometry(0.095, 0);
const opportunityMaterial = new THREE.MeshBasicMaterial({
color: COLORS.cyan,
toneMapped: false
});
const opportunities = new THREE.InstancedMesh(
opportunityGeometry,
opportunityMaterial,
ordinaryDays.length
);
ordinaryDays.forEach((day, instanceIndex) => {
const { x, z } = pathPosition(day, days, spacing);
dummy.position.set(x, 0.16, z);
dummy.rotation.set(0, Math.PI * 0.25, 0);
dummy.scale.setScalar(1);
dummy.updateMatrix();
opportunities.setMatrixAt(instanceIndex, dummy.matrix);
});
opportunities.instanceMatrix.needsUpdate = true;
world.add(opportunities);
// Marked events: low-poly orange shards.
const shardMaterial = new THREE.MeshStandardMaterial({
color: 0xffa25e,
emissive: 0xff4a19,
emissiveIntensity: 1.25,
roughness: 0.38,
metalness: 0.08,
flatShading: true
});
const capMaterial = new THREE.MeshStandardMaterial({
color: 0xffe1a1,
emissive: 0xff7b25,
emissiveIntensity: 1.5,
roughness: 0.3,
metalness: 0.05,
flatShading: true
});
const beamMaterial = new THREE.MeshBasicMaterial({
color: 0xff7838,
transparent: true,
opacity: 0.17,
depthWrite: false,
blending: THREE.AdditiveBlending,
toneMapped: false
});
const ringMaterial = new THREE.MeshBasicMaterial({
color: 0xffa34f,
transparent: true,
opacity: 0.8,
toneMapped: false
});
const shardGeometry = new THREE.ConeGeometry(0.23, 0.76, 5);
const capGeometry = new THREE.OctahedronGeometry(0.14, 0);
const beamGeometry = new THREE.CylinderGeometry(0.035, 0.09, 1.4, 5, 1, true);
const ringGeometry = new THREE.TorusGeometry(0.36, 0.025, 3, 12);
currentEventDays.forEach((day, eventIndex) => {
const { x, z } = pathPosition(day, days, spacing);
const group = new THREE.Group();
group.position.set(x, 0.18, z);
const shard = new THREE.Mesh(shardGeometry, shardMaterial);
shard.position.y = 0.42;
group.add(shard);
const cap = new THREE.Mesh(capGeometry, capMaterial);
cap.position.y = 0.86;
cap.rotation.set(0.2, eventIndex * 0.8, 0.15);
group.add(cap);
const beam = new THREE.Mesh(beamGeometry, beamMaterial);
beam.position.y = 0.7;
group.add(beam);
const ring = new THREE.Mesh(ringGeometry, ringMaterial);
ring.rotation.x = Math.PI / 2;
ring.position.y = 0.04;
group.add(ring);
world.add(group);
eventAnimations.push({
group,
baseY: group.position.y,
phase: eventIndex * 1.73
});
});
// The orange bracket spans the entire sequence: P(at least one).
const bracketPoints = [];
const bracketStep = Math.max(1, Math.floor(days / 100));
for (let i = 0; i < days; i += bracketStep) {
const { x, z } = pathPosition(i, days, spacing);
bracketPoints.push(new THREE.Vector3(x, 1.52, z));
}
const finalPosition = pathPosition(days - 1, days, spacing);
bracketPoints.push(
new THREE.Vector3(finalPosition.x, 1.52, finalPosition.z)
);
const bracketGeometry = new THREE.BufferGeometry().setFromPoints(bracketPoints);
const bracketMaterial = new THREE.LineDashedMaterial({
color: COLORS.orange,
dashSize: 0.72,
gapSize: 0.42,
transparent: true,
opacity: 0.78
});
const bracket = new THREE.Line(bracketGeometry, bracketMaterial);
bracket.computeLineDistances();
world.add(bracket);
const firstPosition = pathPosition(0, days, spacing);
const capGeometryLines = new THREE.BufferGeometry().setFromPoints([
new THREE.Vector3(firstPosition.x, 0.16, firstPosition.z),
new THREE.Vector3(firstPosition.x, 1.52, firstPosition.z),
new THREE.Vector3(finalPosition.x, 0.16, finalPosition.z),
new THREE.Vector3(finalPosition.x, 1.52, finalPosition.z)
]);
const capLines = new THREE.LineSegments(
capGeometryLines,
new THREE.LineBasicMaterial({
color: COLORS.orange,
transparent: true,
opacity: 0.72
})
);
world.add(capLines);
// In-scene labels separate the individual probability from the run probability.
const sequenceChance = 1 - Math.pow(1 - settings.probability, days);
const middleIndex = Math.floor(days / 2);
const middlePosition = pathPosition(middleIndex, days, spacing);
const sequenceLabel = makeTextSprite(
`WHOLE RUN / P(≥1) = ${formatSequenceProbability(sequenceChance)}`,
"#ffb77c",
11.5
);
sequenceLabel.position.set(
middlePosition.x,
2.03,
middlePosition.z
);
world.add(sequenceLabel);
const trialLabel = makeTextSprite(
`ONE TRIAL / p = ${(settings.probability * 100).toFixed(2)}%`,
"#92f2fb",
7.1
);
trialLabel.position.set(
firstPosition.x + 4.7,
0.85,
firstPosition.z + 1.2
);
world.add(trialLabel);
// Sparse day markers.
const dayInterval = days > 300 ? 30 : 30;
for (let day = 0; day < days; day += dayInterval) {
const { x, z } = pathPosition(day, days, spacing);
const label = makeTextSprite(
`DAY ${String(day + 1).padStart(3, "0")}`,
"#6f99a7",
3.7
);
label.position.set(x, -0.18, z + 1.4);
world.add(label);
}
// Animated playhead reveals the sequence after regeneration.
playhead = new THREE.Group();
const playheadRing = new THREE.Mesh(
new THREE.TorusGeometry(0.34, 0.026, 3, 12),
new THREE.MeshBasicMaterial({
color: COLORS.cyan,
transparent: true,
opacity: 0.88,
toneMapped: false
})
);
playheadRing.rotation.x = Math.PI / 2;
playheadRing.position.y = 0.23;
playhead.add(playheadRing);
const playheadStem = new THREE.Mesh(
new THREE.CylinderGeometry(0.018, 0.018, 0.72, 4),
new THREE.MeshBasicMaterial({
color: COLORS.cyan,
transparent: true,
opacity: 0.55,
toneMapped: false
})
);
playheadStem.position.y = 0.58;
playhead.add(playheadStem);
const playheadTip = new THREE.Mesh(
new THREE.ConeGeometry(0.11, 0.23, 4),
new THREE.MeshBasicMaterial({
color: COLORS.cyan,
toneMapped: false
})
);
playheadTip.rotation.z = Math.PI;
playheadTip.position.y = 0.14;
playhead.add(playheadTip);
world.add(playhead);
playheadActive = true;
playheadIndex = 0;
if (pendingFit) {
fitView(true);
pendingFit = false;
}
}
function scheduleBuild() {
cancelAnimationFrame(buildFrame);
buildFrame = requestAnimationFrame(() => {
buildWorld();
});
}
function fitView(immediate = false) {
const settings = getSettings();
const spacing = settings.days > 300 ? 0.81 : 0.91;
const length = (settings.days - 1) * spacing;
const aspect = window.innerWidth / window.innerHeight;
const aspectCorrection = Math.max(1, 1.28 / aspect);
desiredCamera.theta = -1.38;
desiredCamera.phi = 0.96;
desiredCamera.radius = Math.max(78, length * 0.80 * aspectCorrection);
desiredCamera.target.set(0, 0.1, 0);
if (immediate) {
currentCamera.theta = desiredCamera.theta;
currentCamera.phi = desiredCamera.phi;
currentCamera.radius = desiredCamera.radius;
currentCamera.target.copy(desiredCamera.target);
}
}
function updateCamera(delta) {
const smoothing = 1 - Math.pow(0.0007, delta);
currentCamera.theta +=
(desiredCamera.theta - currentCamera.theta) * smoothing;
currentCamera.phi +=
(desiredCamera.phi - currentCamera.phi) * smoothing;
currentCamera.radius +=
(desiredCamera.radius - currentCamera.radius) * smoothing;
currentCamera.target.lerp(desiredCamera.target, smoothing);
const { theta, phi, radius, target } = currentCamera;
const horizontal = Math.sin(phi) * radius;
camera.position.set(
target.x + horizontal * Math.cos(theta),
target.y + Math.cos(phi) * radius,
target.z + horizontal * Math.sin(theta)
);
camera.lookAt(target);
}
function panCamera(deltaX, deltaY) {
const right = new THREE.Vector3().setFromMatrixColumn(camera.matrix, 0);
const up = new THREE.Vector3().setFromMatrixColumn(camera.matrix, 1);
const scale = currentCamera.radius * 0.00125;
desiredCamera.target
.addScaledVector(right, -deltaX * scale)
.addScaledVector(up, deltaY * scale);
}
// Custom camera controls: orbit, zoom, and pan.
const pointers = new Map();
let lastPointer = null;
let lastPinchDistance = null;
canvas.addEventListener("contextmenu", event => event.preventDefault());
canvas.addEventListener("pointerdown", event => {
canvas.setPointerCapture(event.pointerId);
pointers.set(event.pointerId, {
x: event.clientX,
y: event.clientY
});
if (pointers.size === 1) {
lastPointer = {
x: event.clientX,
y: event.clientY,
pan: event.button === 2 || event.shiftKey
};
}
if (pointers.size === 2) {
const values = [...pointers.values()];
lastPinchDistance = Math.hypot(
values[0].x - values[1].x,
values[0].y - values[1].y
);
}
});
canvas.addEventListener("pointermove", event => {
if (!pointers.has(event.pointerId)) return;
const previous = pointers.get(event.pointerId);
pointers.set(event.pointerId, {
x: event.clientX,
y: event.clientY
});
if (pointers.size === 1 && lastPointer) {
const deltaX = event.clientX - lastPointer.x;
const deltaY = event.clientY - lastPointer.y;
if (event.shiftKey || lastPointer.pan) {
panCamera(deltaX, deltaY);
} else {
desiredCamera.theta -= deltaX * 0.005;
desiredCamera.phi = THREE.MathUtils.clamp(
desiredCamera.phi - deltaY * 0.0045,
0.3,
1.48
);
}
lastPointer.x = event.clientX;
lastPointer.y = event.clientY;
} else if (pointers.size === 2 && lastPinchDistance) {
const values = [...pointers.values()];
const distance = Math.hypot(
values[0].x - values[1].x,
values[0].y - values[1].y
);
if (distance > 0) {
desiredCamera.radius = THREE.MathUtils.clamp(
desiredCamera.radius * (lastPinchDistance / distance),
22,
1500
);
}
lastPinchDistance = distance;
}
});
function releasePointer(event) {
pointers.delete(event.pointerId);
if (pointers.size === 0) {
lastPointer = null;
lastPinchDistance = null;
} else if (pointers.size === 1) {
const remaining = [...pointers.values()][0];
lastPointer = {
x: remaining.x,
y: remaining.y,
pan: false
};
lastPinchDistance = null;
}
}
canvas.addEventListener("pointerup", releasePointer);
canvas.addEventListener("pointercancel", releasePointer);
canvas.addEventListener(
"wheel",
event => {
event.preventDefault();
desiredCamera.radius = THREE.MathUtils.clamp(
desiredCamera.radius * Math.exp(event.deltaY * 0.001),
22,
1500
);
},
{ passive: false }
);
window.addEventListener("keydown", event => {
const tag = event.target.tagName;
if (tag === "INPUT" || tag === "BUTTON") return;
const key = event.key.toLowerCase();
if (key === "r") {
fitView(false);
} else if (event.key === "ArrowLeft") {
desiredCamera.theta += 0.08;
} else if (event.key === "ArrowRight") {
desiredCamera.theta -= 0.08;
} else if (event.key === "ArrowUp") {
desiredCamera.phi = Math.max(0.3, desiredCamera.phi - 0.06);
} else if (event.key === "ArrowDown") {
desiredCamera.phi = Math.min(1.48, desiredCamera.phi + 0.06);
} else if (event.key === "+" || event.key === "=") {
desiredCamera.radius = Math.max(22, desiredCamera.radius * 0.9);
} else if (event.key === "-") {
desiredCamera.radius = Math.min(1500, desiredCamera.radius * 1.1);
}
});
function regenerate() {
const settings = getSettings();
currentEventDays = simulate(settings);
updateStats();
scheduleBuild();
}
ui.days.addEventListener("input", () => {
pendingFit = true;
regenerate();
});
ui.probability.addEventListener("input", regenerate);
ui.seed.addEventListener("change", regenerate);
ui.seed.addEventListener("keydown", event => {
if (event.key === "Enter") {
event.preventDefault();
regenerate();
}
});
ui.replay.addEventListener("click", regenerate);
ui.newRun.addEventListener("click", () => {
ui.seed.value = String(Math.floor(Math.random() * 1000000));
regenerate();
});
ui.resetView.addEventListener("click", () => fitView(false));
window.addEventListener("resize", () => {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
fitView(false);
});
function animate() {
const delta = Math.min(clock.getDelta(), 0.05);
const elapsed = clock.elapsedTime;
updateCamera(delta);
for (const animation of eventAnimations) {
const pulse = Math.sin(elapsed * 1.9 + animation.phase);
animation.group.position.y = animation.baseY + pulse * 0.045;
const scale = 1 + pulse * 0.035;
animation.group.scale.setScalar(scale);
}
if (playhead && playheadActive) {
const settings = getSettings();
const spacing = settings.days > 300 ? 0.81 : 0.91;
playheadIndex += delta * 52;
if (playheadIndex >= settings.days) {
playheadActive = false;
playhead.visible = false;
} else {
const { x, z } = pathPosition(
Math.floor(playheadIndex),
settings.days,
spacing
);
playhead.position.set(x, 0, z);
playhead.visible = true;
}
}
renderer.render(scene, camera);
requestAnimationFrame(animate);
}
const initialSettings = getSettings();
currentEventDays = simulate(initialSettings);
updateStats();
buildWorld();
fitView(true);
animate();
requestAnimationFrame(() => {
loading.classList.add("hidden");
});
</script>
</body>
</html>
```