Prompt specification
Build or customize the Three.js 3D scene "Move One Block Before Tipping" 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: Move One Block Before Tipping
Category: Games & Play · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/move-one-block-before-tipping-x3514
Scene Description Prompt:
Make a cutaway Three.js scene in a self-contained HTML file using cdnjs: move one block before tipping. Create a tabletop balance puzzle with bounded block translations. Check quasi-static tipping at every support interface and show the first failing substack before animating a controlled fall.
Working Three.js Starter (move-one-block-before-tipping-x3514):
```html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>Cutaway Balance Puzzle</title>
<style>
:root {
color-scheme: dark;
--bg: #111820;
--panel: #17212b;
--panel-2: #1d2935;
--line: #314150;
--text: #edf4f7;
--muted: #93a7b5;
--cyan: #63d7e8;
--green: #62d59a;
--amber: #f3c969;
--red: #ff6b68;
}
* { 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;
cursor: pointer;
}
button:disabled {
cursor: not-allowed;
opacity: .42;
}
#app {
display: grid;
grid-template-columns: minmax(0, 1fr) 380px;
width: 100%;
height: 100dvh;
}
#stage {
position: relative;
min-width: 0;
min-height: 0;
overflow: hidden;
background: #dce4e8;
}
#stage canvas {
position: absolute;
inset: 0;
display: block;
width: 100%;
height: 100%;
touch-action: none;
}
.scene-hud {
position: absolute;
z-index: 3;
inset: 18px 18px auto;
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 12px;
pointer-events: none;
}
.scene-title {
padding: 11px 13px;
border: 1px solid rgba(255,255,255,.42);
border-radius: 12px;
background: rgba(20,31,40,.82);
box-shadow: 0 12px 35px rgba(22,33,41,.12);
backdrop-filter: blur(10px);
}
.eyebrow {
color: var(--cyan);
font-size: 10px;
font-weight: 800;
letter-spacing: .18em;
text-transform: uppercase;
}
.scene-title strong {
display: block;
margin-top: 3px;
font-size: 16px;
letter-spacing: .01em;
}
.scene-title small {
display: block;
margin-top: 3px;
color: #b7c5cd;
font-size: 11px;
}
.mode-pill {
padding: 8px 10px;
border: 1px solid rgba(255,255,255,.42);
border-radius: 999px;
background: rgba(20,31,40,.82);
color: #dce8ed;
font-size: 10px;
font-weight: 800;
letter-spacing: .12em;
text-transform: uppercase;
backdrop-filter: blur(10px);
}
#sceneCallout {
position: absolute;
z-index: 5;
display: none;
min-width: 205px;
max-width: 270px;
padding: 10px 12px;
border: 1px solid rgba(255,107,104,.85);
border-left: 4px solid var(--red);
border-radius: 9px;
background: rgba(35,20,24,.94);
box-shadow: 0 12px 30px rgba(28,12,16,.2);
color: #fff;
pointer-events: none;
transform: translate(-50%, -100%);
transition: opacity .25s ease;
}
#sceneCallout.visible { display: block; }
#sceneCallout strong {
display: block;
color: #ff908d;
font-size: 11px;
letter-spacing: .08em;
text-transform: uppercase;
}
#sceneCallout span {
display: block;
margin-top: 3px;
color: #f5d8d7;
font-size: 12px;
}
.scene-legend {
position: absolute;
z-index: 3;
left: 18px;
bottom: 18px;
display: flex;
flex-wrap: wrap;
gap: 8px 13px;
max-width: calc(100% - 36px);
padding: 9px 11px;
border: 1px solid rgba(255,255,255,.4);
border-radius: 10px;
background: rgba(20,31,40,.82);
color: #c4d0d6;
font-size: 10px;
pointer-events: none;
backdrop-filter: blur(10px);
}
.legend-item {
display: flex;
align-items: center;
gap: 6px;
white-space: nowrap;
}
.dot {
width: 8px;
height: 8px;
border-radius: 50%;
background: var(--green);
box-shadow: 0 0 0 2px rgba(98,213,154,.15);
}
.dot.amber { background: var(--amber); }
.dot.red { background: var(--red); }
.dot.cyan { background: var(--cyan); }
aside {
min-height: 0;
overflow-y: auto;
border-left: 1px solid var(--line);
background:
radial-gradient(circle at 100% 0%, rgba(99,215,232,.08), transparent 30%),
var(--panel);
padding: 22px 20px 28px;
}
h1 {
margin: 6px 0 8px;
font-size: 24px;
line-height: 1.12;
letter-spacing: -.025em;
}
.intro {
margin: 0;
color: var(--muted);
font-size: 13px;
line-height: 1.55;
}
.objective {
margin: 17px 0;
padding: 12px 13px;
border: 1px solid #385060;
border-radius: 11px;
background: rgba(99,215,232,.055);
font-size: 12px;
line-height: 1.5;
}
.objective strong {
display: block;
margin-bottom: 3px;
color: var(--cyan);
font-size: 10px;
letter-spacing: .13em;
text-transform: uppercase;
}
.section-title {
display: flex;
align-items: center;
justify-content: space-between;
margin: 19px 0 9px;
color: #cbd8df;
font-size: 10px;
font-weight: 800;
letter-spacing: .13em;
text-transform: uppercase;
}
.section-title span {
color: #718795;
font-weight: 600;
letter-spacing: .03em;
text-transform: none;
}
.block-grid {
display: grid;
grid-template-columns: repeat(5, 1fr);
gap: 6px;
}
.block-chip {
min-width: 0;
padding: 9px 3px 8px;
border: 1px solid var(--line);
border-radius: 9px;
background: var(--panel-2);
text-align: center;
transition: border-color .15s, background .15s, transform .15s;
}
.block-chip:hover:not(:disabled) {
border-color: #607c8c;
transform: translateY(-1px);
}
.block-chip.selected {
border-color: var(--cyan);
background: rgba(99,215,232,.12);
}
.block-chip b {
display: block;
font-size: 15px;
}
.block-chip small {
display: block;
margin-top: 2px;
overflow: hidden;
color: var(--muted);
font-size: 8px;
letter-spacing: .06em;
text-transform: uppercase;
white-space: nowrap;
}
.slider-row {
display: grid;
grid-template-columns: 1fr auto;
align-items: center;
gap: 10px;
margin-top: 11px;
}
input[type="range"] {
width: 100%;
accent-color: var(--cyan);
cursor: ew-resize;
}
#translationReadout {
min-width: 76px;
padding: 7px 8px;
border: 1px solid var(--line);
border-radius: 8px;
background: #111a22;
color: #d9e7ec;
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 11px;
text-align: center;
}
.hint {
margin: 7px 0 0;
color: #78909e;
font-size: 10px;
line-height: 1.45;
}
.button-row {
display: grid;
grid-template-columns: 1fr auto;
gap: 8px;
margin-top: 14px;
}
.primary, .secondary {
min-height: 42px;
border-radius: 9px;
font-weight: 800;
font-size: 11px;
letter-spacing: .08em;
text-transform: uppercase;
}
.primary {
border: 1px solid #79e3f0;
background: var(--cyan);
color: #102128;
box-shadow: 0 8px 24px rgba(99,215,232,.12);
}
.primary:hover:not(:disabled) { background: #83e5f2; }
.secondary {
padding: 0 15px;
border: 1px solid var(--line);
background: #1c2833;
color: #b9c9d1;
}
.secondary:hover:not(:disabled) { border-color: #617887; }
.status-card {
margin-top: 18px;
padding: 12px 13px;
border: 1px solid var(--line);
border-radius: 11px;
background: #121b23;
}
.status-card.fail {
border-color: rgba(255,107,104,.55);
background: rgba(255,107,104,.07);
}
.status-card.success {
border-color: rgba(98,213,154,.45);
background: rgba(98,213,154,.06);
}
#statusTitle {
margin: 0 0 4px;
font-size: 13px;
}
#statusDetail {
margin: 0;
color: var(--muted);
font-size: 11px;
line-height: 1.45;
}
#diagnostics {
display: grid;
gap: 6px;
}
.diag-row {
display: grid;
grid-template-columns: 9px minmax(0, 1fr) auto;
align-items: center;
gap: 9px;
padding: 9px 10px;
border: 1px solid #2b3946;
border-radius: 9px;
background: #141e27;
}
.diag-row.fail {
border-color: rgba(255,107,104,.7);
background: rgba(255,107,104,.08);
}
.diag-row.warn {
border-color: rgba(243,201,105,.5);
}
.diag-row .dot { box-shadow: none; }
.diag-name {
display: flex;
align-items: center;
gap: 7px;
min-width: 0;
}
.diag-name strong {
font-size: 11px;
white-space: nowrap;
}
.first-tag {
padding: 2px 4px;
border-radius: 4px;
background: var(--red);
color: #2b1113;
font-size: 7px;
font-weight: 900;
letter-spacing: .08em;
}
.diag-data {
display: block;
margin-top: 3px;
overflow: hidden;
color: #78909e;
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 9px;
text-overflow: ellipsis;
white-space: nowrap;
}
.diag-state {
font-size: 8px;
font-weight: 900;
letter-spacing: .08em;
}
.diag-row.pass .diag-state { color: var(--green); }
.diag-row.warn .diag-state { color: var(--amber); }
.diag-row.fail .diag-state { color: var(--red); }
.toggle-row {
display: flex;
align-items: center;
justify-content: space-between;
margin-top: 11px;
color: #9cb0bc;
font-size: 11px;
}
.toggle-row input { accent-color: var(--cyan); }
.method {
margin-top: 18px;
padding-top: 14px;
border-top: 1px solid var(--line);
color: #718895;
font-size: 10px;
line-height: 1.55;
}
.method strong { color: #aebfc8; }
@media (max-width: 850px) {
#app {
grid-template-columns: 1fr;
grid-template-rows: 62dvh 38dvh;
}
aside {
border-top: 1px solid var(--line);
border-left: 0;
}
.scene-hud {
inset: 10px 10px auto;
}
.scene-title {
padding: 8px 10px;
}
.scene-title small { display: none; }
.scene-legend { left: 10px; bottom: 10px; }
}
</style>
</head>
<body>
<main id="app">
<section id="stage" aria-label="Interactive three-dimensional balance puzzle">
<div class="scene-hud">
<div class="scene-title">
<div class="eyebrow">Cutaway / Section 01</div>
<strong>Quasi-static balance test</strong>
<small>Drag a block along its bounded translation rail.</small>
</div>
<div id="modePill" class="mode-pill">Live scan</div>
</div>
<div id="sceneCallout" role="status">
<strong id="calloutTitle">First failure</strong>
<span id="calloutText"></span>
</div>
<div class="scene-legend">
<span class="legend-item"><i class="dot"></i>Stable contact</span>
<span class="legend-item"><i class="dot amber"></i>Near edge</span>
<span class="legend-item"><i class="dot red"></i>Outside support</span>
<span class="legend-item"><i class="dot cyan"></i>Mass-weighted COM</span>
</div>
</section>
<aside>
<div class="eyebrow">Tabletop mechanics</div>
<h1>One block. One translation.</h1>
<p class="intro">
Shift one block, then test every support interface. The first unstable
substack is isolated before a constrained rotation begins.
</p>
<div class="objective">
<strong>Objective</strong>
Make the stack fail its quasi-static balance test. Try moving the cap
block E beyond the right edge of block D.
</div>
<div class="section-title">
Select one block
<span>Click the scene or use these</span>
</div>
<div id="blockGrid" class="block-grid"></div>
<div class="slider-row">
<input
id="translation"
type="range"
min="-1.25"
max="1.25"
step="0.01"
value="0"
aria-label="Bounded horizontal block translation"
>
<output id="translationReadout">E +0.00 m</output>
</div>
<p class="hint">
Translation is bounded to ±1.25 m. Once moved, the other blocks lock
until Reset is pressed.
</p>
<div class="button-row">
<button id="testButton" class="primary">Test stability</button>
<button id="resetButton" class="secondary">Reset</button>
</div>
<div id="statusCard" class="status-card">
<h2 id="statusTitle">Ready for a translation</h2>
<p id="statusDetail">
Choose one block, move it, and press Test stability.
</p>
</div>
<div class="section-title">
Support-interface scan
<span>Table upward</span>
</div>
<div id="diagnostics"></div>
<label class="toggle-row" for="showForces">
<span>Show COMs and resultant forces</span>
<input id="showForces" type="checkbox" checked>
</label>
<div class="method">
<strong>Test method.</strong>
At each interface, the mass-weighted center of mass of the entire
substack above that interface is compared with the horizontal contact
overlap. A resultant outside the overlap is a tipping failure.
The scan proceeds from the table upward, and the first failing
substack is held and highlighted for 1.35 seconds before rotation.
</div>
</aside>
</main>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
const stage = document.querySelector("#stage");
const blockGrid = document.querySelector("#blockGrid");
const diagnostics = document.querySelector("#diagnostics");
const translation = document.querySelector("#translation");
const translationReadout = document.querySelector("#translationReadout");
const testButton = document.querySelector("#testButton");
const resetButton = document.querySelector("#resetButton");
const showForces = document.querySelector("#showForces");
const statusCard = document.querySelector("#statusCard");
const statusTitle = document.querySelector("#statusTitle");
const statusDetail = document.querySelector("#statusDetail");
const modePill = document.querySelector("#modePill");
const sceneCallout = document.querySelector("#sceneCallout");
const calloutTitle = document.querySelector("#calloutTitle");
const calloutText = document.querySelector("#calloutText");
const MOVEMENT_LIMIT = 1.25;
const EPS = 0.0001;
const RED = new THREE.Color("#ff6b68");
const GREEN = new THREE.Color("#62d59a");
const AMBER = new THREE.Color("#f3c969");
const CYAN = new THREE.Color("#63d7e8");
const blocks = [
{ id: "A", name: "Foot", w: 3.00, h: 0.90, d: 1.45, x: -0.10, color: "#ef8354" },
{ id: "B", name: "Beam", w: 2.50, h: 0.80, d: 1.30, x: 0.05, color: "#f1c75b" },
{ id: "C", name: "Riser", w: 2.00, h: 0.70, d: 1.15, x: 0.18, color: "#55c6a5" },
{ id: "D", name: "Post", w: 1.50, h: 0.60, d: 1.00, x: 0.28, color: "#5795df" },
{ id: "E", name: "Cap", w: 1.10, h: 0.50, d: 0.85, x: 0.35, color: "#a97be5" }
];
let bottom = 0;
for (const b of blocks) {
b.initialX = b.x;
b.y = bottom + b.h / 2;
b.bottom = bottom;
b.top = bottom + b.h;
b.mass = b.w * b.h * b.d;
bottom += b.h;
}
const scene = new THREE.Scene();
scene.background = new THREE.Color("#dce4e8");
scene.fog = new THREE.Fog("#dce4e8", 13, 24);
const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.06;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.domElement.style.touchAction = "none";
stage.prepend(renderer.domElement);
const camera = new THREE.OrthographicCamera(-5, 5, 3.5, -3.5, 0.1, 40);
camera.position.set(0, 3.45, 10);
camera.lookAt(0, 1.65, 0);
scene.add(new THREE.HemisphereLight(0xf5fbff, 0x64717a, 2.05));
const sun = new THREE.DirectionalLight(0xfff6e8, 3.1);
sun.position.set(-4.5, 8, 6.5);
sun.castShadow = true;
sun.shadow.mapSize.set(2048, 2048);
sun.shadow.camera.left = -7;
sun.shadow.camera.right = 7;
sun.shadow.camera.top = 7;
sun.shadow.camera.bottom = -5;
sun.shadow.camera.near = 0.5;
sun.shadow.camera.far = 22;
sun.shadow.bias = -0.00035;
scene.add(sun);
const fill = new THREE.DirectionalLight(0xbfe9ff, 1.0);
fill.position.set(5, 3, 2);
scene.add(fill);
function makeHatchTexture() {
const canvas = document.createElement("canvas");
canvas.width = 1024;
canvas.height = 128;
const ctx = canvas.getContext("2d");
ctx.fillStyle = "#293741";
ctx.fillRect(0, 0, canvas.width, canvas.height);
ctx.strokeStyle = "rgba(187,213,225,.20)";
ctx.lineWidth = 2;
for (let x = -128; x < canvas.width + 128; x += 28) {
ctx.beginPath();
ctx.moveTo(x, 0);
ctx.lineTo(x + 128, 128);
ctx.stroke();
}
ctx.fillStyle = "rgba(222,239,246,.75)";
ctx.font = "600 25px monospace";
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.fillText("FIXED TABLE • EXPOSED CUT FACE • y = 0", 512, 66);
const texture = new THREE.CanvasTexture(canvas);
texture.colorSpace = THREE.SRGBColorSpace;
return texture;
}
const table = new THREE.Mesh(
new THREE.BoxGeometry(8.4, 0.45, 3.4),
new THREE.MeshStandardMaterial({
color: 0x33434e,
roughness: 0.82,
metalness: 0.08
})
);
table.position.set(0, -0.225, 0);
table.castShadow = true;
table.receiveShadow = true;
scene.add(table);
const cutFace = new THREE.Mesh(
new THREE.PlaneGeometry(8.36, 0.43),
new THREE.MeshStandardMaterial({
map: makeHatchTexture(),
roughness: 0.9
})
);
cutFace.position.set(0, -0.225, 1.706);
scene.add(cutFace);
const tableEdge = new THREE.Line(
new THREE.BufferGeometry().setFromPoints([
new THREE.Vector3(-4.18, 0.008, 1.68),
new THREE.Vector3(4.18, 0.008, 1.68)
]),
new THREE.LineBasicMaterial({ color: 0xd9eef3 })
);
scene.add(tableEdge);
const tableGrid = new THREE.GridHelper(8, 32, 0x81939d, 0x9aaab3);
tableGrid.position.y = 0.007;
tableGrid.scale.z = 0.37;
tableGrid.material.transparent = true;
tableGrid.material.opacity = 0.25;
tableGrid.material.depthWrite = false;
scene.add(tableGrid);
const rulerPositions = [];
for (let x = -4; x <= 4.001; x += 0.25) {
const major = Math.abs(x - Math.round(x)) < 0.01;
rulerPositions.push(
x, 0.012, 1.47,
x, 0.012, major ? 1.61 : 1.55
);
}
const ruler = new THREE.LineSegments(
new THREE.BufferGeometry().setAttribute(
"position",
new THREE.Float32BufferAttribute(rulerPositions, 3)
),
new THREE.LineBasicMaterial({
color: 0xb7cbd4,
transparent: true,
opacity: 0.85
})
);
scene.add(ruler);
const backGridPositions = [];
for (let x = -4.5; x <= 4.5; x += 0.5) {
backGridPositions.push(x, -0.7, -1.35, x, 4.6, -1.35);
}
for (let y = -0.5; y <= 4.5; y += 0.5) {
backGridPositions.push(-4.5, y, -1.35, 4.5, y, -1.35);
}
const backGrid = new THREE.LineSegments(
new THREE.BufferGeometry().setAttribute(
"position",
new THREE.Float32BufferAttribute(backGridPositions, 3)
),
new THREE.LineBasicMaterial({
color: 0x8499a5,
transparent: true,
opacity: 0.16
})
);
scene.add(backGrid);
function roundedRectangleShape(w, h, r) {
const s = new THREE.Shape();
const x = -w / 2;
const y = -h / 2;
s.moveTo(x + r, y);
s.lineTo(x + w - r, y);
s.quadraticCurveTo(x + w, y, x + w, y + r);
s.lineTo(x + w, y + h - r);
s.quadraticCurveTo(x + w, y + h, x + w - r, y + h);
s.lineTo(x + r, y + h);
s.quadraticCurveTo(x, y + h, x, y + h - r);
s.lineTo(x, y + r);
s.quadraticCurveTo(x, y, x + r, y);
return s;
}
function makeBlockGeometry(w, h, d) {
const bevel = 0.035;
const shape = roundedRectangleShape(w - bevel * 2, h - bevel * 2, 0.075);
const geometry = new THREE.ExtrudeGeometry(shape, {
depth: d - bevel * 2,
bevelEnabled: true,
bevelThickness: bevel,
bevelSize: bevel,
bevelSegments: 2,
curveSegments: 5,
steps: 1
});
geometry.translate(0, 0, -(d - bevel * 2) / 2);
geometry.computeVertexNormals();
return geometry;
}
function makeLabelTexture(id, name) {
const canvas = document.createElement("canvas");
canvas.width = 256;
canvas.height = 128;
const ctx = canvas.getContext("2d");
ctx.clearRect(0, 0, 256, 128);
ctx.fillStyle = "rgba(12,24,33,.22)";
ctx.strokeStyle = "rgba(255,255,255,.38)";
ctx.lineWidth = 3;
ctx.beginPath();
ctx.roundRect(7, 7, 242, 114, 18);
ctx.fill();
ctx.stroke();
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.fillStyle = "rgba(255,255,255,.96)";
ctx.font = "800 64px system-ui";
ctx.fillText(id, 128, 55);
ctx.fillStyle = "rgba(255,255,255,.78)";
ctx.font = "700 18px monospace";
ctx.fillText(name.toUpperCase(), 128, 99);
const texture = new THREE.CanvasTexture(canvas);
texture.colorSpace = THREE.SRGBColorSpace;
return texture;
}
const blockMeshes = [];
for (const b of blocks) {
const material = new THREE.MeshStandardMaterial({
color: b.color,
roughness: 0.56,
metalness: 0.04
});
const mesh = new THREE.Mesh(makeBlockGeometry(b.w, b.h, b.d), material);
mesh.position.set(b.x, b.y, 0);
mesh.castShadow = true;
mesh.receiveShadow = true;
mesh.userData.blockIndex = blocks.indexOf(b);
const edges = new THREE.LineSegments(
new THREE.EdgesGeometry(mesh.geometry, 25),
new THREE.LineBasicMaterial({
color: 0x24343d,
transparent: true,
opacity: 0.68
})
);
mesh.add(edges);
b.edges = edges;
const label = new THREE.Mesh(
new THREE.PlaneGeometry(b.w * 0.72, b.h * 0.66),
new THREE.MeshBasicMaterial({
map: makeLabelTexture(b.id, b.name),
transparent: true,
depthWrite: false
})
);
label.position.z = b.d / 2 + 0.012;
mesh.add(label);
b.mesh = mesh;
b.material = material;
blockMeshes.push(mesh);
scene.add(mesh);
const chip = document.createElement("button");
chip.className = "block-chip";
chip.type = "button";
chip.innerHTML = `<b>${b.id}</b><small>${b.name}</small>`;
chip.addEventListener("click", () => selectBlock(blocks.indexOf(b)));
blockGrid.appendChild(chip);
b.chip = chip;
}
const forceGroup = new THREE.Group();
scene.add(forceGroup);
const forceVisuals = blocks.map(() => {
const stripMaterial = new THREE.LineBasicMaterial({
color: GREEN,
transparent: true,
opacity: 0.95,
depthTest: false
});
const strip = new THREE.Line(
new THREE.BufferGeometry(),
stripMaterial
);
strip.renderOrder = 20;
const markerMaterial = new THREE.MeshBasicMaterial({
color: CYAN,
depthTest: false
});
const marker = new THREE.Mesh(
new THREE.SphereGeometry(0.045, 16, 12),
markerMaterial
);
marker.renderOrder = 22;
const dropLine = new THREE.Line(
new THREE.BufferGeometry(),
new THREE.LineDashedMaterial({
color: 0x536b78,
dashSize: 0.055,
gapSize: 0.045,
transparent: true,
opacity: 0.68,
depthTest: false
})
);
dropLine.renderOrder = 19;
const arrow = new THREE.ArrowHelper(
new THREE.Vector3(0, -1, 0),
new THREE.Vector3(),
0.3,
GREEN,
0.09,
0.055
);
arrow.traverse(child => {
if (child.material) {
child.material.depthTest = false;
child.renderOrder = 21;
}
});
forceGroup.add(strip, marker, dropLine, arrow);
return { strip, marker, dropLine, arrow };
});
const railMaterial = new THREE.LineBasicMaterial({
color: CYAN,
transparent: true,
opacity: 0.88,
depthTest: false
});
const selectionRail = new THREE.Line(
new THREE.BufferGeometry(),
railMaterial
);
selectionRail.renderOrder = 18;
scene.add(selectionRail);
const railTicks = new THREE.LineSegments(
new THREE.BufferGeometry(),
new THREE.LineBasicMaterial({
color: CYAN,
transparent: true,
opacity: 0.88,
depthTest: false
})
);
railTicks.renderOrder = 18;
scene.add(railTicks);
const pivotGroup = new THREE.Group();
pivotGroup.visible = false;
scene.add(pivotGroup);
const pivotRing = new THREE.Mesh(
new THREE.TorusGeometry(0.085, 0.012, 8, 32),
new THREE.MeshBasicMaterial({
color: RED,
depthTest: false
})
);
pivotRing.renderOrder = 30;
const pivotDot = new THREE.Mesh(
new THREE.SphereGeometry(0.026, 12, 8),
new THREE.MeshBasicMaterial({
color: 0xffffff,
depthTest: false
})
);
pivotDot.renderOrder = 31;
const pivotArc = new THREE.Line(
new THREE.BufferGeometry(),
new THREE.LineBasicMaterial({
color: RED,
transparent: true,
opacity: 0.72,
depthTest: false
})
);
pivotArc.renderOrder = 29;
pivotGroup.add(pivotRing, pivotDot, pivotArc);
let selectedIndex = 4;
let movedIndex = null;
let phase = "ready";
let currentAnalysis = null;
let failure = null;
let analysisTimer = null;
let fall = null;
let calloutActive = false;
let calloutHideAt = 0;
let dragging = false;
let dragPointerId = null;
let dragStartClientX = 0;
let dragStartBlockX = 0;
function clamp(value, min, max) {
return Math.min(max, Math.max(min, value));
}
function signed(value) {
return `${value >= 0 ? "+" : ""}${value.toFixed(2)}`;
}
function stackName(index) {
return blocks.slice(index).map(b => b.id).join("–");
}
function interfaceName(index) {
return index === 0
? `TABLE → ${blocks[0].id}`
: `${blocks[index - 1].id} → ${blocks[index].id}`;
}
function analyze() {
const items = [];
for (let i = 0; i < blocks.length; i++) {
const substack = blocks.slice(i);
const mass = substack.reduce((sum, b) => sum + b.mass, 0);
const comX = substack.reduce((sum, b) => sum + b.x * b.mass, 0) / mass;
const comY = substack.reduce((sum, b) => sum + b.y * b.mass, 0) / mass;
const upper = blocks[i];
let low;
let high;
if (i === 0) {
low = upper.x - upper.w / 2;
high = upper.x + upper.w / 2;
} else {
const lower = blocks[i - 1];
low = Math.max(lower.x - lower.w / 2, upper.x - upper.w / 2);
high = Math.min(lower.x + lower.w / 2, upper.x + upper.w / 2);
}
const hasContact = low <= high + EPS;
let failed = false;
let margin;
let pivot = null;
let direction = 0;
if (!hasContact) {
failed = true;
const candidateCenter = (low + high) / 2;
margin = -Math.max(0.01, Math.abs(comX - candidateCenter));
if (i > 0) {
const lower = blocks[i - 1];
const lowerLeft = lower.x - lower.w / 2;
const lowerRight = lower.x + lower.w / 2;
const lowerCenter = (lowerLeft + lowerRight) / 2;
if (comX >= lowerCenter) {
pivot = lowerRight;
direction = -1;
} else {
pivot = lowerLeft;
direction = 1;
}
}
} else {
margin = Math.min(comX - low, high - comX);
failed = comX < low - EPS || comX > high + EPS;
if (failed) {
if (comX < low) {
pivot = low;
direction = 1;
} else {
pivot = high;
direction = -1;
}
}
}
const marginal = !failed && margin < 0.04;
const interfaceY = i === 0 ? 0 : blocks[i - 1].top;
items.push({
index: i,
interface: interfaceName(i),
substack: stackName(i),
mass,
comX,
comY,
low,
high,
hasContact,
failed,
marginal,
margin,
pivot,
direction,
interfaceY
});
}
return {
items,
firstFailure: items.find(item => item.failed) || null
};
}
function replaceLinePoints(line, points) {
line.geometry.dispose();
line.geometry = new THREE.BufferGeometry().setFromPoints(points);
}
function updateForceVisuals(analysis) {
analysis.items.forEach((item, i) => {
const visual = forceVisuals[i];
const color = item.failed ? RED : item.marginal ? AMBER : GREEN;
visual.strip.material.color.copy(color);
visual.marker.material.color.copy(item.failed ? RED : CYAN);
visual.arrow.setColor(color);
if (item.hasContact) {
replaceLinePoints(visual.strip, [
new THREE.Vector3(item.low, item.interfaceY + 0.012, 0.79),
new THREE.Vector3(item.high, item.interfaceY + 0.012, 0.79)
]);
} else {
replaceLinePoints(visual.strip, [
new THREE.Vector3(item.comX, item.interfaceY + 0.012, 0.79),
new THREE.Vector3(item.comX + 0.001, item.interfaceY + 0.012, 0.79)
]);
}
visual.marker.position.set(item.comX, item.comY, 0.81);
replaceLinePoints(visual.dropLine, [
new THREE.Vector3(item.comX, item.comY, 0.805),
new THREE.Vector3(item.comX, item.interfaceY, 0.805)
]);
visual.dropLine.computeLineDistances();
visual.arrow.position.set(item.comX, item.interfaceY + 0.36, 0.82);
visual.arrow.setLength(0.32, 0.09, 0.055);
});
}
function renderDiagnostics(analysis) {
diagnostics.replaceChildren();
analysis.items.forEach((item, i) => {
const row = document.createElement("div");
row.className = "diag-row";
if (item.failed) row.classList.add("fail");
else if (item.marginal) row.classList.add("warn");
else row.classList.add("pass");
const dot = document.createElement("i");
dot.className = "dot";
if (item.failed) dot.classList.add("red");
else if (item.marginal) dot.classList.add("amber");
const main = document.createElement("div");
const name = document.createElement("div");
name.className = "diag-name";
const strong = document.createElement("strong");
strong.textContent = item.interface;
name.appendChild(strong);
if (analysis.firstFailure === item && item.failed) {
const first = document.createElement("span");
first.className = "first-tag";
first.textContent = "FIRST";
name.appendChild(first);
}
const data = document.createElement("span");
data.className = "diag-data";
const support = item.hasContact
? `[${item.low.toFixed(2)}, ${item.high.toFixed(2)}]`
: "no overlap";
data.textContent =
`${item.substack} · x̄ ${item.comX.toFixed(2)} · ` +
`support ${support} · margin ${signed(item.margin)} m`;
data.title = data.textContent;
main.append(name, data);
const state = document.createElement("span");
state.className = "diag-state";
state.textContent = item.failed
? "FAIL"
: item.marginal
? "EDGE"
: "PASS";
row.append(dot, main, state);
diagnostics.appendChild(row);
});
}
function updateStatus(kind, title, detail) {
statusCard.classList.remove("fail", "success");
if (kind === "fail") statusCard.classList.add("fail");
if (kind === "success") statusCard.classList.add("success");
statusTitle.textContent = title;
statusDetail.textContent = detail;
}
function refreshAnalysis() {
currentAnalysis = analyze();
updateForceVisuals(currentAnalysis);
renderDiagnostics(currentAnalysis);
if (phase === "ready") {
if (currentAnalysis.firstFailure) {
const f = currentAnalysis.firstFailure;
modePill.textContent = "Failure candidate";
updateStatus(
"fail",
"Unstable candidate found",
`${f.interface}: substack ${f.substack} has its resultant outside the contact overlap.`
);
} else {
modePill.textContent = "Live scan";
updateStatus(
"",
"Live scan is stable",
"Move one block or press Test stability to run the controlled test."
);
}
}
}
function updateSelectionRail() {
const b = blocks[selectedIndex];
const y = b.bottom + 0.025;
const z = 0.835;
const minX = b.initialX - MOVEMENT_LIMIT;
const maxX = b.initialX + MOVEMENT_LIMIT;
replaceLinePoints(selectionRail, [
new THREE.Vector3(minX, y, z),
new THREE.Vector3(maxX, y, z)
]);
replaceLinePoints(railTicks, [
new THREE.Vector3(minX, y - 0.055, z),
new THREE.Vector3(minX, y + 0.055, z),
new THREE.Vector3(maxX, y - 0.055, z),
new THREE.Vector3(maxX, y + 0.055, z)
]);
}
function refreshBlockAppearance() {
blocks.forEach((b, i) => {
const isFailureBlock =
failure !== null && i >= failure.index && phase !== "ready";
if (isFailureBlock) {
b.material.color.copy(RED);
b.material.emissive.set(0x6f1717);
b.material.emissiveIntensity = 0.42;
} else {
b.material.color.set(b.color);
b.material.emissive.set(i === selectedIndex ? 0x123640 : 0x000000);
b.material.emissiveIntensity = i === selectedIndex ? 0.38 : 0;
}
b.edges.material.color.set(
isFailureBlock ? 0xffb0ad : i === selectedIndex ? 0xdffcff : 0x24343d
);
b.edges.material.opacity = isFailureBlock || i === selectedIndex ? 0.95 : 0.68;
});
}
function refreshChips() {
blocks.forEach((b, i) => {
b.chip.classList.toggle("selected", i === selectedIndex);
b.chip.disabled = movedIndex !== null && movedIndex !== i;
});
}
function refreshTranslationUI() {
const b = blocks[selectedIndex];
const offset = b.x - b.initialX;
translation.value = offset;
translationReadout.textContent = `${b.id} ${signed(offset)} m`;
translation.disabled = phase === "analysis" || phase === "fall" || phase === "fallen";
}
function selectBlock(index) {
if (phase === "analysis" || phase === "fall" || phase === "fallen") return;
if (movedIndex !== null && movedIndex !== index) return;
selectedIndex = index;
refreshChips();
refreshTranslationUI();
refreshBlockAppearance();
updateSelectionRail();
}
function setTranslation(value, commit = false) {
if (phase === "analysis" || phase === "fall" || phase === "fallen") return;
if (movedIndex !== null && movedIndex !== selectedIndex) return;
const b = blocks[selectedIndex];
const offset = clamp(value, -MOVEMENT_LIMIT, MOVEMENT_LIMIT);
b.x = b.initialX + offset;
b.mesh.position.x = b.x;
if (commit && movedIndex === null) {
movedIndex = selectedIndex;
refreshChips();
}
refreshTranslationUI();
refreshAnalysis();
}
translation.addEventListener("input", () => {
setTranslation(Number(translation.value), true);
});
function showPivot(f) {
pivotGroup.visible = true;
pivotGroup.position.set(f.pivot, f.interfaceY, 0.84);
const points = [];
const radius = 0.38;
for (let i = 0; i <= 24; i++) {
const a = f.direction * (i / 24) * 0.95;
points.push(new THREE.Vector3(
Math.cos(a) * radius,
Math.sin(a) * radius,
0
));
}
replaceLinePoints(pivotArc, points);
}
function hidePivot() {
pivotGroup.visible = false;
}
function showCallout(f) {
calloutActive = true;
calloutTitle.textContent = `First failure · ${f.interface}`;
calloutText.textContent =
`Substack ${f.substack}: resultant x = ${f.comX.toFixed(2)} m is outside its support.`;
sceneCallout.classList.add("visible");
}
function updateCalloutPosition() {
if (!calloutActive || !failure) return;
const substack = blocks.slice(failure.index);
const anchorY = Math.max(...substack.map(b => b.top)) + 0.31;
const point = new THREE.Vector3(
blocks[failure.index].x,
anchorY,
0.2
).project(camera);
const x = (point.x * 0.5 + 0.5) * stage.clientWidth;
const y = (-point.y * 0.5 + 0.5) * stage.clientHeight;
sceneCallout.style.left = `${x}px`;
sceneCallout.style.top = `${y}px`;
}
function onTest() {
if (phase === "analysis" || phase === "fall" || phase === "fallen") return;
const analysis = analyze();
currentAnalysis = analysis;
updateForceVisuals(analysis);
renderDiagnostics(analysis);
failure = analysis.firstFailure;
if (!failure) {
phase = "stable";
modePill.textContent = "All interfaces pass";
testButton.textContent = "Re-test balance";
updateStatus(
"success",
"Stable at every support interface",
"All five substack resultants remain within their contact overlaps."
);
refreshBlockAppearance();
return;
}
phase = "analysis";
testButton.disabled = true;
translation.disabled = true;
modePill.textContent = "Failure isolated";
refreshBlockAppearance();
showPivot(failure);
showCallout(failure);
updateStatus(
"fail",
"First failing substack identified",
`${failure.interface}: substack ${failure.substack}. ` +
`The failing result is held for inspection before the controlled fall.`
);
analysisTimer = window.setTimeout(() => {
if (phase === "analysis" && failure) startFall(failure);
}, 1350);
}
function easeOutCubic(t) {
return 1 - Math.pow(1 - t, 3);
}
function easeInOutCubic(t) {
return t < 0.5
? 4 * t * t * t
: 1 - Math.pow(-2 * t + 2, 3) / 2;
}
function startFall(f) {
phase = "fall";
modePill.textContent = "Controlled fall";
calloutHideAt = performance.now() + 650;
fall = {
start: performance.now(),
failure: f,
original: blocks.slice(f.index).map(b => ({ x: b.x, y: b.y }))
};
updateStatus(
"fail",
"Controlled rotation in progress",
`Substack ${f.substack} rotates about the ${f.direction < 0 ? "right" : "left"} support edge.`
);
}
function updateFall(now) {
if (!fall) return;
const elapsed = now - fall.start;
let degrees;
if (elapsed < 700) {
const t = clamp(elapsed / 700, 0, 1);
degrees = 8 * easeOutCubic(t);
} else if (elapsed < 1900) {
const t = clamp((elapsed - 700) / 1200, 0, 1);
degrees = 8 + (64 - 8) * easeInOutCubic(t);
} else if (elapsed < 2500) {
const t = clamp((elapsed - 1900) / 600, 0, 1);
degrees = 64 + (74 - 64) * easeOutCubic(t);
} else {
const t = clamp((elapsed - 2500) / 650, 0, 1);
degrees = 74 + Math.sin(t * Math.PI * 3) *
Math.exp(-t * 4.5) * 1.8;
}
const theta = fall.failure.direction * THREE.MathUtils.degToRad(degrees);
const cos = Math.cos(theta);
const sin = Math.sin(theta);
fall.original.forEach((original, offset) => {
const b = blocks[fall.failure.index + offset];
const relX = original.x - fall.failure.pivot;
const relY = original.y - fall.failure.interfaceY;
b.mesh.position.x =
fall.failure.pivot + relX * cos - relY * sin;
b.mesh.position.y =
fall.failure.interfaceY + relX * sin + relY * cos;
b.mesh.rotation.z = theta;
});
if (elapsed > 3150) {
phase = "fallen";
modePill.textContent = "Fall complete";
updateStatus(
"fail",
"Controlled fall complete",
`The first failing substack was ${fall.failure.substack}. Reset the puzzle to run another test.`
);
fall = null;
}
}
function resetScene() {
if (analysisTimer !== null) {
clearTimeout(analysisTimer);
analysisTimer = null;
}
phase = "ready";
failure = null;
fall = null;
movedIndex = null;
selectedIndex = 4;
calloutActive = false;
sceneCallout.classList.remove("visible");
hidePivot();
blocks.forEach(b => {
b.x = b.initialX;
b.mesh.position.set(b.x, b.y, 0);
b.mesh.rotation.set(0, 0, 0);
});
testButton.disabled = false;
testButton.textContent = "Test stability";
translation.disabled = false;
modePill.textContent = "Live scan";
refreshChips();
refreshTranslationUI();
refreshBlockAppearance();
updateSelectionRail();
refreshAnalysis();
}
testButton.addEventListener("click", onTest);
resetButton.addEventListener("click", resetScene);
showForces.addEventListener("change", () => {
forceGroup.visible = showForces.checked;
});
const raycaster = new THREE.Raycaster();
const pointer = new THREE.Vector2();
renderer.domElement.addEventListener("pointerdown", event => {
if (phase === "analysis" || phase === "fall" || phase === "fallen") return;
const rect = renderer.domElement.getBoundingClientRect();
pointer.x = ((event.clientX - rect.left) / rect.width) * 2 - 1;
pointer.y = -((event.clientY - rect.top) / rect.height) * 2 + 1;
raycaster.setFromCamera(pointer, camera);
const hit = raycaster.intersectObjects(blockMeshes, false)[0];
if (!hit) return;
const index = hit.object.userData.blockIndex;
if (movedIndex !== null && movedIndex !== index) {
statusDetail.textContent =
"One block has already been translated. Reset before choosing another.";
return;
}
selectBlock(index);
dragging = true;
dragPointerId = event.pointerId;
dragStartClientX = event.clientX;
dragStartBlockX = blocks[index].x;
renderer.domElement.setPointerCapture(event.pointerId);
});
renderer.domElement.addEventListener("pointermove", event => {
if (!dragging || event.pointerId !== dragPointerId) return;
const rect = renderer.domElement.getBoundingClientRect();
const worldPerPixel =
(camera.right - camera.left) / (camera.zoom * rect.width);
const delta = (event.clientX - dragStartClientX) * worldPerPixel;
const b = blocks[selectedIndex];
const nextX = clamp(
b.initialX + (dragStartBlockX - b.initialX + delta),
b.initialX - MOVEMENT_LIMIT,
b.initialX + MOVEMENT_LIMIT
);
b.x = nextX;
b.mesh.position.x = nextX;
refreshTranslationUI();
refreshAnalysis();
});
function endDrag(event) {
if (!dragging || event.pointerId !== dragPointerId) return;
dragging = false;
dragPointerId = null;
if (renderer.domElement.hasPointerCapture(event.pointerId)) {
renderer.domElement.releasePointerCapture(event.pointerId);
}
if (movedIndex === null) {
movedIndex = selectedIndex;
refreshChips();
}
}
renderer.domElement.addEventListener("pointerup", endDrag);
renderer.domElement.addEventListener("pointercancel", endDrag);
window.addEventListener("keydown", event => {
if (event.target instanceof HTMLInputElement) return;
if (event.key !== "ArrowLeft" && event.key !== "ArrowRight") return;
if (phase === "analysis" || phase === "fall" || phase === "fallen") return;
event.preventDefault();
const b = blocks[selectedIndex];
const direction = event.key === "ArrowRight" ? 1 : -1;
setTranslation((b.x - b.initialX) + direction * 0.05, true);
});
function resize() {
const width = stage.clientWidth;
const height = stage.clientHeight;
const aspect = width / Math.max(height, 1);
const viewHeight = Math.max(6.2, 9.0 / aspect);
camera.left = -viewHeight * aspect / 2;
camera.right = viewHeight * aspect / 2;
camera.top = viewHeight / 2;
camera.bottom = -viewHeight / 2;
camera.updateProjectionMatrix();
renderer.setSize(width, height, false);
}
window.addEventListener("resize", resize);
resize();
refreshChips();
refreshTranslationUI();
refreshBlockAppearance();
updateSelectionRail();
refreshAnalysis();
function animate(now) {
requestAnimationFrame(animate);
if (phase === "fall") {
updateFall(now);
}
if (calloutActive && now > calloutHideAt) {
calloutActive = false;
sceneCallout.style.opacity = "0";
} else {
sceneCallout.style.opacity = "1";
}
updateCalloutPosition();
renderer.render(scene, camera);
}
requestAnimationFrame(animate);
</script>
</body>
</html>
```