Prompt specification
Build or customize the Three.js 3D scene "Soft and stiff stop comparison" 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: Soft and stiff stop comparison
Category: Science & Physics · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/soft-and-stiff-stop-comparison-x1398
Scene Description Prompt:
Stop identical model carts from equal speed using longer and shorter prescribed force pulses; show equal momentum change with differing force-time profiles. Use Three.js from cdnjs in a single HTML file, with stylized solid shapes.
Working Three.js Starter (soft-and-stiff-stop-comparison-x1398):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Equal Impulse, Different Force Pulses</title>
<style>
:root {
--bg: #07111f;
--panel: rgba(12, 25, 42, 0.9);
--panel-border: rgba(156, 190, 224, 0.16);
--text: #edf7ff;
--muted: #91a9bf;
--long: #48d9ff;
--short: #ffb454;
--impulse: #b8ff72;
--track: #1a2b40;
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: var(--bg);
color: var(--text);
font-family:
Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
button,
input,
select {
font: inherit;
}
#stage {
position: fixed;
inset: 0;
}
#stage canvas {
display: block;
width: 100%;
height: 100%;
touch-action: none;
}
.vignette {
position: fixed;
inset: 0;
pointer-events: none;
background:
radial-gradient(
circle at 52% 43%,
transparent 25%,
rgba(3, 10, 20, 0.2) 75%,
rgba(3, 8, 16, 0.68) 100%
);
}
header {
position: fixed;
top: 25px;
left: 28px;
z-index: 5;
max-width: 390px;
pointer-events: none;
}
.eyebrow {
color: var(--impulse);
font-size: 11px;
font-weight: 800;
letter-spacing: 0.18em;
text-transform: uppercase;
margin-bottom: 7px;
}
h1 {
margin: 0;
font-size: clamp(24px, 2.4vw, 37px);
line-height: 1.05;
letter-spacing: -0.035em;
}
header p {
margin: 9px 0 0;
color: var(--muted);
font-size: 13px;
line-height: 1.45;
max-width: 365px;
}
.panel {
position: fixed;
z-index: 10;
background: var(--panel);
border: 1px solid var(--panel-border);
border-radius: 18px;
box-shadow: 0 20px 60px rgba(0, 0, 0, 0.32);
backdrop-filter: blur(18px);
}
#controls {
top: 146px;
left: 24px;
width: 302px;
padding: 19px;
}
#analysis {
top: 25px;
right: 24px;
width: 370px;
padding: 19px;
}
.panel-title {
display: flex;
align-items: center;
justify-content: space-between;
gap: 10px;
margin-bottom: 17px;
font-size: 13px;
font-weight: 800;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.badge {
padding: 5px 8px;
border: 1px solid rgba(184, 255, 114, 0.25);
border-radius: 999px;
color: var(--impulse);
background: rgba(184, 255, 114, 0.08);
font-size: 9px;
letter-spacing: 0.07em;
white-space: nowrap;
}
.control {
margin: 0 0 17px;
}
.control-row {
display: flex;
justify-content: space-between;
align-items: baseline;
gap: 12px;
margin-bottom: 8px;
font-size: 12px;
}
.control-row label {
font-weight: 700;
}
.control-row output {
color: var(--muted);
font-variant-numeric: tabular-nums;
font-size: 11px;
text-align: right;
}
.long-text {
color: var(--long);
}
.short-text {
color: var(--short);
}
input[type="range"] {
appearance: none;
width: 100%;
height: 5px;
margin: 0;
border-radius: 99px;
background: var(--track);
cursor: pointer;
}
input[type="range"]::-webkit-slider-thumb {
appearance: none;
width: 16px;
height: 16px;
border-radius: 50%;
background: #eef9ff;
border: 3px solid #14283c;
box-shadow: 0 0 0 2px rgba(255, 255, 255, 0.18);
}
input[type="range"]::-moz-range-thumb {
width: 12px;
height: 12px;
border-radius: 50%;
background: #eef9ff;
border: 3px solid #14283c;
}
#longDuration::-webkit-slider-thumb {
background: var(--long);
}
#shortDuration::-webkit-slider-thumb {
background: var(--short);
}
.button-row {
display: grid;
grid-template-columns: 1fr auto;
gap: 9px;
margin-top: 19px;
}
button {
min-height: 42px;
border: 0;
border-radius: 11px;
padding: 0 16px;
color: #07111f;
background: var(--impulse);
font-weight: 850;
cursor: pointer;
transition:
transform 120ms ease,
filter 120ms ease;
}
button:hover {
filter: brightness(1.08);
transform: translateY(-1px);
}
button:active {
transform: translateY(0);
}
button.secondary {
color: var(--text);
background: #192c42;
border: 1px solid var(--panel-border);
}
.status {
margin-top: 13px;
min-height: 31px;
color: var(--muted);
font-size: 11px;
line-height: 1.45;
}
.status strong {
color: var(--text);
font-variant-numeric: tabular-nums;
}
.chart-wrap {
position: relative;
margin: 4px -3px 10px;
border-radius: 13px;
overflow: hidden;
background: rgba(4, 13, 24, 0.5);
border: 1px solid rgba(156, 190, 224, 0.09);
}
#forceChart {
display: block;
width: 100%;
height: auto;
}
.chart-axis {
stroke: #6c8298;
stroke-width: 1;
}
.chart-grid {
stroke: rgba(148, 175, 201, 0.12);
stroke-width: 1;
stroke-dasharray: 3 5;
}
.chart-label {
fill: #8299ae;
font-size: 9px;
font-family: inherit;
}
.pulse-line {
fill: none;
stroke-width: 3;
stroke-linejoin: round;
vector-effect: non-scaling-stroke;
}
.pulse-area {
stroke: none;
}
.progress-line {
stroke-width: 1;
stroke-dasharray: 3 3;
opacity: 0.65;
vector-effect: non-scaling-stroke;
}
.legend {
display: flex;
gap: 15px;
margin: 0 0 14px;
color: var(--muted);
font-size: 10px;
}
.legend-item {
display: flex;
align-items: center;
gap: 6px;
}
.swatch {
width: 17px;
height: 4px;
border-radius: 4px;
}
.equation {
display: grid;
grid-template-columns: 1fr auto 1fr;
align-items: center;
gap: 8px;
padding: 11px 12px;
margin: 12px 0;
border: 1px solid rgba(184, 255, 114, 0.14);
border-radius: 12px;
background: rgba(184, 255, 114, 0.055);
color: var(--muted);
font-size: 10px;
text-align: center;
}
.equation strong {
color: var(--impulse);
font-size: 12px;
white-space: nowrap;
}
.ledger {
border-top: 1px solid var(--panel-border);
padding-top: 13px;
}
.ledger-title {
display: flex;
justify-content: space-between;
gap: 12px;
margin-bottom: 11px;
font-size: 11px;
font-weight: 800;
letter-spacing: 0.06em;
text-transform: uppercase;
}
.ledger-title strong {
color: var(--impulse);
letter-spacing: 0;
}
.ledger-row {
display: grid;
grid-template-columns: 50px 1fr 73px;
align-items: center;
gap: 9px;
margin-top: 8px;
color: var(--muted);
font-size: 10px;
}
.ledger-row strong {
color: var(--text);
font-size: 10px;
font-variant-numeric: tabular-nums;
text-align: right;
}
.meter {
height: 7px;
overflow: hidden;
border-radius: 99px;
background: #172a3e;
}
.meter i {
display: block;
width: 0;
height: 100%;
border-radius: inherit;
background: var(--impulse);
transition: width 60ms linear;
}
.world-label {
position: fixed;
z-index: 4;
min-width: 118px;
padding: 7px 10px;
border: 1px solid rgba(255, 255, 255, 0.12);
border-radius: 9px;
background: rgba(7, 17, 31, 0.86);
box-shadow: 0 8px 24px rgba(0, 0, 0, 0.24);
pointer-events: none;
transform: translate(-50%, -100%);
text-align: center;
backdrop-filter: blur(8px);
}
.world-label b {
display: block;
font-size: 9px;
letter-spacing: 0.1em;
}
.world-label span {
display: block;
margin-top: 3px;
color: var(--muted);
font-size: 9px;
font-variant-numeric: tabular-nums;
}
#labelLong b {
color: var(--long);
}
#labelShort b {
color: var(--short);
}
#instructions {
position: fixed;
z-index: 5;
left: 50%;
bottom: 20px;
transform: translateX(-50%);
padding: 8px 13px;
border: 1px solid rgba(156, 190, 224, 0.13);
border-radius: 999px;
background: rgba(7, 17, 31, 0.7);
color: var(--muted);
font-size: 10px;
pointer-events: none;
white-space: nowrap;
}
@media (max-width: 900px) {
header {
top: 17px;
left: 17px;
}
header p {
display: none;
}
#controls {
top: auto;
left: 12px;
bottom: 12px;
width: 285px;
padding: 15px;
}
#analysis {
top: 12px;
right: 12px;
width: 330px;
padding: 15px;
}
#instructions {
display: none;
}
}
@media (max-width: 650px) {
h1 {
font-size: 22px;
}
#analysis {
top: 78px;
width: calc(100% - 24px);
}
#analysis .ledger,
#analysis .equation {
display: none;
}
#controls {
width: calc(100% - 24px);
max-height: 49vh;
overflow-y: auto;
}
.world-label {
transform: translate(-50%, -100%) scale(0.88);
}
}
</style>
</head>
<body>
<div id="stage"></div>
<div class="vignette"></div>
<header>
<div class="eyebrow">Momentum laboratory</div>
<h1>Equal impulse.<br>Different force profiles.</h1>
<p>
Two identical carts begin with the same velocity. A longer, weaker pulse
and a shorter, stronger pulse remove exactly the same momentum.
</p>
</header>
<section class="panel" id="controls" aria-label="Simulation controls">
<div class="panel-title">
<span>Pulse controls</span>
<span class="badge">Equal area</span>
</div>
<div class="control">
<div class="control-row">
<label for="longDuration" class="long-text">Long pulse</label>
<output id="longOut"></output>
</div>
<input
id="longDuration"
type="range"
min="0.8"
max="5.5"
step="0.1"
value="4.0"
>
</div>
<div class="control">
<div class="control-row">
<label for="shortDuration" class="short-text">Short pulse</label>
<output id="shortOut"></output>
</div>
<input
id="shortDuration"
type="range"
min="0.4"
max="5.3"
step="0.1"
value="1.5"
>
</div>
<div class="control">
<div class="control-row">
<label for="initialSpeed">Common initial speed</label>
<output id="speedOut"></output>
</div>
<input
id="initialSpeed"
type="range"
min="2"
max="6"
step="0.1"
value="4"
>
</div>
<div class="control">
<div class="control-row">
<label for="rate">Simulation rate</label>
<output id="rateOut">1.0×</output>
</div>
<input
id="rate"
type="range"
min="0.5"
max="2.5"
step="0.25"
value="1"
>
</div>
<div class="button-row">
<button id="playButton" type="button">Run pulses</button>
<button id="resetButton" class="secondary" type="button">Reset</button>
</div>
<div class="status" id="status" aria-live="polite"></div>
</section>
<section class="panel" id="analysis" aria-label="Force-time and momentum analysis">
<div class="panel-title">
<span>Force–time profiles</span>
<span class="badge">Same area = same Δp</span>
</div>
<div class="chart-wrap">
<svg
id="forceChart"
viewBox="0 0 330 205"
role="img"
aria-label="Force versus time graph comparing a long pulse and a short pulse with equal impulse"
>
<defs>
<clipPath id="plotClip">
<rect x="43" y="13" width="273" height="151" rx="4"></rect>
</clipPath>
</defs>
<line class="chart-grid" x1="43" y1="45" x2="316" y2="45"></line>
<line class="chart-grid" x1="43" y1="86" x2="316" y2="86"></line>
<line class="chart-grid" x1="43" y1="127" x2="316" y2="127"></line>
<line class="chart-axis" x1="43" y1="13" x2="43" y2="164"></line>
<line class="chart-axis" x1="43" y1="164" x2="316" y2="164"></line>
<text class="chart-label" x="12" y="23">F</text>
<text class="chart-label" x="12" y="31">(N)</text>
<text class="chart-label" id="chartYMax" x="38" y="17" text-anchor="end"></text>
<text class="chart-label" id="chartXMax" x="316" y="181" text-anchor="end"></text>
<text class="chart-label" x="43" y="197">0</text>
<text class="chart-label" x="316" y="197" text-anchor="end">time (s)</text>
<g clip-path="url(#plotClip)">
<path id="longArea" class="pulse-area"></path>
<path id="shortArea" class="pulse-area"></path>
<line id="longProgress" class="progress-line"></line>
<line id="shortProgress" class="progress-line"></line>
<path id="longPulse" class="pulse-line"></path>
<path id="shortPulse" class="pulse-line"></path>
<circle id="longDot" r="4.5"></circle>
<circle id="shortDot" r="4.5"></circle>
</g>
<text id="longChartText" class="chart-label"></text>
<text id="shortChartText" class="chart-label"></text>
</svg>
</div>
<div class="legend">
<div class="legend-item">
<span class="swatch" style="background: var(--long)"></span>
Longer, lower force
</div>
<div class="legend-item">
<span class="swatch" style="background: var(--short)"></span>
Shorter, higher force
</div>
</div>
<div class="equation">
<span>J = F Δt</span>
<strong>Jlong = Jshort</strong>
<span>Δp = −J</span>
</div>
<div class="ledger">
<div class="ledger-title">
<span>Momentum ledger</span>
<strong id="commonDelta"></strong>
</div>
<div class="ledger-row">
<span class="long-text">Long</span>
<div class="meter"><i id="longMeter"></i></div>
<strong id="longMomentum"></strong>
</div>
<div class="ledger-row">
<span class="short-text">Short</span>
<div class="meter"><i id="shortMeter"></i></div>
<strong id="shortMomentum"></strong>
</div>
</div>
</section>
<div id="labelLong" class="world-label">
<b>LONG PULSE</b>
<span></span>
</div>
<div id="labelShort" class="world-label">
<b>SHORT PULSE</b>
<span></span>
</div>
<div id="instructions">Drag to orbit · Scroll to zoom</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);
// -------------------------------------------------------------------------
// Physical model
// -------------------------------------------------------------------------
const MASS = 1.25; // kg, identical carts
const START_X = -6.35;
const LONG_COLOR = 0x48d9ff;
const SHORT_COLOR = 0xffb454;
const settings = {
longDuration: 4.0,
shortDuration: 1.5,
initialSpeed: 4.0,
rate: 1.0
};
let simulationTime = 0;
let running = false;
let completed = false;
function impulse() {
return MASS * settings.initialSpeed;
}
function longForce() {
return impulse() / settings.longDuration;
}
function shortForce() {
return impulse() / settings.shortDuration;
}
// -------------------------------------------------------------------------
// Three.js scene
// -------------------------------------------------------------------------
const stage = $("stage");
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x07111f);
scene.fog = new THREE.Fog(0x07111f, 20, 37);
const camera = new THREE.PerspectiveCamera(
43,
window.innerWidth / window.innerHeight,
0.1,
100
);
const renderer = new THREE.WebGLRenderer({
antialias: true,
alpha: false,
powerPreference: "high-performance"
});
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.15;
stage.appendChild(renderer.domElement);
const hemi = new THREE.HemisphereLight(0xc9ecff, 0x101827, 2.1);
scene.add(hemi);
const keyLight = new THREE.DirectionalLight(0xffffff, 2.7);
keyLight.position.set(3, 10, 7);
keyLight.castShadow = true;
keyLight.shadow.mapSize.set(2048, 2048);
keyLight.shadow.camera.left = -14;
keyLight.shadow.camera.right = 14;
keyLight.shadow.camera.top = 10;
keyLight.shadow.camera.bottom = -10;
keyLight.shadow.camera.near = 0.5;
keyLight.shadow.camera.far = 35;
scene.add(keyLight);
const rimLight = new THREE.PointLight(0x5acbff, 28, 24, 2);
rimLight.position.set(-7, 5, -7);
scene.add(rimLight);
const warmLight = new THREE.PointLight(0xffaa55, 18, 20, 2);
warmLight.position.set(7, 3, 7);
scene.add(warmLight);
const groundMaterial = new THREE.MeshStandardMaterial({
color: 0x0c1726,
roughness: 0.94,
metalness: 0.02
});
const ground = new THREE.Mesh(
new THREE.BoxGeometry(30, 0.35, 17),
groundMaterial
);
ground.position.y = -0.49;
ground.receiveShadow = true;
scene.add(ground);
const grid = new THREE.GridHelper(28, 28, 0x29405a, 0x182b40);
grid.position.y = -0.305;
grid.material.transparent = true;
grid.material.opacity = 0.46;
scene.add(grid);
const laneZ = {
long: -2.05,
short: 2.05
};
const trackBaseMaterial = new THREE.MeshStandardMaterial({
color: 0x132337,
roughness: 0.78,
metalness: 0.18
});
const railMaterial = new THREE.MeshStandardMaterial({
color: 0x35506b,
roughness: 0.42,
metalness: 0.52
});
const tickMaterial = new THREE.MeshStandardMaterial({
color: 0x52708b,
roughness: 0.6,
metalness: 0.25
});
function createLane(z) {
const base = new THREE.Mesh(
new THREE.BoxGeometry(20, 0.12, 1.42),
trackBaseMaterial
);
base.position.set(0, -0.285, z);
base.receiveShadow = true;
scene.add(base);
[-0.58, 0.58].forEach((offset) => {
const rail = new THREE.Mesh(
new THREE.BoxGeometry(20, 0.075, 0.075),
railMaterial
);
rail.position.set(0, -0.195, z + offset);
rail.castShadow = true;
rail.receiveShadow = true;
scene.add(rail);
});
const startLine = new THREE.Mesh(
new THREE.BoxGeometry(0.07, 0.045, 1.15),
new THREE.MeshStandardMaterial({
color: 0xeaf7ff,
emissive: 0x446070,
emissiveIntensity: 0.35,
roughness: 0.5
})
);
startLine.position.set(START_X, -0.185, z);
scene.add(startLine);
}
createLane(laneZ.long);
createLane(laneZ.short);
for (let x = -6; x <= 6; x += 3) {
[-2.05, 2.05].forEach((z) => {
const tick = new THREE.Mesh(
new THREE.BoxGeometry(0.045, 0.035, 1.05),
tickMaterial
);
tick.position.set(x, -0.178, z);
scene.add(tick);
});
}
// Small, solid reference posts at the starting line.
const postMaterial = new THREE.MeshStandardMaterial({
color: 0x6b879f,
roughness: 0.45,
metalness: 0.5
});
[-2.05, 2.05].forEach((z) => {
const post = new THREE.Mesh(
new THREE.CylinderGeometry(0.07, 0.09, 1.2, 10),
postMaterial
);
post.position.set(START_X, 0.32, z - 0.85);
post.castShadow = true;
scene.add(post);
});
function createCart(color, z) {
const group = new THREE.Group();
const bodyMaterial = new THREE.MeshStandardMaterial({
color,
roughness: 0.38,
metalness: 0.18
});
const darkMaterial = new THREE.MeshStandardMaterial({
color: 0x132030,
roughness: 0.42,
metalness: 0.42
});
const windowMaterial = new THREE.MeshStandardMaterial({
color: 0xb9efff,
roughness: 0.18,
metalness: 0.05,
emissive: color,
emissiveIntensity: 0.08
});
const body = new THREE.Mesh(
new THREE.BoxGeometry(1.34, 0.42, 0.88),
bodyMaterial
);
body.position.y = 0.2;
body.castShadow = true;
body.receiveShadow = true;
group.add(body);
const lowerBody = new THREE.Mesh(
new THREE.BoxGeometry(1.46, 0.16, 0.94),
darkMaterial
);
lowerBody.position.y = -0.03;
lowerBody.castShadow = true;
group.add(lowerBody);
const cab = new THREE.Mesh(
new THREE.BoxGeometry(0.48, 0.43, 0.68),
bodyMaterial
);
cab.position.set(-0.12, 0.61, 0);
cab.castShadow = true;
group.add(cab);
const windowPane = new THREE.Mesh(
new THREE.BoxGeometry(0.51, 0.22, 0.71),
windowMaterial
);
windowPane.position.set(-0.12, 0.66, 0);
windowPane.castShadow = true;
group.add(windowPane);
const frontBumper = new THREE.Mesh(
new THREE.BoxGeometry(0.09, 0.18, 0.95),
darkMaterial
);
frontBumper.position.x = 0.735;
frontBumper.castShadow = true;
group.add(frontBumper);
const wheels = [];
const wheelGeometry = new THREE.CylinderGeometry(
0.19,
0.19,
0.13,
16
);
wheelGeometry.rotateX(Math.PI / 2);
[-0.43, 0.43].forEach((x) => {
[-0.49, 0.49].forEach((wheelZ) => {
const wheel = new THREE.Mesh(wheelGeometry, darkMaterial);
wheel.position.set(x, -0.09, wheelZ);
wheel.castShadow = true;
group.add(wheel);
wheels.push(wheel);
});
});
group.position.set(START_X, 0, z);
scene.add(group);
return { group, wheels };
}
function createForceArrow(color) {
const group = new THREE.Group();
const material = new THREE.MeshStandardMaterial({
color: 0xb8ff72,
emissive: 0x4e7d24,
emissiveIntensity: 0.7,
roughness: 0.38,
metalness: 0.12
});
const shaft = new THREE.Mesh(
new THREE.CylinderGeometry(0.055, 0.055, 1, 12),
material
);
shaft.rotation.z = Math.PI / 2;
shaft.castShadow = true;
group.add(shaft);
const cone = new THREE.Mesh(
new THREE.ConeGeometry(0.15, 0.3, 12),
material
);
cone.rotation.z = Math.PI / 2;
cone.castShadow = true;
group.add(cone);
group.visible = false;
scene.add(group);
return { group, shaft, cone };
}
const longCart = createCart(LONG_COLOR, laneZ.long);
const shortCart = createCart(SHORT_COLOR, laneZ.short);
const longArrow = createForceArrow(LONG_COLOR);
const shortArrow = createForceArrow(SHORT_COLOR);
// -------------------------------------------------------------------------
// Direct camera controls: no addons are used.
// -------------------------------------------------------------------------
const cameraState = {
target: new THREE.Vector3(-0.9, 0.15, 0),
radius: 15.8,
theta: 0.13,
phi: 1.02
};
function updateCamera() {
const { target, radius, theta, phi } = cameraState;
camera.position.set(
target.x + radius * Math.sin(phi) * Math.sin(theta),
target.y + radius * Math.cos(phi),
target.z + radius * Math.sin(phi) * Math.cos(theta)
);
camera.lookAt(target);
}
let dragging = false;
let previousX = 0;
let previousY = 0;
renderer.domElement.addEventListener("pointerdown", (event) => {
dragging = true;
previousX = event.clientX;
previousY = event.clientY;
renderer.domElement.setPointerCapture(event.pointerId);
});
renderer.domElement.addEventListener("pointermove", (event) => {
if (!dragging) return;
const dx = event.clientX - previousX;
const dy = event.clientY - previousY;
cameraState.theta -= dx * 0.005;
cameraState.phi = THREE.MathUtils.clamp(
cameraState.phi - dy * 0.005,
0.28,
1.38
);
previousX = event.clientX;
previousY = event.clientY;
updateCamera();
});
function endDrag(event) {
dragging = false;
if (
event.pointerId !== undefined &&
renderer.domElement.hasPointerCapture(event.pointerId)
) {
renderer.domElement.releasePointerCapture(event.pointerId);
}
}
renderer.domElement.addEventListener("pointerup", endDrag);
renderer.domElement.addEventListener("pointercancel", endDrag);
renderer.domElement.addEventListener("contextmenu", (event) => {
event.preventDefault();
});
renderer.domElement.addEventListener(
"wheel",
(event) => {
event.preventDefault();
cameraState.radius = THREE.MathUtils.clamp(
cameraState.radius + event.deltaY * 0.012,
8.5,
25
);
updateCamera();
},
{ passive: false }
);
updateCamera();
// -------------------------------------------------------------------------
// Force-time chart
// -------------------------------------------------------------------------
const plot = {
left: 43,
right: 316,
top: 13,
bottom: 164
};
let chartMaxTime = 1;
let chartMaxForce = 1;
function updateChart() {
const maxDuration = Math.max(
settings.longDuration,
settings.shortDuration
);
chartMaxTime = maxDuration * 1.08;
chartMaxForce =
Math.max(longForce(), shortForce()) * 1.18;
const timeToX = (time) =>
plot.left +
(time / chartMaxTime) * (plot.right - plot.left);
const forceToY = (force) =>
plot.bottom -
(force / chartMaxForce) * (plot.bottom - plot.top);
function pulsePath(duration, force) {
const x0 = timeToX(0);
const x1 = timeToX(duration);
const y0 = plot.bottom;
const y1 = forceToY(force);
return {
area: `M ${x0} ${y0} L ${x0} ${y1} L ${x1} ${y1} L ${x1} ${y0} Z`,
line: `M ${x0} ${y0} L ${x0} ${y1} L ${x1} ${y1} L ${x1} ${y0}`,
x1,
y1
};
}
const longPath = pulsePath(
settings.longDuration,
longForce()
);
const shortPath = pulsePath(
settings.shortDuration,
shortForce()
);
$("longArea").setAttribute("d", longPath.area);
$("longArea").setAttribute("fill", "#48d9ff");
$("longArea").setAttribute("opacity", "0.13");
$("shortArea").setAttribute("d", shortPath.area);
$("shortArea").setAttribute("fill", "#ffb454");
$("shortArea").setAttribute("opacity", "0.17");
$("longPulse").setAttribute("d", longPath.line);
$("longPulse").setAttribute("stroke", "#48d9ff");
$("shortPulse").setAttribute("d", shortPath.line);
$("shortPulse").setAttribute("stroke", "#ffb454");
$("longProgress").setAttribute("stroke", "#48d9ff");
$("shortProgress").setAttribute("stroke", "#ffb454");
$("longDot").setAttribute("fill", "#48d9ff");
$("shortDot").setAttribute("fill", "#ffb454");
$("longChartText").setAttribute("fill", "#48d9ff");
$("shortChartText").setAttribute("fill", "#ffb454");
$("longChartText").setAttribute(
"x",
Math.max(plot.left + 3, longPath.x1 - 5)
);
$("longChartText").setAttribute(
"y",
Math.max(plot.top + 10, longPath.y1 - 7)
);
$("longChartText").setAttribute("text-anchor", "end");
$("longChartText").textContent = `${longForce().toFixed(2)} N`;
$("shortChartText").setAttribute(
"x",
Math.min(plot.right - 3, shortPath.x1 - 5)
);
$("shortChartText").setAttribute(
"y",
Math.max(plot.top + 10, shortPath.y1 - 7)
);
$("shortChartText").setAttribute("text-anchor", "end");
$("shortChartText").textContent = `${shortForce().toFixed(2)} N`;
$("chartYMax").textContent = chartMaxForce.toFixed(1);
$("chartXMax").textContent = `${chartMaxTime.toFixed(1)} s`;
}
function updateChartProgress() {
const timeToX = (time) =>
plot.left +
(time / chartMaxTime) * (plot.right - plot.left);
const forceToY = (force) =>
plot.bottom -
(force / chartMaxForce) * (plot.bottom - plot.top);
function updateOne(prefix, duration, force) {
const effectiveTime = Math.min(simulationTime, duration);
const x = timeToX(effectiveTime);
const y = forceToY(force);
const progress = $(`${prefix}Progress`);
const dot = $(`${prefix}Dot`);
progress.setAttribute("x1", x);
progress.setAttribute("x2", x);
progress.setAttribute("y1", plot.bottom);
progress.setAttribute("y2", y);
progress.setAttribute(
"opacity",
simulationTime > duration ? "0.18" : "0.65"
);
dot.setAttribute("cx", x);
dot.setAttribute("cy", y);
}
updateOne("long", settings.longDuration, longForce());
updateOne("short", settings.shortDuration, shortForce());
}
// -------------------------------------------------------------------------
// UI and simulation state
// -------------------------------------------------------------------------
function formatNumber(value, digits = 2) {
return value.toFixed(digits);
}
function updateControlOutputs() {
$("longOut").textContent =
`${formatNumber(settings.longDuration, 1)} s · ` +
`${formatNumber(longForce())} N`;
$("shortOut").textContent =
`${formatNumber(settings.shortDuration, 1)} s · ` +
`${formatNumber(shortForce())} N`;
$("speedOut").textContent =
`${formatNumber(settings.initialSpeed, 1)} m/s`;
$("rateOut").textContent =
`${formatNumber(settings.rate, 2).replace(/0$/, "")}×`;
$("commonDelta").textContent =
`Δp = −${formatNumber(impulse())} N·s`;
}
function resetSimulation() {
simulationTime = 0;
running = false;
completed = false;
longCart.group.position.x = START_X;
shortCart.group.position.x = START_X;
longCart.wheels.forEach((wheel) => {
wheel.rotation.z = 0;
});
shortCart.wheels.forEach((wheel) => {
wheel.rotation.z = 0;
});
$("playButton").textContent = "Run pulses";
updateScene(0);
updateUI();
}
function toggleSimulation() {
if (completed) {
resetSimulation();
}
running = !running;
$("playButton").textContent = running ? "Pause" : "Resume";
updateUI();
}
$("playButton").addEventListener("click", toggleSimulation);
$("resetButton").addEventListener("click", resetSimulation);
$("longDuration").addEventListener("input", (event) => {
let value = Number(event.target.value);
// Keep the “long” pulse genuinely longer than the “short” pulse.
value = Math.max(value, settings.shortDuration + 0.2);
value = Math.min(value, 5.5);
event.target.value = value;
settings.longDuration = value;
updateControlOutputs();
updateChart();
resetSimulation();
});
$("shortDuration").addEventListener("input", (event) => {
let value = Number(event.target.value);
value = Math.min(value, settings.longDuration - 0.2);
value = Math.max(value, 0.4);
event.target.value = value;
settings.shortDuration = value;
updateControlOutputs();
updateChart();
resetSimulation();
});
$("initialSpeed").addEventListener("input", (event) => {
settings.initialSpeed = Number(event.target.value);
updateControlOutputs();
updateChart();
resetSimulation();
});
$("rate").addEventListener("input", (event) => {
settings.rate = Number(event.target.value);
updateControlOutputs();
});
function updateArrow(arrow, cart, z, force, active) {
arrow.group.visible = active;
if (!active) return;
const length = THREE.MathUtils.clamp(
0.58 + force * 0.25,
0.68,
1.85
);
arrow.shaft.scale.y = length;
arrow.shaft.position.x = -length / 2;
arrow.cone.position.x = -length - 0.13;
arrow.group.position.set(
cart.group.position.x + 0.72,
1.28,
z
);
}
function pulseState(time, duration) {
const clampedTime = THREE.MathUtils.clamp(
time,
0,
duration
);
const speed = settings.initialSpeed *
(1 - clampedTime / duration);
const displacement =
settings.initialSpeed * clampedTime -
(settings.initialSpeed /
(2 * duration)) * clampedTime * clampedTime;
return {
speed: Math.max(0, speed),
x: START_X + displacement,
active: time > 0 && time <= duration,
deliveredFraction: clampedTime / duration
};
}
function updateScene() {
const longState = pulseState(
simulationTime,
settings.longDuration
);
const shortState = pulseState(
simulationTime,
settings.shortDuration
);
longCart.group.position.x = longState.x;
shortCart.group.position.x = shortState.x;
const longDistance = longState.x - START_X;
const shortDistance = shortState.x - START_X;
longCart.wheels.forEach((wheel) => {
wheel.rotation.z = -longDistance / 0.19;
});
shortCart.wheels.forEach((wheel) => {
wheel.rotation.z = -shortDistance / 0.19;
});
updateArrow(
longArrow,
longCart,
laneZ.long,
longForce(),
longState.active
);
updateArrow(
shortArrow,
shortCart,
laneZ.short,
shortForce(),
shortState.active
);
updateChartProgress();
}
function updateWorldLabel(element, x, y, z) {
const projected = new THREE.Vector3(x, y, z).project(camera);
const visible =
projected.z > -1 &&
projected.z < 1 &&
Math.abs(projected.x) < 1.2 &&
Math.abs(projected.y) < 1.2;
element.style.display = visible ? "block" : "none";
if (!visible) return;
const screenX = (projected.x * 0.5 + 0.5) * window.innerWidth;
const screenY = (-projected.y * 0.5 + 0.5) * window.innerHeight;
element.style.left = `${screenX}px`;
element.style.top = `${screenY}px`;
}
function updateUI() {
const longState = pulseState(
simulationTime,
settings.longDuration
);
const shortState = pulseState(
simulationTime,
settings.shortDuration
);
const longMomentum = MASS * longState.speed;
const shortMomentum = MASS * shortState.speed;
$("longMomentum").textContent =
`p ${formatNumber(longMomentum)}`;
$("shortMomentum").textContent =
`p ${formatNumber(shortMomentum)}`;
$("longMeter").style.width =
`${longState.deliveredFraction * 100}%`;
$("shortMeter").style.width =
`${shortState.deliveredFraction * 100}%`;
$("labelLong").querySelector("span").textContent =
`${formatNumber(longState.speed)} m/s · ` +
`F ${formatNumber(longForce())} N`;
$("labelShort").querySelector("span").textContent =
`${formatNumber(shortState.speed)} m/s · ` +
`F ${formatNumber(shortForce())} N`;
if (completed) {
$("status").innerHTML =
`<strong>Both carts stopped.</strong> ` +
`Each changed momentum by −${formatNumber(impulse())} N·s.`;
} else if (running) {
const active = [];
if (longState.active) active.push("long");
if (shortState.active) active.push("short");
$("status").innerHTML =
`<strong>t = ${formatNumber(simulationTime)} s</strong> · ` +
(
active.length
? `${active.join(" and ")} pulse active`
: "Both carts stopped"
);
} else {
$("status").innerHTML =
`<strong>Ready.</strong> ` +
`Each pulse will deliver ${formatNumber(impulse())} N·s.`;
}
}
// -------------------------------------------------------------------------
// Animation loop
// -------------------------------------------------------------------------
let previousFrame = performance.now();
function animate(now) {
const delta = Math.min((now - previousFrame) / 1000, 0.05);
previousFrame = now;
if (running) {
simulationTime += delta * settings.rate;
const maximumTime = Math.max(
settings.longDuration,
settings.shortDuration
);
if (simulationTime >= maximumTime) {
simulationTime = maximumTime;
running = false;
completed = true;
$("playButton").textContent = "Run again";
}
}
updateScene();
updateUI();
updateWorldLabel(
$("labelLong"),
longCart.group.position.x,
1.82,
laneZ.long
);
updateWorldLabel(
$("labelShort"),
shortCart.group.position.x,
1.82,
laneZ.short
);
renderer.render(scene, camera);
requestAnimationFrame(animate);
}
function resize() {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
}
window.addEventListener("resize", resize);
updateControlOutputs();
updateChart();
resetSimulation();
requestAnimationFrame(animate);
</script>
</body>
</html>
```