Prompt specification
Build or customize the Three.js 3D scene "Passing train sound-wave exhibit" 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: Passing train sound-wave exhibit
Category: Voxel Worlds · Style: Voxel 3D
License: MIT · Reference: https://three3d.app/scene/passing-train-sound-wave-exhibit-x1539
Scene Description Prompt:
Please create one self-contained HTML file with Three.js from cdnjs showing the Doppler effect from relative motion. Compose a short track, moving train, and stationary observer with visible emitted fronts; show arrival timing without requiring a realistic acoustic simulation of the train. Voxel style.
Working Three.js Starter (passing-train-sound-wave-exhibit-x1539):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Doppler Voxel Lab</title>
<style>
:root {
color-scheme: dark;
--bg: #091321;
--panel: rgba(11, 25, 42, 0.86);
--border: rgba(139, 211, 255, 0.22);
--cyan: #58e6ff;
--orange: #ff9b52;
--yellow: #ffd166;
--muted: #8da5bb;
--text: #eef8ff;
}
* { box-sizing: border-box; }
html, body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: var(--bg);
font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
color: var(--text);
}
button, input { font: inherit; }
#scene {
position: fixed;
inset: 0;
width: 100%;
height: 100%;
display: block;
touch-action: none;
outline: none;
}
.brand {
position: fixed;
top: 22px;
left: 24px;
z-index: 5;
pointer-events: none;
text-shadow: 0 2px 18px rgba(0, 0, 0, 0.45);
}
.eyebrow {
color: var(--cyan);
font: 700 11px/1.2 ui-monospace, SFMono-Regular, Menlo, monospace;
letter-spacing: 0.18em;
}
h1 {
margin: 7px 0 4px;
font-size: clamp(25px, 3vw, 42px);
line-height: 0.95;
letter-spacing: -0.045em;
}
h1 span { color: var(--orange); }
.brand p {
margin: 9px 0 10px;
color: #b7c9d9;
font-size: 13px;
}
.phase {
display: inline-block;
padding: 6px 10px;
border: 1px solid rgba(88, 230, 255, 0.36);
border-radius: 999px;
background: rgba(12, 37, 56, 0.72);
color: var(--cyan);
font: 800 10px/1 ui-monospace, SFMono-Regular, Menlo, monospace;
letter-spacing: 0.14em;
}
.phase[data-state="receding"] {
color: var(--orange);
border-color: rgba(255, 155, 82, 0.42);
}
.phase[data-state="passing"] {
color: var(--yellow);
border-color: rgba(255, 209, 102, 0.48);
}
.panel {
border: 1px solid var(--border);
background: var(--panel);
box-shadow: 0 18px 60px rgba(0, 0, 0, 0.28);
backdrop-filter: blur(14px);
-webkit-backdrop-filter: blur(14px);
}
.readout {
position: fixed;
top: 22px;
right: 22px;
z-index: 5;
width: 340px;
padding: 17px;
border-radius: 16px;
}
.panel-title {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 14px;
font: 800 11px/1 ui-monospace, SFMono-Regular, Menlo, monospace;
letter-spacing: 0.15em;
}
.panel-title span:last-child {
color: var(--muted);
font-size: 9px;
letter-spacing: 0.08em;
}
.metrics {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 8px;
}
.metric {
min-width: 0;
padding: 11px 9px;
border-radius: 10px;
background: rgba(255, 255, 255, 0.035);
border: 1px solid rgba(255, 255, 255, 0.055);
}
.metric label {
display: block;
margin-bottom: 7px;
color: var(--muted);
font: 700 9px/1 ui-monospace, SFMono-Regular, Menlo, monospace;
letter-spacing: 0.1em;
white-space: nowrap;
}
.metric strong {
display: block;
font-size: 23px;
line-height: 1;
font-variant-numeric: tabular-nums;
}
.metric small {
display: block;
margin-top: 5px;
color: var(--muted);
font-size: 9px;
}
#gapValue { color: var(--cyan); }
#rateValue { color: var(--yellow); }
#shiftValue { color: var(--orange); }
.prediction {
display: flex;
justify-content: space-between;
gap: 14px;
margin: 13px 0 10px;
color: #afc3d5;
font-size: 11px;
line-height: 1.4;
}
#predictionValue {
flex: 0 0 auto;
color: var(--text);
font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
font-weight: 800;
}
.timeline-wrap {
position: relative;
height: 130px;
overflow: hidden;
border-radius: 10px;
background:
linear-gradient(rgba(88, 230, 255, 0.025), rgba(88, 230, 255, 0.025)),
rgba(3, 11, 21, 0.52);
border: 1px solid rgba(255, 255, 255, 0.055);
}
#timeline {
width: 100%;
height: 100%;
display: block;
}
.timeline-caption {
display: flex;
justify-content: space-between;
margin-top: 8px;
color: var(--muted);
font-size: 10px;
line-height: 1.35;
}
.cyan { color: var(--cyan); }
.orange { color: var(--orange); }
.controls {
position: fixed;
z-index: 8;
bottom: 20px;
left: 50%;
transform: translateX(-50%);
width: min(980px, calc(100% - 32px));
padding: 13px 15px;
border-radius: 16px;
display: flex;
align-items: center;
gap: 12px;
flex-wrap: wrap;
}
.button {
min-height: 38px;
padding: 0 13px;
border: 1px solid rgba(141, 211, 255, 0.24);
border-radius: 9px;
background: rgba(255, 255, 255, 0.055);
color: var(--text);
cursor: pointer;
font-weight: 750;
font-size: 12px;
transition: background 120ms ease, transform 120ms ease;
}
.button:hover {
background: rgba(88, 230, 255, 0.12);
transform: translateY(-1px);
}
.button.primary {
min-width: 86px;
border-color: rgba(88, 230, 255, 0.5);
background: rgba(88, 230, 255, 0.13);
color: var(--cyan);
}
.control {
display: grid;
grid-template-columns: auto minmax(90px, 1fr) auto;
align-items: center;
gap: 9px;
min-width: 245px;
flex: 1 1 245px;
}
.control label {
color: #bed0df;
font: 750 10px/1 ui-monospace, SFMono-Regular, Menlo, monospace;
letter-spacing: 0.06em;
text-transform: uppercase;
white-space: nowrap;
}
.control output {
min-width: 66px;
color: var(--cyan);
text-align: right;
font: 750 11px/1 ui-monospace, SFMono-Regular, Menlo, monospace;
white-space: nowrap;
}
input[type="range"] {
width: 100%;
accent-color: var(--cyan);
cursor: pointer;
}
.toggle {
display: flex;
align-items: center;
gap: 7px;
color: #b8c9d8;
font-size: 11px;
white-space: nowrap;
cursor: pointer;
}
.toggle input {
accent-color: var(--orange);
width: 16px;
height: 16px;
}
.hint {
position: fixed;
z-index: 4;
left: 24px;
bottom: 94px;
color: rgba(192, 214, 230, 0.72);
font: 11px/1.4 ui-monospace, SFMono-Regular, Menlo, monospace;
pointer-events: none;
text-shadow: 0 2px 10px #000;
}
#fallback[hidden] { display: none; }
#fallback {
position: fixed;
inset: 0;
z-index: 20;
display: grid;
place-items: center;
padding: 30px;
background: #091321;
color: white;
text-align: center;
}
@media (max-width: 820px) {
.brand {
top: 14px;
left: 14px;
}
.brand p { display: none; }
h1 { font-size: 25px; }
.readout {
top: 82px;
right: 12px;
width: 300px;
padding: 13px;
}
.timeline-wrap { height: 105px; }
.hint { display: none; }
.controls {
bottom: 10px;
width: calc(100% - 20px);
padding: 10px;
gap: 9px;
}
.control {
min-width: 210px;
flex-basis: 210px;
}
}
@media (max-width: 500px) {
.readout {
top: 77px;
right: 8px;
width: calc(100% - 16px);
}
.timeline-wrap { height: 88px; }
.timeline-caption { display: none; }
.controls { gap: 7px; }
.control { flex-basis: 100%; }
.button { padding: 0 10px; }
}
</style>
</head>
<body>
<canvas id="scene" aria-label="Interactive voxel visualization of the Doppler effect"></canvas>
<header class="brand">
<div class="eyebrow">RELATIVE MOTION / WAVE VISUALIZER</div>
<h1>DOPPLER <span>VOXEL LAB</span></h1>
<p>Moving source • stationary observer • visible wave fronts</p>
<span id="phase" class="phase" data-state="approaching">APPROACHING</span>
</header>
<aside class="readout panel">
<div class="panel-title">
<span>ARRIVAL TIMING</span>
<span>SCHEMATIC · c = 7.5 u/s</span>
</div>
<div class="metrics">
<div class="metric">
<label>ARRIVAL GAP</label>
<strong id="gapValue">—</strong>
<small>seconds</small>
</div>
<div class="metric">
<label>OBSERVED RATE</label>
<strong id="rateValue">—</strong>
<small>Hz</small>
</div>
<div class="metric">
<label>SHIFT</label>
<strong id="shiftValue">—</strong>
<small>vs. source</small>
</div>
</div>
<div class="prediction">
<span>Instant radial-motion estimate</span>
<span id="predictionValue">+0%</span>
</div>
<div class="timeline-wrap">
<canvas id="timeline" aria-label="Timeline of emitted and received wave fronts"></canvas>
</div>
<div class="timeline-caption">
<span><b class="cyan">●</b> Emission time</span>
<span><b class="orange">●</b> Observer arrival</span>
<span>Spacing shows frequency shift</span>
</div>
</aside>
<div class="hint">DRAG TO ORBIT · WHEEL TO ZOOM · SPACE TO PAUSE · R TO RESET</div>
<section class="controls panel" aria-label="Simulation controls">
<button id="playButton" class="button primary" type="button">Ⅱ Pause</button>
<button id="resetButton" class="button" type="button">↺ Reset</button>
<button id="directionButton" class="button" type="button">Travel →</button>
<div class="control">
<label for="speedInput">Train speed</label>
<input id="speedInput" type="range" min="0.5" max="5.5" step="0.1" value="2.4">
<output id="speedValue" for="speedInput">2.4 u/s</output>
</div>
<div class="control">
<label for="periodInput">Source period</label>
<input id="periodInput" type="range" min="0.5" max="1.2" step="0.05" value="0.8">
<output id="periodValue" for="periodInput">0.80 s</output>
</div>
<label class="toggle">
<input id="pingToggle" type="checkbox">
Simple arrival pings
</label>
</section>
<div id="fallback" hidden>
<div>
<h2>WebGL is unavailable</h2>
<p>This visualization needs a browser with WebGL enabled.</p>
</div>
</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 sceneCanvas = $("scene");
const timelineCanvas = $("timeline");
const timelineContext = timelineCanvas.getContext("2d");
let renderer;
try {
renderer = new THREE.WebGLRenderer({
canvas: sceneCanvas,
antialias: true,
alpha: false
});
} catch (error) {
$("fallback").hidden = false;
throw error;
}
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.12;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x0a1627);
scene.fog = new THREE.Fog(0x0a1627, 34, 66);
const camera = new THREE.PerspectiveCamera(43, 1, 0.1, 120);
const cameraTarget = new THREE.Vector3(0, 0.8, 0);
let cameraAzimuth = 0.68;
let cameraElevation = 0.52;
let cameraRadius = 35;
const hemisphere = new THREE.HemisphereLight(0xc7e8ff, 0x17261f, 2.1);
scene.add(hemisphere);
const sun = new THREE.DirectionalLight(0xfff0d6, 3.0);
sun.position.set(12, 24, 14);
sun.castShadow = true;
sun.shadow.mapSize.set(2048, 2048);
sun.shadow.camera.left = -25;
sun.shadow.camera.right = 25;
sun.shadow.camera.top = 20;
sun.shadow.camera.bottom = -20;
sun.shadow.camera.near = 1;
sun.shadow.camera.far = 65;
sun.shadow.bias = -0.0004;
scene.add(sun);
const rim = new THREE.DirectionalLight(0x4abfff, 1.4);
rim.position.set(-14, 9, -12);
scene.add(rim);
const unitBox = new THREE.BoxGeometry(1, 1, 1);
const materialCache = new Map();
function solidMaterial(color) {
if (!materialCache.has(color)) {
materialCache.set(color, new THREE.MeshStandardMaterial({
color,
roughness: 0.83,
metalness: 0.04,
flatShading: true
}));
}
return materialCache.get(color);
}
function makeBox(parent, size, position, color, customMaterial = null) {
const mesh = new THREE.Mesh(
unitBox,
customMaterial || solidMaterial(color)
);
mesh.scale.set(size[0], size[1], size[2]);
mesh.position.set(position[0], position[1], position[2]);
mesh.castShadow = true;
mesh.receiveShadow = true;
parent.add(mesh);
return mesh;
}
function makeLabel(text, accent = "#58e6ff") {
const canvas = document.createElement("canvas");
canvas.width = 512;
canvas.height = 96;
const context = canvas.getContext("2d");
context.fillStyle = "rgba(7, 17, 31, 0.88)";
context.fillRect(0, 0, canvas.width, canvas.height);
context.fillStyle = accent;
context.fillRect(0, 0, 8, canvas.height);
context.strokeStyle = accent;
context.lineWidth = 3;
context.strokeRect(2, 2, canvas.width - 4, canvas.height - 4);
context.fillStyle = "#eff9ff";
context.font = "800 31px monospace";
context.textAlign = "center";
context.textBaseline = "middle";
context.fillText(text, canvas.width / 2, canvas.height / 2 + 1);
const texture = new THREE.CanvasTexture(canvas);
texture.colorSpace = THREE.SRGBColorSpace;
const sprite = new THREE.Sprite(new THREE.SpriteMaterial({
map: texture,
transparent: true,
depthTest: false,
depthWrite: false
}));
sprite.scale.set(3.7, 0.69, 1);
sprite.renderOrder = 20;
return sprite;
}
// ------------------------------------------------------------
// Voxel environment
// ------------------------------------------------------------
makeBox(scene, [48, 0.5, 28], [0, -0.36, 0], 0x172c26);
const tileGeometry = new THREE.BoxGeometry(2, 0.08, 2);
const tileMaterial = new THREE.MeshStandardMaterial({
vertexColors: true,
roughness: 1,
flatShading: true
});
const tileCountX = 24;
const tileCountZ = 14;
const tileMesh = new THREE.InstancedMesh(
tileGeometry,
tileMaterial,
tileCountX * tileCountZ
);
tileMesh.receiveShadow = true;
const tileDummy = new THREE.Object3D();
const tileColors = [0x1b332b, 0x1d372e, 0x203a30, 0x192f28];
let tileIndex = 0;
for (let x = 0; x < tileCountX; x++) {
for (let z = 0; z < tileCountZ; z++) {
const worldX = -23 + x * 2;
const worldZ = -13 + z * 2;
tileDummy.position.set(worldX, -0.045, worldZ);
tileDummy.rotation.set(0, 0, 0);
tileDummy.scale.set(1, 1, 1);
tileDummy.updateMatrix();
tileMesh.setMatrixAt(tileIndex, tileDummy.matrix);
const colorIndex = (x * 7 + z * 11) % tileColors.length;
tileMesh.setColorAt(tileIndex, new THREE.Color(tileColors[colorIndex]));
tileIndex++;
}
}
tileMesh.instanceMatrix.needsUpdate = true;
tileMesh.instanceColor.needsUpdate = true;
scene.add(tileMesh);
// Short track.
makeBox(scene, [40, 0.16, 3.0], [0, 0.06, 0], 0x48505a);
const sleeperMaterial = new THREE.MeshStandardMaterial({
color: 0x6b4936,
roughness: 0.95,
flatShading: true
});
for (let x = -18.6; x <= 18.6; x += 1.2) {
makeBox(scene, [0.45, 0.18, 2.4], [x, 0.19, 0], 0, sleeperMaterial);
}
const railMaterial = new THREE.MeshStandardMaterial({
color: 0xa8bbc7,
roughness: 0.3,
metalness: 0.72,
flatShading: true
});
makeBox(scene, [40, 0.12, 0.13], [0, 0.32, -0.72], 0, railMaterial);
makeBox(scene, [40, 0.12, 0.13], [0, 0.32, 0.72], 0, railMaterial);
// A dotted sightline from track to observer.
const sightlineMaterial = new THREE.MeshBasicMaterial({
color: 0x42677d,
transparent: true,
opacity: 0.65
});
for (let i = 0; i < 9; i++) {
makeBox(
scene,
[0.09, 0.035, 0.22],
[0, 0.07, 0.75 + i * 0.48],
0,
sightlineMaterial
);
}
// Stationary observer platform.
makeBox(scene, [3.0, 0.16, 2.35], [0, 0.08, 5.0], 0x334653);
makeBox(scene, [3.15, 0.08, 0.22], [0, 0.2, 6.08], 0xffc857);
function addTree(x, z, scale = 1) {
const tree = new THREE.Group();
tree.position.set(x, 0, z);
tree.scale.setScalar(scale);
makeBox(tree, [0.38, 1.35, 0.38], [0, 0.68, 0], 0x65432e);
makeBox(tree, [1.65, 1.25, 1.65], [0, 1.65, 0], 0x245f4a);
makeBox(tree, [1.15, 0.95, 1.15], [0.2, 2.45, -0.1], 0x31775b);
makeBox(tree, [0.75, 0.7, 0.75], [-0.2, 3.02, 0.08], 0x3c8966);
scene.add(tree);
}
[
[-16, -8.8, 1.0],
[-11, -10.1, 0.8],
[10, -9.4, 1.1],
[15, -7.7, 0.85],
[-17, 9.2, 0.8],
[16, 9.5, 0.95]
].forEach(values => addTree(...values));
function addBuilding(x, z, color, height) {
makeBox(scene, [4.2, height, 3.4], [x, height / 2, z], color);
makeBox(scene, [4.5, 0.22, 3.7], [x, height + 0.11, z], 0x405567);
const windowMaterial = new THREE.MeshStandardMaterial({
color: 0x77b8d5,
emissive: 0x17394c,
emissiveIntensity: 0.6,
roughness: 0.25,
flatShading: true
});
for (let row = 0; row < Math.max(1, Math.floor(height / 1.4)); row++) {
for (let column = -1; column <= 1; column++) {
makeBox(
scene,
[0.55, 0.55, 0.05],
[x + column * 1.05, 0.9 + row * 1.25, z + 1.73],
0,
windowMaterial
);
}
}
}
addBuilding(-13.5, -10.5, 0x344b60, 2.8);
addBuilding(4.5, -11.1, 0x455064, 3.6);
addBuilding(14.0, -10.3, 0x344b60, 2.5);
// Blocky clouds.
const cloudMaterial = new THREE.MeshStandardMaterial({
color: 0xaec6d7,
roughness: 1,
flatShading: true
});
function addCloud(x, y, z) {
makeBox(scene, [2.8, 0.7, 1.1], [x, y, z], 0, cloudMaterial);
makeBox(scene, [1.6, 1.0, 1.25], [x - 0.7, y + 0.4, z], 0, cloudMaterial);
makeBox(scene, [1.5, 0.8, 1.1], [x + 0.9, y + 0.3, z], 0, cloudMaterial);
}
addCloud(-14, 8.3, -11);
addCloud(8, 9.2, -13);
addCloud(18, 7.8, -7);
// ------------------------------------------------------------
// Voxel train
// ------------------------------------------------------------
const train = new THREE.Group();
scene.add(train);
const orange = 0xf16b4a;
const yellow = 0xffc857;
const teal = 0x45c6b7;
const dark = 0x172534;
const windowMaterial = new THREE.MeshStandardMaterial({
color: 0x23455c,
emissive: 0x102d3d,
emissiveIntensity: 0.65,
roughness: 0.2,
metalness: 0.25,
flatShading: true
});
const headlightMaterial = new THREE.MeshStandardMaterial({
color: 0xfff3b0,
emissive: 0xffc857,
emissiveIntensity: 2.2,
roughness: 0.25,
flatShading: true
});
// Locomotive.
makeBox(train, [3.0, 0.32, 1.66], [-1.45, 1.0, 0], dark);
makeBox(train, [2.9, 1.02, 1.52], [-1.45, 1.57, 0], orange);
makeBox(train, [3.06, 0.22, 1.68], [-1.48, 2.16, 0], yellow);
makeBox(train, [0.22, 0.95, 1.54], [0.04, 1.57, 0], yellow);
makeBox(train, [0.46, 0.58, 0.46], [-2.25, 2.51, 0], dark);
makeBox(train, [0.58, 0.14, 0.58], [-2.25, 2.84, 0], 0x3c4650);
// Locomotive windows.
makeBox(train, [0.06, 0.48, 1.12], [0.17, 1.77, 0], 0, windowMaterial);
for (const side of [-1, 1]) {
for (const x of [-0.55, -1.45, -2.35]) {
makeBox(train, [0.55, 0.46, 0.05], [x, 1.78, side * 0.78], 0, windowMaterial);
}
}
// Headlights and horn.
for (const side of [-1, 1]) {
makeBox(train, [0.08, 0.19, 0.2], [0.19, 1.5, side * 0.47], 0, headlightMaterial);
}
makeBox(train, [0.3, 0.18, 0.28], [0.17, 2.22, 0], 0x394755);
makeBox(train, [0.36, 0.12, 0.12], [0.36, 2.22, 0], yellow);
// One carriage.
makeBox(train, [2.75, 0.3, 1.66], [-4.72, 1.0, 0], dark);
makeBox(train, [2.62, 1.08, 1.52], [-4.72, 1.67, 0], teal);
makeBox(train, [2.78, 0.22, 1.68], [-4.72, 2.3, 0], 0xeaf5ed);
makeBox(train, [0.55, 0.18, 0.22], [-3.22, 1.03, 0], 0x82909b);
for (const side of [-1, 1]) {
for (const x of [-5.45, -4.72, -3.99]) {
makeBox(train, [0.52, 0.5, 0.05], [x, 1.88, side * 0.78], 0, windowMaterial);
}
}
// Voxel wheels.
function addWheel(x, z) {
makeBox(train, [0.57, 0.57, 0.25], [x, 0.65, z], dark);
makeBox(train, [0.23, 0.23, 0.27], [x, 0.65, z], yellow);
}
for (const z of [-0.78, 0.78]) {
addWheel(-0.45, z);
addWheel(-2.25, z);
addWheel(-4.05, z);
addWheel(-5.45, z);
}
// ------------------------------------------------------------
// Stationary observer
// ------------------------------------------------------------
const observer = new THREE.Group();
observer.position.set(0, 0, 5);
scene.add(observer);
makeBox(observer, [0.29, 0.73, 0.34], [-0.19, 0.58, 0], dark);
makeBox(observer, [0.29, 0.73, 0.34], [0.19, 0.58, 0], dark);
makeBox(observer, [0.74, 0.82, 0.43], [0, 1.4, 0], 0x397fc2);
makeBox(observer, [0.23, 0.76, 0.3], [-0.49, 1.38, 0], 0xf0b38a);
makeBox(observer, [0.23, 0.76, 0.3], [0.49, 1.38, 0], 0xf0b38a);
makeBox(observer, [0.53, 0.53, 0.51], [0, 2.1, 0], 0xf0b38a);
makeBox(observer, [0.57, 0.15, 0.55], [0, 2.41, 0], 0x3a2a29);
makeBox(observer, [0.18, 0.42, 0.52], [0, 2.14, 0.04], 0x3a2a29);
const observerLabel = makeLabel("OBSERVER", "#58e6ff");
observerLabel.position.set(0, 3.18, 5);
scene.add(observerLabel);
const sourceLabel = makeLabel("MOVING SOURCE", "#ff9b52");
scene.add(sourceLabel);
// Observer arrival halo and light beam.
const haloMaterial = new THREE.MeshBasicMaterial({
color: 0x58e6ff,
transparent: true,
opacity: 0.24,
depthWrite: false
});
const observerHalo = new THREE.Group();
observerHalo.position.set(0, 0.22, 5);
for (let i = 0; i < 16; i++) {
const angle = i / 16 * Math.PI * 2;
makeBox(
observerHalo,
[0.18, 0.18, 0.18],
[Math.cos(angle) * 0.88, 0, Math.sin(angle) * 0.88],
0,
haloMaterial
);
}
scene.add(observerHalo);
const beamMaterial = new THREE.MeshBasicMaterial({
color: 0x58e6ff,
transparent: true,
opacity: 0,
depthWrite: false,
blending: THREE.AdditiveBlending
});
for (const x of [-0.32, 0.32]) {
for (const z of [-0.32, 0.32]) {
makeBox(scene, [0.12, 3.2, 0.12], [x, 1.8, 5 + z], 0, beamMaterial);
}
}
const observerLight = new THREE.PointLight(0x58e6ff, 0, 7, 2);
observerLight.position.set(0, 2.4, 5);
scene.add(observerLight);
// ------------------------------------------------------------
// Simulation
// ------------------------------------------------------------
const SOUND_SPEED = 7.5;
const OBSERVER_X = 0;
const OBSERVER_Z = 5;
const FRONT_SEGMENTS = 36;
const MAX_FRONT_RADIUS = 24;
const frontGeometry = new THREE.BoxGeometry(0.27, 0.27, 0.27);
let simulationTime = 0;
let running = true;
let direction = 1;
let trainSpeed = 2.4;
let sourcePeriod = 0.8;
let nextEmission = 0.18;
let trainStopped = false;
let observerFlash = 0;
let lastArrivalTime = null;
let lastArrivalGap = null;
let lastObservedRatio = null;
const pulses = [];
const eventLog = [];
const currentSource = new THREE.Vector3();
function updateCurrentSource() {
train.updateMatrixWorld(true);
currentSource.copy(train.localToWorld(new THREE.Vector3(0.28, 2.15, 0)));
sourceLabel.position.set(currentSource.x, currentSource.y + 1.22, currentSource.z);
}
function estimatedRatioAt(source, velocity = trainSpeed) {
const dx = source.x - OBSERVER_X;
const dz = source.z - OBSERVER_Z;
const distance = Math.max(0.001, Math.hypot(dx, dz));
// Positive closing speed means the source is approaching the observer.
const radialClosingSpeed = -(dx * direction * velocity / distance);
return THREE.MathUtils.clamp(
SOUND_SPEED / (SOUND_SPEED - radialClosingSpeed),
0.25,
3.5
);
}
function emitPulse() {
const source = currentSource.clone();
const distance = Math.hypot(
source.x - OBSERVER_X,
source.z - OBSERVER_Z
);
const arrivalTime = simulationTime + distance / SOUND_SPEED;
const sourceRate = 1 / sourcePeriod;
const material = new THREE.MeshBasicMaterial({
color: 0x4de5ff,
transparent: true,
opacity: 0.82,
depthWrite: false,
blending: THREE.AdditiveBlending
});
const instances = new THREE.InstancedMesh(
frontGeometry,
material,
FRONT_SEGMENTS
);
instances.instanceMatrix.setUsage(THREE.DynamicDrawUsage);
const group = new THREE.Group();
group.position.copy(source);
group.add(instances);
scene.add(group);
const pulse = {
group,
instances,
material,
source,
emitTime: simulationTime,
arrivalTime,
sourceRate,
predictedRatio: estimatedRatioAt(source),
arrived: false,
actualArrival: null
};
pulses.push(pulse);
eventLog.push(pulse);
if (eventLog.length > 120) {
eventLog.shift();
}
}
function markArrival(pulse) {
if (pulse.arrived) return;
pulse.arrived = true;
pulse.actualArrival = simulationTime;
observerFlash = 1;
let ratio = pulse.predictedRatio;
if (lastArrivalTime !== null) {
lastArrivalGap = simulationTime - lastArrivalTime;
const observedRate = 1 / Math.max(0.001, lastArrivalGap);
ratio = observedRate / pulse.sourceRate;
}
lastArrivalTime = simulationTime;
lastObservedRatio = ratio;
playArrivalPing(ratio);
}
function updateFronts() {
for (let i = pulses.length - 1; i >= 0; i--) {
const pulse = pulses[i];
const radius = (simulationTime - pulse.emitTime) * SOUND_SPEED;
const dummy = new THREE.Object3D();
for (let segment = 0; segment < FRONT_SEGMENTS; segment++) {
const angle = segment / FRONT_SEGMENTS * Math.PI * 2;
const scale = 0.8 + 0.18 * Math.sin(segment * 1.73);
dummy.position.set(
Math.cos(angle) * radius,
0,
Math.sin(angle) * radius
);
dummy.rotation.set(0, -angle, 0);
dummy.scale.setScalar(scale);
dummy.updateMatrix();
pulse.instances.setMatrixAt(segment, dummy.matrix);
}
pulse.instances.instanceMatrix.needsUpdate = true;
pulse.material.opacity = 0.84 * THREE.MathUtils.clamp(
1 - radius / MAX_FRONT_RADIUS,
0,
1
);
if (!pulse.arrived && simulationTime >= pulse.arrivalTime) {
markArrival(pulse);
}
if (radius > MAX_FRONT_RADIUS) {
scene.remove(pulse.group);
pulse.material.dispose();
pulses.splice(i, 1);
}
}
}
function resetSimulation() {
for (const pulse of pulses) {
scene.remove(pulse.group);
pulse.material.dispose();
}
pulses.length = 0;
eventLog.length = 0;
simulationTime = 0;
nextEmission = 0.18;
trainStopped = false;
observerFlash = 0;
lastArrivalTime = null;
lastArrivalGap = null;
lastObservedRatio = null;
train.rotation.y = direction > 0 ? 0 : Math.PI;
train.position.x = direction > 0 ? -11.4 : 11.4;
updateCurrentSource();
running = true;
syncPlayButton();
updateReadout();
}
function syncPlayButton() {
$("playButton").textContent = running ? "Ⅱ Pause" : "▶ Play";
}
// ------------------------------------------------------------
// Optional simple arrival pings
// ------------------------------------------------------------
let audioContext = null;
async function ensureAudio() {
if (!$("pingToggle").checked) return null;
if (!audioContext) {
const AudioContextClass = window.AudioContext || window.webkitAudioContext;
if (!AudioContextClass) return null;
audioContext = new AudioContextClass();
}
if (audioContext.state === "suspended") {
await audioContext.resume();
}
return audioContext;
}
function playArrivalPing(ratio) {
if (!$("pingToggle").checked) return;
ensureAudio().then(context => {
if (!context) return;
const now = context.currentTime;
const oscillator = context.createOscillator();
const gain = context.createGain();
oscillator.type = "sine";
oscillator.frequency.setValueAtTime(
THREE.MathUtils.clamp(520 * ratio, 170, 1200),
now
);
gain.gain.setValueAtTime(0.0001, now);
gain.gain.exponentialRampToValueAtTime(0.11, now + 0.012);
gain.gain.exponentialRampToValueAtTime(0.0001, now + 0.12);
oscillator.connect(gain);
gain.connect(context.destination);
oscillator.start(now);
oscillator.stop(now + 0.13);
}).catch(() => {
// Audio is optional; the visual simulation continues if blocked.
});
}
// ------------------------------------------------------------
// Timeline
// ------------------------------------------------------------
let timelineWidth = 1;
let timelineHeight = 1;
let timelineDpr = 1;
function resizeTimeline() {
const rect = timelineCanvas.getBoundingClientRect();
timelineWidth = Math.max(1, rect.width);
timelineHeight = Math.max(1, rect.height);
timelineDpr = Math.min(window.devicePixelRatio, 2);
timelineCanvas.width = Math.floor(timelineWidth * timelineDpr);
timelineCanvas.height = Math.floor(timelineHeight * timelineDpr);
timelineContext.setTransform(timelineDpr, 0, 0, timelineDpr, 0, 0);
}
function drawTimeline() {
const context = timelineContext;
context.setTransform(timelineDpr, 0, 0, timelineDpr, 0, 0);
context.clearRect(0, 0, timelineWidth, timelineHeight);
const left = 43;
const right = timelineWidth - 12;
const top = 8;
const bottom = timelineHeight - 18;
const emissionY = 30;
const arrivalY = timelineHeight - 34;
const startTime = Math.max(0, simulationTime - 10);
const endTime = simulationTime + 1;
const timeRange = Math.max(0.001, endTime - startTime);
const mapTime = time => left + (time - startTime) / timeRange * (right - left);
context.strokeStyle = "rgba(160, 195, 220, 0.09)";
context.lineWidth = 1;
for (let i = 0; i <= 5; i++) {
const x = left + (right - left) * i / 5;
context.beginPath();
context.moveTo(x, top);
context.lineTo(x, bottom);
context.stroke();
}
context.setLineDash([4, 5]);
context.strokeStyle = "rgba(255, 255, 255, 0.18)";
context.beginPath();
context.moveTo(left, emissionY);
context.lineTo(right, emissionY);
context.moveTo(left, arrivalY);
context.lineTo(right, arrivalY);
context.stroke();
context.setLineDash([]);
context.font = "700 9px ui-monospace, monospace";
context.fillStyle = "#58e6ff";
context.textAlign = "left";
context.fillText("EMIT", 5, emissionY + 3);
context.fillStyle = "#ff9b52";
context.fillText("ARR", 5, arrivalY + 3);
for (const event of eventLog) {
if (event.arrivalTime < startTime || event.emitTime > endTime) continue;
const emitX = THREE.MathUtils.clamp(mapTime(event.emitTime), left, right);
const arrivalX = mapTime(event.arrivalTime);
context.strokeStyle = "rgba(88, 230, 255, 0.22)";
context.lineWidth = 1;
context.beginPath();
context.moveTo(emitX, emissionY);
context.lineTo(arrivalX, arrivalY);
context.stroke();
context.fillStyle = "#58e6ff";
context.beginPath();
context.arc(emitX, emissionY, 3.1, 0, Math.PI * 2);
context.fill();
if (event.arrived) {
context.fillStyle = "#ff9b52";
context.beginPath();
context.arc(arrivalX, arrivalY, 3.8, 0, Math.PI * 2);
context.fill();
} else {
context.strokeStyle = "#ff9b52";
context.lineWidth = 1.5;
context.beginPath();
context.arc(arrivalX, arrivalY, 3.5, 0, Math.PI * 2);
context.stroke();
}
}
context.font = "9px ui-monospace, monospace";
context.fillStyle = "rgba(185, 207, 222, 0.6)";
context.textAlign = "left";
context.fillText("−10s", left, timelineHeight - 3);
context.textAlign = "right";
context.fillText("now", right, timelineHeight - 3);
}
// ------------------------------------------------------------
// Readout and controls
// ------------------------------------------------------------
function updateReadout() {
const sourceRate = 1 / sourcePeriod;
if (lastArrivalGap !== null) {
$("gapValue").textContent = lastArrivalGap.toFixed(2);
$("rateValue").textContent = (1 / lastArrivalGap).toFixed(2);
$("shiftValue").textContent = `${lastObservedRatio >= 1 ? "+" : ""}${(
(lastObservedRatio - 1) * 100
).toFixed(0)}%`;
} else {
$("gapValue").textContent = "—";
$("rateValue").textContent = "—";
$("shiftValue").textContent = "—";
}
const effectiveVelocity = trainStopped ? 0 : trainSpeed;
const currentEstimate = estimatedRatioAt(currentSource, effectiveVelocity);
const estimateShift = (currentEstimate - 1) * 100;
$("predictionValue").textContent = `${estimateShift >= 0 ? "+" : ""}${estimateShift.toFixed(0)}%`;
let phase = "RECEDING";
if (trainStopped) {
phase = "END OF TRACK";
} else if (Math.abs(currentSource.x) < 1.15) {
phase = "PASSING";
} else if (currentSource.x * direction < 0) {
phase = "APPROACHING";
}
$("phase").textContent = phase;
$("phase").dataset.state = phase.toLowerCase().replace(/\s+/g, "-");
}
$("playButton").addEventListener("click", () => {
running = !running;
syncPlayButton();
});
$("resetButton").addEventListener("click", resetSimulation);
$("directionButton").addEventListener("click", () => {
direction *= -1;
$("directionButton").textContent = direction > 0 ? "Travel →" : "Travel ←";
resetSimulation();
});
$("speedInput").addEventListener("input", event => {
trainSpeed = Number(event.target.value);
$("speedValue").textContent = `${trainSpeed.toFixed(1)} u/s`;
});
$("periodInput").addEventListener("input", event => {
sourcePeriod = Number(event.target.value);
$("periodValue").textContent = `${sourcePeriod.toFixed(2)} s`;
lastArrivalTime = null;
lastArrivalGap = null;
lastObservedRatio = null;
});
$("pingToggle").addEventListener("change", () => {
ensureAudio().catch(() => {});
});
window.addEventListener("keydown", event => {
const tagName = document.activeElement?.tagName;
if (["INPUT", "BUTTON", "SELECT", "TEXTAREA"].includes(tagName)) return;
if (event.code === "Space") {
event.preventDefault();
running = !running;
syncPlayButton();
}
if (event.key.toLowerCase() === "r") {
resetSimulation();
}
});
// ------------------------------------------------------------
// Camera controls implemented directly, without add-ons
// ------------------------------------------------------------
let dragging = false;
let pointerX = 0;
let pointerY = 0;
sceneCanvas.addEventListener("pointerdown", event => {
dragging = true;
pointerX = event.clientX;
pointerY = event.clientY;
sceneCanvas.setPointerCapture(event.pointerId);
});
sceneCanvas.addEventListener("pointermove", event => {
if (!dragging) return;
const deltaX = event.clientX - pointerX;
const deltaY = event.clientY - pointerY;
pointerX = event.clientX;
pointerY = event.clientY;
cameraAzimuth -= deltaX * 0.006;
cameraElevation = THREE.MathUtils.clamp(
cameraElevation + deltaY * 0.005,
0.22,
1.18
);
});
function stopDragging(event) {
dragging = false;
if (event.pointerId !== undefined && sceneCanvas.hasPointerCapture(event.pointerId)) {
sceneCanvas.releasePointerCapture(event.pointerId);
}
}
sceneCanvas.addEventListener("pointerup", stopDragging);
sceneCanvas.addEventListener("pointercancel", stopDragging);
sceneCanvas.addEventListener("wheel", event => {
event.preventDefault();
cameraRadius = THREE.MathUtils.clamp(
cameraRadius + event.deltaY * 0.025,
21,
52
);
}, { passive: false });
function updateCamera() {
const horizontalRadius = Math.cos(cameraElevation) * cameraRadius;
camera.position.set(
cameraTarget.x + Math.sin(cameraAzimuth) * horizontalRadius,
cameraTarget.y + Math.sin(cameraElevation) * cameraRadius,
cameraTarget.z + Math.cos(cameraAzimuth) * horizontalRadius
);
camera.lookAt(cameraTarget);
}
function resize() {
renderer.setSize(window.innerWidth, window.innerHeight, false);
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
resizeTimeline();
}
window.addEventListener("resize", resize);
// ------------------------------------------------------------
// Main loop
// ------------------------------------------------------------
resetSimulation();
resize();
let previousFrameTime = performance.now();
function animate(now) {
const deltaTime = Math.min((now - previousFrameTime) / 1000, 0.05);
previousFrameTime = now;
if (running) {
simulationTime += deltaTime;
if (!trainStopped) {
train.position.x += direction * trainSpeed * deltaTime;
if (
(direction > 0 && train.position.x >= 18.2) ||
(direction < 0 && train.position.x <= -18.2)
) {
train.position.x = direction > 0 ? 18.2 : -18.2;
trainStopped = true;
}
}
updateCurrentSource();
if (!trainStopped && simulationTime >= nextEmission) {
emitPulse();
nextEmission += sourcePeriod;
}
}
updateFronts();
observerFlash = Math.max(0, observerFlash - deltaTime * 2.7);
observerHalo.rotation.y = simulationTime * 0.65;
observerHalo.scale.setScalar(1 + observerFlash * 0.7);
haloMaterial.opacity = 0.18 + observerFlash * 0.72;
beamMaterial.opacity = observerFlash * 0.48;
observerLight.intensity = observerFlash * 9;
updateCamera();
updateReadout();
drawTimeline();
renderer.render(scene, camera);
requestAnimationFrame(animate);
}
requestAnimationFrame(animate);
</script>
</body>
</html>
```