Prompt specification
Build or customize the Three.js 3D scene "Shelf support footprint study" 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: Shelf support footprint study
Category: Voxel Worlds · Style: Voxel 3D
License: MIT · Reference: https://three3d.app/scene/shelf-support-footprint-study-x0225
Scene Description Prompt:
Please create one self-contained HTML file with Three.js from cdnjs showing shelf stability. Place a narrow shelving unit on a marked base polygon with movable weight blocks; show an illustrative center-of-mass projection relative to its supporting footprint. Voxel style.
Working Three.js Starter (shelf-support-footprint-study-x0225):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Voxel Shelf Stability</title>
<style>
:root {
--ink: #292824;
--muted: #716d63;
--paper: rgba(249, 246, 237, 0.94);
--border: rgba(41, 40, 36, 0.16);
--green: #2f8f67;
--amber: #d18b32;
--red: #cc5148;
--cyan: #28b7bd;
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: #e8e4da;
color: var(--ink);
font-family:
Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
#stage {
position: fixed;
inset: 0;
}
#stage canvas {
display: block;
width: 100%;
height: 100%;
touch-action: none;
cursor: grab;
}
.brand {
position: fixed;
top: 24px;
left: 26px;
z-index: 10;
pointer-events: none;
text-shadow: 0 1px 0 rgba(255, 255, 255, 0.45);
}
.eyebrow {
display: block;
margin-bottom: 6px;
color: #716c60;
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 11px;
font-weight: 800;
letter-spacing: 0.18em;
text-transform: uppercase;
}
.brand h1 {
margin: 0;
font-size: clamp(26px, 3vw, 42px);
line-height: 0.95;
letter-spacing: -0.055em;
}
.brand p {
max-width: 390px;
margin: 10px 0 0;
color: #69655d;
font-size: 13px;
line-height: 1.45;
}
.panel {
position: fixed;
z-index: 20;
right: 22px;
bottom: 22px;
width: min(350px, calc(100vw - 44px));
padding: 16px;
border: 1px solid var(--border);
border-radius: 16px;
background: var(--paper);
box-shadow:
0 16px 45px rgba(56, 48, 35, 0.14),
0 2px 7px rgba(56, 48, 35, 0.08);
backdrop-filter: blur(12px);
user-select: none;
}
.status {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
padding: 12px 13px;
border: 1px solid rgba(47, 143, 103, 0.22);
border-radius: 11px;
background: rgba(47, 143, 103, 0.08);
transition:
border-color 160ms ease,
background 160ms ease;
}
.status[data-state="marginal"] {
border-color: rgba(209, 139, 50, 0.28);
background: rgba(209, 139, 50, 0.09);
}
.status[data-state="critical"] {
border-color: rgba(204, 81, 72, 0.28);
background: rgba(204, 81, 72, 0.09);
}
.status[data-state="tipping"] {
border-color: rgba(204, 81, 72, 0.5);
background: rgba(204, 81, 72, 0.14);
}
.status-main {
display: flex;
align-items: center;
gap: 10px;
}
.status-dot {
width: 10px;
height: 10px;
flex: 0 0 auto;
border-radius: 50%;
background: var(--green);
box-shadow: 0 0 0 4px rgba(47, 143, 103, 0.12);
}
.status[data-state="marginal"] .status-dot {
background: var(--amber);
box-shadow: 0 0 0 4px rgba(209, 139, 50, 0.12);
}
.status[data-state="critical"] .status-dot,
.status[data-state="tipping"] .status-dot {
background: var(--red);
box-shadow: 0 0 0 4px rgba(204, 81, 72, 0.12);
}
#statusLabel {
font-size: 13px;
font-weight: 850;
letter-spacing: 0.08em;
}
#statusHint {
max-width: 185px;
color: var(--muted);
font-size: 11px;
line-height: 1.35;
text-align: right;
}
.metrics {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 8px;
margin-top: 10px;
}
.metric {
min-width: 0;
padding: 10px 9px;
border: 1px solid rgba(41, 40, 36, 0.1);
border-radius: 10px;
background: rgba(255, 255, 255, 0.5);
}
.metric span {
display: block;
margin-bottom: 5px;
color: var(--muted);
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 9px;
font-weight: 800;
letter-spacing: 0.09em;
text-transform: uppercase;
}
.metric strong {
display: block;
overflow: hidden;
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 13px;
text-overflow: ellipsis;
white-space: nowrap;
}
.legend {
display: flex;
flex-wrap: wrap;
gap: 10px 15px;
margin: 12px 2px 10px;
color: #5f5b53;
font-size: 11px;
}
.legend-item {
display: inline-flex;
align-items: center;
gap: 6px;
}
.swatch {
width: 9px;
height: 9px;
border-radius: 2px;
background: var(--cyan);
}
.swatch.com {
background: #e45868;
border-radius: 50%;
}
.swatch.footprint {
border: 1px dashed #d18b32;
background: rgba(209, 139, 50, 0.15);
}
.actions {
display: grid;
grid-template-columns: repeat(2, 1fr);
gap: 7px;
}
button {
min-height: 35px;
padding: 8px 10px;
border: 1px solid rgba(41, 40, 36, 0.16);
border-radius: 9px;
background: rgba(255, 255, 255, 0.72);
color: var(--ink);
font: inherit;
font-size: 11px;
font-weight: 750;
cursor: pointer;
transition:
transform 100ms ease,
background 100ms ease;
}
button:hover {
background: #fff;
transform: translateY(-1px);
}
button:active {
transform: translateY(0);
}
.help {
margin: 11px 2px 0;
color: var(--muted);
font-size: 11px;
line-height: 1.45;
}
.help kbd {
padding: 1px 5px;
border: 1px solid rgba(41, 40, 36, 0.15);
border-bottom-width: 2px;
border-radius: 4px;
background: rgba(255, 255, 255, 0.65);
color: #4d4942;
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 9px;
}
.camera-note {
position: fixed;
z-index: 10;
bottom: 24px;
left: 26px;
padding: 9px 11px;
border: 1px solid rgba(41, 40, 36, 0.12);
border-radius: 9px;
background: rgba(249, 246, 237, 0.78);
color: #666158;
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 10px;
pointer-events: none;
backdrop-filter: blur(8px);
}
#loading {
position: fixed;
z-index: 100;
inset: 0;
display: grid;
place-items: center;
background: #e8e4da;
color: #625e55;
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 12px;
letter-spacing: 0.12em;
text-transform: uppercase;
}
@media (max-width: 720px) {
.brand {
top: 18px;
left: 18px;
}
.brand p {
display: none;
}
.panel {
right: 12px;
bottom: 12px;
width: calc(100vw - 24px);
}
.camera-note {
display: none;
}
.status {
align-items: flex-start;
}
#statusHint {
max-width: 150px;
}
}
</style>
</head>
<body>
<div id="stage"></div>
<header class="brand">
<span class="eyebrow">Voxel Mechanics / 01</span>
<h1>Shelf Stability</h1>
<p>
Drag the weighted blocks across each shelf. The projected center of mass
is compared with the narrow supporting footprint.
</p>
</header>
<section class="panel" aria-label="Stability controls and readings">
<div id="status" class="status" data-state="stable">
<div class="status-main">
<span class="status-dot"></span>
<span id="statusLabel">STABLE</span>
</div>
<span id="statusHint">Projection is safely inside the support area.</span>
</div>
<div class="metrics">
<div class="metric">
<span>Projected load</span>
<strong id="loadValue">0 kg</strong>
</div>
<div class="metric">
<span>COM X / Z</span>
<strong id="comValue">+0.00 / +0.00</strong>
</div>
<div class="metric">
<span>Edge margin</span>
<strong id="marginValue">0%</strong>
</div>
</div>
<div class="legend" aria-label="Visualization legend">
<span class="legend-item">
<i class="swatch com"></i>
Center of mass
</span>
<span class="legend-item">
<i class="swatch"></i>
Ground projection
</span>
<span class="legend-item">
<i class="swatch footprint"></i>
Supporting footprint
</span>
</div>
<div class="actions">
<button id="centerLoad" type="button">Center load</button>
<button id="tipTest" type="button">Tip test</button>
<button id="resetBlocks" type="button">Reset blocks</button>
<button id="resetView" type="button">Reset view</button>
</div>
<p class="help">
<kbd>Drag block</kbd> to move load ·
<kbd>Drag background</kbd> to orbit ·
<kbd>Scroll</kbd> to zoom ·
<kbd>Double-click</kbd> resets the camera.
</p>
</section>
<div class="camera-note">ORTHOGRAPHIC CAMERA / CUSTOM CONTROLS</div>
<div id="loading">Building stability scene…</div>
<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 loading = document.querySelector("#loading");
const statusElement = document.querySelector("#status");
const statusLabel = document.querySelector("#statusLabel");
const statusHint = document.querySelector("#statusHint");
const loadValue = document.querySelector("#loadValue");
const comValue = document.querySelector("#comValue");
const marginValue = document.querySelector("#marginValue");
// -------------------------------------------------------------------------
// Renderer, scene, and lighting
// -------------------------------------------------------------------------
const scene = new THREE.Scene();
scene.background = new THREE.Color(0xe8e4da);
scene.fog = new THREE.Fog(0xe8e4da, 12, 24);
const renderer = new THREE.WebGLRenderer({
antialias: false,
powerPreference: "high-performance"
});
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFShadowMap;
renderer.outputColorSpace = THREE.SRGBColorSpace;
stage.appendChild(renderer.domElement);
const camera = new THREE.OrthographicCamera(-5, 5, 3, -3, 0.1, 100);
const hemisphere = new THREE.HemisphereLight(0xfff8e8, 0x6e7880, 2.1);
scene.add(hemisphere);
const keyLight = new THREE.DirectionalLight(0xfff1d2, 3.2);
keyLight.position.set(4.5, 8, 5.5);
keyLight.castShadow = true;
keyLight.shadow.mapSize.set(2048, 2048);
keyLight.shadow.camera.left = -6;
keyLight.shadow.camera.right = 6;
keyLight.shadow.camera.top = 6;
keyLight.shadow.camera.bottom = -6;
keyLight.shadow.camera.near = 1;
keyLight.shadow.camera.far = 20;
keyLight.shadow.bias = -0.0004;
scene.add(keyLight);
const rimLight = new THREE.DirectionalLight(0x9edee0, 1.05);
rimLight.position.set(-5, 4, -4);
scene.add(rimLight);
// Three-band toon gradient gives the scene a stepped, voxel-like look.
const gradientData = new Uint8Array([65, 150, 255]);
const toonGradient = new THREE.DataTexture(
gradientData,
gradientData.length,
1,
THREE.RedFormat
);
toonGradient.minFilter = THREE.NearestFilter;
toonGradient.magFilter = THREE.NearestFilter;
toonGradient.generateMipmaps = false;
toonGradient.needsUpdate = true;
function toonMaterial(color, extra = {}) {
return new THREE.MeshToonMaterial({
color,
gradientMap: toonGradient,
...extra
});
}
const edgeMaterial = new THREE.LineBasicMaterial({
color: 0x514b42,
transparent: true,
opacity: 0.64
});
function addEdges(mesh, material = edgeMaterial) {
const edges = new THREE.LineSegments(
new THREE.EdgesGeometry(mesh.geometry),
material
);
mesh.add(edges);
return edges;
}
function makeBox(
width,
height,
depth,
color,
position,
parent = scene,
castShadow = true
) {
const mesh = new THREE.Mesh(
new THREE.BoxGeometry(width, height, depth),
toonMaterial(color)
);
mesh.position.copy(position);
mesh.castShadow = castShadow;
mesh.receiveShadow = true;
addEdges(mesh);
parent.add(mesh);
return mesh;
}
// -------------------------------------------------------------------------
// Marked base polygon
// -------------------------------------------------------------------------
const BASE_TOP = 0.16;
const polygon = [
[-2.30, -0.78],
[-1.72, -1.43],
[0.95, -1.53],
[2.10, -0.92],
[2.30, 0.48],
[1.48, 1.38],
[-0.70, 1.52],
[-2.14, 0.92]
];
const baseShape = new THREE.Shape();
polygon.forEach(([x, z], index) => {
if (index === 0) baseShape.moveTo(x, -z);
else baseShape.lineTo(x, -z);
});
baseShape.closePath();
const baseGeometry = new THREE.ExtrudeGeometry(baseShape, {
depth: BASE_TOP,
bevelEnabled: false,
steps: 1
});
baseGeometry.rotateX(-Math.PI / 2);
const base = new THREE.Mesh(
baseGeometry,
toonMaterial(0xc9b998)
);
base.receiveShadow = true;
base.castShadow = true;
addEdges(base);
scene.add(base);
const borderPoints = polygon.map(
([x, z]) => new THREE.Vector3(x, BASE_TOP + 0.008, z)
);
const baseBorder = new THREE.LineLoop(
new THREE.BufferGeometry().setFromPoints(borderPoints),
new THREE.LineBasicMaterial({ color: 0x5f5748 })
);
scene.add(baseBorder);
// Painted corner marks on the base platform.
const paintMaterial = toonMaterial(0xe4b653);
const paintPositions = [
[-1.75, 0.92],
[1.73, 0.88],
[1.72, -0.91],
[-1.77, -0.88]
];
paintPositions.forEach(([x, z], index) => {
const stripe = makeBox(
0.36,
0.012,
0.055,
0xe4b653,
new THREE.Vector3(x, BASE_TOP + 0.012, z),
scene,
false
);
stripe.rotation.y = index % 2 === 0 ? 0.55 : -0.55;
stripe.material = paintMaterial;
});
function makeTextTexture(text, options = {}) {
const canvas = document.createElement("canvas");
canvas.width = options.width || 512;
canvas.height = options.height || 128;
const context = canvas.getContext("2d");
context.clearRect(0, 0, canvas.width, canvas.height);
if (options.background) {
context.fillStyle = options.background;
context.fillRect(0, 0, canvas.width, canvas.height);
}
context.fillStyle = options.color || "#5c5548";
context.font = options.font || "700 34px monospace";
context.textAlign = "center";
context.textBaseline = "middle";
context.fillText(text, canvas.width / 2, canvas.height / 2 + 2);
const texture = new THREE.CanvasTexture(canvas);
texture.colorSpace = THREE.SRGBColorSpace;
texture.minFilter = THREE.LinearFilter;
texture.magFilter = THREE.LinearFilter;
return texture;
}
const baseText = new THREE.Mesh(
new THREE.PlaneGeometry(1.65, 0.35),
new THREE.MeshBasicMaterial({
map: makeTextTexture("BASE / SUPPORT ZONE"),
transparent: true,
depthWrite: false
})
);
baseText.rotation.x = -Math.PI / 2;
baseText.position.set(0, BASE_TOP + 0.018, -1.04);
scene.add(baseText);
// Floor plane.
const floor = new THREE.Mesh(
new THREE.PlaneGeometry(30, 30),
toonMaterial(0xe5e0d5)
);
floor.rotation.x = -Math.PI / 2;
floor.position.y = -0.012;
floor.receiveShadow = true;
scene.add(floor);
// -------------------------------------------------------------------------
// Shelf structure
// -------------------------------------------------------------------------
const SHELF_WIDTH = 1.62;
const SHELF_DEPTH = 0.78;
const BOARD_THICKNESS = 0.09;
const shelfCenters = [0.25, 1.06, 1.87, 2.68];
const shelfGroup = new THREE.Group();
scene.add(shelfGroup);
// Narrow runners establish the actual supporting footprint.
const FOOTPRINT_HALF_X = 0.34;
const FOOTPRINT_HALF_Z = 0.25;
[-0.30, 0.30].forEach((x) => {
makeBox(
0.18,
0.05,
0.52,
0x515b5b,
new THREE.Vector3(x, BASE_TOP + 0.025, 0),
shelfGroup
);
});
// Four voxel posts.
[-0.77, 0.77].forEach((x) => {
[-0.34, 0.34].forEach((z) => {
makeBox(
0.10,
2.68,
0.10,
0x5c6664,
new THREE.Vector3(x, BASE_TOP + 1.34, z),
shelfGroup
);
});
});
// Shelf boards and front lips.
shelfCenters.forEach((y, index) => {
makeBox(
SHELF_WIDTH,
BOARD_THICKNESS,
SHELF_DEPTH,
index % 2 === 0 ? 0x927c61 : 0x85745f,
new THREE.Vector3(0, y, 0),
shelfGroup
);
makeBox(
SHELF_WIDTH,
0.035,
0.035,
0xd4a95c,
new THREE.Vector3(0, y + 0.025, SHELF_DEPTH / 2 + 0.014),
shelfGroup
);
});
// Small top caps.
[-0.77, 0.77].forEach((x) => {
makeBox(
0.14,
0.08,
0.82,
0x4c5654,
new THREE.Vector3(x, 2.82, 0),
shelfGroup
);
});
// -------------------------------------------------------------------------
// Supporting footprint
// -------------------------------------------------------------------------
const footprintFill = new THREE.Mesh(
new THREE.PlaneGeometry(
FOOTPRINT_HALF_X * 2,
FOOTPRINT_HALF_Z * 2
),
new THREE.MeshBasicMaterial({
color: 0xe0a23e,
transparent: true,
opacity: 0.16,
depthWrite: false,
side: THREE.DoubleSide
})
);
footprintFill.rotation.x = -Math.PI / 2;
footprintFill.position.y = BASE_TOP + 0.013;
scene.add(footprintFill);
const footprintPoints = [
new THREE.Vector3(
-FOOTPRINT_HALF_X,
BASE_TOP + 0.023,
-FOOTPRINT_HALF_Z
),
new THREE.Vector3(
FOOTPRINT_HALF_X,
BASE_TOP + 0.023,
-FOOTPRINT_HALF_Z
),
new THREE.Vector3(
FOOTPRINT_HALF_X,
BASE_TOP + 0.023,
FOOTPRINT_HALF_Z
),
new THREE.Vector3(
-FOOTPRINT_HALF_X,
BASE_TOP + 0.023,
FOOTPRINT_HALF_Z
)
];
const footprintLine = new THREE.LineLoop(
new THREE.BufferGeometry().setFromPoints(footprintPoints),
new THREE.LineDashedMaterial({
color: 0xd18b32,
dashSize: 0.065,
gapSize: 0.04,
transparent: true,
opacity: 0.95
})
);
footprintLine.computeLineDistances();
scene.add(footprintLine);
// Small footprint corner blocks.
const cornerMaterial = new THREE.MeshBasicMaterial({
color: 0xe2a743
});
[
[-1, -1],
[1, -1],
[1, 1],
[-1, 1]
].forEach(([sx, sz]) => {
const corner = new THREE.Mesh(
new THREE.BoxGeometry(0.12, 0.015, 0.035),
cornerMaterial
);
corner.position.set(
sx * FOOTPRINT_HALF_X,
BASE_TOP + 0.025,
sz * FOOTPRINT_HALF_Z
);
scene.add(corner);
});
// -------------------------------------------------------------------------
// Movable weight blocks
// -------------------------------------------------------------------------
const blockSpecs = [
{
shelf: 0, x: 0.38, z: 0.17,
w: 0.42, h: 0.34, d: 0.30,
mass: 32, color: 0xe46e55
},
{
shelf: 0, x: -0.52, z: -0.17,
w: 0.30, h: 0.28, d: 0.26,
mass: 8, color: 0x4d9bba
},
{
shelf: 1, x: 0.42, z: 0.18,
w: 0.36, h: 0.36, d: 0.30,
mass: 24, color: 0xe6b646
},
{
shelf: 1, x: -0.47, z: -0.18,
w: 0.28, h: 0.27, d: 0.24,
mass: 6, color: 0x6f9e72
},
{
shelf: 2, x: 0.40, z: 0.17,
w: 0.39, h: 0.34, d: 0.32,
mass: 28, color: 0xb47bb5
},
{
shelf: 2, x: -0.45, z: -0.18,
w: 0.30, h: 0.29, d: 0.26,
mass: 7, color: 0x4f9fa0
},
{
shelf: 3, x: 0.36, z: 0.17,
w: 0.35, h: 0.31, d: 0.28,
mass: 22, color: 0xe16b79
},
{
shelf: 3, x: -0.42, z: -0.17,
w: 0.27, h: 0.26, d: 0.24,
mass: 5, color: 0x7088b1
}
];
const blocks = [];
const blockMeshes = [];
function blockXLimit(spec) {
return SHELF_WIDTH / 2 - spec.w / 2 - 0.025;
}
function blockZLimit(spec) {
return SHELF_DEPTH / 2 - spec.d / 2 - 0.03;
}
function makeMassLabel(mass, width) {
const canvas = document.createElement("canvas");
canvas.width = 256;
canvas.height = 128;
const context = canvas.getContext("2d");
context.fillStyle = "#f7f1df";
context.fillRect(0, 0, 256, 128);
context.strokeStyle = "#514b42";
context.lineWidth = 8;
context.strokeRect(4, 4, 248, 120);
context.fillStyle = "#3d3933";
context.font = "800 53px monospace";
context.textAlign = "center";
context.textBaseline = "middle";
context.fillText(`${mass}kg`, 128, 66);
const texture = new THREE.CanvasTexture(canvas);
texture.colorSpace = THREE.SRGBColorSpace;
texture.minFilter = THREE.LinearFilter;
const label = new THREE.Mesh(
new THREE.PlaneGeometry(Math.min(width * 0.76, 0.43), 0.16),
new THREE.MeshBasicMaterial({
map: texture,
side: THREE.DoubleSide
})
);
label.position.z = 0.001;
return label;
}
blockSpecs.forEach((spec, index) => {
const shelfTop = shelfCenters[spec.shelf] + BOARD_THICKNESS / 2;
const group = new THREE.Group();
group.position.set(
spec.x,
shelfTop + spec.h / 2,
spec.z
);
scene.add(group);
const mesh = new THREE.Mesh(
new THREE.BoxGeometry(spec.w, spec.h, spec.d),
toonMaterial(spec.color)
);
mesh.castShadow = true;
mesh.receiveShadow = true;
addEdges(mesh);
group.add(mesh);
mesh.userData.blockIndex = index;
const label = makeMassLabel(spec.mass, spec.w);
label.position.set(0, 0, spec.d / 2 + 0.004);
group.add(label);
const block = {
...spec,
index,
group,
mesh,
shelfTop,
initialX: spec.x,
initialZ: spec.z,
targetX: spec.x,
targetZ: spec.z
};
blocks.push(block);
blockMeshes.push(mesh);
});
// Selection outline under the active block.
const selectionGeometry = new THREE.BufferGeometry().setFromPoints([
new THREE.Vector3(-0.5, 0, -0.5),
new THREE.Vector3(0.5, 0, -0.5),
new THREE.Vector3(0.5, 0, 0.5),
new THREE.Vector3(-0.5, 0, 0.5)
]);
const selectionOutline = new THREE.LineLoop(
selectionGeometry,
new THREE.LineBasicMaterial({
color: 0x28b7bd,
depthTest: false,
transparent: true,
opacity: 0.95
})
);
selectionOutline.renderOrder = 20;
selectionOutline.visible = false;
scene.add(selectionOutline);
function updateSelectionOutline() {
if (!selectedBlock) {
selectionOutline.visible = false;
return;
}
const halfW = selectedBlock.w / 2 + 0.025;
const halfD = selectedBlock.d / 2 + 0.025;
const points = [
new THREE.Vector3(-halfW, 0, -halfD),
new THREE.Vector3(halfW, 0, -halfD),
new THREE.Vector3(halfW, 0, halfD),
new THREE.Vector3(-halfW, 0, halfD)
];
selectionOutline.geometry.dispose();
selectionOutline.geometry = new THREE.BufferGeometry().setFromPoints(points);
selectionOutline.position.set(
selectedBlock.group.position.x,
selectedBlock.shelfTop + 0.014,
selectedBlock.group.position.z
);
selectionOutline.visible = true;
}
// -------------------------------------------------------------------------
// Center-of-mass visualization
// -------------------------------------------------------------------------
const FRAME_MASS = 9;
const FRAME_COM_Y = 1.45;
const comSphere = new THREE.Mesh(
new THREE.SphereGeometry(0.075, 12, 8),
new THREE.MeshBasicMaterial({
color: 0xe45868,
depthTest: false
})
);
comSphere.renderOrder = 25;
scene.add(comSphere);
const comRing = new THREE.Mesh(
new THREE.TorusGeometry(0.11, 0.012, 6, 20),
new THREE.MeshBasicMaterial({
color: 0xffffff,
depthTest: false
})
);
comRing.renderOrder = 26;
scene.add(comRing);
const verticalLine = new THREE.Line(
new THREE.BufferGeometry(),
new THREE.LineDashedMaterial({
color: 0x28b7bd,
dashSize: 0.075,
gapSize: 0.045,
transparent: true,
opacity: 0.95,
depthTest: false
})
);
verticalLine.renderOrder = 24;
scene.add(verticalLine);
const projectionCross = new THREE.Group();
const projectionMaterial = new THREE.MeshBasicMaterial({
color: 0x28b7bd,
depthTest: false
});
const crossX = new THREE.Mesh(
new THREE.BoxGeometry(0.24, 0.016, 0.032),
projectionMaterial
);
const crossZ = new THREE.Mesh(
new THREE.BoxGeometry(0.032, 0.016, 0.24),
projectionMaterial
);
projectionCross.add(crossX, crossZ);
projectionCross.renderOrder = 24;
scene.add(projectionCross);
const centerOfMass = new THREE.Vector3();
let projectedMargin = 0;
function updateCenterOfMass() {
let totalMass = FRAME_MASS;
let x = 0;
let y = FRAME_MASS * FRAME_COM_Y;
let z = 0;
blocks.forEach((block) => {
const position = block.group.position;
totalMass += block.mass;
x += position.x * block.mass;
y += position.y * block.mass;
z += position.z * block.mass;
});
centerOfMass.set(x / totalMass, y / totalMass, z / totalMass);
comSphere.position.copy(centerOfMass);
comRing.position.copy(centerOfMass);
const linePoints = [
new THREE.Vector3(
centerOfMass.x,
centerOfMass.y,
centerOfMass.z
),
new THREE.Vector3(
centerOfMass.x,
BASE_TOP + 0.035,
centerOfMass.z
)
];
verticalLine.geometry.dispose();
verticalLine.geometry = new THREE.BufferGeometry().setFromPoints(linePoints);
verticalLine.computeLineDistances();
projectionCross.position.set(
centerOfMass.x,
BASE_TOP + 0.034,
centerOfMass.z
);
const marginX = FOOTPRINT_HALF_X - Math.abs(centerOfMass.x);
const marginZ = FOOTPRINT_HALF_Z - Math.abs(centerOfMass.z);
projectedMargin = Math.min(
marginX / FOOTPRINT_HALF_X,
marginZ / FOOTPRINT_HALF_Z
);
const outside =
Math.abs(centerOfMass.x) > FOOTPRINT_HALF_X ||
Math.abs(centerOfMass.z) > FOOTPRINT_HALF_Z;
let state;
let label;
let hint;
if (outside) {
state = "tipping";
label = "TIPPING";
hint = "Projection is outside the supporting footprint.";
} else if (projectedMargin < 0.08) {
state = "critical";
label = "EDGE RISK";
hint = "Very little margin remains before the unit tips.";
} else if (projectedMargin < 0.18) {
state = "marginal";
label = "MARGINAL";
hint = "Projection is close to the edge of the support area.";
} else {
state = "stable";
label = "STABLE";
hint = "Projection is safely inside the support area.";
}
statusElement.dataset.state = state;
statusLabel.textContent = label;
statusHint.textContent = hint;
const totalLoad = blocks.reduce((sum, block) => sum + block.mass, 0);
loadValue.textContent = `${totalLoad} kg`;
comValue.textContent =
`${centerOfMass.x >= 0 ? "+" : ""}${centerOfMass.x.toFixed(2)} / ` +
`${centerOfMass.z >= 0 ? "+" : ""}${centerOfMass.z.toFixed(2)}`;
marginValue.textContent = `${Math.round(projectedMargin * 100)}%`;
updateSelectionOutline();
}
// -------------------------------------------------------------------------
// Custom orthographic camera controls
// -------------------------------------------------------------------------
const orbit = {
azimuth: 0.68,
elevation: 0.62,
viewSize: 5.35,
target: new THREE.Vector3(0, 1.15, 0)
};
function updateCamera() {
const radius = 10;
camera.position.set(
orbit.target.x +
radius * Math.cos(orbit.elevation) * Math.sin(orbit.azimuth),
orbit.target.y + radius * Math.sin(orbit.elevation),
orbit.target.z +
radius * Math.cos(orbit.elevation) * Math.cos(orbit.azimuth)
);
camera.lookAt(orbit.target);
const aspect = window.innerWidth / window.innerHeight;
let width;
let height;
if (aspect >= 1) {
height = orbit.viewSize;
width = height * aspect;
} else {
width = orbit.viewSize;
height = width / aspect;
}
camera.left = -width / 2;
camera.right = width / 2;
camera.top = height / 2;
camera.bottom = -height / 2;
camera.updateProjectionMatrix();
}
function resetCamera() {
orbit.azimuth = 0.68;
orbit.elevation = 0.62;
orbit.viewSize = 5.35;
orbit.target.set(0, 1.15, 0);
updateCamera();
}
updateCamera();
window.addEventListener("resize", () => {
renderer.setSize(window.innerWidth, window.innerHeight);
updateCamera();
});
renderer.domElement.addEventListener(
"wheel",
(event) => {
event.preventDefault();
orbit.viewSize = THREE.MathUtils.clamp(
orbit.viewSize * Math.exp(event.deltaY * 0.001),
3.6,
8.0
);
updateCamera();
},
{ passive: false }
);
renderer.domElement.addEventListener("dblclick", resetCamera);
// -------------------------------------------------------------------------
// Block dragging and camera orbit
// -------------------------------------------------------------------------
const raycaster = new THREE.Raycaster();
const pointer = new THREE.Vector2();
const dragPlane = new THREE.Plane(
new THREE.Vector3(0, 1, 0),
0
);
const dragOffset = new THREE.Vector3();
let selectedBlock = null;
let draggingBlock = false;
let orbiting = false;
let pointerStartX = 0;
let pointerStartY = 0;
let lastPointerX = 0;
let lastPointerY = 0;
function updatePointer(event) {
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);
}
function pickBlock(event) {
updatePointer(event);
const hits = raycaster.intersectObjects(blockMeshes, false);
if (!hits.length) return null;
return blocks[hits[0].object.userData.blockIndex];
}
function intersectsOtherBlock(candidateX, candidateZ, block) {
return blocks.some((other) => {
if (other === block || other.shelf !== block.shelf) return false;
const xOverlap =
Math.abs(candidateX - other.group.position.x) <
(block.w + other.w) / 2 + 0.012;
const zOverlap =
Math.abs(candidateZ - other.group.position.z) <
(block.d + other.d) / 2 + 0.012;
return xOverlap && zOverlap;
});
}
function moveBlockTo(block, x, z) {
const maxX = blockXLimit(block);
const maxZ = blockZLimit(block);
const oldX = block.group.position.x;
const oldZ = block.group.position.z;
const clampedX = THREE.MathUtils.clamp(x, -maxX, maxX);
const clampedZ = THREE.MathUtils.clamp(z, -maxZ, maxZ);
if (!intersectsOtherBlock(clampedX, clampedZ, block)) {
block.group.position.x = clampedX;
block.group.position.z = clampedZ;
} else if (!intersectsOtherBlock(clampedX, oldZ, block)) {
block.group.position.x = clampedX;
} else if (!intersectsOtherBlock(oldX, clampedZ, block)) {
block.group.position.z = clampedZ;
}
block.targetX = block.group.position.x;
block.targetZ = block.group.position.z;
}
renderer.domElement.addEventListener("pointerdown", (event) => {
if (event.button !== 0) return;
const block = pickBlock(event);
if (block) {
selectedBlock = block;
draggingBlock = true;
dragPlane.constant = -block.group.position.y;
updatePointer(event);
const intersection = new THREE.Vector3();
raycaster.ray.intersectPlane(dragPlane, intersection);
dragOffset.set(
block.group.position.x - intersection.x,
0,
block.group.position.z - intersection.z
);
renderer.domElement.setPointerCapture(event.pointerId);
renderer.domElement.style.cursor = "grabbing";
updateSelectionOutline();
} else {
orbiting = true;
pointerStartX = event.clientX;
pointerStartY = event.clientY;
lastPointerX = event.clientX;
lastPointerY = event.clientY;
renderer.domElement.setPointerCapture(event.pointerId);
renderer.domElement.style.cursor = "grabbing";
}
});
renderer.domElement.addEventListener("pointermove", (event) => {
if (draggingBlock && selectedBlock) {
updatePointer(event);
const intersection = new THREE.Vector3();
if (raycaster.ray.intersectPlane(dragPlane, intersection)) {
moveBlockTo(
selectedBlock,
intersection.x + dragOffset.x,
intersection.z + dragOffset.z
);
updateCenterOfMass();
}
return;
}
if (orbiting) {
const dx = event.clientX - lastPointerX;
const dy = event.clientY - lastPointerY;
orbit.azimuth -= dx * 0.008;
orbit.elevation = THREE.MathUtils.clamp(
orbit.elevation + dy * 0.005,
0.30,
1.12
);
lastPointerX = event.clientX;
lastPointerY = event.clientY;
updateCamera();
return;
}
const hovered = pickBlock(event);
renderer.domElement.style.cursor = hovered ? "grab" : "default";
});
function finishPointer(event) {
draggingBlock = false;
orbiting = false;
renderer.domElement.style.cursor = "default";
if (renderer.domElement.hasPointerCapture(event.pointerId)) {
renderer.domElement.releasePointerCapture(event.pointerId);
}
}
renderer.domElement.addEventListener("pointerup", finishPointer);
renderer.domElement.addEventListener("pointercancel", finishPointer);
renderer.domElement.addEventListener("pointerleave", (event) => {
if (!draggingBlock && !orbiting) {
renderer.domElement.style.cursor = "default";
}
if (event.buttons === 0) finishPointer(event);
});
// -------------------------------------------------------------------------
// Load presets
// -------------------------------------------------------------------------
function resetBlocks() {
blocks.forEach((block) => {
block.targetX = block.initialX;
block.targetZ = block.initialZ;
});
}
function centerLoad() {
const byShelf = new Map();
blocks.forEach((block) => {
if (!byShelf.has(block.shelf)) byShelf.set(block.shelf, []);
byShelf.get(block.shelf).push(block);
});
byShelf.forEach((shelfBlocks) => {
shelfBlocks.sort((a, b) => b.mass - a.mass);
shelfBlocks.forEach((block, index) => {
block.targetX = index === 0 ? -0.23 : 0.23;
block.targetZ = 0;
});
});
}
function tipTest() {
blocks.forEach((block) => {
const heavy = block.mass >= 20;
block.targetX = heavy
? blockXLimit(block)
: -blockXLimit(block);
block.targetZ = block.initialZ;
});
}
document.querySelector("#centerLoad").addEventListener("click", centerLoad);
document.querySelector("#tipTest").addEventListener("click", tipTest);
document.querySelector("#resetBlocks").addEventListener("click", resetBlocks);
document.querySelector("#resetView").addEventListener("click", resetCamera);
// -------------------------------------------------------------------------
// Animation loop
// -------------------------------------------------------------------------
const clock = new THREE.Clock();
function animate() {
requestAnimationFrame(animate);
const delta = Math.min(clock.getDelta(), 0.05);
const smoothing = 1 - Math.exp(-delta * 11);
let moved = false;
if (!draggingBlock) {
blocks.forEach((block) => {
const dx = block.targetX - block.group.position.x;
const dz = block.targetZ - block.group.position.z;
if (Math.abs(dx) > 0.0005 || Math.abs(dz) > 0.0005) {
block.group.position.x += dx * smoothing;
block.group.position.z += dz * smoothing;
moved = true;
}
});
}
if (moved) updateCenterOfMass();
comRing.rotation.x += delta * 0.8;
comRing.rotation.y += delta * 1.2;
renderer.render(scene, camera);
}
updateCenterOfMass();
updateSelectionOutline();
animate();
loading.remove();
</script>
</body>
</html>
```