Prompt specification
Build or customize the Three.js 3D scene "Doppler arrival-counter 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: Doppler arrival-counter explorer
Category: Voxel Worlds · Style: Voxel 3D
License: MIT · Reference: https://three3d.app/scene/doppler-arrival-counter-explorer-x1540
Scene Description Prompt:
Please create one self-contained HTML file with Three.js from cdnjs showing the Doppler effect from relative motion. Let users vary source and observer speeds below the model's wave speed; calculate observed frequency and flag invalid or unsupported configurations rather than silently extrapolating. Voxel style.
Working Three.js Starter (doppler-arrival-counter-explorer-x1540):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Voxel Doppler Lab</title>
<style>
:root {
--bg: #07131d;
--panel: rgba(9, 24, 36, 0.94);
--panel-edge: #29485c;
--text: #e8f4fa;
--muted: #91acbc;
--cyan: #58d7ff;
--orange: #ffad42;
--green: #67e8a7;
--red: #ff647c;
--yellow: #ffd166;
--shadow: rgba(0, 0, 0, 0.35);
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: var(--bg);
color: var(--text);
font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas,
"Liberation Mono", monospace;
}
button,
input {
font: inherit;
}
#stage {
position: fixed;
inset: 0;
}
#stage canvas {
display: block;
width: 100%;
height: 100%;
touch-action: none;
cursor: grab;
}
#stage canvas:active {
cursor: grabbing;
}
.panel {
position: fixed;
z-index: 10;
background: var(--panel);
border: 2px solid var(--panel-edge);
box-shadow: 7px 7px 0 var(--shadow);
}
header {
top: 22px;
left: 22px;
width: min(430px, calc(100vw - 44px));
padding: 18px 20px;
}
.eyebrow {
margin-bottom: 6px;
color: var(--cyan);
font-size: 11px;
font-weight: 800;
letter-spacing: 0.18em;
text-transform: uppercase;
}
h1 {
margin: 0;
font-size: clamp(25px, 4vw, 39px);
line-height: 1;
letter-spacing: -0.06em;
}
header p {
margin: 12px 0 0;
color: var(--muted);
font-size: 12px;
line-height: 1.55;
}
.controls {
top: 22px;
right: 22px;
width: 365px;
max-height: calc(100vh - 44px);
padding: 16px;
overflow-y: auto;
scrollbar-width: thin;
scrollbar-color: var(--panel-edge) transparent;
}
.status-box {
padding: 11px;
background: #0b1d2a;
border: 1px solid #234153;
}
.status-row {
display: flex;
align-items: center;
gap: 9px;
}
.badge {
display: inline-block;
flex: 0 0 auto;
padding: 5px 7px;
border: 1px solid currentColor;
font-size: 10px;
font-weight: 900;
letter-spacing: 0.08em;
}
.badge[data-kind="valid"] {
color: var(--green);
background: rgba(103, 232, 167, 0.08);
}
.badge[data-kind="paused"] {
color: var(--yellow);
background: rgba(255, 209, 102, 0.08);
}
.badge[data-kind="invalid"] {
color: var(--red);
background: rgba(255, 100, 124, 0.09);
}
.badge[data-kind="unsupported"] {
color: var(--orange);
background: rgba(255, 173, 66, 0.09);
}
#statusText {
color: var(--muted);
font-size: 11px;
line-height: 1.4;
}
.medium-row {
display: grid;
grid-template-columns: 1fr auto;
gap: 8px;
align-items: center;
margin-top: 10px;
padding: 10px 11px;
background: #0b1d2a;
border: 1px solid #234153;
color: var(--muted);
font-size: 11px;
}
.medium-row strong {
color: var(--cyan);
font-size: 14px;
}
.section-title {
margin: 16px 0 9px;
color: var(--muted);
font-size: 10px;
font-weight: 800;
letter-spacing: 0.14em;
text-transform: uppercase;
}
.speed-control {
margin-bottom: 14px;
padding: 11px;
background: #0b1d2a;
border: 1px solid #234153;
}
.speed-heading {
display: flex;
justify-content: space-between;
align-items: center;
gap: 10px;
margin-bottom: 9px;
font-size: 12px;
font-weight: 800;
}
.speed-heading.source {
color: var(--orange);
}
.speed-heading.observer {
color: var(--cyan);
}
.speed-entry {
display: grid;
grid-template-columns: 1fr 84px;
gap: 10px;
align-items: center;
}
input[type="range"] {
width: 100%;
margin: 0;
accent-color: var(--cyan);
cursor: pointer;
}
.speed-control.source input[type="range"] {
accent-color: var(--orange);
}
input[type="number"] {
width: 100%;
padding: 7px 6px;
border: 1px solid #3a5a6d;
border-radius: 0;
background: #07131d;
color: var(--text);
text-align: right;
}
.speed-control small {
display: block;
margin-top: 7px;
color: var(--muted);
font-size: 9px;
line-height: 1.4;
}
.frequency-grid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 9px;
}
.frequency-card {
padding: 11px;
background: #0b1d2a;
border: 1px solid #234153;
}
.frequency-card span {
display: block;
color: var(--muted);
font-size: 9px;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.frequency-card strong {
display: block;
margin-top: 5px;
font-size: 23px;
letter-spacing: -0.06em;
}
.frequency-card.observed strong {
color: var(--cyan);
}
#ratioText,
#sensorText {
margin: 8px 0 0;
color: var(--muted);
font-size: 10px;
line-height: 1.45;
}
.formula {
margin-top: 12px;
padding: 11px;
background: #0b1d2a;
border-left: 3px solid var(--cyan);
color: #d9edf7;
font-family: Georgia, "Times New Roman", serif;
font-size: 16px;
text-align: center;
}
.assumptions {
margin: 9px 0 0;
color: var(--muted);
font-size: 10px;
line-height: 1.5;
}
.buttons {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 8px;
margin-top: 14px;
}
button {
min-height: 38px;
padding: 8px;
border: 1px solid #416176;
border-radius: 0;
background: #102b3c;
color: var(--text);
cursor: pointer;
font-size: 10px;
font-weight: 800;
letter-spacing: 0.04em;
text-transform: uppercase;
}
button:hover:not(:disabled) {
border-color: var(--cyan);
background: #15384d;
}
button:disabled {
cursor: not-allowed;
opacity: 0.45;
}
#audioButton {
grid-column: 1 / -1;
}
#audioButton.active {
border-color: var(--green);
color: var(--green);
}
.legend {
position: fixed;
z-index: 8;
left: 22px;
bottom: 22px;
display: flex;
gap: 15px;
padding: 10px 13px;
background: rgba(7, 19, 29, 0.84);
border: 1px solid #29485c;
color: var(--muted);
font-size: 10px;
}
.legend-item {
display: flex;
align-items: center;
gap: 6px;
}
.swatch {
width: 10px;
height: 10px;
background: currentColor;
box-shadow: 2px 2px 0 rgba(0, 0, 0, 0.35);
}
.source-color {
color: var(--orange);
}
.observer-color {
color: var(--cyan);
}
.wave-color {
color: #a8ddff;
}
.actor-label {
position: fixed;
z-index: 6;
pointer-events: none;
transform: translate(-50%, -100%);
padding: 5px 7px;
border: 1px solid currentColor;
background: rgba(7, 19, 29, 0.9);
font-size: 10px;
font-weight: 900;
letter-spacing: 0.07em;
white-space: nowrap;
}
.actor-label.source {
color: var(--orange);
}
.actor-label.observer {
color: var(--cyan);
}
.actor-label small {
display: block;
margin-top: 2px;
color: var(--muted);
font-size: 8px;
font-weight: 500;
letter-spacing: 0;
}
#loading {
position: fixed;
inset: 0;
z-index: 30;
display: grid;
place-items: center;
background: var(--bg);
color: var(--cyan);
font-size: 12px;
letter-spacing: 0.12em;
text-transform: uppercase;
}
@media (max-width: 760px) {
header {
top: 10px;
left: 10px;
width: calc(100vw - 20px);
padding: 13px 15px;
}
header p {
display: none;
}
.controls {
top: auto;
right: 10px;
bottom: 10px;
left: 10px;
width: auto;
max-height: 48vh;
padding: 12px;
}
.legend {
display: none;
}
.actor-label {
font-size: 8px;
}
}
</style>
</head>
<body>
<div id="stage"></div>
<header class="panel">
<div class="eyebrow">Relative Motion Laboratory</div>
<h1>Voxel Doppler</h1>
<p>
Move the source and observer through a stationary medium. Expanding
voxel wavefronts show how relative motion changes the received frequency.
</p>
</header>
<aside class="controls panel" aria-label="Doppler controls">
<div class="status-box">
<div class="status-row">
<span id="statusBadge" class="badge" data-kind="valid">SUPPORTED</span>
<span id="statusText" aria-live="polite">
Both speeds are inside the supported model.
</span>
</div>
</div>
<div class="medium-row">
<span>Stationary medium wave speed</span>
<strong>c = 1.20 u/s</strong>
</div>
<div class="section-title">Signed velocities</div>
<section class="speed-control source">
<div class="speed-heading source">
<span>Source speed</span>
<span>orange</span>
</div>
<div class="speed-entry">
<input
id="sourceRange"
type="range"
min="-1.08"
max="1.08"
step="0.01"
value="0.42"
aria-label="Source speed"
/>
<input
id="sourceNumber"
type="number"
min="-1.08"
max="1.08"
step="0.01"
value="0.42"
aria-label="Source speed in model units per second"
/>
</div>
<small>
Model units per second. Positive means right; negative means left.
Strict requirement: |vₛ| < c.
</small>
</section>
<section class="speed-control observer">
<div class="speed-heading observer">
<span>Observer speed</span>
<span>cyan</span>
</div>
<div class="speed-entry">
<input
id="observerRange"
type="range"
min="-1.08"
max="1.08"
step="0.01"
value="0.05"
aria-label="Observer speed"
/>
<input
id="observerNumber"
type="number"
min="-1.08"
max="1.08"
step="0.01"
value="0.05"
aria-label="Observer speed in model units per second"
/>
</div>
<small>
Model units per second. Positive means right; negative means left.
Strict requirement: |vₒ| < c.
</small>
</section>
<div class="section-title">Frequency result</div>
<div class="frequency-grid">
<div class="frequency-card">
<span>Emitted f₀</span>
<strong id="emittedFrequency">0.65 Hz</strong>
</div>
<div class="frequency-card observed">
<span>Observed f</span>
<strong id="observedFrequency">—</strong>
</div>
</div>
<p id="ratioText"></p>
<p id="sensorText">Waiting for the first detected arrival.</p>
<div class="formula">
f<sub>obs</sub> =
f<sub>0</sub>
<span style="white-space: nowrap">
· (c − v<sub>o</sub>) / (c − v<sub>s</sub>)
</span>
</div>
<p class="assumptions">
Supported assumptions: steady source, stationary medium, straight-line
motion, source behind observer, and both speeds strictly below c.
If the trajectories meet, the order-reversed geometry is flagged instead
of being extrapolated.
</p>
<div class="buttons">
<button id="pauseButton">Pause</button>
<button id="resetButton">Reset Positions</button>
<button id="audioButton">Enable Audible Proxy</button>
</div>
</aside>
<div id="sourceLabel" class="actor-label source">
SOURCE
<small id="sourceLabelSpeed">vₛ = +0.42 u/s</small>
</div>
<div id="observerLabel" class="actor-label observer">
OBSERVER
<small id="observerLabelSpeed">vₒ = +0.05 u/s</small>
</div>
<div class="legend">
<div class="legend-item">
<span class="swatch source-color"></span>
Source
</div>
<div class="legend-item">
<span class="swatch wave-color"></span>
Expanding wavefronts
</div>
<div class="legend-item">
<span class="swatch observer-color"></span>
Observer
</div>
</div>
<div id="loading">Loading Three.js core…</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 MODEL = Object.freeze({
waveSpeed: 1.2,
emittedFrequency: 0.65,
sourceStartX: -2.6,
observerStartX: 2.6,
waveCenterY: 0.62,
maxPulseAge: 18
});
const state = {
mode: "valid",
paused: false,
time: 0,
sourceX: MODEL.sourceStartX,
observerX: MODEL.observerStartX,
speeds: {
source: 0.42,
observer: 0.05
},
pulses: [],
nextEmission: 0,
lastArrival: null,
measuredFrequency: null,
arrivalFlash: 0,
audioOn: false
};
let audioContext = null;
let oscillator = null;
let audioGain = null;
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x07131d);
scene.fog = new THREE.Fog(0x07131d, 17, 36);
const camera = new THREE.PerspectiveCamera(
43,
window.innerWidth / window.innerHeight,
0.1,
100
);
const renderer = new THREE.WebGLRenderer({
antialias: true,
powerPreference: "high-performance"
});
renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.domElement.setAttribute(
"aria-label",
"Interactive three-dimensional voxel Doppler simulation"
);
$("stage").appendChild(renderer.domElement);
const hemisphere = new THREE.HemisphereLight(0xb8e7ff, 0x10202c, 2.1);
scene.add(hemisphere);
const keyLight = new THREE.DirectionalLight(0xfff0d0, 3.0);
keyLight.position.set(6, 10, 7);
keyLight.castShadow = true;
keyLight.shadow.mapSize.set(1024, 1024);
keyLight.shadow.camera.left = -13;
keyLight.shadow.camera.right = 13;
keyLight.shadow.camera.top = 10;
keyLight.shadow.camera.bottom = -10;
keyLight.shadow.camera.near = 1;
keyLight.shadow.camera.far = 35;
scene.add(keyLight);
const rimLight = new THREE.DirectionalLight(0x57cfff, 1.7);
rimLight.position.set(-8, 4, -6);
scene.add(rimLight);
// ---- Voxel floor -------------------------------------------------------
function createFloor() {
const columns = 31;
const rows = 13;
const spacing = 0.6;
const count = columns * rows;
const geometry = new THREE.BoxGeometry(0.55, 0.11, 0.55);
const material = new THREE.MeshStandardMaterial({
roughness: 0.93,
metalness: 0.02,
vertexColors: true
});
const floor = new THREE.InstancedMesh(geometry, material, count);
floor.receiveShadow = true;
const dummy = new THREE.Object3D();
const color = new THREE.Color();
let index = 0;
for (let row = 0; row < rows; row++) {
for (let column = 0; column < columns; column++) {
const x = (column - (columns - 1) / 2) * spacing;
const z = (row - (rows - 1) / 2) * spacing;
dummy.position.set(x, -0.105, z);
dummy.rotation.set(0, 0, 0);
dummy.scale.set(1, 1, 1);
dummy.updateMatrix();
floor.setMatrixAt(index, dummy.matrix);
const lane = Math.abs(z) < 0.35;
const variation = ((column * 17 + row * 11) % 7) / 255;
if (lane) {
color.setRGB(0.065 + variation, 0.16 + variation, 0.21 + variation);
} else {
color.setRGB(
0.035 + variation * 0.4,
0.085 + variation * 0.35,
0.12 + variation * 0.45
);
}
floor.setColorAt(index, color);
index++;
}
}
floor.instanceMatrix.needsUpdate = true;
floor.instanceColor.needsUpdate = true;
scene.add(floor);
// Pixel-like dashed rail along the source/observer path.
const railGeometry = new THREE.BoxGeometry(0.32, 0.035, 0.09);
const railMaterial = new THREE.MeshStandardMaterial({
color: 0x37647a,
emissive: 0x102d3a,
emissiveIntensity: 0.35,
roughness: 0.75
});
for (let i = -29; i <= 29; i++) {
const dash = new THREE.Mesh(railGeometry, railMaterial);
dash.position.set(i * 0.54, -0.035, 0);
dash.receiveShadow = true;
scene.add(dash);
}
}
createFloor();
// ---- Voxel actors ------------------------------------------------------
function createVoxelActor(color, observer = false) {
const group = new THREE.Group();
const bodyMaterial = new THREE.MeshStandardMaterial({
color,
roughness: 0.52,
metalness: 0.12,
emissive: color,
emissiveIntensity: 0.18
});
const darkMaterial = new THREE.MeshStandardMaterial({
color: 0x172633,
roughness: 0.85,
metalness: 0.05
});
const lightMaterial = new THREE.MeshStandardMaterial({
color: 0xeafaff,
emissive: 0xaeeaff,
emissiveIntensity: 0.8,
roughness: 0.4
});
function addBox(size, position, material) {
const mesh = new THREE.Mesh(
new THREE.BoxGeometry(size[0], size[1], size[2]),
material
);
mesh.position.set(position[0], position[1], position[2]);
mesh.castShadow = true;
mesh.receiveShadow = true;
group.add(mesh);
return mesh;
}
if (!observer) {
addBox([0.28, 0.2, 0.42], [-0.27, 0.1, 0], darkMaterial);
addBox([0.28, 0.2, 0.42], [0.27, 0.1, 0], darkMaterial);
addBox([0.64, 0.58, 0.64], [0, 0.48, 0], bodyMaterial);
addBox([0.84, 0.18, 0.84], [0, 0.86, 0], bodyMaterial);
addBox([0.18, 0.3, 0.46], [0.45, 0.5, 0], darkMaterial);
addBox([0.13, 0.13, 0.13], [0, 0.53, 0.38], lightMaterial);
addBox([0.25, 0.14, 0.25], [-0.2, 1.02, 0], darkMaterial);
} else {
addBox([0.9, 0.16, 0.9], [0, 0.08, 0], darkMaterial);
addBox([0.54, 0.72, 0.54], [0, 0.5, 0], bodyMaterial);
addBox([0.76, 0.4, 0.76], [0, 1.03, 0], bodyMaterial);
addBox([0.13, 0.3, 0.13], [0, 1.38, 0], darkMaterial);
addBox([0.2, 0.12, 0.2], [0, 1.57, 0], lightMaterial);
addBox([0.36, 0.14, 0.13], [0, 1.05, 0.4], lightMaterial);
}
const arrow = createVoxelArrow(color);
arrow.position.set(0, 0.015, -0.78);
group.add(arrow);
group.userData.arrow = arrow;
group.userData.bodyMaterial = bodyMaterial;
return group;
}
function createVoxelArrow(color) {
const group = new THREE.Group();
const material = new THREE.MeshStandardMaterial({
color,
emissive: color,
emissiveIntensity: 0.35,
roughness: 0.65
});
const shaft = new THREE.Mesh(
new THREE.BoxGeometry(0.68, 0.07, 0.11),
material
);
shaft.position.x = 0.35;
group.add(shaft);
for (const z of [-0.18, 0, 0.18]) {
const head = new THREE.Mesh(
new THREE.BoxGeometry(0.17, 0.12, 0.13),
material
);
head.position.set(0.76, 0, z);
group.add(head);
}
return group;
}
const sourceActor = createVoxelActor(0xff9d32, false);
const observerActor = createVoxelActor(0x35c9f3, true);
scene.add(sourceActor, observerActor);
// ---- Voxel wavefronts --------------------------------------------------
const WAVE_POINT_COUNT = 112;
const MAX_PULSES = 20;
const waveDirections = [];
const goldenAngle = Math.PI * (3 - Math.sqrt(5));
for (let i = 0; i < WAVE_POINT_COUNT; i++) {
const y = 1 - (2 * (i + 0.5)) / WAVE_POINT_COUNT;
const radius = Math.sqrt(Math.max(0, 1 - y * y));
const angle = goldenAngle * i;
waveDirections.push(
new THREE.Vector3(
Math.cos(angle) * radius,
y,
Math.sin(angle) * radius
)
);
}
const waveGeometry = new THREE.BoxGeometry(1, 1, 1);
const waveMaterial = new THREE.MeshBasicMaterial({
color: 0x91ddff,
transparent: true,
opacity: 0.53,
depthWrite: false
});
const waveMesh = new THREE.InstancedMesh(
waveGeometry,
waveMaterial,
MAX_PULSES * WAVE_POINT_COUNT
);
waveMesh.instanceMatrix.setUsage(THREE.DynamicDrawUsage);
waveMesh.frustumCulled = false;
waveMesh.renderOrder = 2;
scene.add(waveMesh);
const waveDummy = new THREE.Object3D();
// Observer arrival burst, also made from cubes.
const burstMaterial = new THREE.MeshBasicMaterial({
color: 0xc4f2ff,
transparent: true,
opacity: 0,
depthWrite: false
});
const arrivalBurst = new THREE.Group();
for (let i = 0; i < 16; i++) {
const angle = (i / 16) * Math.PI * 2;
const cube = new THREE.Mesh(
new THREE.BoxGeometry(0.13, 0.13, 0.13),
burstMaterial
);
cube.position.set(
Math.cos(angle) * 0.72,
Math.sin(angle) * 0.72,
0
);
arrivalBurst.add(cube);
}
arrivalBurst.position.z = 0.42;
scene.add(arrivalBurst);
// ---- Camera controls implemented locally --------------------------------
const cameraControl = {
yaw: 0.62,
pitch: 0.43,
zoom: 1,
dragging: false,
lastX: 0,
lastY: 0,
target: new THREE.Vector3(0, 0.55, 0)
};
renderer.domElement.addEventListener("pointerdown", (event) => {
cameraControl.dragging = true;
cameraControl.lastX = event.clientX;
cameraControl.lastY = event.clientY;
renderer.domElement.setPointerCapture(event.pointerId);
});
renderer.domElement.addEventListener("pointermove", (event) => {
if (!cameraControl.dragging) return;
const deltaX = event.clientX - cameraControl.lastX;
const deltaY = event.clientY - cameraControl.lastY;
cameraControl.lastX = event.clientX;
cameraControl.lastY = event.clientY;
cameraControl.yaw -= deltaX * 0.006;
cameraControl.pitch = THREE.MathUtils.clamp(
cameraControl.pitch + deltaY * 0.005,
0.08,
1.2
);
});
function endCameraDrag(event) {
cameraControl.dragging = false;
if (
event.pointerId !== undefined &&
renderer.domElement.hasPointerCapture(event.pointerId)
) {
renderer.domElement.releasePointerCapture(event.pointerId);
}
}
renderer.domElement.addEventListener("pointerup", endCameraDrag);
renderer.domElement.addEventListener("pointercancel", endCameraDrag);
renderer.domElement.addEventListener(
"wheel",
(event) => {
event.preventDefault();
cameraControl.zoom = THREE.MathUtils.clamp(
cameraControl.zoom * Math.exp(event.deltaY * 0.001),
0.55,
2.2
);
},
{ passive: false }
);
renderer.domElement.addEventListener("dblclick", () => {
cameraControl.yaw = 0.62;
cameraControl.pitch = 0.43;
cameraControl.zoom = 1;
});
function updateCamera() {
const separation = Math.abs(state.observerX - state.sourceX);
const distance =
Math.max(10.5, separation * 1.03 + 5.3) * cameraControl.zoom;
const midpoint = (state.sourceX + state.observerX) * 0.5;
cameraControl.target.x +=
(midpoint - cameraControl.target.x) * 0.08;
const horizontalDistance = Math.cos(cameraControl.pitch) * distance;
const offset = new THREE.Vector3(
Math.sin(cameraControl.yaw) * horizontalDistance,
Math.sin(cameraControl.pitch) * distance,
Math.cos(cameraControl.yaw) * horizontalDistance
);
camera.position.copy(cameraControl.target).add(offset);
camera.lookAt(cameraControl.target);
camera.updateMatrixWorld();
}
// ---- Physics and UI ----------------------------------------------------
function signed(value) {
return `${value >= 0 ? "+" : ""}${value.toFixed(2)}`;
}
function setStatus(kind, label, message) {
$("statusBadge").dataset.kind = kind;
$("statusBadge").textContent = label;
$("statusText").textContent = message;
}
function getObservedFrequency() {
if (state.mode !== "valid") return null;
const { waveSpeed: c, emittedFrequency: f0 } = MODEL;
const { source: vs, observer: vo } = state.speeds;
// Both denominators and numerators are positive because |v| < c.
return f0 * ((c - vo) / (c - vs));
}
function arrivalTimeFor(emissionTime) {
const c = MODEL.waveSpeed;
const vs = state.speeds.source;
const vo = state.speeds.observer;
return (
MODEL.observerStartX -
MODEL.sourceStartX +
(c - vs) * emissionTime
) / (c - vo);
}
function createPulse(emissionTime) {
const centerX =
MODEL.sourceStartX + state.speeds.source * emissionTime;
state.pulses.push({
emissionTime,
centerX,
arrivalTime: arrivalTimeFor(emissionTime),
counted: false
});
}
function resetSimulation() {
state.time = 0;
state.sourceX = MODEL.sourceStartX;
state.observerX = MODEL.observerStartX;
state.pulses = [];
state.lastArrival = null;
state.measuredFrequency = null;
state.arrivalFlash = 0;
state.mode = "valid";
state.paused = false;
const period = 1 / MODEL.emittedFrequency;
// Seed a few older wavefronts so the scene is active immediately.
// Only use emissions for which the source was still behind the observer.
for (let k = 7; k >= 1; k--) {
const emissionTime = -k * period;
if (-emissionTime > MODEL.maxPulseAge) continue;
const centerX =
MODEL.sourceStartX + state.speeds.source * emissionTime;
const observerAtEmission =
MODEL.observerStartX + state.speeds.observer * emissionTime;
if (centerX >= observerAtEmission - 0.05) continue;
const arrivalTime = arrivalTimeFor(emissionTime);
if (arrivalTime > 0 && arrivalTime < 24) {
createPulse(emissionTime);
}
}
createPulse(0);
state.pulses.sort((a, b) => a.emissionTime - b.emissionTime);
state.nextEmission = period;
sourceActor.position.x = state.sourceX;
observerActor.position.x = state.observerX;
updateActorVisuals();
updateReadouts();
updateAudio();
}
function validateAndApply() {
const sourceValue = Number.parseFloat($("sourceNumber").value);
const observerValue = Number.parseFloat($("observerNumber").value);
const c = MODEL.waveSpeed;
const sourceValid =
Number.isFinite(sourceValue) && Math.abs(sourceValue) < c;
const observerValid =
Number.isFinite(observerValue) && Math.abs(observerValue) < c;
if (!sourceValid || !observerValid) {
state.mode = "invalid";
state.paused = true;
setStatus(
"invalid",
"INVALID INPUT",
"Each speed must satisfy |v| < 1.20 u/s. No result is being extrapolated."
);
$("pauseButton").disabled = true;
$("resetButton").disabled = true;
$("audioButton").disabled = true;
updateReadouts();
updateAudio();
return;
}
state.speeds.source = sourceValue;
state.speeds.observer = observerValue;
$("pauseButton").disabled = false;
$("resetButton").disabled = false;
$("audioButton").disabled = false;
resetSimulation();
setStatus(
"valid",
"SUPPORTED",
"Both speeds are sub-wave-speed and the source starts behind the observer."
);
}
function updateActorVisuals() {
sourceActor.position.x = state.sourceX;
observerActor.position.x = state.observerX;
const sourceArrow = sourceActor.userData.arrow;
const observerArrow = observerActor.userData.arrow;
const sourceSpeed = state.speeds.source;
const observerSpeed = state.speeds.observer;
sourceArrow.visible = Math.abs(sourceSpeed) > 0.025;
observerArrow.visible = Math.abs(observerSpeed) > 0.025;
sourceArrow.rotation.y = sourceSpeed < 0 ? Math.PI : 0;
observerArrow.rotation.y = observerSpeed < 0 ? Math.PI : 0;
sourceArrow.scale.x =
0.65 + (Math.abs(sourceSpeed) / MODEL.waveSpeed) * 0.55;
observerArrow.scale.x =
0.65 + (Math.abs(observerSpeed) / MODEL.waveSpeed) * 0.55;
$("sourceLabelSpeed").textContent =
`vₛ = ${signed(sourceSpeed)} u/s`;
$("observerLabelSpeed").textContent =
`vₒ = ${signed(observerSpeed)} u/s`;
}
function updateSimulation(deltaTime) {
if (state.mode !== "valid" || state.paused) return;
state.time += deltaTime;
const vs = state.speeds.source;
const vo = state.speeds.observer;
// Detect a future meeting of the two straight-line trajectories.
// At that point the source would no longer remain behind the observer,
// so the current directional formula is deliberately not extrapolated.
if (vs > vo) {
const crossingTime =
(MODEL.observerStartX - MODEL.sourceStartX) / (vs - vo);
if (crossingTime > 0 && state.time >= crossingTime) {
state.time = Math.max(0, crossingTime - 0.035);
state.sourceX = MODEL.sourceStartX + vs * state.time;
state.observerX = MODEL.observerStartX + vo * state.time;
state.mode = "unsupported";
state.paused = true;
setStatus(
"unsupported",
"UNSUPPORTED",
"The trajectories meet. Order-reversed source/observer geometry is not evaluated."
);
$("pauseButton").disabled = true;
$("audioButton").disabled = true;
updateActorVisuals();
updateReadouts();
updateAudio();
return;
}
}
state.sourceX = MODEL.sourceStartX + vs * state.time;
state.observerX = MODEL.observerStartX + vo * state.time;
const period = 1 / MODEL.emittedFrequency;
while (state.time >= state.nextEmission) {
createPulse(state.nextEmission);
state.nextEmission += period;
}
for (const pulse of state.pulses) {
if (!pulse.counted && state.time >= pulse.arrivalTime) {
pulse.counted = true;
if (state.lastArrival !== null) {
const interval = pulse.arrivalTime - state.lastArrival;
if (interval > 0) {
state.measuredFrequency = 1 / interval;
}
}
state.lastArrival = pulse.arrivalTime;
state.arrivalFlash = 1;
}
}
state.pulses = state.pulses.filter((pulse) => {
const age = state.time - pulse.emissionTime;
const sinceArrival = pulse.counted
? state.time - pulse.arrivalTime
: 0;
return age < MODEL.maxPulseAge && sinceArrival < 3;
});
updateActorVisuals();
}
function updateWaveVisuals() {
let instance = 0;
for (const pulse of state.pulses) {
const age = state.time - pulse.emissionTime;
if (age < 0 || age > MODEL.maxPulseAge) continue;
const radius = MODEL.waveSpeed * age;
for (const direction of waveDirections) {
waveDummy.position.set(
pulse.centerX + direction.x * radius,
MODEL.waveCenterY + direction.y * radius,
direction.z * radius
);
waveDummy.rotation.set(0, 0, 0);
waveDummy.scale.set(0.17, 0.17, 0.17);
waveDummy.updateMatrix();
waveMesh.setMatrixAt(instance, waveDummy.matrix);
instance++;
if (instance >= MAX_PULSES * WAVE_POINT_COUNT) break;
}
if (instance >= MAX_PULSES * WAVE_POINT_COUNT) break;
}
waveMesh.count = instance;
waveMesh.instanceMatrix.needsUpdate = true;
}
function updateReadouts() {
const observed = getObservedFrequency();
$("emittedFrequency").textContent =
`${MODEL.emittedFrequency.toFixed(2)} Hz`;
if (observed === null) {
$("observedFrequency").textContent = "—";
$("ratioText").textContent =
"Observed frequency is not evaluated for this configuration.";
$("sensorText").textContent =
"No observed-frequency result is being extrapolated.";
return;
}
const ratio = observed / MODEL.emittedFrequency;
$("observedFrequency").textContent = `${observed.toFixed(2)} Hz`;
$("ratioText").textContent =
`Received/emitted ratio: ×${ratio.toFixed(3)}. ` +
(ratio > 1.001
? "The observer is approaching the wavefronts."
: ratio < 0.999
? "The observer is receding from the wavefronts."
: "The observed and emitted frequencies are equal.");
if (state.measuredFrequency !== null) {
$("sensorText").textContent =
`Detected arrival interval gives ` +
`${state.measuredFrequency.toFixed(3)} Hz; ` +
"the analytic value is the steady-state result.";
} else {
$("sensorText").textContent =
"Waiting for the first detected arrival.";
}
}
// ---- Optional audible proxy --------------------------------------------
async function toggleAudio() {
if (!audioContext) {
const AudioContextClass =
window.AudioContext || window.webkitAudioContext;
if (!AudioContextClass) {
setStatus(
"unsupported",
"UNSUPPORTED",
"This browser does not expose the Web Audio API."
);
return;
}
audioContext = new AudioContextClass();
oscillator = audioContext.createOscillator();
audioGain = audioContext.createGain();
oscillator.type = "sine";
oscillator.frequency.value = 220;
audioGain.gain.value = 0;
oscillator.connect(audioGain);
audioGain.connect(audioContext.destination);
oscillator.start();
}
await audioContext.resume();
state.audioOn = !state.audioOn;
$("audioButton").textContent = state.audioOn
? "Disable Audible Proxy"
: "Enable Audible Proxy";
$("audioButton").classList.toggle("active", state.audioOn);
updateAudio();
}
function updateAudio() {
if (!audioContext || !oscillator || !audioGain) return;
const now = audioContext.currentTime;
const observed = getObservedFrequency();
if (state.audioOn && observed !== null) {
const ratio = observed / MODEL.emittedFrequency;
oscillator.frequency.setTargetAtTime(220 * ratio, now, 0.025);
audioGain.gain.setTargetAtTime(0.035, now, 0.035);
} else {
audioGain.gain.setTargetAtTime(0, now, 0.025);
}
}
// ---- Input handling ----------------------------------------------------
$("sourceRange").addEventListener("input", () => {
$("sourceNumber").value = $("sourceRange").value;
validateAndApply();
});
$("observerRange").addEventListener("input", () => {
$("observerNumber").value = $("observerRange").value;
validateAndApply();
});
$("sourceNumber").addEventListener("change", () => {
const value = Number.parseFloat($("sourceNumber").value);
if (
Number.isFinite(value) &&
value >= Number($("sourceRange").min) &&
value <= Number($("sourceRange").max)
) {
$("sourceRange").value = String(value);
}
validateAndApply();
});
$("observerNumber").addEventListener("change", () => {
const value = Number.parseFloat($("observerNumber").value);
if (
Number.isFinite(value) &&
value >= Number($("observerRange").min) &&
value <= Number($("observerRange").max)
) {
$("observerRange").value = String(value);
}
validateAndApply();
});
$("pauseButton").addEventListener("click", () => {
if (state.mode !== "valid") return;
state.paused = !state.paused;
$("pauseButton").textContent = state.paused ? "Resume" : "Pause";
if (state.paused) {
setStatus(
"paused",
"PAUSED",
"The supported steady-state result is retained while the animation is paused."
);
} else {
setStatus(
"valid",
"SUPPORTED",
"Both speeds are inside the supported model and the source remains behind."
);
}
});
$("resetButton").addEventListener("click", () => {
if (state.mode === "invalid") return;
resetSimulation();
setStatus(
"valid",
"SUPPORTED",
"Positions reset. Both speeds remain inside the supported model."
);
});
$("audioButton").addEventListener("click", toggleAudio);
// ---- Labels and animation ----------------------------------------------
const projected = new THREE.Vector3();
function positionLabel(element, worldPosition) {
projected.copy(worldPosition).project(camera);
const visible = projected.z > -1 && projected.z < 1;
element.style.display = visible ? "block" : "none";
if (!visible) return;
element.style.left =
`${(projected.x * 0.5 + 0.5) * window.innerWidth}px`;
element.style.top =
`${(-projected.y * 0.5 + 0.5) * window.innerHeight}px`;
}
const sourceLabelPosition = new THREE.Vector3();
const observerLabelPosition = new THREE.Vector3();
function updateLabels() {
sourceLabelPosition.set(state.sourceX, 1.48, 0);
observerLabelPosition.set(state.observerX, 1.96, 0);
positionLabel($("sourceLabel"), sourceLabelPosition);
positionLabel($("observerLabel"), observerLabelPosition);
}
function resize() {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
}
window.addEventListener("resize", resize);
resetSimulation();
updateCamera();
$("loading").remove();
let previousTime = performance.now();
function animate(now) {
const deltaTime = Math.min((now - previousTime) / 1000, 0.05);
previousTime = now;
updateSimulation(deltaTime);
updateWaveVisuals();
if (!state.paused || state.mode === "valid") {
state.arrivalFlash = Math.max(
0,
state.arrivalFlash - deltaTime * 2.8
);
}
arrivalBurst.position.x = state.observerX;
arrivalBurst.position.y = MODEL.waveCenterY;
arrivalBurst.scale.setScalar(
1 + (1 - state.arrivalFlash) * 0.95
);
burstMaterial.opacity = state.arrivalFlash * 0.8;
observerActor.userData.bodyMaterial.emissiveIntensity =
0.18 + state.arrivalFlash * 2.2;
updateCamera();
scene.updateMatrixWorld(true);
updateLabels();
updateReadouts();
renderer.render(scene, camera);
requestAnimationFrame(animate);
}
requestAnimationFrame(animate);
</script>
</body>
</html>
```