Prompt specification
Build or customize the Three.js 3D scene "Small and large learning-rate 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: Small and large learning-rate comparison
Category: Algorithms & Systems · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/small-and-large-learning-rate-comparison-x1882
Scene Description Prompt:
Make one HTML file using Three.js from cdnjs for this stylized scene: Run gradient descent from the same start using two step sizes on a known quadratic function; show convergence or oscillation according to the actual update rule.
Working Three.js Starter (small-and-large-learning-rate-comparison-x1882):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Gradient Descent — Two Step Sizes</title>
<style>
:root {
--bg: #070b18;
--panel: rgba(13, 20, 39, 0.78);
--panel-border: rgba(165, 196, 255, 0.16);
--text: #eef4ff;
--muted: #9caecc;
--green: #42f5b5;
--orange: #ffb454;
--blue: #79a8ff;
}
* { 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; }
#stage {
position: fixed;
inset: 0;
}
#stage canvas {
display: block;
width: 100%;
height: 100%;
outline: none;
touch-action: none;
}
.ui {
position: fixed;
inset: 0;
pointer-events: none;
}
.glass {
background: linear-gradient(145deg, rgba(20, 29, 54, 0.9), var(--panel));
border: 1px solid var(--panel-border);
box-shadow:
0 18px 50px rgba(0, 0, 0, 0.28),
inset 0 1px 0 rgba(255, 255, 255, 0.045);
backdrop-filter: blur(18px);
-webkit-backdrop-filter: blur(18px);
}
.title-card {
position: absolute;
top: 22px;
left: 22px;
width: min(460px, calc(100vw - 44px));
padding: 20px 22px;
border-radius: 20px;
}
.eyebrow {
margin-bottom: 8px;
color: var(--blue);
font-size: 11px;
font-weight: 800;
letter-spacing: 0.17em;
text-transform: uppercase;
}
h1 {
margin: 0;
font-size: clamp(25px, 3vw, 36px);
line-height: 1.04;
letter-spacing: -0.04em;
}
.subtitle {
margin: 11px 0 0;
max-width: 410px;
color: var(--muted);
font-size: 13px;
line-height: 1.55;
}
.formula {
display: flex;
flex-wrap: wrap;
gap: 8px;
margin-top: 15px;
}
.formula span {
padding: 7px 10px;
border: 1px solid rgba(121, 168, 255, 0.18);
border-radius: 9px;
background: rgba(121, 168, 255, 0.075);
color: #cfe0ff;
font-family: "SFMono-Regular", Consolas, monospace;
font-size: 12px;
}
#run-panel {
position: absolute;
top: 22px;
right: 22px;
width: 350px;
padding: 16px;
border-radius: 20px;
pointer-events: auto;
}
.panel-heading {
display: flex;
align-items: center;
justify-content: space-between;
margin: 0 2px 12px;
}
.panel-heading h2 {
margin: 0;
font-size: 14px;
letter-spacing: -0.01em;
}
.panel-heading span {
color: var(--muted);
font-size: 10px;
letter-spacing: 0.12em;
text-transform: uppercase;
}
.run-card {
position: relative;
margin-top: 10px;
padding: 14px;
overflow: hidden;
border: 1px solid rgba(255, 255, 255, 0.08);
border-radius: 15px;
background: rgba(255, 255, 255, 0.035);
}
.run-card::before {
position: absolute;
inset: 0 auto 0 0;
width: 3px;
content: "";
background: var(--run-color);
box-shadow: 0 0 18px var(--run-color);
}
.run-head {
display: flex;
align-items: center;
justify-content: space-between;
gap: 10px;
}
.run-name {
display: flex;
align-items: center;
gap: 8px;
font-size: 13px;
font-weight: 750;
}
.dot {
width: 8px;
height: 8px;
border-radius: 50%;
background: var(--run-color);
box-shadow: 0 0 12px var(--run-color);
}
.eta {
color: var(--run-color);
font-family: "SFMono-Regular", Consolas, monospace;
font-size: 12px;
font-weight: 750;
}
.badge {
display: inline-flex;
margin-top: 9px;
padding: 4px 8px;
border: 1px solid color-mix(in srgb, var(--run-color) 35%, transparent);
border-radius: 999px;
background: color-mix(in srgb, var(--run-color) 10%, transparent);
color: var(--run-color);
font-size: 10px;
font-weight: 800;
letter-spacing: 0.05em;
text-transform: uppercase;
}
.factors {
margin: 9px 0 12px;
color: var(--muted);
font-family: "SFMono-Regular", Consolas, monospace;
font-size: 10px;
line-height: 1.5;
}
.stats {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 7px;
}
.stat {
padding: 8px 7px;
border-radius: 10px;
background: rgba(0, 0, 0, 0.18);
}
.stat label {
display: block;
margin-bottom: 4px;
color: var(--muted);
font-size: 9px;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.stat strong {
display: block;
overflow: hidden;
color: #f5f8ff;
font-family: "SFMono-Regular", Consolas, monospace;
font-size: 12px;
font-weight: 650;
text-overflow: ellipsis;
white-space: nowrap;
}
.history-panel {
position: absolute;
right: 22px;
bottom: 22px;
width: 350px;
padding: 14px 16px 12px;
border-radius: 18px;
pointer-events: auto;
}
.history-head {
display: flex;
align-items: baseline;
justify-content: space-between;
gap: 12px;
margin-bottom: 8px;
}
.history-head h2 {
margin: 0;
font-size: 13px;
}
.history-head span {
color: var(--muted);
font-size: 10px;
}
#historyPlot {
display: block;
width: 100%;
height: 142px;
}
.plot-legend {
display: flex;
gap: 15px;
margin-top: 3px;
color: var(--muted);
font-size: 10px;
}
.plot-legend i {
display: inline-block;
width: 15px;
height: 2px;
margin-right: 5px;
vertical-align: middle;
background: currentColor;
}
#transport {
position: absolute;
bottom: 22px;
left: 50%;
display: flex;
align-items: center;
gap: 9px;
padding: 9px;
border-radius: 16px;
transform: translateX(-50%);
pointer-events: auto;
}
button {
min-height: 38px;
padding: 0 14px;
border: 1px solid rgba(255, 255, 255, 0.12);
border-radius: 10px;
background: rgba(255, 255, 255, 0.065);
color: var(--text);
cursor: pointer;
font-size: 12px;
font-weight: 700;
transition: 140ms ease;
}
button:hover {
border-color: rgba(121, 168, 255, 0.42);
background: rgba(121, 168, 255, 0.12);
transform: translateY(-1px);
}
button.primary {
border-color: rgba(66, 245, 181, 0.28);
background: rgba(66, 245, 181, 0.12);
color: #a9ffe2;
}
.speed-control {
display: flex;
align-items: center;
gap: 8px;
padding: 0 8px;
color: var(--muted);
font-size: 10px;
white-space: nowrap;
}
input[type="range"] {
width: 88px;
accent-color: var(--blue);
}
#speedValue {
width: 35px;
color: var(--text);
font-family: "SFMono-Regular", Consolas, monospace;
text-align: right;
}
.legend {
position: absolute;
bottom: 22px;
left: 22px;
max-width: 330px;
padding: 13px 15px;
border-radius: 15px;
color: var(--muted);
font-size: 11px;
line-height: 1.55;
}
.legend-row {
display: flex;
align-items: center;
gap: 7px;
margin-bottom: 4px;
color: var(--text);
font-weight: 700;
}
.legend-row i {
width: 18px;
height: 3px;
border-radius: 999px;
background: currentColor;
}
#loading {
position: fixed;
inset: 0;
z-index: 20;
display: grid;
place-items: center;
background: var(--bg);
color: var(--muted);
font-size: 13px;
letter-spacing: 0.12em;
text-transform: uppercase;
}
@media (max-width: 1100px) {
.legend { display: none; }
#transport { left: 22px; transform: none; }
}
@media (max-width: 820px) {
.title-card {
top: 12px;
left: 12px;
width: calc(100vw - 24px);
padding: 15px 17px;
}
.title-card .subtitle { display: none; }
.formula { margin-top: 10px; }
.formula span { font-size: 10px; padding: 5px 7px; }
#run-panel {
top: auto;
right: 12px;
bottom: 82px;
left: 12px;
width: auto;
padding: 10px;
}
#run-panel .panel-heading { display: none; }
.run-card {
display: inline-block;
width: calc(50% - 6px);
margin: 0;
padding: 10px;
vertical-align: top;
}
.run-card + .run-card { margin-left: 6px; }
.factors { display: none; }
.stats { margin-top: 8px; gap: 4px; }
.stat { padding: 6px 4px; }
.stat strong { font-size: 10px; }
.history-panel { display: none; }
#transport {
right: 12px;
bottom: 12px;
left: 12px;
justify-content: center;
}
}
</style>
</head>
<body>
<div id="stage"></div>
<div class="ui">
<header class="glass title-card">
<div class="eyebrow">Interactive 3D · Quadratic Optimization</div>
<h1>One start. Two step sizes.</h1>
<p class="subtitle">
Both runs begin at exactly the same point. The surface height is the
objective value, while the surface coordinates are the two variables.
</p>
<div class="formula">
<span>f(x,y) = ½(x² + 4y²)</span>
<span>∇f = (x, 4y)</span>
<span>pₖ₊₁ = pₖ − η∇f(pₖ)</span>
</div>
</header>
<section id="run-panel" class="glass" aria-label="Gradient descent run details">
<div class="panel-heading">
<h2>Live descent</h2>
<span>same start: (3.4, 2.2)</span>
</div>
<article class="run-card" style="--run-color: var(--green)">
<div class="run-head">
<div class="run-name"><span class="dot"></span>Stable step</div>
<div class="eta">η = 0.20</div>
</div>
<div id="stable-live" class="badge">Descending</div>
<div class="factors">xₖ₊₁ = 0.80xₖ · yₖ₊₁ = 0.20yₖ</div>
<div class="stats">
<div class="stat"><label>Objective</label><strong id="stable-f">—</strong></div>
<div class="stat"><label>Distance</label><strong id="stable-dist">—</strong></div>
<div class="stat"><label>Iteration</label><strong id="stable-step">0</strong></div>
</div>
</article>
<article class="run-card" style="--run-color: var(--orange)">
<div class="run-head">
<div class="run-name"><span class="dot"></span>Marginal step</div>
<div class="eta">η = 0.50</div>
</div>
<div id="osc-live" class="badge">Bounded oscillation</div>
<div class="factors">xₖ₊₁ = 0.50xₖ · yₖ₊₁ = −1.00yₖ</div>
<div class="stats">
<div class="stat"><label>Objective</label><strong id="osc-f">—</strong></div>
<div class="stat"><label>Distance</label><strong id="osc-dist">—</strong></div>
<div class="stat"><label>Iteration</label><strong id="osc-step">0</strong></div>
</div>
</article>
</section>
<section class="glass history-panel" aria-label="Coordinate history chart">
<div class="history-head">
<h2>Signed y-coordinate</h2>
<span>the oscillating direction</span>
</div>
<canvas id="historyPlot"></canvas>
<div class="plot-legend">
<span style="color: var(--green)"><i></i>η = 0.20</span>
<span style="color: var(--orange)"><i></i>η = 0.50</span>
</div>
</section>
<div id="transport" class="glass">
<button id="pauseButton" class="primary" type="button">Pause</button>
<button id="restartButton" type="button">Restart</button>
<label class="speed-control" for="speed">
Speed
<input id="speed" type="range" min="1" max="8" step="0.5" value="3.5" />
<span id="speedValue">3.5/s</span>
</label>
</div>
<div class="glass legend">
<div class="legend-row">
<span style="color: var(--green)"><i></i></span>
<span style="color: var(--orange)"><i></i></span>
Both trails
</div>
Vertical height is f(x,y). Drag to orbit, scroll to zoom, and
double-click to reset the camera.
</div>
</div>
<div id="loading">Loading Three.js…</div>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
// ------------------------------------------------------------
// Objective and exact gradient-descent update
// ------------------------------------------------------------
const objective = (x, y) => 0.5 * (x * x + 4 * y * y);
const START = Object.freeze({ x: 3.4, y: 2.2 });
const HALF_DOMAIN = 4.5;
const VERTICAL_SCALE = 0.14;
const MAX_TRAIL_POINTS = 1000;
const stage = document.getElementById("stage");
const renderer = new THREE.WebGLRenderer({
antialias: true,
powerPreference: "high-performance"
});
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.12;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
stage.appendChild(renderer.domElement);
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x070b18);
scene.fog = new THREE.Fog(0x070b18, 15, 31);
const camera = new THREE.PerspectiveCamera(
43,
window.innerWidth / window.innerHeight,
0.1,
80
);
// ------------------------------------------------------------
// Lighting
// ------------------------------------------------------------
scene.add(new THREE.HemisphereLight(0xa8d3ff, 0x28152f, 1.75));
const keyLight = new THREE.DirectionalLight(0xffffff, 3.0);
keyLight.position.set(5, 12, 8);
keyLight.castShadow = true;
keyLight.shadow.mapSize.set(1024, 1024);
keyLight.shadow.camera.left = -7;
keyLight.shadow.camera.right = 7;
keyLight.shadow.camera.top = 7;
keyLight.shadow.camera.bottom = -7;
keyLight.shadow.camera.near = 0.5;
keyLight.shadow.camera.far = 30;
keyLight.shadow.bias = -0.0004;
scene.add(keyLight);
const rimLight = new THREE.DirectionalLight(0x785cff, 1.6);
rimLight.position.set(-7, 5, -6);
scene.add(rimLight);
// ------------------------------------------------------------
// Quadratic surface
// ------------------------------------------------------------
const surfaceSegments = 90;
const vertexCount = (surfaceSegments + 1) ** 2;
const positions = new Float32Array(vertexCount * 3);
const colors = new Float32Array(vertexCount * 3);
const indices = [];
const lowColor = new THREE.Color(0x183c78);
const highColor = new THREE.Color(0xf07855);
const tempColor = new THREE.Color();
let vertexIndex = 0;
for (let iz = 0; iz <= surfaceSegments; iz++) {
const y = -HALF_DOMAIN +
(2 * HALF_DOMAIN * iz) / surfaceSegments;
for (let ix = 0; ix <= surfaceSegments; ix++) {
const x = -HALF_DOMAIN +
(2 * HALF_DOMAIN * ix) / surfaceSegments;
const f = objective(x, y);
const height = f * VERTICAL_SCALE;
const t = THREE.MathUtils.clamp(f / 50.6, 0, 1);
positions[vertexIndex * 3] = x;
positions[vertexIndex * 3 + 1] = height;
positions[vertexIndex * 3 + 2] = y;
tempColor.copy(lowColor).lerp(highColor, Math.pow(t, 0.78));
tempColor.offsetHSL(0, 0, 0.035 * Math.sin(t * Math.PI));
colors[vertexIndex * 3] = tempColor.r;
colors[vertexIndex * 3 + 1] = tempColor.g;
colors[vertexIndex * 3 + 2] = tempColor.b;
vertexIndex++;
}
}
for (let iz = 0; iz < surfaceSegments; iz++) {
for (let ix = 0; ix < surfaceSegments; ix++) {
const a = iz * (surfaceSegments + 1) + ix;
const b = a + 1;
const c = a + surfaceSegments + 1;
const d = c + 1;
indices.push(a, c, b, b, c, d);
}
}
const surfaceGeometry = new THREE.BufferGeometry();
surfaceGeometry.setAttribute(
"position",
new THREE.BufferAttribute(positions, 3)
);
surfaceGeometry.setAttribute(
"color",
new THREE.BufferAttribute(colors, 3)
);
surfaceGeometry.setIndex(indices);
surfaceGeometry.computeVertexNormals();
const surface = new THREE.Mesh(
surfaceGeometry,
new THREE.MeshStandardMaterial({
vertexColors: true,
roughness: 0.68,
metalness: 0.08,
side: THREE.DoubleSide
})
);
surface.receiveShadow = true;
surface.castShadow = true;
scene.add(surface);
// ------------------------------------------------------------
// Grid drawn directly on the curved surface
// ------------------------------------------------------------
const gridVertices = [];
const gridSamples = 72;
for (let fixed = -4; fixed <= 4; fixed += 0.5) {
for (let i = 0; i < gridSamples; i++) {
const y0 = -HALF_DOMAIN + (2 * HALF_DOMAIN * i) / gridSamples;
const y1 = -HALF_DOMAIN +
(2 * HALF_DOMAIN * (i + 1)) / gridSamples;
gridVertices.push(
fixed,
objective(fixed, y0) * VERTICAL_SCALE + 0.012,
y0,
fixed,
objective(fixed, y1) * VERTICAL_SCALE + 0.012,
y1
);
gridVertices.push(
y0,
objective(y0, fixed) * VERTICAL_SCALE + 0.012,
fixed,
y1,
objective(y1, fixed) * VERTICAL_SCALE + 0.012,
fixed
);
}
}
const gridGeometry = new THREE.BufferGeometry();
gridGeometry.setAttribute(
"position",
new THREE.Float32BufferAttribute(gridVertices, 3)
);
const grid = new THREE.LineSegments(
gridGeometry,
new THREE.LineBasicMaterial({
color: 0xd5e7ff,
transparent: true,
opacity: 0.12,
depthWrite: false
})
);
scene.add(grid);
// ------------------------------------------------------------
// Convex polygon clipping, used to keep contours inside the domain
// ------------------------------------------------------------
function clipPolygon(polygon, axis, boundary, keepGreater) {
if (!polygon.length) return [];
const output = [];
let previous = polygon[polygon.length - 1];
let previousInside = keepGreater
? previous[axis] >= boundary
: previous[axis] <= boundary;
for (const current of polygon) {
const currentInside = keepGreater
? current[axis] >= boundary
: current[axis] <= boundary;
if (currentInside !== previousInside) {
const denominator = current[axis] - previous[axis];
const t = Math.abs(denominator) > 1e-10
? (boundary - previous[axis]) / denominator
: 0;
output.push([
previous[0] + t * (current[0] - previous[0]),
previous[1] + t * (current[1] - previous[1])
]);
}
if (currentInside) output.push(current);
previous = current;
previousInside = currentInside;
}
return output;
}
// Contours f(x,y) = c.
for (const level of [1, 2, 4, 8, 16, 32]) {
const polygon = [];
for (let i = 0; i < 180; i++) {
const angle = (i / 180) * Math.PI * 2;
polygon.push([
Math.sqrt(2 * level) * Math.cos(angle),
Math.sqrt(level / 2) * Math.sin(angle)
]);
}
let clipped = clipPolygon(polygon, 0, -HALF_DOMAIN, true);
clipped = clipPolygon(clipped, 0, HALF_DOMAIN, false);
clipped = clipPolygon(clipped, 1, -HALF_DOMAIN, true);
clipped = clipPolygon(clipped, 1, HALF_DOMAIN, false);
if (clipped.length < 3) continue;
const contourPoints = clipped.map(
([x, y]) =>
new THREE.Vector3(
x,
level * VERTICAL_SCALE + 0.026,
y
)
);
const contour = new THREE.LineLoop(
new THREE.BufferGeometry().setFromPoints(contourPoints),
new THREE.LineBasicMaterial({
color: 0xc7e2ff,
transparent: true,
opacity: 0.36,
depthWrite: false
})
);
scene.add(contour);
}
// Surface boundary and coordinate axes.
const boundaryPoints = [];
const boundarySamples = 48;
for (let i = 0; i < boundarySamples; i++) {
const t0 = (i / boundarySamples) * 4;
const t1 = ((i + 1) / boundarySamples) * 4;
const edgePoints = [
[-HALF_DOMAIN + t0, -HALF_DOMAIN],
[-HALF_DOMAIN + t1, -HALF_DOMAIN],
[HALF_DOMAIN, -HALF_DOMAIN + t0],
[HALF_DOMAIN, -HALF_DOMAIN + t1],
[HALF_DOMAIN - t0, HALF_DOMAIN],
[HALF_DOMAIN - t1, HALF_DOMAIN],
[-HALF_DOMAIN, HALF_DOMAIN - t0],
[-HALF_DOMAIN, HALF_DOMAIN - t1]
];
for (let p = 0; p < edgePoints.length; p += 2) {
const [x0, y0] = edgePoints[p];
const [x1, y1] = edgePoints[p + 1];
boundaryPoints.push(
new THREE.Vector3(x0, objective(x0, y0) * VERTICAL_SCALE, y0),
new THREE.Vector3(x1, objective(x1, y1) * VERTICAL_SCALE, y1)
);
}
}
scene.add(
new THREE.LineSegments(
new THREE.BufferGeometry().setFromPoints(boundaryPoints),
new THREE.LineBasicMaterial({
color: 0x8fb6ff,
transparent: true,
opacity: 0.55
})
)
);
const axisMaterial = new THREE.LineBasicMaterial({
color: 0xbdd4ff,
transparent: true,
opacity: 0.65
});
scene.add(
new THREE.Line(
new THREE.BufferGeometry().setFromPoints([
new THREE.Vector3(-HALF_DOMAIN, 0.035, 0),
new THREE.Vector3(HALF_DOMAIN, 0.035, 0)
]),
axisMaterial
)
);
scene.add(
new THREE.Line(
new THREE.BufferGeometry().setFromPoints([
new THREE.Vector3(0, 0.035, -HALF_DOMAIN),
new THREE.Vector3(0, 0.035, HALF_DOMAIN)
]),
axisMaterial
)
);
// Minimum marker.
const minimum = new THREE.Mesh(
new THREE.SphereGeometry(0.055, 20, 14),
new THREE.MeshStandardMaterial({
color: 0x9affd7,
emissive: 0x42f5b5,
emissiveIntensity: 1.7,
roughness: 0.3
})
);
minimum.position.y = 0.055;
scene.add(minimum);
const minimumRing = new THREE.Mesh(
new THREE.RingGeometry(0.10, 0.17, 48),
new THREE.MeshBasicMaterial({
color: 0x42f5b5,
transparent: true,
opacity: 0.65,
side: THREE.DoubleSide,
depthWrite: false
})
);
minimumRing.rotation.x = -Math.PI / 2;
minimumRing.position.y = 0.026;
scene.add(minimumRing);
// Shared start marker.
const startRing = new THREE.Mesh(
new THREE.TorusGeometry(0.18, 0.025, 12, 48),
new THREE.MeshBasicMaterial({
color: 0xffffff,
transparent: true,
opacity: 0.9
})
);
startRing.rotation.x = Math.PI / 2;
startRing.position.set(
START.x,
objective(START.x, START.y) * VERTICAL_SCALE + 0.08,
START.y
);
scene.add(startRing);
// Small in-scene axis labels made without external assets.
function makeLabelSprite(text) {
const canvas = document.createElement("canvas");
canvas.width = 128;
canvas.height = 64;
const context = canvas.getContext("2d");
context.clearRect(0, 0, 128, 64);
context.font = "700 38px system-ui";
context.textAlign = "center";
context.textBaseline = "middle";
context.shadowColor = "rgba(0,0,0,.8)";
context.shadowBlur = 10;
context.fillStyle = "#eaf2ff";
context.fillText(text, 64, 32);
const texture = new THREE.CanvasTexture(canvas);
texture.colorSpace = THREE.SRGBColorSpace;
const sprite = new THREE.Sprite(
new THREE.SpriteMaterial({
map: texture,
transparent: true,
depthTest: false,
depthWrite: false
})
);
sprite.scale.set(0.55, 0.275, 1);
return sprite;
}
const xLabel = makeLabelSprite("x");
xLabel.position.set(4.72, 0.12, 0);
scene.add(xLabel);
const yLabel = makeLabelSprite("y");
yLabel.position.set(0, 0.12, 4.72);
scene.add(yLabel);
// ------------------------------------------------------------
// Trajectory objects
// ------------------------------------------------------------
function createTrail(color) {
const geometry = new THREE.BufferGeometry();
const attribute = new THREE.BufferAttribute(
new Float32Array(MAX_TRAIL_POINTS * 3),
3
);
attribute.setUsage(THREE.DynamicDrawUsage);
geometry.setAttribute("position", attribute);
geometry.setDrawRange(0, 0);
const line = new THREE.Line(
geometry,
new THREE.LineBasicMaterial({
color,
transparent: true,
opacity: 0.95,
depthWrite: false
})
);
line.frustumCulled = false;
line.renderOrder = 3;
const points = new THREE.Points(
geometry,
new THREE.PointsMaterial({
color,
size: 0.06,
sizeAttenuation: true,
transparent: true,
opacity: 0.9,
depthWrite: false
})
);
points.frustumCulled = false;
points.renderOrder = 4;
scene.add(line, points);
return { geometry, attribute, line, points };
}
const stableMarker = new THREE.Mesh(
new THREE.SphereGeometry(0.095, 24, 16),
new THREE.MeshStandardMaterial({
color: 0x42f5b5,
emissive: 0x42f5b5,
emissiveIntensity: 1.1,
roughness: 0.28,
metalness: 0.12
})
);
stableMarker.castShadow = true;
scene.add(stableMarker);
const oscillateMarker = new THREE.Mesh(
new THREE.OctahedronGeometry(0.13, 0),
new THREE.MeshBasicMaterial({
color: 0xffb454,
wireframe: true,
transparent: true,
opacity: 0.95,
depthWrite: false
})
);
oscillateMarker.renderOrder = 5;
scene.add(oscillateMarker);
const runs = [
{
key: "stable",
eta: 0.2,
color: 0x42f5b5,
x: START.x,
y: START.y,
step: 0,
pointCount: 0,
history: [],
marker: stableMarker,
trail: createTrail(0x42f5b5),
stableDone: false
},
{
key: "oscillate",
eta: 0.5,
color: 0xffb454,
x: START.x,
y: START.y,
step: 0,
pointCount: 0,
history: [],
marker: oscillateMarker,
trail: createTrail(0xffb454),
stableDone: false
}
];
function appendTrailPoint(run) {
if (run.pointCount >= MAX_TRAIL_POINTS) return;
const array = run.trail.attribute.array;
const offset = run.pointCount * 3;
const height = objective(run.x, run.y) * VERTICAL_SCALE + 0.035;
array[offset] = run.x;
array[offset + 1] = height;
array[offset + 2] = run.y;
run.pointCount++;
run.trail.geometry.setDrawRange(0, run.pointCount);
run.trail.attribute.needsUpdate = true;
}
function updateMarker(run) {
run.marker.position.set(
run.x,
objective(run.x, run.y) * VERTICAL_SCALE + 0.09,
run.y
);
}
// The actual update rule used by the animation:
// x <- x - eta * df/dx, with df/dx = x
// y <- y - eta * df/dy, with df/dy = 4y
function performGradientDescentStep(run) {
const gradientX = run.x;
const gradientY = 4 * run.y;
run.x -= run.eta * gradientX;
run.y -= run.eta * gradientY;
run.step++;
run.history.push(run.y);
appendTrailPoint(run);
updateMarker(run);
if (
run.key === "stable" &&
Math.hypot(run.x, run.y) < 0.001
) {
run.stableDone = true;
}
}
// ------------------------------------------------------------
// UI updates and history plot
// ------------------------------------------------------------
const stableF = document.getElementById("stable-f");
const stableDist = document.getElementById("stable-dist");
const stableStep = document.getElementById("stable-step");
const stableLive = document.getElementById("stable-live");
const oscF = document.getElementById("osc-f");
const oscDist = document.getElementById("osc-dist");
const oscStep = document.getElementById("osc-step");
const oscLive = document.getElementById("osc-live");
function updateCards() {
const stable = runs[0];
const oscillate = runs[1];
stableF.textContent = objective(stable.x, stable.y).toFixed(4);
stableDist.textContent = Math.hypot(stable.x, stable.y).toFixed(4);
stableStep.textContent = stable.step;
stableLive.textContent = stable.stableDone ? "Converged" : "Descending";
oscF.textContent = objective(oscillate.x, oscillate.y).toFixed(4);
oscDist.textContent = Math.hypot(oscillate.x, oscillate.y).toFixed(4);
oscStep.textContent = oscillate.step;
oscLive.textContent = "Bounded oscillation";
}
const historyCanvas = document.getElementById("historyPlot");
const historyContext = historyCanvas.getContext("2d");
function drawHistory() {
const rect = historyCanvas.getBoundingClientRect();
if (!rect.width || !rect.height) return;
const dpr = Math.min(window.devicePixelRatio, 2);
const pixelWidth = Math.round(rect.width * dpr);
const pixelHeight = Math.round(rect.height * dpr);
if (
historyCanvas.width !== pixelWidth ||
historyCanvas.height !== pixelHeight
) {
historyCanvas.width = pixelWidth;
historyCanvas.height = pixelHeight;
}
const context = historyContext;
context.setTransform(dpr, 0, 0, dpr, 0, 0);
context.clearRect(0, 0, rect.width, rect.height);
const margin = { left: 34, right: 10, top: 10, bottom: 25 };
const width = rect.width - margin.left - margin.right;
const height = rect.height - margin.top - margin.bottom;
const maxStep = Math.max(...runs.map(run => run.step));
const first = Math.max(0, maxStep - 44);
const last = Math.max(10, maxStep + 1);
const visibleValues = [];
for (const run of runs) {
visibleValues.push(
...run.history.slice(first, Math.min(run.history.length, last + 1))
);
}
const maxAbsY = Math.max(1, ...visibleValues.map(value => Math.abs(value)));
const maxY = Math.ceil(maxAbsY * 1.18 * 2) / 2;
function mapX(index) {
return margin.left +
((index - first) / Math.max(1, last - first)) * width;
}
function mapY(value) {
return margin.top + height * (0.5 - value / (2 * maxY));
}
// Horizontal grid and zero line.
context.lineWidth = 1;
for (let i = 0; i <= 4; i++) {
const value = -maxY + (2 * maxY * i) / 4;
const y = mapY(value);
context.strokeStyle = Math.abs(value) < 1e-8
? "rgba(205,222,255,.30)"
: "rgba(160,190,240,.10)";
context.beginPath();
context.moveTo(margin.left, y);
context.lineTo(margin.left + width, y);
context.stroke();
}
context.font = "9px system-ui";
context.fillStyle = "rgba(170,190,225,.72)";
context.textAlign = "right";
context.fillText(maxY.toFixed(1), margin.left - 7, mapY(maxY) + 3);
context.fillText("0", margin.left - 7, mapY(0) + 3);
context.fillText((-maxY).toFixed(1), margin.left - 7, mapY(-maxY) + 3);
context.textAlign = "left";
context.fillText(`k=${first}`, margin.left, rect.height - 5);
context.textAlign = "right";
context.fillText(`k=${last}`, margin.left + width, rect.height - 5);
// Actual signed-y samples from both runs.
for (const run of runs) {
context.strokeStyle = run.key === "stable"
? "#42f5b5"
: "#ffb454";
context.lineWidth = 2;
context.lineJoin = "round";
context.lineCap = "round";
context.beginPath();
let started = false;
for (let index = first; index < run.history.length; index++) {
const x = mapX(index);
const y = mapY(run.history[index]);
if (!started) {
context.moveTo(x, y);
started = true;
} else {
context.lineTo(x, y);
}
}
context.stroke();
}
}
function resetRuns() {
for (const run of runs) {
run.x = START.x;
run.y = START.y;
run.step = 0;
run.pointCount = 0;
run.stableDone = false;
run.history = [run.y];
run.trail.geometry.setDrawRange(0, 0);
appendTrailPoint(run);
updateMarker(run);
}
updateCards();
drawHistory();
}
// ------------------------------------------------------------
// Camera controls implemented directly (no addons)
// ------------------------------------------------------------
const cameraTarget = new THREE.Vector3(0, 1.35, 0);
const desiredCamera = {
theta: 0.67,
phi: 0.92,
radius: 14.5
};
const currentCamera = {
theta: desiredCamera.theta,
phi: desiredCamera.phi,
radius: desiredCamera.radius
};
let dragging = false;
let previousPointerX = 0;
let previousPointerY = 0;
renderer.domElement.addEventListener("pointerdown", event => {
if (event.button !== 0) return;
dragging = true;
previousPointerX = event.clientX;
previousPointerY = event.clientY;
renderer.domElement.setPointerCapture(event.pointerId);
});
renderer.domElement.addEventListener("pointermove", event => {
if (!dragging) return;
const deltaX = event.clientX - previousPointerX;
const deltaY = event.clientY - previousPointerY;
previousPointerX = event.clientX;
previousPointerY = event.clientY;
desiredCamera.theta -= deltaX * 0.006;
desiredCamera.phi = THREE.MathUtils.clamp(
desiredCamera.phi - deltaY * 0.005,
0.42,
1.38
);
});
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(
"wheel",
event => {
event.preventDefault();
desiredCamera.radius = THREE.MathUtils.clamp(
desiredCamera.radius * Math.exp(event.deltaY * 0.001),
8,
23
);
},
{ passive: false }
);
renderer.domElement.addEventListener("dblclick", () => {
desiredCamera.theta = 0.67;
desiredCamera.phi = 0.92;
desiredCamera.radius = 14.5;
});
function updateCamera(delta) {
const smoothing = 1 - Math.exp(-7 * delta);
currentCamera.theta = THREE.MathUtils.lerp(
currentCamera.theta,
desiredCamera.theta,
smoothing
);
currentCamera.phi = THREE.MathUtils.lerp(
currentCamera.phi,
desiredCamera.phi,
smoothing
);
currentCamera.radius = THREE.MathUtils.lerp(
currentCamera.radius,
desiredCamera.radius,
smoothing
);
const { theta, phi, radius } = currentCamera;
camera.position.set(
cameraTarget.x + radius * Math.sin(phi) * Math.sin(theta),
cameraTarget.y + radius * Math.cos(phi),
cameraTarget.z + radius * Math.sin(phi) * Math.cos(theta)
);
camera.lookAt(cameraTarget);
}
// ------------------------------------------------------------
// Transport controls
// ------------------------------------------------------------
let running = true;
let speed = 3.5;
let accumulator = 0;
const pauseButton = document.getElementById("pauseButton");
const restartButton = document.getElementById("restartButton");
const speedInput = document.getElementById("speed");
const speedValue = document.getElementById("speedValue");
pauseButton.addEventListener("click", () => {
running = !running;
pauseButton.textContent = running ? "Pause" : "Resume";
pauseButton.classList.toggle("primary", running);
accumulator = 0;
});
restartButton.addEventListener("click", () => {
resetRuns();
running = true;
pauseButton.textContent = "Pause";
pauseButton.classList.add("primary");
accumulator = 0;
});
speedInput.addEventListener("input", () => {
speed = Number(speedInput.value);
speedValue.textContent = `${speed.toFixed(1)}/s`;
});
window.addEventListener("keydown", event => {
if (event.target instanceof HTMLInputElement) return;
if (event.code === "Space") {
event.preventDefault();
pauseButton.click();
}
if (event.key.toLowerCase() === "r") {
restartButton.click();
}
});
function resize() {
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
drawHistory();
}
window.addEventListener("resize", resize);
// ------------------------------------------------------------
// Main loop
// ------------------------------------------------------------
const clock = new THREE.Clock();
function animate() {
requestAnimationFrame(animate);
const delta = Math.min(clock.getDelta(), 0.05);
if (running) {
accumulator += delta * speed;
while (accumulator >= 1) {
for (const run of runs) {
if (run.key === "stable" && run.stableDone) continue;
performGradientDescentStep(run);
}
accumulator -= 1;
updateCards();
drawHistory();
}
}
updateCamera(delta);
const pulse = 1 + Math.sin(clock.elapsedTime * 2.4) * 0.12;
minimumRing.scale.setScalar(pulse);
startRing.rotation.z += delta * 0.35;
renderer.render(scene, camera);
}
resize();
resetRuns();
document.getElementById("loading").remove();
animate();
</script>
</body>
</html>
```