Prompt specification
Build or customize the Three.js 3D scene "Force-history motion 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: Force-history motion explorer
Category: Voxel Worlds · Style: Voxel 3D
License: MIT · Reference: https://three3d.app/scene/force-history-motion-explorer-x1404
Scene Description Prompt:
Apply force pulses to a voxel cart and separately display position, velocity, and acceleration. Integrate motion consistently. Three.js from cdnjs, one HTML file.
Working Three.js Starter (force-history-motion-explorer-x1404):
```html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Voxel Dynamics — Force Pulse Lab</title>
<style>
:root {
color-scheme: dark;
--bg: #07111f;
--panel: rgba(10, 22, 38, 0.88);
--panel-border: rgba(130, 190, 255, 0.16);
--text: #eaf4ff;
--muted: #8ca3bd;
--cyan: #46dcff;
--green: #54f2a5;
--pink: #ff5db1;
--orange: #ffb347;
}
* {
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 {
font: inherit;
}
button {
color: inherit;
}
#scene-wrap {
position: fixed;
inset: 0;
}
#scene-wrap > canvas {
display: block;
width: 100%;
height: 100%;
touch-action: none;
outline: none;
}
.topbar {
position: fixed;
z-index: 10;
top: 16px;
left: 18px;
right: 18px;
display: flex;
align-items: center;
justify-content: space-between;
pointer-events: none;
}
.brand {
display: flex;
align-items: center;
gap: 12px;
padding: 10px 14px;
border: 1px solid var(--panel-border);
border-radius: 12px;
background: rgba(7, 17, 31, 0.72);
backdrop-filter: blur(12px);
}
.brand-mark {
width: 31px;
height: 31px;
border-radius: 7px;
background:
linear-gradient(135deg, var(--orange) 0 48%, transparent 48% 52%),
linear-gradient(135deg, #1b7894 0 48%, transparent 48% 52%),
#10263e;
box-shadow: 0 0 24px rgba(70, 220, 255, 0.18);
}
.brand h1 {
margin: 0;
font-size: 14px;
letter-spacing: 0.14em;
text-transform: uppercase;
}
.brand p {
margin: 3px 0 0;
color: var(--muted);
font-size: 11px;
}
.status {
display: flex;
align-items: center;
gap: 8px;
padding: 9px 12px;
border: 1px solid var(--panel-border);
border-radius: 999px;
background: rgba(7, 17, 31, 0.72);
color: var(--muted);
font-size: 11px;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.status-dot {
width: 7px;
height: 7px;
border-radius: 50%;
background: var(--green);
box-shadow: 0 0 12px var(--green);
}
.status-dot.paused {
background: var(--orange);
box-shadow: 0 0 12px var(--orange);
}
.panel {
position: fixed;
z-index: 8;
border: 1px solid var(--panel-border);
border-radius: 15px;
background: var(--panel);
box-shadow: 0 18px 60px rgba(0, 0, 0, 0.28);
backdrop-filter: blur(16px);
}
.control-panel {
top: 88px;
left: 18px;
width: 276px;
padding: 17px;
}
.telemetry-panel {
top: 88px;
right: 18px;
width: 324px;
padding: 13px;
max-height: calc(100vh - 108px);
overflow: auto;
scrollbar-width: thin;
}
.section-title {
margin: 0 0 13px;
color: var(--muted);
font-size: 10px;
font-weight: 750;
letter-spacing: 0.15em;
text-transform: uppercase;
}
.control-section + .control-section {
margin-top: 18px;
padding-top: 16px;
border-top: 1px solid rgba(130, 190, 255, 0.1);
}
.range-label {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 8px;
color: var(--muted);
font-size: 12px;
}
output {
color: var(--text);
font-variant-numeric: tabular-nums;
}
input[type="range"] {
width: 100%;
accent-color: var(--orange);
cursor: pointer;
}
.range-scale {
display: flex;
justify-content: space-between;
margin-top: 3px;
color: #647b95;
font-size: 9px;
}
.direction-pad {
display: grid;
grid-template-columns: repeat(3, 46px);
grid-template-rows: repeat(2, 42px);
justify-content: center;
gap: 7px;
margin: 12px 0 6px;
}
.dir-button {
border: 1px solid rgba(130, 190, 255, 0.18);
border-radius: 10px;
background: rgba(35, 66, 96, 0.4);
cursor: pointer;
font-size: 20px;
transition:
transform 100ms ease,
background 100ms ease,
border-color 100ms ease;
}
.dir-button:hover {
border-color: var(--orange);
background: rgba(255, 179, 71, 0.14);
transform: translateY(-1px);
}
.dir-button:active {
transform: translateY(1px) scale(0.96);
}
.dir-button[data-dir="forward"] {
grid-column: 2;
grid-row: 1;
}
.dir-button[data-dir="left"] {
grid-column: 1;
grid-row: 2;
}
.dir-button[data-dir="backward"] {
grid-column: 2;
grid-row: 2;
}
.dir-button[data-dir="right"] {
grid-column: 3;
grid-row: 2;
}
.hint {
margin: 9px 0 0;
color: var(--muted);
font-size: 11px;
line-height: 1.45;
}
.hint strong {
color: #d8e9fb;
font-weight: 600;
}
.button-row {
display: flex;
gap: 7px;
}
.action-button {
flex: 1;
min-height: 35px;
border: 1px solid rgba(130, 190, 255, 0.17);
border-radius: 9px;
background: rgba(28, 53, 78, 0.56);
color: #d8e9fb;
cursor: pointer;
font-size: 11px;
transition: background 120ms ease;
}
.action-button:hover {
background: rgba(49, 88, 121, 0.7);
}
.action-button.primary {
border-color: rgba(84, 242, 165, 0.28);
color: var(--green);
}
.readout {
display: grid;
grid-template-columns: 1fr auto;
gap: 8px;
margin-top: 8px;
color: var(--muted);
font-size: 11px;
}
.readout strong {
color: var(--text);
font-variant-numeric: tabular-nums;
}
.metric-card {
overflow: hidden;
border: 1px solid rgba(130, 190, 255, 0.1);
border-radius: 12px;
background: rgba(16, 34, 55, 0.62);
}
.metric-card + .metric-card {
margin-top: 10px;
}
.metric-header {
display: flex;
align-items: center;
justify-content: space-between;
padding: 11px 12px 8px;
}
.metric-name {
display: flex;
align-items: center;
gap: 8px;
font-size: 11px;
font-weight: 750;
letter-spacing: 0.12em;
text-transform: uppercase;
}
.metric-dot {
width: 8px;
height: 8px;
border-radius: 3px;
box-shadow: 0 0 12px currentColor;
}
.position .metric-dot {
color: var(--cyan);
background: var(--cyan);
}
.velocity .metric-dot {
color: var(--green);
background: var(--green);
}
.acceleration .metric-dot {
color: var(--pink);
background: var(--pink);
}
.metric-magnitude {
color: var(--muted);
font-size: 10px;
font-variant-numeric: tabular-nums;
}
.metric-vector {
padding: 0 12px 9px;
color: #dceaff;
font-family: "SFMono-Regular", Consolas, monospace;
font-size: 12px;
font-variant-numeric: tabular-nums;
}
.graph {
display: block;
width: 100%;
height: 68px;
background: rgba(4, 13, 24, 0.48);
}
.graph-key {
display: flex;
gap: 12px;
padding: 6px 12px 8px;
color: var(--muted);
font-size: 9px;
}
.graph-key span {
display: inline-flex;
align-items: center;
gap: 5px;
}
.key-x {
color: var(--cyan);
}
.key-z {
color: var(--orange);
}
.legend {
position: fixed;
z-index: 7;
left: 50%;
bottom: 18px;
transform: translateX(-50%);
display: flex;
gap: 16px;
align-items: center;
padding: 9px 14px;
border: 1px solid var(--panel-border);
border-radius: 999px;
background: rgba(7, 17, 31, 0.74);
backdrop-filter: blur(12px);
color: var(--muted);
font-size: 10px;
pointer-events: none;
}
.legend-item {
display: inline-flex;
align-items: center;
gap: 6px;
white-space: nowrap;
}
.legend-line {
width: 16px;
height: 2px;
border-radius: 2px;
}
.footer-help {
position: fixed;
z-index: 5;
left: 18px;
bottom: 17px;
color: rgba(166, 188, 211, 0.62);
font-size: 10px;
pointer-events: none;
}
@media (max-width: 900px) {
.control-panel {
top: auto;
bottom: 14px;
left: 12px;
width: 248px;
max-height: 48vh;
overflow: auto;
}
.telemetry-panel {
top: 78px;
right: 12px;
width: 278px;
}
.footer-help {
display: none;
}
.legend {
left: auto;
right: 12px;
bottom: 14px;
transform: none;
}
}
@media (max-width: 600px) {
.brand p,
.footer-help,
.legend {
display: none;
}
.topbar {
top: 8px;
left: 8px;
right: 8px;
}
.brand {
padding: 8px 10px;
}
.status {
padding: 8px 10px;
}
.control-panel {
left: 8px;
right: 8px;
bottom: 8px;
width: auto;
max-height: 39vh;
}
.telemetry-panel {
top: 70px;
right: 8px;
width: 218px;
max-height: 49vh;
}
.graph {
height: 50px;
}
.metric-vector {
font-size: 10px;
}
}
</style>
</head>
<body>
<div id="scene-wrap" aria-label="Interactive 3D voxel cart simulation"></div>
<header class="topbar">
<div class="brand">
<div class="brand-mark"></div>
<div>
<h1>Voxel Dynamics</h1>
<p>Force pulse laboratory</p>
</div>
</div>
<div class="status">
<span id="status-dot" class="status-dot"></span>
<span id="run-status">Simulation running</span>
</div>
</header>
<aside class="panel control-panel">
<section class="control-section">
<h2 class="section-title">Pulse Controls</h2>
<label class="range-label" for="force-range">
<span>Force magnitude</span>
<output id="force-output">90 N</output>
</label>
<input id="force-range" type="range" min="20" max="180" step="5" value="90" />
<div class="range-scale"><span>20 N</span><span>180 N</span></div>
<label class="range-label" for="duration-range" style="margin-top: 12px">
<span>Pulse duration</span>
<output id="duration-output">0.35 s</output>
</label>
<input id="duration-range" type="range" min="0.1" max="1" step="0.05" value="0.35" />
<div class="range-scale"><span>0.10 s</span><span>1.00 s</span></div>
</section>
<section class="control-section">
<h2 class="section-title">Camera-Relative Direction</h2>
<div class="direction-pad">
<button class="dir-button" data-dir="forward" title="Pulse forward">↑</button>
<button class="dir-button" data-dir="left" title="Pulse left">←</button>
<button class="dir-button" data-dir="backward" title="Pulse backward">↓</button>
<button class="dir-button" data-dir="right" title="Pulse right">→</button>
</div>
<p class="hint">
<strong>Click the ground</strong> to pulse toward that point.
Keyboard: <strong>WASD</strong> or arrow keys.
</p>
</section>
<section class="control-section">
<h2 class="section-title">Simulation</h2>
<div class="button-row">
<button id="pause-button" class="action-button primary">Pause</button>
<button id="reset-button" class="action-button">Reset</button>
<button id="clear-button" class="action-button">Clear pulses</button>
</div>
<div class="readout">
<span>Active pulses</span><strong id="pulse-readout">0</strong>
</div>
<div class="readout">
<span>Net force</span><strong id="force-readout">0.0 N</strong>
</div>
<div class="readout">
<span>Cart mass</span><strong>8.0 kg</strong>
</div>
<div class="readout">
<span>Integrator</span><strong>120 Hz semi-implicit</strong>
</div>
<p class="hint">
Planar X–Z model. Linear drag is included as a force.
Left drag orbits, right drag pans, and the wheel zooms.
</p>
</section>
</aside>
<aside class="panel telemetry-panel">
<h2 class="section-title">Separate State Readouts</h2>
<section class="metric-card position">
<div class="metric-header">
<div class="metric-name"><span class="metric-dot"></span>Position</div>
<div id="position-magnitude" class="metric-magnitude">r = 0.00 m</div>
</div>
<div id="position-vector" class="metric-vector">[ +0.00, 0.00, +0.00 ] m</div>
<canvas id="position-graph" class="graph"></canvas>
<div class="graph-key">
<span class="key-x">━ X position</span>
<span class="key-z">━ Z position</span>
</div>
</section>
<section class="metric-card velocity">
<div class="metric-header">
<div class="metric-name"><span class="metric-dot"></span>Velocity</div>
<div id="velocity-magnitude" class="metric-magnitude">|v| = 0.00 m/s</div>
</div>
<div id="velocity-vector" class="metric-vector">[ +0.00, 0.00, +0.00 ] m/s</div>
<canvas id="velocity-graph" class="graph"></canvas>
<div class="graph-key">
<span class="key-x">━ X velocity</span>
<span class="key-z">━ Z velocity</span>
</div>
</section>
<section class="metric-card acceleration">
<div class="metric-header">
<div class="metric-name"><span class="metric-dot"></span>Acceleration</div>
<div id="acceleration-magnitude" class="metric-magnitude">|a| = 0.00 m/s²</div>
</div>
<div id="acceleration-vector" class="metric-vector">[ +0.00, 0.00, +0.00 ] m/s²</div>
<canvas id="acceleration-graph" class="graph"></canvas>
<div class="graph-key">
<span class="key-x">━ X acceleration</span>
<span class="key-z">━ Z acceleration</span>
</div>
</section>
</aside>
<div class="legend">
<span class="legend-item"><i class="legend-line" style="background:#54f2a5"></i>Velocity</span>
<span class="legend-item"><i class="legend-line" style="background:#ff5db1"></i>Acceleration</span>
<span class="legend-item"><i class="legend-line" style="background:#ffb347"></i>Net force</span>
<span class="legend-item"><i class="legend-line" style="background:#46dcff"></i>Position</span>
</div>
<div class="footer-help">Drag to orbit · Right-drag to pan · Scroll to zoom · Space to pause</div>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
// -------------------------------------------------------------------------
// DOM references
// -------------------------------------------------------------------------
const sceneWrap = document.querySelector("#scene-wrap");
const forceRange = document.querySelector("#force-range");
const durationRange = document.querySelector("#duration-range");
const forceOutput = document.querySelector("#force-output");
const durationOutput = document.querySelector("#duration-output");
const pauseButton = document.querySelector("#pause-button");
const resetButton = document.querySelector("#reset-button");
const clearButton = document.querySelector("#clear-button");
const runStatus = document.querySelector("#run-status");
const statusDot = document.querySelector("#status-dot");
const pulseReadout = document.querySelector("#pulse-readout");
const forceReadout = document.querySelector("#force-readout");
const positionVectorElement = document.querySelector("#position-vector");
const positionMagnitudeElement = document.querySelector("#position-magnitude");
const velocityVectorElement = document.querySelector("#velocity-vector");
const velocityMagnitudeElement = document.querySelector("#velocity-magnitude");
const accelerationVectorElement = document.querySelector("#acceleration-vector");
const accelerationMagnitudeElement = document.querySelector("#acceleration-magnitude");
const positionGraph = document.querySelector("#position-graph");
const velocityGraph = document.querySelector("#velocity-graph");
const accelerationGraph = document.querySelector("#acceleration-graph");
// -------------------------------------------------------------------------
// Renderer, scene, camera
// -------------------------------------------------------------------------
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x07111f);
scene.fog = new THREE.Fog(0x07111f, 24, 68);
const camera = new THREE.PerspectiveCamera(
48,
window.innerWidth / window.innerHeight,
0.1,
160
);
const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.08;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.domElement.tabIndex = 0;
sceneWrap.appendChild(renderer.domElement);
const hemisphereLight = new THREE.HemisphereLight(0xb9ddff, 0x172033, 2.15);
scene.add(hemisphereLight);
const keyLight = new THREE.DirectionalLight(0xffffff, 3.1);
keyLight.position.set(7, 13, 5);
keyLight.castShadow = true;
keyLight.shadow.mapSize.set(2048, 2048);
keyLight.shadow.camera.left = -22;
keyLight.shadow.camera.right = 22;
keyLight.shadow.camera.top = 22;
keyLight.shadow.camera.bottom = -22;
keyLight.shadow.camera.near = 1;
keyLight.shadow.camera.far = 45;
keyLight.shadow.bias = -0.00015;
scene.add(keyLight);
const rimLight = new THREE.DirectionalLight(0x38bfff, 1.15);
rimLight.position.set(-8, 5, -9);
scene.add(rimLight);
// -------------------------------------------------------------------------
// Ground
// -------------------------------------------------------------------------
const ground = new THREE.Mesh(
new THREE.PlaneGeometry(120, 120),
new THREE.MeshStandardMaterial({
color: 0x081421,
roughness: 0.96,
metalness: 0.05
})
);
ground.rotation.x = -Math.PI / 2;
ground.receiveShadow = true;
scene.add(ground);
const grid = new THREE.GridHelper(80, 80, 0x28506d, 0x173047);
grid.position.y = 0.008;
grid.material.transparent = true;
grid.material.opacity = 0.32;
scene.add(grid);
// -------------------------------------------------------------------------
// Voxel cart
// -------------------------------------------------------------------------
const cart = new THREE.Group();
scene.add(cart);
const wheelMeshes = [];
function addVoxel(parent, size, position, color, options = {}) {
const geometry = new THREE.BoxGeometry(size.x, size.y, size.z);
const material = new THREE.MeshStandardMaterial({
color,
roughness: options.roughness ?? 0.72,
metalness: options.metalness ?? 0.08,
emissive: options.emissive ?? 0x000000,
emissiveIntensity: options.emissiveIntensity ?? 0
});
const mesh = new THREE.Mesh(geometry, material);
mesh.position.copy(position);
mesh.castShadow = true;
mesh.receiveShadow = true;
parent.add(mesh);
return mesh;
}
const chassisMaterial = new THREE.MeshStandardMaterial({
color: 0x25384a,
roughness: 0.56,
metalness: 0.35
});
const chassis = new THREE.Mesh(
new THREE.BoxGeometry(1.42, 0.22, 0.9),
chassisMaterial
);
chassis.position.y = 0.41;
chassis.castShadow = true;
chassis.receiveShadow = true;
cart.add(chassis);
const bodyMaterial = new THREE.MeshStandardMaterial({
color: 0xff9f32,
roughness: 0.55,
metalness: 0.1,
emissive: 0x6f2500,
emissiveIntensity: 0.09
});
addVoxel(
cart,
new THREE.Vector3(1.18, 0.36, 0.73),
new THREE.Vector3(0, 0.69, 0),
0xff9f32,
{ emissive: 0x6f2500, emissiveIntensity: 0.09 }
).material = bodyMaterial;
addVoxel(
cart,
new THREE.Vector3(0.43, 0.43, 0.48),
new THREE.Vector3(-0.27, 1.06, -0.03),
0x42c9e8,
{ emissive: 0x063643, emissiveIntensity: 0.18 }
);
addVoxel(
cart,
new THREE.Vector3(0.43, 0.43, 0.48),
new THREE.Vector3(0.27, 1.06, -0.03),
0xe75b67,
{ emissive: 0x3c0710, emissiveIntensity: 0.14 }
);
addVoxel(
cart,
new THREE.Vector3(0.38, 0.34, 0.42),
new THREE.Vector3(0, 1.43, -0.03),
0xffd36b,
{ emissive: 0x4b2d00, emissiveIntensity: 0.12 }
);
const wheelMaterial = new THREE.MeshStandardMaterial({
color: 0x101923,
roughness: 0.82,
metalness: 0.12
});
const hubMaterial = new THREE.MeshStandardMaterial({
color: 0x8ea7b8,
roughness: 0.4,
metalness: 0.65
});
for (const x of [-0.73, 0.73]) {
for (const z of [-0.48, 0.48]) {
const wheel = addVoxel(
cart,
new THREE.Vector3(0.24, 0.34, 0.34),
new THREE.Vector3(x, 0.22, z),
0x101923,
{ roughness: 0.82 }
);
wheel.material = wheelMaterial;
wheelMeshes.push(wheel);
addVoxel(
cart,
new THREE.Vector3(0.26, 0.12, 0.12),
new THREE.Vector3(x, 0.22, z),
0x8ea7b8,
{ roughness: 0.4, metalness: 0.65 }
).material = hubMaterial;
}
}
// Front-facing sensor.
addVoxel(
cart,
new THREE.Vector3(0.28, 0.12, 0.06),
new THREE.Vector3(0, 0.75, 0.395),
0x72efff,
{ emissive: 0x1abbd4, emissiveIntensity: 1.1 }
);
const pulseLight = new THREE.PointLight(0xff9f32, 0, 7, 2);
pulseLight.position.set(0, 1.2, 0);
cart.add(pulseLight);
// Soft contact shadow.
const shadow = new THREE.Mesh(
new THREE.CircleGeometry(1.0, 40),
new THREE.MeshBasicMaterial({
color: 0x000000,
transparent: true,
opacity: 0.25,
depthWrite: false
})
);
shadow.rotation.x = -Math.PI / 2;
shadow.position.y = 0.014;
scene.add(shadow);
// Position marker on the ground.
const positionMarker = new THREE.Mesh(
new THREE.RingGeometry(0.12, 0.18, 32),
new THREE.MeshBasicMaterial({
color: 0x46dcff,
transparent: true,
opacity: 0.9,
side: THREE.DoubleSide,
depthWrite: false
})
);
positionMarker.rotation.x = -Math.PI / 2;
positionMarker.position.y = 0.025;
scene.add(positionMarker);
// -------------------------------------------------------------------------
// State arrows
// -------------------------------------------------------------------------
const velocityArrow = new THREE.ArrowHelper(
new THREE.Vector3(1, 0, 0),
new THREE.Vector3(),
1,
0x54f2a5,
0.28,
0.16
);
const accelerationArrow = new THREE.ArrowHelper(
new THREE.Vector3(1, 0, 0),
new THREE.Vector3(),
1,
0xff5db1,
0.28,
0.16
);
const forceArrow = new THREE.ArrowHelper(
new THREE.Vector3(1, 0, 0),
new THREE.Vector3(),
1,
0xffb347,
0.28,
0.16
);
scene.add(velocityArrow, accelerationArrow, forceArrow);
// -------------------------------------------------------------------------
// Trail
// -------------------------------------------------------------------------
const trailPoints = [];
const trailGeometry = new THREE.BufferGeometry().setFromPoints([
new THREE.Vector3(),
new THREE.Vector3()
]);
const trail = new THREE.Line(
trailGeometry,
new THREE.LineBasicMaterial({
color: 0x46dcff,
transparent: true,
opacity: 0.56
})
);
scene.add(trail);
// -------------------------------------------------------------------------
// Physics state
//
// Fixed-step semi-implicit Euler:
// a[n] = F[n] / m
// v[n+1] = v[n] + a[n] * dt
// x[n+1] = x[n] + v[n+1] * dt
//
// All active pulses and linear drag are evaluated on the same fixed step.
// -------------------------------------------------------------------------
const MASS = 8;
const LINEAR_DRAG = 1.25; // N per (m/s)
const FIXED_DT = 1 / 120;
const MAX_FRAME_DT = 0.05;
const state = {
position: new THREE.Vector3(),
velocity: new THREE.Vector3(),
acceleration: new THREE.Vector3()
};
const activePulses = [];
const pulseEffects = [];
const history = {
position: [],
velocity: [],
acceleration: []
};
let accumulator = 0;
let sampleClock = 0;
let paused = false;
let desiredHeading = 0;
let currentHeading = 0;
const netForce = new THREE.Vector3();
function applyPulse(direction) {
const pulseDirection = direction.clone();
pulseDirection.y = 0;
if (pulseDirection.lengthSq() < 0.000001) return;
pulseDirection.normalize();
const force = Number(forceRange.value);
const duration = Number(durationRange.value);
activePulses.push({
direction: pulseDirection,
force,
remaining: duration,
totalDuration: duration
});
desiredHeading = Math.atan2(pulseDirection.x, pulseDirection.z);
createPulseEffect();
}
function createPulseEffect() {
const material = new THREE.MeshBasicMaterial({
color: 0xffb347,
transparent: true,
opacity: 0.9,
side: THREE.DoubleSide,
depthWrite: false
});
const ring = new THREE.Mesh(
new THREE.RingGeometry(0.34, 0.43, 32),
material
);
ring.rotation.x = -Math.PI / 2;
ring.position.set(state.position.x, 0.03, state.position.z);
scene.add(ring);
pulseEffects.push({
mesh: ring,
life: 0.55,
maxLife: 0.55
});
}
function stepPhysics(dt) {
netForce.set(0, 0, 0);
// Sum every force that is active during this step.
for (const pulse of activePulses) {
netForce.addScaledVector(pulse.direction, pulse.force);
}
// Linear drag is a force, so it participates in the same acceleration.
netForce.addScaledVector(state.velocity, -LINEAR_DRAG);
state.acceleration.copy(netForce).divideScalar(MASS);
// Semi-implicit Euler: update velocity before position.
state.velocity.addScaledVector(state.acceleration, dt);
state.position.addScaledVector(state.velocity, dt);
// The model is constrained to the ground plane.
state.position.y = 0;
// Consume pulse time only on fixed physics steps.
for (let i = activePulses.length - 1; i >= 0; i--) {
activePulses[i].remaining -= dt;
if (activePulses[i].remaining <= 0) {
activePulses.splice(i, 1);
}
}
sampleClock += dt;
if (sampleClock >= 0.05) {
sampleClock -= 0.05;
recordHistory();
}
}
function recordHistory() {
const maxSamples = 240;
history.position.push({
x: state.position.x,
z: state.position.z
});
history.velocity.push({
x: state.velocity.x,
z: state.velocity.z
});
history.acceleration.push({
x: state.acceleration.x,
z: state.acceleration.z
});
for (const key of Object.keys(history)) {
if (history[key].length > maxSamples) {
history[key].shift();
}
}
trailPoints.push(state.position.clone());
if (trailPoints.length > 300) trailPoints.shift();
trailGeometry.setFromPoints(trailPoints);
trailGeometry.setDrawRange(0, trailPoints.length);
}
function resetSimulation() {
state.position.set(0, 0, 0);
state.velocity.set(0, 0, 0);
state.acceleration.set(0, 0, 0);
activePulses.length = 0;
pulseEffects.length = 0;
accumulator = 0;
sampleClock = 0;
desiredHeading = 0;
currentHeading = 0;
history.position.length = 0;
history.velocity.length = 0;
history.acceleration.length = 0;
trailPoints.length = 0;
trailPoints.push(state.position.clone(), state.position.clone());
trailGeometry.setFromPoints(trailPoints);
recordHistory();
updateTelemetry();
}
// -------------------------------------------------------------------------
// Custom camera controls
// -------------------------------------------------------------------------
const cameraTarget = new THREE.Vector3(0, 0.8, 0);
let cameraRadius = 16;
let cameraTheta = 0.72;
let cameraPhi = 1.03;
const spherical = new THREE.Spherical();
const cameraOffset = new THREE.Vector3();
function updateCamera() {
spherical.set(cameraRadius, cameraPhi, cameraTheta);
cameraOffset.setFromSpherical(spherical);
camera.position.copy(cameraTarget).add(cameraOffset);
camera.lookAt(cameraTarget);
}
updateCamera();
const pointerState = {
down: false,
button: 0,
id: -1,
startX: 0,
startY: 0,
previousX: 0,
previousY: 0,
moved: 0
};
const raycaster = new THREE.Raycaster();
const pointerNDC = new THREE.Vector2();
renderer.domElement.addEventListener("contextmenu", event => {
event.preventDefault();
});
renderer.domElement.addEventListener("pointerdown", event => {
pointerState.down = true;
pointerState.button = event.button;
pointerState.id = event.pointerId;
pointerState.startX = event.clientX;
pointerState.startY = event.clientY;
pointerState.previousX = event.clientX;
pointerState.previousY = event.clientY;
pointerState.moved = 0;
renderer.domElement.setPointerCapture(event.pointerId);
});
renderer.domElement.addEventListener("pointermove", event => {
if (!pointerState.down || event.pointerId !== pointerState.id) return;
const dx = event.clientX - pointerState.previousX;
const dy = event.clientY - pointerState.previousY;
pointerState.previousX = event.clientX;
pointerState.previousY = event.clientY;
pointerState.moved += Math.hypot(dx, dy);
if (pointerState.button === 0) {
cameraTheta -= dx * 0.005;
cameraPhi = THREE.MathUtils.clamp(
cameraPhi - dy * 0.005,
0.24,
1.38
);
} else if (pointerState.button === 2) {
const forward = new THREE.Vector3();
camera.getWorldDirection(forward);
const right = new THREE.Vector3()
.crossVectors(forward, camera.up)
.normalize();
const cameraUp = new THREE.Vector3()
.crossVectors(right, forward)
.normalize();
const scale = cameraRadius * 0.0016;
cameraTarget.addScaledVector(right, -dx * scale);
cameraTarget.addScaledVector(cameraUp, dy * scale);
}
updateCamera();
});
renderer.domElement.addEventListener("pointerup", event => {
if (!pointerState.down || event.pointerId !== pointerState.id) return;
const wasClick =
pointerState.button === 0 && pointerState.moved < 6;
pointerState.down = false;
if (renderer.domElement.hasPointerCapture(event.pointerId)) {
renderer.domElement.releasePointerCapture(event.pointerId);
}
if (wasClick) pulseTowardScreenPoint(event.clientX, event.clientY);
});
renderer.domElement.addEventListener("pointercancel", event => {
pointerState.down = false;
if (renderer.domElement.hasPointerCapture(event.pointerId)) {
renderer.domElement.releasePointerCapture(event.pointerId);
}
});
renderer.domElement.addEventListener(
"wheel",
event => {
event.preventDefault();
cameraRadius = THREE.MathUtils.clamp(
cameraRadius * Math.exp(event.deltaY * 0.001),
5,
42
);
updateCamera();
},
{ passive: false }
);
function pulseTowardScreenPoint(clientX, clientY) {
const rect = renderer.domElement.getBoundingClientRect();
pointerNDC.x = ((clientX - rect.left) / rect.width) * 2 - 1;
pointerNDC.y = -((clientY - rect.top) / rect.height) * 2 + 1;
raycaster.setFromCamera(pointerNDC, camera);
const hit = raycaster.intersectObject(ground, false)[0];
if (!hit) return;
const direction = hit.point.clone().sub(state.position);
direction.y = 0;
if (direction.length() < 0.7) return;
applyPulse(direction);
}
// -------------------------------------------------------------------------
// Direction controls and keyboard
// -------------------------------------------------------------------------
function getCameraRelativeDirection(name) {
const forward = cameraTarget.clone().sub(camera.position);
forward.y = 0;
forward.normalize();
const right = new THREE.Vector3(-forward.z, 0, forward.x);
switch (name) {
case "forward":
return forward;
case "backward":
return forward.clone().negate();
case "left":
return right.clone().negate();
case "right":
return right;
default:
return forward;
}
}
document.querySelectorAll("[data-dir]").forEach(button => {
button.addEventListener("click", () => {
applyPulse(getCameraRelativeDirection(button.dataset.dir));
});
});
window.addEventListener("keydown", event => {
const tag = event.target?.tagName;
if (["INPUT", "TEXTAREA", "SELECT"].includes(tag)) return;
if (event.repeat) return;
const keyDirections = {
KeyW: "forward",
ArrowUp: "forward",
KeyS: "backward",
ArrowDown: "backward",
KeyA: "left",
ArrowLeft: "left",
KeyD: "right",
ArrowRight: "right"
};
if (keyDirections[event.code]) {
event.preventDefault();
applyPulse(getCameraRelativeDirection(keyDirections[event.code]));
}
if (event.code === "Space") {
event.preventDefault();
togglePause();
}
if (event.code === "KeyR") {
resetSimulation();
}
});
forceRange.addEventListener("input", () => {
forceOutput.textContent = `${forceRange.value} N`;
});
durationRange.addEventListener("input", () => {
durationOutput.textContent = `${Number(durationRange.value).toFixed(2)} s`;
});
function togglePause() {
paused = !paused;
accumulator = 0;
pauseButton.textContent = paused ? "Resume" : "Pause";
runStatus.textContent = paused ? "Simulation paused" : "Simulation running";
statusDot.classList.toggle("paused", paused);
}
pauseButton.addEventListener("click", togglePause);
resetButton.addEventListener("click", resetSimulation);
clearButton.addEventListener("click", () => {
activePulses.length = 0;
updateTelemetry();
});
// -------------------------------------------------------------------------
// Telemetry and graphs
// -------------------------------------------------------------------------
function signed(value, digits = 2) {
const threshold = 0.5 * Math.pow(10, -digits);
const normalized = Math.abs(value) < threshold ? 0 : value;
return `${normalized >= 0 ? "+" : ""}${normalized.toFixed(digits)}`;
}
function updateTelemetry() {
const positionMagnitude = Math.hypot(
state.position.x,
state.position.z
);
const speed = state.velocity.length();
const accelerationMagnitude = state.acceleration.length();
const forceMagnitude = netForce.length();
positionVectorElement.textContent =
`[ ${signed(state.position.x)}, 0.00, ${signed(state.position.z)} ] m`;
positionMagnitudeElement.textContent =
`r = ${positionMagnitude.toFixed(2)} m`;
velocityVectorElement.textContent =
`[ ${signed(state.velocity.x)}, 0.00, ${signed(state.velocity.z)} ] m/s`;
velocityMagnitudeElement.textContent =
`|v| = ${speed.toFixed(2)} m/s`;
accelerationVectorElement.textContent =
`[ ${signed(state.acceleration.x)}, 0.00, ${signed(state.acceleration.z)} ] m/s²`;
accelerationMagnitudeElement.textContent =
`|a| = ${accelerationMagnitude.toFixed(2)} m/s²`;
pulseReadout.textContent = String(activePulses.length);
forceReadout.textContent = `${forceMagnitude.toFixed(1)} N`;
drawGraph(positionGraph, history.position);
drawGraph(velocityGraph, history.velocity);
drawGraph(accelerationGraph, history.acceleration);
}
function drawGraph(canvas, entries) {
const rect = canvas.getBoundingClientRect();
if (rect.width < 2 || rect.height < 2) return;
const dpr = Math.min(window.devicePixelRatio || 1, 2);
const pixelWidth = Math.round(rect.width * dpr);
const pixelHeight = Math.round(rect.height * dpr);
if (canvas.width !== pixelWidth || canvas.height !== pixelHeight) {
canvas.width = pixelWidth;
canvas.height = pixelHeight;
}
const context = canvas.getContext("2d");
context.setTransform(dpr, 0, 0, dpr, 0, 0);
const width = rect.width;
const height = rect.height;
context.clearRect(0, 0, width, height);
context.fillStyle = "rgba(4, 13, 24, 0.45)";
context.fillRect(0, 0, width, height);
let maxAbs = 0.05;
for (const entry of entries) {
maxAbs = Math.max(maxAbs, Math.abs(entry.x), Math.abs(entry.z));
}
const range = maxAbs * 1.18;
const paddingX = 8;
const paddingY = 8;
const plotWidth = width - paddingX * 2;
const plotHeight = height - paddingY * 2;
const centerY = height / 2;
context.strokeStyle = "rgba(130, 190, 255, 0.10)";
context.lineWidth = 1;
for (let i = 0; i <= 4; i++) {
const y = paddingY + (plotHeight * i) / 4;
context.beginPath();
context.moveTo(paddingX, y);
context.lineTo(width - paddingX, y);
context.stroke();
}
context.strokeStyle = "rgba(180, 215, 240, 0.2)";
context.beginPath();
context.moveTo(paddingX, centerY);
context.lineTo(width - paddingX, centerY);
context.stroke();
if (entries.length === 0) return;
function plotChannel(key, color) {
context.strokeStyle = color;
context.lineWidth = 1.6;
context.beginPath();
entries.forEach((entry, index) => {
const x =
paddingX +
(plotWidth * index) / Math.max(1, entries.length - 1);
const y =
centerY -
(entry[key] / range) * (plotHeight / 2);
if (index === 0) context.moveTo(x, y);
else context.lineTo(x, y);
});
context.stroke();
}
plotChannel("x", "#46dcff");
plotChannel("z", "#ffb347");
}
// -------------------------------------------------------------------------
// Visual updates
// -------------------------------------------------------------------------
function updateArrow(helper, vector, origin, scale, minimum, maximum) {
const magnitude = vector.length();
if (magnitude < 0.015) {
helper.visible = false;
return;
}
helper.visible = true;
helper.position.copy(origin);
helper.setDirection(vector.clone().normalize());
const length = THREE.MathUtils.clamp(
magnitude * scale,
minimum,
maximum
);
helper.setLength(
length,
Math.min(0.3, length * 0.3),
Math.min(0.17, length * 0.16)
);
}
function updateVisuals(frameDt) {
cart.position.set(state.position.x, 0, state.position.z);
shadow.position.set(state.position.x, 0.014, state.position.z);
positionMarker.position.set(state.position.x, 0.025, state.position.z);
const speed = state.velocity.length();
if (speed > 0.04) {
desiredHeading = Math.atan2(state.velocity.x, state.velocity.z);
}
const headingDifference = Math.atan2(
Math.sin(desiredHeading - currentHeading),
Math.cos(desiredHeading - currentHeading)
);
currentHeading +=
headingDifference * (1 - Math.exp(-9 * frameDt));
cart.rotation.y = currentHeading;
for (const wheel of wheelMeshes) {
wheel.rotation.x -= (speed * frameDt) / 0.22;
}
const pulseGlow = activePulses.length > 0;
bodyMaterial.emissiveIntensity = pulseGlow ? 0.36 : 0.09;
pulseLight.intensity = pulseGlow ? 2.4 : 0;
const origin = new THREE.Vector3(
state.position.x,
0,
state.position.z
);
const velocityOrigin = origin.clone().setY(1.72);
const accelerationOrigin = origin.clone().add(
new THREE.Vector3(-0.38, 0.76, 0)
);
const forceOrigin = origin.clone().add(
new THREE.Vector3(0.38, 0.76, 0)
);
updateArrow(
velocityArrow,
state.velocity,
velocityOrigin,
0.65,
0.35,
4.5
);
updateArrow(
accelerationArrow,
state.acceleration,
accelerationOrigin,
0.17,
0.28,
3.2
);
updateArrow(
forceArrow,
netForce,
forceOrigin,
0.025,
0.28,
3.7
);
}
function updatePulseEffects(frameDt) {
for (let i = pulseEffects.length - 1; i >= 0; i--) {
const effect = pulseEffects[i];
effect.life -= frameDt;
if (effect.life <= 0) {
scene.remove(effect.mesh);
effect.mesh.geometry.dispose();
effect.mesh.material.dispose();
pulseEffects.splice(i, 1);
continue;
}
const progress = 1 - effect.life / effect.maxLife;
const scale = 1 + progress * 3.3;
effect.mesh.scale.setScalar(scale);
effect.mesh.material.opacity = 0.9 * (1 - progress);
}
}
// -------------------------------------------------------------------------
// Main loop
// -------------------------------------------------------------------------
const clock = new THREE.Clock();
let telemetryClock = 0;
function animate() {
requestAnimationFrame(animate);
const frameDt = Math.min(clock.getDelta(), MAX_FRAME_DT);
if (!paused) {
accumulator += frameDt;
let stepCount = 0;
while (accumulator >= FIXED_DT && stepCount < 12) {
stepPhysics(FIXED_DT);
accumulator -= FIXED_DT;
stepCount++;
}
}
updateVisuals(frameDt);
updatePulseEffects(frameDt);
telemetryClock += frameDt;
if (telemetryClock >= 1 / 20) {
telemetryClock = 0;
updateTelemetry();
}
renderer.render(scene, camera);
}
window.addEventListener("resize", () => {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
updateTelemetry();
});
resetSimulation();
animate();
</script>
</body>
</html>
```