Prompt specification
Build or customize the Three.js 3D scene "Controller-gain exploration rig" 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: Controller-gain exploration rig
Category: Voxel Worlds · Style: Voxel 3D
License: MIT · Reference: https://three3d.app/scene/controller-gain-exploration-rig-x1872
Scene Description Prompt:
Build a self-contained HTML scene with Three.js from cdnjs featuring feedback control around a target value. Let users vary proportional gain and damping in a defined linear system; show settling, oscillation, or instability honestly and prevent unstable values from crashing the visualization. Voxel style.
Working Three.js Starter (controller-gain-exploration-rig-x1872):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Voxel Feedback Control Lab</title>
<style>
:root {
color-scheme: dark;
--bg: #061018;
--panel: rgba(7, 19, 27, 0.9);
--border: rgba(116, 211, 238, 0.18);
--muted: #8199a7;
--text: #e7f6fb;
--cyan: #48dcff;
--green: #53f5a5;
--orange: #ffb454;
--red: #ff667d;
}
* {
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, monospace;
}
canvas.webgl {
position: fixed;
inset: 0;
display: block;
width: 100%;
height: 100%;
touch-action: none;
}
.panel {
position: fixed;
z-index: 10;
background: var(--panel);
border: 1px solid var(--border);
border-radius: 14px;
box-shadow: 0 18px 50px rgba(0, 0, 0, 0.32);
backdrop-filter: blur(14px);
}
#controls {
top: 18px;
left: 18px;
width: 340px;
max-height: calc(100vh - 36px);
padding: 18px;
overflow: auto;
scrollbar-width: thin;
}
#telemetry {
top: 18px;
right: 18px;
width: 390px;
padding: 17px;
}
.eyebrow {
margin: 0 0 7px;
color: var(--cyan);
font-size: 10px;
font-weight: 800;
letter-spacing: 0.18em;
text-transform: uppercase;
}
h1 {
margin: 0;
font-size: 23px;
line-height: 1.1;
letter-spacing: -0.04em;
}
.intro {
margin: 10px 0 14px;
color: var(--muted);
font-size: 11px;
line-height: 1.55;
}
.target-chip {
display: inline-flex;
align-items: center;
gap: 7px;
margin-bottom: 13px;
padding: 6px 9px;
color: var(--green);
background: rgba(83, 245, 165, 0.08);
border: 1px solid rgba(83, 245, 165, 0.2);
border-radius: 6px;
font-size: 11px;
font-weight: 800;
}
.target-chip::before {
width: 7px;
height: 7px;
content: "";
background: var(--green);
box-shadow: 0 0 12px var(--green);
}
.equation {
margin: 0 0 15px;
padding: 11px;
color: #c9eaf5;
background: rgba(72, 220, 255, 0.055);
border-left: 3px solid var(--cyan);
border-radius: 4px;
font-size: 11px;
line-height: 1.65;
}
.equation strong {
color: var(--cyan);
}
.note {
margin: 8px 0 15px;
color: #8fa9b8;
font-size: 10px;
line-height: 1.5;
}
.control {
margin: 0 0 16px;
}
.control-head {
display: flex;
align-items: baseline;
justify-content: space-between;
gap: 12px;
margin-bottom: 8px;
}
.control label {
color: #cce4ed;
font-size: 11px;
font-weight: 800;
letter-spacing: 0.04em;
}
.control output {
color: var(--cyan);
font-size: 13px;
font-weight: 900;
}
input[type="range"] {
width: 100%;
height: 4px;
margin: 0;
appearance: none;
background: linear-gradient(
90deg,
rgba(72, 220, 255, 0.6),
rgba(72, 220, 255, 0.12)
);
border-radius: 999px;
outline: none;
cursor: pointer;
}
input[type="range"]::-webkit-slider-thumb {
width: 15px;
height: 15px;
appearance: none;
background: #d8f8ff;
border: 3px solid #20bde6;
border-radius: 2px;
box-shadow: 0 0 12px rgba(72, 220, 255, 0.45);
}
input[type="range"]::-moz-range-thumb {
width: 11px;
height: 11px;
background: #d8f8ff;
border: 3px solid #20bde6;
border-radius: 2px;
}
.range-labels {
display: flex;
justify-content: space-between;
margin-top: 6px;
color: #617b89;
font-size: 9px;
}
.section-title {
margin: 16px 0 8px;
color: #7793a2;
font-size: 9px;
font-weight: 800;
letter-spacing: 0.16em;
text-transform: uppercase;
}
.preset-grid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 7px;
}
button,
select {
min-height: 34px;
color: #d9edf5;
background: rgba(79, 151, 177, 0.09);
border: 1px solid rgba(96, 186, 216, 0.2);
border-radius: 6px;
font: inherit;
font-size: 10px;
font-weight: 800;
cursor: pointer;
transition: background 120ms ease, border-color 120ms ease;
}
button:hover,
select:hover {
background: rgba(72, 220, 255, 0.15);
border-color: rgba(72, 220, 255, 0.45);
}
button:active {
transform: translateY(1px);
}
.action-grid {
display: grid;
grid-template-columns: 1fr 1fr 1fr;
gap: 7px;
}
#pauseBtn {
color: #061018;
background: var(--cyan);
border-color: var(--cyan);
}
.speed-row {
display: flex;
align-items: center;
justify-content: space-between;
gap: 10px;
margin-top: 10px;
color: #829caa;
font-size: 10px;
}
select {
min-height: 29px;
padding: 0 9px;
}
.camera-hint {
margin: 13px 0 0;
padding-top: 11px;
color: #607986;
border-top: 1px solid rgba(116, 211, 238, 0.1);
font-size: 9px;
line-height: 1.5;
}
.status-header {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
margin-bottom: 10px;
}
.status {
padding: 6px 8px;
border: 1px solid;
border-radius: 5px;
font-size: 9px;
font-weight: 900;
letter-spacing: 0.07em;
text-align: right;
}
.status.good {
color: var(--green);
background: rgba(83, 245, 165, 0.08);
border-color: rgba(83, 245, 165, 0.3);
}
.status.info {
color: var(--cyan);
background: rgba(72, 220, 255, 0.08);
border-color: rgba(72, 220, 255, 0.3);
}
.status.warn {
color: var(--orange);
background: rgba(255, 180, 84, 0.08);
border-color: rgba(255, 180, 84, 0.3);
}
.status.bad {
color: var(--red);
background: rgba(255, 102, 125, 0.08);
border-color: rgba(255, 102, 125, 0.32);
}
#regime {
min-height: 34px;
margin: 0 0 13px;
color: #9bb5c2;
font-size: 10px;
line-height: 1.55;
}
.metric-grid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 8px;
}
.metric {
min-height: 61px;
padding: 9px;
background: rgba(77, 150, 177, 0.055);
border: 1px solid rgba(99, 179, 207, 0.12);
border-radius: 7px;
}
.metric-label {
display: block;
margin-bottom: 7px;
color: #668391;
font-size: 8px;
font-weight: 800;
letter-spacing: 0.12em;
}
.metric-value {
color: #e7f6fb;
font-size: 13px;
font-weight: 800;
}
.chart-heading {
display: flex;
align-items: center;
justify-content: space-between;
margin: 15px 0 7px;
color: #708b99;
font-size: 9px;
font-weight: 800;
letter-spacing: 0.13em;
}
#clock {
color: var(--cyan);
}
#chart {
display: block;
width: 100%;
height: 165px;
background: rgba(0, 7, 11, 0.48);
border: 1px solid rgba(116, 211, 238, 0.12);
border-radius: 8px;
}
.legend {
display: flex;
align-items: center;
gap: 14px;
margin-top: 9px;
color: #6f8997;
font-size: 9px;
}
.legend span {
display: inline-flex;
align-items: center;
gap: 5px;
}
.legend i {
width: 13px;
height: 3px;
display: inline-block;
background: var(--cyan);
}
.legend .target-line {
height: 2px;
background: var(--green);
}
.legend .limit-line {
height: 2px;
background: var(--red);
}
@media (max-width: 850px) {
#controls {
top: 12px;
left: 12px;
width: calc(100% - 24px);
max-height: 44vh;
padding: 14px;
}
#telemetry {
top: auto;
right: 12px;
bottom: 12px;
width: calc(100% - 24px);
padding: 13px;
}
#chart {
height: 120px;
}
.intro,
.note {
display: none;
}
.equation {
margin-bottom: 10px;
}
.control {
margin-bottom: 11px;
}
}
</style>
</head>
<body>
<section id="controls" class="panel">
<p class="eyebrow">System 01 / Closed Loop</p>
<h1>Voxel Feedback Lab</h1>
<div class="target-chip">TARGET r = 2.0</div>
<p class="intro">
Tune the PD feedback loop and observe the real linear response.
The plant starts at x = 0 with zero velocity.
</p>
<div class="equation">
<strong>Plant:</strong> ẍ = 4(x − r) + u<br>
<strong>Control:</strong> u = −K<sub>p</sub>(x − r) − bẋ<br>
<strong>Closed loop:</strong><br>
ë + bė + (K<sub>p</sub> − 4)e = 0
</div>
<p class="note">
The test plant intentionally has an unstable +4 mode.
Tracking is asymptotically stable only when K<sub>p</sub> > 4 and b > 0.
</p>
<div class="control">
<div class="control-head">
<label for="gain">PROPORTIONAL GAIN K<sub>p</sub></label>
<output id="gainValue" for="gain">6.0</output>
</div>
<input id="gain" type="range" min="0" max="12" step="0.1" value="6">
<div class="range-labels">
<span>0</span>
<span>unstable / marginal at 4</span>
<span>12</span>
</div>
</div>
<div class="control">
<div class="control-head">
<label for="damping">VELOCITY DAMPING b</label>
<output id="dampingValue" for="damping">1.20</output>
</div>
<input id="damping" type="range" min="0" max="6" step="0.05" value="1.2">
<div class="range-labels">
<span>0 / undamped</span>
<span>s⁻¹</span>
<span>6</span>
</div>
</div>
<div class="section-title">Response Presets</div>
<div class="preset-grid">
<button data-kp="6" data-b="4">OVERDAMPED</button>
<button data-kp="6" data-b="0.35">OSCILLATORY</button>
<button data-kp="4" data-b="1.2">MARGINAL</button>
<button data-kp="2" data-b="1.2">UNSTABLE</button>
</div>
<div class="section-title">Simulation</div>
<div class="action-grid">
<button id="pauseBtn">PAUSE</button>
<button id="resetBtn">RESET</button>
<button id="kickBtn">KICK</button>
</div>
<div class="speed-row">
<span>SIMULATION SPEED</span>
<select id="speed">
<option value="0.5">0.5×</option>
<option value="1" selected>1×</option>
<option value="1.5">1.5×</option>
<option value="2">2×</option>
</select>
</div>
<p class="camera-hint">
Drag the scene to orbit · mouse wheel to zoom · double-click to reset the camera.
Unstable responses are allowed to diverge, but stop at a visible safety limit.
</p>
</section>
<section id="telemetry" class="panel">
<div class="status-header">
<p class="eyebrow">Live State</p>
<span id="status" class="status good">SETTLING</span>
</div>
<p id="regime">Underdamped, oscillatory settling.</p>
<div class="metric-grid">
<div class="metric">
<span class="metric-label">OUTPUT x</span>
<span id="metricOutput" class="metric-value">0.000</span>
</div>
<div class="metric">
<span class="metric-label">ERROR x − r</span>
<span id="metricError" class="metric-value">−2.000</span>
</div>
<div class="metric">
<span class="metric-label">CONTROL u</span>
<span id="metricEffort" class="metric-value">12.000</span>
</div>
<div class="metric">
<span class="metric-label">CLOSED-LOOP ζ</span>
<span id="metricZeta" class="metric-value">0.424</span>
</div>
<div class="metric" style="grid-column: 1 / -1">
<span class="metric-label">CHARACTERISTIC POLES</span>
<span id="metricPoles" class="metric-value">−0.60 ± 1.28i</span>
</div>
</div>
<div class="chart-heading">
<span>OUTPUT TRACE / 12 s WINDOW</span>
<span id="clock">t = 0.00 s</span>
</div>
<canvas id="chart"></canvas>
<div class="legend">
<span><i></i> output x(t)</span>
<span><i class="target-line"></i> target</span>
<span><i class="limit-line"></i> safety limit</span>
</div>
</section>
<script type="module">
import * as THREE from "https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
// -------------------------------------------------------------------------
// Scene
// -------------------------------------------------------------------------
const TARGET = 2.0;
const SAFETY_LIMIT = 7.5;
const FIXED_DT = 1 / 120;
const params = {
kp: 6.0,
b: 1.2
};
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x061018);
scene.fog = new THREE.Fog(0x061018, 13, 31);
const camera = new THREE.PerspectiveCamera(
43,
innerWidth / innerHeight,
0.1,
100
);
const renderer = new THREE.WebGLRenderer({
antialias: true,
powerPreference: "high-performance"
});
renderer.domElement.className = "webgl";
renderer.setSize(innerWidth, innerHeight);
renderer.setPixelRatio(Math.min(devicePixelRatio, 2));
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.18;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
document.body.prepend(renderer.domElement);
scene.add(new THREE.HemisphereLight(0xb9eaff, 0x071016, 1.65));
const keyLight = new THREE.DirectionalLight(0xffffff, 3.1);
keyLight.position.set(6, 11, 7);
keyLight.castShadow = true;
keyLight.shadow.mapSize.set(2048, 2048);
keyLight.shadow.camera.left = -12;
keyLight.shadow.camera.right = 12;
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(0x3ccfff, 1.3);
rimLight.position.set(-7, 4, -8);
scene.add(rimLight);
// -------------------------------------------------------------------------
// Voxel environment
// -------------------------------------------------------------------------
function box(width, height, depth, material, x, y, z, parent = scene) {
const mesh = new THREE.Mesh(
new THREE.BoxGeometry(width, height, depth),
material
);
mesh.position.set(x, y, z);
mesh.castShadow = true;
mesh.receiveShadow = true;
parent.add(mesh);
return mesh;
}
const baseMaterial = new THREE.MeshStandardMaterial({
color: 0x071319,
roughness: 0.95,
metalness: 0.05
});
box(18.5, 0.32, 12.5, baseMaterial, 0, -0.38, 0);
const tileGeometry = new THREE.BoxGeometry(0.91, 0.12, 0.91);
const tileMaterial = new THREE.MeshStandardMaterial({
color: 0xffffff,
roughness: 0.92,
metalness: 0.03
});
const tileCount = 17 * 11;
const tiles = new THREE.InstancedMesh(tileGeometry, tileMaterial, tileCount);
const dummy = new THREE.Object3D();
const tileColor = new THREE.Color();
let tileIndex = 0;
for (let x = -8; x <= 8; x++) {
for (let z = -5; z <= 5; z++) {
dummy.position.set(x, -0.19, z);
dummy.updateMatrix();
tiles.setMatrixAt(tileIndex, dummy.matrix);
const checker = (x + z) & 1;
tileColor.set(checker ? 0x10232c : 0x0b1a22);
tiles.setColorAt(tileIndex, tileColor);
tileIndex++;
}
}
tiles.instanceMatrix.needsUpdate = true;
tiles.instanceColor.needsUpdate = true;
tiles.receiveShadow = true;
scene.add(tiles);
const railMaterial = new THREE.MeshStandardMaterial({
color: 0x355564,
roughness: 0.45,
metalness: 0.68
});
const sleeperMaterial = new THREE.MeshStandardMaterial({
color: 0x172b34,
roughness: 0.8,
metalness: 0.18
});
box(17.2, 0.13, 0.12, railMaterial, 0, 0.015, -0.7);
box(17.2, 0.13, 0.12, railMaterial, 0, 0.015, 0.7);
for (let x = -8; x <= 8; x++) {
box(0.12, 0.08, 1.65, sleeperMaterial, x, -0.01, 0);
}
const tickMaterial = new THREE.MeshStandardMaterial({
color: 0x50798a,
emissive: 0x0b2832,
emissiveIntensity: 0.6,
roughness: 0.55
});
for (let x = -7; x <= 7; x++) {
box(0.07, 0.055, 0.22, tickMaterial, x, 0.09, 1.02);
}
// Target beacon.
const targetGroup = new THREE.Group();
targetGroup.position.x = TARGET;
scene.add(targetGroup);
const greenMaterial = new THREE.MeshStandardMaterial({
color: 0x43e99a,
emissive: 0x08783e,
emissiveIntensity: 0.8,
roughness: 0.4
});
for (let i = 0; i < 6; i++) {
const scale = 0.34 - i * 0.025;
box(
scale,
0.28,
scale,
i === 5 ? greenMaterial : targetGroup.userData.dim || greenMaterial,
0,
0.18 + i * 0.31,
-1.25
);
}
const beaconTop = box(
0.43,
0.43,
0.43,
new THREE.MeshStandardMaterial({
color: 0xb6ffe0,
emissive: 0x2aff91,
emissiveIntensity: 1.3,
roughness: 0.25
}),
TARGET,
2.25,
-1.25
);
box(0.72, 0.07, 0.12, greenMaterial, TARGET, 0.11, 0);
box(0.12, 0.07, 0.72, greenMaterial, TARGET, 0.11, 0);
const targetLight = new THREE.PointLight(0x3dff9a, 3.2, 7);
targetLight.position.set(TARGET, 2.1, -1.1);
scene.add(targetLight);
// Output vehicle.
const plantGroup = new THREE.Group();
scene.add(plantGroup);
const cyanMaterial = new THREE.MeshStandardMaterial({
color: 0x38c9ef,
emissive: 0x063a4c,
emissiveIntensity: 0.75,
roughness: 0.38,
metalness: 0.28
});
const blueMaterial = new THREE.MeshStandardMaterial({
color: 0x167797,
emissive: 0x031d2b,
emissiveIntensity: 0.5,
roughness: 0.5,
metalness: 0.35
});
const orangeMaterial = new THREE.MeshStandardMaterial({
color: 0xff9f43,
emissive: 0x6a2700,
emissiveIntensity: 0.65,
roughness: 0.4
});
box(1.18, 0.25, 1.22, blueMaterial, 0, 0.2, 0, plantGroup);
box(0.72, 0.58, 0.8, cyanMaterial, 0, 0.62, 0, plantGroup);
box(0.5, 0.3, 0.58, orangeMaterial, 0, 1.06, 0, plantGroup);
box(0.18, 0.18, 0.18, greenMaterial, 0, 1.3, 0, plantGroup);
const plantLight = new THREE.PointLight(0x35caff, 2.3, 5);
plantLight.position.set(0, 1.2, 0);
plantGroup.add(plantLight);
// Error bracket between output and target.
const errorMaterial = new THREE.MeshStandardMaterial({
color: 0xffb454,
emissive: 0x5a2600,
emissiveIntensity: 0.75,
roughness: 0.4
});
const errorBar = box(1, 0.075, 0.075, errorMaterial, 0, 0.27, 0.97);
const errorEndA = box(0.075, 0.28, 0.075, errorMaterial, 0, 0.27, 0.97);
const errorEndB = box(0.075, 0.28, 0.075, errorMaterial, 0, 0.27, 0.97);
// Control-effort voxel gauge.
const effortSegments = [];
const effortOff = new THREE.MeshStandardMaterial({
color: 0x10252f,
emissive: 0x02090d,
roughness: 0.8
});
const effortPositive = new THREE.MeshStandardMaterial({
color: 0x43dfff,
emissive: 0x075268,
emissiveIntensity: 0.9
});
const effortNegative = new THREE.MeshStandardMaterial({
color: 0xff8b4f,
emissive: 0x5b2100,
emissiveIntensity: 0.9
});
for (let i = 0; i < 9; i++) {
effortSegments.push(
box(
0.14,
0.14,
0.14,
effortOff,
-0.83,
0.28 + i * 0.23,
-0.78,
plantGroup
)
);
}
// Historical output trail.
const trailGeometry = new THREE.BoxGeometry(0.11, 0.11, 0.11);
const trailMaterial = new THREE.MeshStandardMaterial({
color: 0xffffff,
roughness: 0.45,
emissive: 0x072d39,
emissiveIntensity: 0.45
});
const maxTrail = 720;
const trail = new THREE.InstancedMesh(trailGeometry, trailMaterial, maxTrail);
trail.instanceMatrix.setUsage(THREE.DynamicDrawUsage);
trail.count = 0;
trail.frustumCulled = false;
scene.add(trail);
// Canvas-texture labels, generated locally.
function createLabel(text, color = "#dff8ff", width = 3.0) {
const canvas = document.createElement("canvas");
canvas.width = 320;
canvas.height = 72;
const context = canvas.getContext("2d");
const texture = new THREE.CanvasTexture(canvas);
texture.colorSpace = THREE.SRGBColorSpace;
const material = new THREE.SpriteMaterial({
map: texture,
transparent: true,
depthTest: false,
depthWrite: false
});
const sprite = new THREE.Sprite(material);
sprite.scale.set(width, width * 72 / 320, 1);
function setText(nextText) {
context.clearRect(0, 0, canvas.width, canvas.height);
context.fillStyle = "rgba(4, 15, 22, 0.88)";
context.fillRect(0, 0, canvas.width, canvas.height);
context.strokeStyle = color;
context.lineWidth = 3;
context.strokeRect(2, 2, canvas.width - 4, canvas.height - 4);
context.fillStyle = color;
context.font = "bold 27px monospace";
context.textAlign = "center";
context.textBaseline = "middle";
context.fillText(nextText, canvas.width / 2, canvas.height / 2 + 1);
texture.needsUpdate = true;
}
setText(text);
return { sprite, setText };
}
const targetLabel = createLabel("TARGET r = 2.0", "#53f5a5", 3.2);
targetLabel.sprite.position.set(TARGET, 3.05, -1.25);
scene.add(targetLabel.sprite);
const outputLabel = createLabel("OUTPUT x = 0.000", "#48dcff", 3.1);
outputLabel.sprite.position.set(0, 1.95, 0);
plantGroup.add(outputLabel.sprite);
// -------------------------------------------------------------------------
// Direct camera controls — no addons
// -------------------------------------------------------------------------
const cameraState = {
azimuth: 0.57,
elevation: 0.52,
radius: 15.8
};
function updateCamera() {
const { azimuth, elevation, radius } = cameraState;
const horizontal = radius * Math.cos(elevation);
camera.position.set(
Math.sin(azimuth) * horizontal,
Math.sin(elevation) * radius,
Math.cos(azimuth) * horizontal
);
camera.lookAt(0, 0.9, 0);
}
function resetCamera() {
cameraState.azimuth = 0.57;
cameraState.elevation = 0.52;
cameraState.radius = 15.8;
updateCamera();
}
updateCamera();
let dragging = false;
let pointerX = 0;
let pointerY = 0;
renderer.domElement.addEventListener("pointerdown", (event) => {
if (event.button !== 0) return;
dragging = true;
pointerX = event.clientX;
pointerY = event.clientY;
renderer.domElement.setPointerCapture(event.pointerId);
});
renderer.domElement.addEventListener("pointermove", (event) => {
if (!dragging) return;
const dx = event.clientX - pointerX;
const dy = event.clientY - pointerY;
pointerX = event.clientX;
pointerY = event.clientY;
cameraState.azimuth -= dx * 0.006;
cameraState.elevation = THREE.MathUtils.clamp(
cameraState.elevation + dy * 0.005,
0.16,
1.25
);
updateCamera();
});
function endDrag(event) {
dragging = false;
if (event.pointerId !== undefined) {
if (renderer.domElement.hasPointerCapture(event.pointerId)) {
renderer.domElement.releasePointerCapture(event.pointerId);
}
}
}
renderer.domElement.addEventListener("pointerup", endDrag);
renderer.domElement.addEventListener("pointercancel", endDrag);
renderer.domElement.addEventListener(
"wheel",
(event) => {
event.preventDefault();
cameraState.radius = THREE.MathUtils.clamp(
cameraState.radius + event.deltaY * 0.012,
7.5,
25
);
updateCamera();
},
{ passive: false }
);
renderer.domElement.addEventListener("dblclick", resetCamera);
// -------------------------------------------------------------------------
// Linear system and stable fixed-step integration
// -------------------------------------------------------------------------
const state = {
x: 0,
v: 0,
t: 0
};
let running = true;
let halted = false;
let accumulator = 0;
let sampleAccumulator = 0;
let history = [];
let speed = 1;
// Closed-loop equation:
// e = x - TARGET
// e'' = (4 - Kp)e - b e'
function derivative(x, v) {
const error = x - TARGET;
return {
x: v,
v: (4 - params.kp) * error - params.b * v
};
}
function rk4Step(dt) {
const x = state.x;
const v = state.v;
const k1 = derivative(x, v);
const k2 = derivative(
x + k1.x * dt * 0.5,
v + k1.v * dt * 0.5
);
const k3 = derivative(
x + k2.x * dt * 0.5,
v + k2.v * dt * 0.5
);
const k4 = derivative(
x + k3.x * dt,
v + k3.v * dt
);
state.x += dt / 6 * (k1.x + 2 * k2.x + 2 * k3.x + k4.x);
state.v += dt / 6 * (k1.v + 2 * k2.v + 2 * k3.v + k4.v);
state.t += dt;
}
function controlEffort() {
return -params.kp * (state.x - TARGET) - params.b * state.v;
}
function resetSimulation() {
state.x = 0;
state.v = 0;
state.t = 0;
running = true;
halted = false;
accumulator = 0;
sampleAccumulator = 0;
history = [{ t: 0, x: 0 }];
pauseButton.textContent = "PAUSE";
updateTrail();
updateTelemetry();
drawChart();
}
function addHistorySample() {
history.push({ t: state.t, x: state.x });
if (history.length > maxTrail) history.shift();
updateTrail();
}
function updateTrail() {
const count = history.length;
trail.count = count;
const color = new THREE.Color();
for (let i = 0; i < count; i++) {
const sample = history[i];
const age = count > 1 ? i / (count - 1) : 1;
dummy.position.set(
THREE.MathUtils.clamp(sample.x, -SAFETY_LIMIT, SAFETY_LIMIT),
0.18,
1.32
);
dummy.rotation.set(0, 0, 0);
dummy.scale.setScalar(0.75 + age * 0.5);
dummy.updateMatrix();
trail.setMatrixAt(i, dummy.matrix);
color.setHSL(0.53 - age * 0.19, 0.78, 0.56);
trail.setColorAt(i, color);
}
trail.instanceMatrix.needsUpdate = true;
if (trail.instanceColor) trail.instanceColor.needsUpdate = true;
}
// -------------------------------------------------------------------------
// Exact pole analysis and UI telemetry
// -------------------------------------------------------------------------
const gainInput = document.getElementById("gain");
const dampingInput = document.getElementById("damping");
const gainValue = document.getElementById("gainValue");
const dampingValue = document.getElementById("dampingValue");
const pauseButton = document.getElementById("pauseBtn");
const resetButton = document.getElementById("resetBtn");
const kickButton = document.getElementById("kickBtn");
const speedSelect = document.getElementById("speed");
const statusElement = document.getElementById("status");
const regimeElement = document.getElementById("regime");
const metricOutput = document.getElementById("metricOutput");
const metricError = document.getElementById("metricError");
const metricEffort = document.getElementById("metricEffort");
const metricZeta = document.getElementById("metricZeta");
const metricPoles = document.getElementById("metricPoles");
const clockElement = document.getElementById("clock");
function analyzeSystem() {
const a = params.kp - 4;
const discriminant = params.b * params.b - 4 * a;
let poles;
if (discriminant >= 0) {
const root = Math.sqrt(discriminant);
poles = [
{ re: (-params.b + root) / 2, im: 0 },
{ re: (-params.b - root) / 2, im: 0 }
];
} else {
poles = [
{ re: -params.b / 2, im: Math.sqrt(-discriminant) / 2 },
{ re: -params.b / 2, im: -Math.sqrt(-discriminant) / 2 }
];
}
let mode;
let detail;
let tone;
if (a < 0) {
mode = "UNSTABLE";
detail = "Positive pole: the output diverges instead of settling.";
tone = "bad";
} else if (Math.abs(params.b) < 1e-9) {
mode = "NO SETTLING";
detail = "Zero damping: persistent oscillation, or a marginal zero-pole case.";
tone = "warn";
} else if (Math.abs(a) < 1e-9) {
mode = "MARGINAL";
detail = "A pole is at zero, so convergence to the target is not guaranteed.";
tone = "warn";
} else if (discriminant < 0) {
mode = "OSCILLATORY SETTLING";
detail = "Complex poles: the output oscillates while its envelope decays.";
tone = "info";
} else if (Math.abs(discriminant) < 0.002) {
mode = "CRITICAL SETTLING";
detail = "Repeated real pole: the fastest non-oscillatory return.";
tone = "good";
} else {
mode = "SETTLING";
detail = "Distinct real poles: overdamped, non-oscillatory convergence.";
tone = "good";
}
return { a, discriminant, poles, mode, detail, tone };
}
function formatPole(pole) {
const sign = pole.re < 0 ? "−" : "";
const magnitude = Math.abs(pole.re).toFixed(2);
if (Math.abs(pole.im) < 1e-7) return `${sign}${magnitude}`;
return `${sign}${magnitude} ± ${Math.abs(pole.im).toFixed(2)}i`;
}
function signed(value, digits = 3) {
if (Math.abs(value) < 0.0005) value = 0;
return `${value < 0 ? "−" : "+"}${Math.abs(value).toFixed(digits)}`;
}
function updateTelemetry() {
const analysis = analyzeSystem();
const effort = controlEffort();
const error = state.x - TARGET;
if (halted) {
statusElement.textContent = "DIVERGED / LIMIT";
statusElement.className = "status bad";
regimeElement.textContent =
"The unstable trajectory reached the visible safety limit and was stopped. No settling is implied.";
} else {
statusElement.textContent = analysis.mode;
statusElement.className = `status ${analysis.tone}`;
regimeElement.textContent = analysis.detail;
}
metricOutput.textContent = state.x.toFixed(3);
metricError.textContent = signed(error);
metricEffort.textContent = signed(effort);
if (analysis.a > 0 && params.b > 0) {
metricZeta.textContent = (
params.b / (2 * Math.sqrt(analysis.a))
).toFixed(3);
} else {
metricZeta.textContent = "—";
}
metricPoles.textContent = analysis.poles.map(formatPole).join(", ");
clockElement.textContent = `t = ${state.t.toFixed(2)} s`;
outputLabel.setText(`OUTPUT x = ${state.x.toFixed(3)}`);
const litSegments = Math.min(
effortSegments.length,
Math.ceil(Math.abs(effort) / 4)
);
for (let i = 0; i < effortSegments.length; i++) {
effortSegments[i].material =
i < litSegments
? effort >= 0
? effortPositive
: effortNegative
: effortOff;
}
plantLight.intensity = 1.8 + Math.min(2.4, Math.abs(effort) * 0.08);
}
function refreshParameterLabels() {
gainValue.textContent = params.kp.toFixed(1);
dampingValue.textContent = params.b.toFixed(2);
}
gainInput.addEventListener("input", () => {
params.kp = Number(gainInput.value);
refreshParameterLabels();
resetSimulation();
});
dampingInput.addEventListener("input", () => {
params.b = Number(dampingInput.value);
refreshParameterLabels();
resetSimulation();
});
document.querySelectorAll(".preset").forEach(() => {});
document.querySelectorAll("[data-kp]").forEach((button) => {
button.addEventListener("click", () => {
params.kp = Number(button.dataset.kp);
params.b = Number(button.dataset.b);
gainInput.value = String(params.kp);
dampingInput.value = String(params.b);
refreshParameterLabels();
resetSimulation();
});
});
pauseButton.addEventListener("click", () => {
if (halted) return;
running = !running;
accumulator = 0;
pauseButton.textContent = running ? "PAUSE" : "RESUME";
});
resetButton.addEventListener("click", resetSimulation);
kickButton.addEventListener("click", () => {
if (halted) resetSimulation();
state.v += 4.2;
addHistorySample();
updateTelemetry();
});
speedSelect.addEventListener("change", () => {
speed = Number(speedSelect.value);
});
// -------------------------------------------------------------------------
// Output trace chart
// -------------------------------------------------------------------------
const chart = document.getElementById("chart");
const chartContext = chart.getContext("2d");
function drawChart() {
const width = chart.clientWidth;
const height = chart.clientHeight;
if (!width || !height) return;
const dpr = Math.min(devicePixelRatio, 2);
const pixelWidth = Math.round(width * dpr);
const pixelHeight = Math.round(height * dpr);
if (chart.width !== pixelWidth || chart.height !== pixelHeight) {
chart.width = pixelWidth;
chart.height = pixelHeight;
}
chartContext.setTransform(dpr, 0, 0, dpr, 0, 0);
chartContext.clearRect(0, 0, width, height);
const margin = { left: 31, right: 10, top: 10, bottom: 22 };
const plotWidth = width - margin.left - margin.right;
const plotHeight = height - margin.top - margin.bottom;
const timeStart = Math.max(0, state.t - 12);
const timeEnd = Math.max(12, state.t);
const yMin = -8;
const yMax = 8;
const mapX = (t) =>
margin.left + ((t - timeStart) / (timeEnd - timeStart)) * plotWidth;
const mapY = (x) =>
margin.top + ((yMax - x) / (yMax - yMin)) * plotHeight;
chartContext.font = "9px monospace";
chartContext.textBaseline = "middle";
// Grid.
for (const value of [-8, -4, 0, 2, 4, 8]) {
const y = mapY(value);
chartContext.strokeStyle =
value === 2 ? "rgba(83,245,165,0.18)" : "rgba(111,159,178,0.10)";
chartContext.lineWidth = 1;
chartContext.beginPath();
chartContext.moveTo(margin.left, y);
chartContext.lineTo(width - margin.right, y);
chartContext.stroke();
chartContext.fillStyle = "#54707f";
chartContext.textAlign = "right";
chartContext.fillText(String(value), margin.left - 6, y);
}
// Safety limits.
chartContext.setLineDash([4, 4]);
chartContext.strokeStyle = "rgba(255,102,125,0.45)";
for (const value of [-SAFETY_LIMIT, SAFETY_LIMIT]) {
const y = mapY(value);
chartContext.beginPath();
chartContext.moveTo(margin.left, y);
chartContext.lineTo(width - margin.right, y);
chartContext.stroke();
}
chartContext.setLineDash([]);
// Target.
chartContext.setLineDash([6, 5]);
chartContext.strokeStyle = "#53f5a5";
chartContext.lineWidth = 1.3;
chartContext.beginPath();
chartContext.moveTo(margin.left, mapY(TARGET));
chartContext.lineTo(width - margin.right, mapY(TARGET));
chartContext.stroke();
chartContext.setLineDash([]);
// Actual simulation trace.
chartContext.save();
chartContext.beginPath();
chartContext.rect(
margin.left,
margin.top,
plotWidth,
plotHeight
);
chartContext.clip();
chartContext.strokeStyle = "#48dcff";
chartContext.lineWidth = 2;
chartContext.beginPath();
let started = false;
for (const sample of history) {
if (sample.t < timeStart - 0.2) continue;
const x = mapX(sample.t);
const y = mapY(sample.x);
if (!started) {
chartContext.moveTo(x, y);
started = true;
} else {
chartContext.lineTo(x, y);
}
}
chartContext.stroke();
const currentX = mapX(state.t);
const currentY = mapY(state.x);
chartContext.fillStyle = halted ? "#ff667d" : "#d9f9ff";
chartContext.fillRect(currentX - 3, currentY - 3, 6, 6);
chartContext.restore();
// Time labels.
chartContext.fillStyle = "#54707f";
chartContext.textAlign = "left";
chartContext.fillText(
`${timeStart.toFixed(1)}s`,
margin.left,
height - 8
);
chartContext.textAlign = "right";
chartContext.fillText(
`${timeEnd.toFixed(1)}s`,
width - margin.right,
height - 8
);
}
// -------------------------------------------------------------------------
// Animation loop
// -------------------------------------------------------------------------
let previousTime = performance.now();
let lastChartTime = 0;
let lastTelemetryTime = 0;
function animate(now) {
const frameDelta = Math.min((now - previousTime) / 1000, 0.05);
previousTime = now;
if (running && !halted) {
accumulator += frameDelta * speed;
let steps = 0;
while (accumulator >= FIXED_DT && steps < 30) {
rk4Step(FIXED_DT);
accumulator -= FIXED_DT;
sampleAccumulator += FIXED_DT;
steps++;
if (sampleAccumulator >= 0.04) {
sampleAccumulator -= 0.04;
addHistorySample();
}
// Hard safety boundary: preserve the divergence result without allowing
// invalid values or unbounded geometry to enter the renderer.
if (
!Number.isFinite(state.x) ||
!Number.isFinite(state.v) ||
Math.abs(state.x) > SAFETY_LIMIT
) {
if (Number.isFinite(state.x)) {
state.x = THREE.MathUtils.clamp(
state.x,
-SAFETY_LIMIT,
SAFETY_LIMIT
);
} else {
state.x = 0;
state.v = 0;
}
halted = true;
running = false;
pauseButton.textContent = "STOPPED";
addHistorySample();
break;
}
}
}
const visualX = THREE.MathUtils.clamp(
state.x,
-SAFETY_LIMIT,
SAFETY_LIMIT
);
plantGroup.position.x = visualX;
const errorDistance = TARGET - visualX;
const errorMagnitude = Math.max(0.001, Math.abs(errorDistance));
errorBar.scale.x = errorMagnitude;
errorBar.position.x = (TARGET + visualX) * 0.5;
errorEndA.position.x = visualX;
errorEndB.position.x = TARGET;
const errorColor =
Math.abs(state.x - TARGET) < 0.15 ? 0x53f5a5 : 0xffb454;
errorMaterial.color.setHex(errorColor);
errorMaterial.emissive.setHex(errorColor);
errorMaterial.emissiveIntensity = 0.45;
beaconTop.material.emissiveIntensity =
1.05 + Math.sin(now * 0.003) * 0.35;
if (now - lastTelemetryTime > 60) {
updateTelemetry();
lastTelemetryTime = now;
}
if (now - lastChartTime > 50) {
drawChart();
lastChartTime = now;
}
renderer.render(scene, camera);
requestAnimationFrame(animate);
}
window.addEventListener("resize", () => {
camera.aspect = innerWidth / innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(innerWidth, innerHeight);
renderer.setPixelRatio(Math.min(devicePixelRatio, 2));
drawChart();
});
refreshParameterLabels();
resetSimulation();
requestAnimationFrame(animate);
</script>
</body>
</html>
```