Prompt specification
Build or customize the Three.js 3D scene "Packing a handcart balance scene" 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: Packing a handcart balance scene
Category: Voxel Worlds · Style: Voxel 3D
License: MIT · Reference: https://three3d.app/scene/packing-a-handcart-balance-scene-x1367
Scene Description Prompt:
Move mass-labeled boxes on a voxel handcart and track its combined center of mass against wheel supports. Three.js from cdnjs, one HTML file.
Working Three.js Starter (packing-a-handcart-balance-scene-x1367):
```html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Voxel Handcart — Center of Mass Tracker</title>
<style>
:root {
color-scheme: dark;
--panel: rgba(15, 23, 42, 0.88);
--border: rgba(148, 163, 184, 0.24);
--muted: #94a3b8;
--text: #e2e8f0;
--stable: #22c55e;
--edge: #f59e0b;
--unstable: #ef4444;
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: #cbd5e1;
font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
#app {
position: fixed;
inset: 0;
}
#app canvas {
display: block;
width: 100%;
height: 100%;
touch-action: none;
}
.title-card {
position: fixed;
top: 18px;
left: 18px;
z-index: 5;
max-width: 390px;
padding: 14px 16px;
color: var(--text);
background: var(--panel);
border: 1px solid var(--border);
border-radius: 14px;
box-shadow: 0 14px 35px rgba(15, 23, 42, 0.2);
backdrop-filter: blur(12px);
pointer-events: none;
}
.title-card h1 {
margin: 0 0 4px;
font-size: 17px;
letter-spacing: 0.01em;
}
.title-card p {
margin: 0;
color: var(--muted);
font-size: 12px;
line-height: 1.45;
}
.panel {
position: fixed;
top: 18px;
right: 18px;
z-index: 10;
width: 326px;
padding: 14px;
color: var(--text);
background: var(--panel);
border: 1px solid var(--border);
border-radius: 16px;
box-shadow: 0 18px 45px rgba(15, 23, 42, 0.24);
backdrop-filter: blur(14px);
}
.status-row {
display: flex;
align-items: center;
justify-content: space-between;
gap: 10px;
margin-bottom: 12px;
}
.status {
display: inline-flex;
align-items: center;
gap: 7px;
font-size: 12px;
font-weight: 800;
letter-spacing: 0.08em;
}
.status::before {
content: "";
width: 9px;
height: 9px;
border-radius: 50%;
background: var(--stable);
box-shadow: 0 0 12px currentColor;
}
.status[data-level="stable"] {
color: var(--stable);
}
.status[data-level="edge"] {
color: var(--edge);
}
.status[data-level="unstable"] {
color: var(--unstable);
}
.total {
color: var(--muted);
font-size: 12px;
}
.total strong {
color: var(--text);
font-size: 14px;
}
.stats {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 7px;
margin-bottom: 11px;
}
.stat {
padding: 8px 9px;
background: rgba(148, 163, 184, 0.08);
border: 1px solid rgba(148, 163, 184, 0.12);
border-radius: 9px;
}
.stat span {
display: block;
margin-bottom: 3px;
color: var(--muted);
font-size: 10px;
text-transform: uppercase;
letter-spacing: 0.06em;
}
.stat strong {
font-size: 13px;
font-variant-numeric: tabular-nums;
}
.map-wrap {
margin: 8px 0 12px;
overflow: hidden;
background: rgba(2, 6, 23, 0.48);
border: 1px solid rgba(148, 163, 184, 0.18);
border-radius: 10px;
}
.map-wrap canvas {
display: block;
width: 100%;
height: auto;
}
.selection {
padding-top: 11px;
border-top: 1px solid var(--border);
}
.selection-head {
display: flex;
justify-content: space-between;
align-items: baseline;
margin-bottom: 7px;
}
.selection-head strong {
font-size: 13px;
}
.selection-head span {
color: var(--muted);
font-size: 11px;
}
input[type="range"] {
width: 100%;
margin: 3px 0 10px;
accent-color: #38bdf8;
cursor: pointer;
}
.button-row {
display: flex;
gap: 7px;
margin-top: 8px;
}
button {
flex: 1;
padding: 8px 9px;
color: var(--text);
background: rgba(148, 163, 184, 0.12);
border: 1px solid rgba(148, 163, 184, 0.2);
border-radius: 8px;
font: inherit;
font-size: 11px;
font-weight: 700;
cursor: pointer;
transition: background 120ms ease, border-color 120ms ease;
}
button:hover {
background: rgba(56, 189, 248, 0.18);
border-color: rgba(56, 189, 248, 0.45);
}
button.warning:hover {
background: rgba(239, 68, 68, 0.18);
border-color: rgba(239, 68, 68, 0.5);
}
.views {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 7px;
}
.help {
position: fixed;
left: 18px;
bottom: 18px;
z-index: 5;
padding: 10px 13px;
color: #cbd5e1;
background: rgba(15, 23, 42, 0.8);
border: 1px solid var(--border);
border-radius: 10px;
font-size: 11px;
line-height: 1.55;
backdrop-filter: blur(10px);
pointer-events: none;
}
.help strong {
color: #f8fafc;
}
@media (max-width: 720px) {
.title-card {
top: 10px;
left: 10px;
right: 10px;
max-width: none;
}
.panel {
top: auto;
right: 10px;
bottom: 10px;
width: min(326px, calc(100vw - 20px));
}
.help {
display: none;
}
}
</style>
</head>
<body>
<div id="app"></div>
<div class="title-card">
<h1>Voxel Handcart · Center of Mass Tracker</h1>
<p>
Drag the mass-labeled crates. The yellow sphere is the combined center of
mass; its vertical projection is compared with the wheel contact supports.
</p>
</div>
<aside class="panel">
<div class="status-row">
<div id="status" class="status" data-level="stable">STABLE</div>
<div class="total">Total <strong id="totalMass">139 kg</strong></div>
</div>
<div class="stats">
<div class="stat">
<span>COM X / Z</span>
<strong id="comValue">0.00 / 0.00 m</strong>
</div>
<div class="stat">
<span>Support margin</span>
<strong id="marginValue">0.00 m</strong>
</div>
<div class="stat">
<span>COM height</span>
<strong id="heightValue">0.00 m</strong>
</div>
<div class="stat">
<span>Support test</span>
<strong id="supportValue">Inside</strong>
</div>
</div>
<div class="map-wrap">
<canvas id="map" width="520" height="320"></canvas>
</div>
<div class="selection">
<div class="selection-head">
<strong id="selectionName">Crate B</strong>
<span id="massValue">45 kg</span>
</div>
<input
id="massSlider"
type="range"
min="5"
max="300"
step="1"
value="45"
aria-label="Selected crate mass"
>
<div class="button-row">
<button id="reset">Reset</button>
<button id="tipTest" class="warning">Tip test</button>
</div>
<div class="button-row views">
<button data-view="iso">Perspective</button>
<button data-view="top">Top</button>
<button data-view="side">Side</button>
</div>
</div>
</aside>
<div class="help">
<strong>Drag crate</strong> to move it ·
<strong>drag background</strong> to orbit ·
<strong>right-drag</strong> to pan ·
<strong>wheel</strong> to zoom ·
<strong>arrow keys</strong> nudge selected crate
</div>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
// -------------------------------------------------------------------------
// Renderer and scene
// -------------------------------------------------------------------------
const app = document.getElementById("app");
const renderer = new THREE.WebGLRenderer({
antialias: true,
powerPreference: "high-performance"
});
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.08;
app.appendChild(renderer.domElement);
const scene = new THREE.Scene();
scene.background = new THREE.Color(0xcbd5e1);
scene.fog = new THREE.Fog(0xcbd5e1, 14, 29);
const camera = new THREE.PerspectiveCamera(
43,
window.innerWidth / window.innerHeight,
0.05,
80
);
const orbit = {
target: new THREE.Vector3(0, 0.9, 0),
radius: 8.4,
theta: 0.72,
phi: 1.02
};
function applyCamera() {
const spherical = new THREE.Spherical(
orbit.radius,
orbit.phi,
orbit.theta
);
const offset = new THREE.Vector3().setFromSpherical(spherical);
camera.position.copy(orbit.target).add(offset);
camera.lookAt(orbit.target);
}
applyCamera();
scene.add(new THREE.HemisphereLight(0xf8fafc, 0x64748b, 2.0));
const sun = new THREE.DirectionalLight(0xfff7ed, 3.0);
sun.position.set(5, 9, 6);
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 = -7;
sun.shadow.camera.near = 0.5;
sun.shadow.camera.far = 25;
sun.shadow.normalBias = 0.025;
scene.add(sun);
const fill = new THREE.DirectionalLight(0xbae6fd, 1.1);
fill.position.set(-5, 4, -4);
scene.add(fill);
const materials = {
wood: new THREE.MeshStandardMaterial({
color: 0xb77943,
roughness: 0.82
}),
woodDark: new THREE.MeshStandardMaterial({
color: 0x704329,
roughness: 0.88
}),
woodLight: new THREE.MeshStandardMaterial({
color: 0xd69b5d,
roughness: 0.8
}),
metal: new THREE.MeshStandardMaterial({
color: 0x475569,
roughness: 0.38,
metalness: 0.65
}),
rubber: new THREE.MeshStandardMaterial({
color: 0x111827,
roughness: 0.94
}),
rubberEdge: new THREE.MeshStandardMaterial({
color: 0x334155,
roughness: 0.9
}),
grip: new THREE.MeshStandardMaterial({
color: 0x1e293b,
roughness: 0.95
})
};
const DECK_TOP = 1.24;
const DECK_X = 1.82;
const DECK_Z = 1.08;
const CART_MASS = 52;
const CART_COM = new THREE.Vector3(-0.30, 1.00, 0);
// -------------------------------------------------------------------------
// Ground and voxel handcart
// -------------------------------------------------------------------------
const ground = new THREE.Mesh(
new THREE.PlaneGeometry(50, 50),
new THREE.MeshStandardMaterial({
color: 0xd7dee8,
roughness: 0.96
})
);
ground.rotation.x = -Math.PI / 2;
ground.position.y = -0.015;
ground.receiveShadow = true;
scene.add(ground);
const grid = new THREE.GridHelper(18, 36, 0x94a3b8, 0xaab5c3);
grid.position.y = 0.002;
grid.material.transparent = true;
grid.material.opacity = 0.28;
scene.add(grid);
function addBox(parent, size, position, material, castShadow = true) {
const mesh = new THREE.Mesh(
new THREE.BoxGeometry(size[0], size[1], size[2]),
material
);
mesh.position.set(position[0], position[1], position[2]);
mesh.castShadow = castShadow;
mesh.receiveShadow = true;
parent.add(mesh);
return mesh;
}
const cart = new THREE.Group();
scene.add(cart);
// Main frame.
addBox(cart, [3.72, 0.18, 2.22], [0, 0.99, 0], materials.woodDark);
addBox(cart, [3.58, 0.18, 0.18], [0, 0.78, -0.82], materials.metal);
addBox(cart, [3.58, 0.18, 0.18], [0, 0.78, 0.82], materials.metal);
// Individual deck planks.
const plankCount = 6;
const gap = 0.035;
const plankDepth = (2.2 - gap * (plankCount - 1)) / plankCount;
for (let i = 0; i < plankCount; i++) {
const z = -1.1 + plankDepth / 2 + i * (plankDepth + gap);
const plankMaterial = i % 2 ? materials.wood : materials.woodLight;
addBox(cart, [3.74, 0.16, plankDepth], [0, 1.16, z], plankMaterial);
}
// Low retaining rails.
addBox(cart, [3.76, 0.16, 0.12], [0, 1.31, -1.13], materials.woodDark);
addBox(cart, [3.76, 0.16, 0.12], [0, 1.31, 1.13], materials.woodDark);
addBox(cart, [0.12, 0.16, 2.25], [1.88, 1.31, 0], materials.woodDark);
// Axles.
addBox(cart, [0.17, 0.17, 2.72], [-0.85, 0.63, 0], materials.metal);
addBox(cart, [0.17, 0.17, 2.72], [0.85, 0.63, 0], materials.metal);
function createVoxelWheel(x, z) {
const group = new THREE.Group();
group.position.set(x, 0.64, z);
const cell = 0.23;
const blockSize = 0.235;
for (let gy = -2; gy <= 2; gy++) {
for (let gx = -2; gx <= 2; gx++) {
const distance = Math.hypot(gx, gy);
if (distance > 2.08) continue;
const material =
Math.abs(gx) + Math.abs(gy) === 3
? materials.rubberEdge
: materials.rubber;
addBox(
group,
[blockSize, blockSize, 0.30],
[gx * cell, gy * cell, 0],
material
);
}
}
addBox(
group,
[0.34, 0.34, 0.38],
[0, 0, 0],
materials.metal
);
cart.add(group);
}
for (const x of [-0.85, 0.85]) {
for (const z of [-1.22, 1.22]) {
createVoxelWheel(x, z);
}
}
// Push handles.
for (const z of [-0.78, 0.78]) {
addBox(cart, [1.55, 0.13, 0.13], [-2.47, 1.20, z], materials.metal);
addBox(cart, [0.55, 0.18, 0.18], [-3.10, 1.20, z], materials.grip);
}
addBox(cart, [0.14, 0.14, 1.70], [-3.13, 1.20, 0], materials.metal);
// -------------------------------------------------------------------------
// Wheel support patches and combined support hull
// -------------------------------------------------------------------------
const supportCenters = [
{ x: -0.85, z: -1.22 },
{ x: -0.85, z: 1.22 },
{ x: 0.85, z: -1.22 },
{ x: 0.85, z: 1.22 }
];
const patchHalfX = 0.10;
const patchHalfZ = 0.12;
const supportHalfX = 0.85 + patchHalfX;
const supportHalfZ = 1.22 + patchHalfZ;
const supportPolygon = [
{ x: -supportHalfX, z: -supportHalfZ },
{ x: supportHalfX, z: -supportHalfZ },
{ x: supportHalfX, z: supportHalfZ },
{ x: -supportHalfX, z: supportHalfZ }
];
const supportFill = new THREE.Mesh(
new THREE.PlaneGeometry(supportHalfX * 2, supportHalfZ * 2),
new THREE.MeshBasicMaterial({
color: 0x22c55e,
transparent: true,
opacity: 0.12,
depthWrite: false,
side: THREE.DoubleSide
})
);
supportFill.rotation.x = -Math.PI / 2;
supportFill.position.y = 0.012;
scene.add(supportFill);
const supportOutline = new THREE.LineLoop(
new THREE.BufferGeometry().setFromPoints(
supportPolygon.map(p => new THREE.Vector3(p.x, 0.022, p.z))
),
new THREE.LineBasicMaterial({
color: 0x22c55e,
transparent: true,
opacity: 0.95
})
);
scene.add(supportOutline);
for (const center of supportCenters) {
const patch = new THREE.Mesh(
new THREE.PlaneGeometry(patchHalfX * 2, patchHalfZ * 2),
new THREE.MeshBasicMaterial({
color: 0xf59e0b,
transparent: true,
opacity: 0.58,
depthWrite: false
})
);
patch.rotation.x = -Math.PI / 2;
patch.position.set(center.x, 0.025, center.z);
scene.add(patch);
}
// -------------------------------------------------------------------------
// Labels
// -------------------------------------------------------------------------
function roundedRect(ctx, x, y, w, h, radius) {
const r = Math.min(radius, w / 2, h / 2);
ctx.beginPath();
ctx.moveTo(x + r, y);
ctx.arcTo(x + w, y, x + w, y + h, r);
ctx.arcTo(x + w, y + h, x, y + h, r);
ctx.arcTo(x, y + h, x, y, r);
ctx.arcTo(x, y, x + w, y, r);
ctx.closePath();
}
function createSpriteTexture(width = 512, height = 240) {
const canvas = document.createElement("canvas");
canvas.width = width;
canvas.height = height;
const texture = new THREE.CanvasTexture(canvas);
texture.colorSpace = THREE.SRGBColorSpace;
texture.minFilter = THREE.LinearFilter;
return { canvas, ctx: canvas.getContext("2d"), texture };
}
function makeMassSprite(crate) {
const label = createSpriteTexture();
const sprite = new THREE.Sprite(
new THREE.SpriteMaterial({
map: label.texture,
transparent: true,
depthTest: false,
depthWrite: false
})
);
sprite.scale.set(0.93, 0.44, 1);
sprite.position.set(0, crate.size[1] + 0.26, 0);
sprite.renderOrder = 20;
crate.group.add(sprite);
crate.label = { ...label, sprite };
drawMassLabel(crate);
}
function drawMassLabel(crate) {
const { ctx, canvas, texture } = crate.label;
ctx.clearRect(0, 0, canvas.width, canvas.height);
roundedRect(ctx, 8, 8, 496, 224, 28);
ctx.fillStyle = "rgba(15, 23, 42, 0.94)";
ctx.fill();
ctx.strokeStyle = crate.color;
ctx.lineWidth = 8;
ctx.stroke();
ctx.fillStyle = crate.color;
roundedRect(ctx, 26, 28, 12, 184, 6);
ctx.fill();
ctx.textAlign = "center";
ctx.fillStyle = "#e2e8f0";
ctx.font = "700 38px system-ui, sans-serif";
ctx.fillText(crate.name.toUpperCase(), 270, 78);
ctx.fillStyle = "#ffffff";
ctx.font = "800 82px system-ui, sans-serif";
ctx.fillText(`${crate.mass} kg`, 270, 170);
texture.needsUpdate = true;
}
// -------------------------------------------------------------------------
// Cargo crates
// -------------------------------------------------------------------------
const cargo = [];
const pickMeshes = [];
function createCargo(name, mass, size, position, color) {
const group = new THREE.Group();
group.position.set(position[0], DECK_TOP, position[1]);
scene.add(group);
const bodyMaterial = new THREE.MeshStandardMaterial({
color,
roughness: 0.72,
metalness: 0.04
});
const mesh = addBox(
group,
size,
[0, size[1] / 2, 0],
bodyMaterial
);
const strapMaterial = new THREE.MeshStandardMaterial({
color: 0xf8fafc,
roughness: 0.8
});
// Voxel-style packing straps.
addBox(
group,
[0.075, 0.026, size[2] + 0.035],
[0, size[1] + 0.014, 0],
strapMaterial
);
addBox(
group,
[0.075, size[1] + 0.025, 0.026],
[0, size[1] / 2, size[2] / 2 + 0.014],
strapMaterial
);
const crate = {
name,
mass,
size,
color,
group,
mesh,
home: {
mass,
position: new THREE.Vector3(position[0], DECK_TOP, position[1])
}
};
makeMassSprite(crate);
cargo.push(crate);
pickMeshes.push(mesh);
return crate;
}
createCargo(
"Crate A",
24,
[0.85, 0.72, 0.78],
[-0.95, 0.43],
0x38bdf8
);
createCargo(
"Crate B",
45,
[1.05, 0.90, 0.95],
[0.15, -0.38],
0xf59e0b
);
createCargo(
"Crate C",
18,
[0.70, 0.60, 0.68],
[0.95, 0.48],
0xa78bfa
);
let selectedCargo = cargo[1];
const selectionHelper = new THREE.BoxHelper(selectedCargo.mesh, 0x22d3ee);
selectionHelper.material.depthTest = false;
selectionHelper.material.transparent = true;
selectionHelper.material.opacity = 0.95;
selectionHelper.renderOrder = 30;
scene.add(selectionHelper);
// -------------------------------------------------------------------------
// Center-of-mass visualization
// -------------------------------------------------------------------------
const comMaterial = new THREE.MeshStandardMaterial({
color: 0xfde047,
emissive: 0xf59e0b,
emissiveIntensity: 0.65,
roughness: 0.25,
metalness: 0.15
});
const comDot = new THREE.Mesh(
new THREE.SphereGeometry(0.115, 24, 16),
comMaterial
);
comDot.castShadow = true;
scene.add(comDot);
const comLineGeometry = new THREE.BufferGeometry().setFromPoints([
new THREE.Vector3(),
new THREE.Vector3()
]);
const comLine = new THREE.Line(
comLineGeometry,
new THREE.LineDashedMaterial({
color: 0xfde047,
dashSize: 0.11,
gapSize: 0.075,
transparent: true,
opacity: 0.9
})
);
scene.add(comLine);
const projectedMarker = new THREE.Mesh(
new THREE.RingGeometry(0.105, 0.165, 32),
new THREE.MeshBasicMaterial({
color: 0xfde047,
side: THREE.DoubleSide,
transparent: true,
opacity: 0.95,
depthTest: false
})
);
projectedMarker.rotation.x = -Math.PI / 2;
projectedMarker.position.y = 0.035;
projectedMarker.renderOrder = 25;
scene.add(projectedMarker);
const projectedCross = new THREE.LineSegments(
new THREE.BufferGeometry().setFromPoints([
new THREE.Vector3(-0.28, 0, 0),
new THREE.Vector3(0.28, 0, 0),
new THREE.Vector3(0, 0, -0.28),
new THREE.Vector3(0, 0, 0.28)
]),
new THREE.LineBasicMaterial({
color: 0xfde047,
transparent: true,
opacity: 0.9,
depthTest: false
})
);
projectedCross.position.y = 0.038;
projectedCross.renderOrder = 25;
scene.add(projectedCross);
const comLabel = createSpriteTexture(512, 210);
const comLabelSprite = new THREE.Sprite(
new THREE.SpriteMaterial({
map: comLabel.texture,
transparent: true,
depthTest: false,
depthWrite: false
})
);
comLabelSprite.scale.set(1.18, 0.48, 1);
comLabelSprite.renderOrder = 40;
scene.add(comLabelSprite);
const MAX_TRAIL = 180;
const trail = [];
const trailGeometry = new THREE.BufferGeometry();
trailGeometry.setAttribute(
"position",
new THREE.Float32BufferAttribute(new Float32Array(MAX_TRAIL * 3), 3)
);
trailGeometry.setDrawRange(0, 0);
const trailLine = new THREE.Line(
trailGeometry,
new THREE.LineBasicMaterial({
color: 0xfde047,
transparent: true,
opacity: 0.55
})
);
scene.add(trailLine);
// -------------------------------------------------------------------------
// HUD and top-down support map
// -------------------------------------------------------------------------
const statusElement = document.getElementById("status");
const totalMassElement = document.getElementById("totalMass");
const comValueElement = document.getElementById("comValue");
const marginValueElement = document.getElementById("marginValue");
const heightValueElement = document.getElementById("heightValue");
const supportValueElement = document.getElementById("supportValue");
const selectionNameElement = document.getElementById("selectionName");
const massValueElement = document.getElementById("massValue");
const massSlider = document.getElementById("massSlider");
const mapCanvas = document.getElementById("map");
const mapContext = mapCanvas.getContext("2d");
const statusColors = {
stable: { hex: 0x22c55e, css: "#22c55e" },
edge: { hex: 0xf59e0b, css: "#f59e0b" },
unstable: { hex: 0xef4444, css: "#ef4444" }
};
let analysisDirty = true;
let currentAnalysis = null;
function signedDistanceToSupport(x, z) {
let minimum = Infinity;
for (let i = 0; i < supportPolygon.length; i++) {
const a = supportPolygon[i];
const b = supportPolygon[(i + 1) % supportPolygon.length];
const ex = b.x - a.x;
const ez = b.z - a.z;
const length = Math.hypot(ex, ez);
const cross = ex * (z - a.z) - ez * (x - a.x);
minimum = Math.min(minimum, cross / length);
}
return minimum;
}
function mapPoint(x, z) {
const minX = -3.35;
const maxX = 3.35;
const minZ = -1.85;
const maxZ = 1.85;
return {
x: ((x - minX) / (maxX - minX)) * mapCanvas.width,
y: ((z - minZ) / (maxZ - minZ)) * mapCanvas.height
};
}
function drawMap(analysis) {
const ctx = mapContext;
const w = mapCanvas.width;
const h = mapCanvas.height;
ctx.clearRect(0, 0, w, h);
ctx.fillStyle = "#07111f";
ctx.fillRect(0, 0, w, h);
// Grid.
ctx.strokeStyle = "rgba(148,163,184,0.12)";
ctx.lineWidth = 1;
for (let i = 0; i <= 8; i++) {
const x = (i / 8) * w;
const y = (i / 8) * h;
ctx.beginPath();
ctx.moveTo(x, 0);
ctx.lineTo(x, h);
ctx.stroke();
ctx.beginPath();
ctx.moveTo(0, y);
ctx.lineTo(w, y);
ctx.stroke();
}
// Support hull.
ctx.beginPath();
supportPolygon.forEach((p, i) => {
const mapped = mapPoint(p.x, p.z);
if (i === 0) ctx.moveTo(mapped.x, mapped.y);
else ctx.lineTo(mapped.x, mapped.y);
});
ctx.closePath();
ctx.fillStyle = analysis.status === "unstable"
? "rgba(239,68,68,0.18)"
: analysis.status === "edge"
? "rgba(245,158,11,0.18)"
: "rgba(34,197,94,0.16)";
ctx.fill();
ctx.strokeStyle = statusColors[analysis.status].css;
ctx.lineWidth = 3;
ctx.stroke();
// Contact patches.
ctx.fillStyle = "rgba(245,158,11,0.8)";
for (const center of supportCenters) {
const p = mapPoint(center.x, center.z);
ctx.fillRect(
p.x - (patchHalfX / 6.7) * w,
p.y - (patchHalfZ / 3.7) * h,
(patchHalfX * 2 / 6.7) * w,
(patchHalfZ * 2 / 3.7) * h
);
}
// Cargo footprints.
cargo.forEach((crate, index) => {
const p = mapPoint(crate.group.position.x, crate.group.position.z);
const size = Math.max(19, crate.size[0] * 29);
ctx.fillStyle = `#${crate.color.toString(16).padStart(6, "0")}`;
ctx.fillRect(p.x - size / 2, p.y - size / 2, size, size);
ctx.strokeStyle = "rgba(255,255,255,0.8)";
ctx.lineWidth = 1.5;
ctx.strokeRect(p.x - size / 2, p.y - size / 2, size, size);
ctx.fillStyle = "#07111f";
ctx.font = "800 14px system-ui";
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.fillText(String.fromCharCode(65 + index), p.x, p.y);
});
// COM path.
if (trail.length > 1) {
ctx.beginPath();
trail.forEach((point, index) => {
const p = mapPoint(point.x, point.y);
if (index === 0) ctx.moveTo(p.x, p.y);
else ctx.lineTo(p.x, p.y);
});
ctx.strokeStyle = "rgba(253,224,71,0.48)";
ctx.lineWidth = 2.5;
ctx.stroke();
}
// Current COM projection.
const com = mapPoint(analysis.com.x, analysis.com.z);
ctx.strokeStyle = "#fde047";
ctx.lineWidth = 3;
ctx.beginPath();
ctx.arc(com.x, com.y, 9, 0, Math.PI * 2);
ctx.stroke();
ctx.beginPath();
ctx.moveTo(com.x - 15, com.y);
ctx.lineTo(com.x + 15, com.y);
ctx.moveTo(com.x, com.y - 15);
ctx.lineTo(com.x, com.y + 15);
ctx.stroke();
ctx.fillStyle = "#94a3b8";
ctx.font = "700 12px system-ui";
ctx.textAlign = "left";
ctx.textBaseline = "bottom";
ctx.fillText("TOP VIEW", 12, 18);
}
function drawComLabel(total, com) {
const { ctx, canvas, texture } = comLabel;
ctx.clearRect(0, 0, canvas.width, canvas.height);
roundedRect(ctx, 8, 8, 496, 194, 26);
ctx.fillStyle = "rgba(15,23,42,0.95)";
ctx.fill();
ctx.strokeStyle = "#fde047";
ctx.lineWidth = 7;
ctx.stroke();
ctx.textAlign = "center";
ctx.fillStyle = "#fde047";
ctx.font = "800 43px system-ui";
ctx.fillText("COM", 256, 66);
ctx.fillStyle = "#f8fafc";
ctx.font = "750 36px system-ui";
ctx.fillText(`${total} kg`, 256, 119);
ctx.fillStyle = "#94a3b8";
ctx.font = "600 24px system-ui";
ctx.fillText(
`X ${com.x.toFixed(2)} · Z ${com.z.toFixed(2)} m`,
256,
166
);
texture.needsUpdate = true;
}
function updateAnalysis() {
let total = CART_MASS;
const weighted = CART_COM.clone().multiplyScalar(CART_MASS);
for (const crate of cargo) {
const center = crate.group.position.clone();
center.y += crate.size[1] / 2;
weighted.addScaledVector(center, crate.mass);
total += crate.mass;
}
const com = weighted.multiplyScalar(1 / total);
const margin = signedDistanceToSupport(com.x, com.z);
let status = "stable";
let label = "STABLE";
if (margin < 0) {
status = "unstable";
label = "OUTSIDE SUPPORT";
} else if (margin < 0.18) {
status = "edge";
label = "NEAR EDGE";
}
const color = statusColors[status];
// Main scene visualization.
comDot.position.copy(com);
comDot.material.color.setHex(color.hex);
comDot.material.emissive.setHex(color.hex);
projectedMarker.position.set(com.x, 0.035, com.z);
projectedMarker.material.color.setHex(color.hex);
projectedCross.position.set(com.x, 0.038, com.z);
projectedCross.material.color.setHex(color.hex);
supportFill.material.color.setHex(color.hex);
supportOutline.material.color.setHex(color.hex);
const linePositions = comLine.geometry.attributes.position;
linePositions.setXYZ(0, com.x, com.y, com.z);
linePositions.setXYZ(1, com.x, 0.04, com.z);
linePositions.needsUpdate = true;
comLine.material.color.setHex(color.hex);
comLine.computeLineDistances();
comLabelSprite.position.set(com.x, com.y + 0.37, com.z);
drawComLabel(total, com);
// Trail.
const last = trail[trail.length - 1];
if (!last || Math.hypot(last.x - com.x, last.y - com.z) > 0.009) {
trail.push(new THREE.Vector2(com.x, com.z));
if (trail.length > MAX_TRAIL) trail.shift();
}
const trailPositions = trailGeometry.attributes.position;
for (let i = 0; i < trail.length; i++) {
trailPositions.setXYZ(i, trail[i].x, 0.045, trail[i].y);
}
trailPositions.needsUpdate = true;
trailGeometry.setDrawRange(0, trail.length);
trailLine.material.color.setHex(color.hex);
// HUD.
statusElement.dataset.level = status;
statusElement.textContent = label;
totalMassElement.textContent = `${total.toFixed(0)} kg`;
comValueElement.textContent =
`${com.x.toFixed(2)} / ${com.z.toFixed(2)} m`;
marginValueElement.textContent =
`${margin < 0 ? "−" : "+"}${Math.abs(margin).toFixed(2)} m`;
marginValueElement.style.color = color.css;
heightValueElement.textContent = `${com.y.toFixed(2)} m`;
supportValueElement.textContent = margin < 0 ? "Outside" : "Inside";
supportValueElement.style.color = color.css;
currentAnalysis = {
com,
total,
margin,
status
};
drawMap(currentAnalysis);
analysisDirty = false;
}
function refreshSelection() {
for (const crate of cargo) {
const selected = crate === selectedCargo;
crate.mesh.material.emissive.setHex(selected ? 0x075985 : 0x000000);
crate.mesh.material.emissiveIntensity = selected ? 0.38 : 0;
}
selectionNameElement.textContent = selectedCargo.name;
massSlider.value = selectedCargo.mass;
massValueElement.textContent = `${selectedCargo.mass} kg`;
}
// -------------------------------------------------------------------------
// Crate dragging and custom camera controls
// -------------------------------------------------------------------------
const raycaster = new THREE.Raycaster();
const pointer = new THREE.Vector2();
const dragPlane = new THREE.Plane();
const dragPoint = new THREE.Vector3();
const dragOffset = new THREE.Vector2();
let draggingCrate = false;
let orbitMode = null;
let lastPointerX = 0;
let lastPointerY = 0;
function setPointer(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 clampCrate(crate) {
const halfX = crate.size[0] / 2 + 0.04;
const halfZ = crate.size[2] / 2 + 0.04;
crate.group.position.x = THREE.MathUtils.clamp(
crate.group.position.x,
-DECK_X + halfX,
DECK_X - halfX
);
crate.group.position.z = THREE.MathUtils.clamp(
crate.group.position.z,
-DECK_Z + halfZ,
DECK_Z - halfZ
);
}
renderer.domElement.addEventListener("pointerdown", event => {
setPointer(event);
if (event.button === 0) {
const hits = raycaster.intersectObjects(pickMeshes, false);
if (hits.length) {
const mesh = hits[0].object;
const crate = cargo.find(item => item.mesh === mesh);
selectedCargo = crate;
refreshSelection();
draggingCrate = true;
orbitMode = null;
const planeY = DECK_TOP + crate.size[1] / 2;
dragPlane.set(new THREE.Vector3(0, 1, 0), -planeY);
if (raycaster.ray.intersectPlane(dragPlane, dragPoint)) {
dragOffset.set(
crate.group.position.x - dragPoint.x,
crate.group.position.z - dragPoint.z
);
}
renderer.domElement.setPointerCapture(event.pointerId);
renderer.domElement.style.cursor = "grabbing";
event.preventDefault();
return;
}
}
orbitMode = event.button === 2 || event.button === 1 ? "pan" : "orbit";
lastPointerX = event.clientX;
lastPointerY = event.clientY;
renderer.domElement.setPointerCapture(event.pointerId);
});
renderer.domElement.addEventListener("pointermove", event => {
if (draggingCrate && selectedCargo) {
setPointer(event);
if (raycaster.ray.intersectPlane(dragPlane, dragPoint)) {
selectedCargo.group.position.x = dragPoint.x + dragOffset.x;
selectedCargo.group.position.z = dragPoint.z + dragOffset.y;
clampCrate(selectedCargo);
analysisDirty = true;
}
return;
}
if (orbitMode) {
const dx = event.clientX - lastPointerX;
const dy = event.clientY - lastPointerY;
lastPointerX = event.clientX;
lastPointerY = event.clientY;
if (orbitMode === "orbit") {
orbit.theta -= dx * 0.006;
orbit.phi = THREE.MathUtils.clamp(
orbit.phi - dy * 0.006,
0.18,
1.48
);
} else {
const right = new THREE.Vector3();
const up = new THREE.Vector3();
camera.matrixWorld.extractBasis(right, up, new THREE.Vector3());
const scale = orbit.radius * 0.00135;
orbit.target.addScaledVector(right, -dx * scale);
orbit.target.addScaledVector(up, dy * scale);
}
applyCamera();
return;
}
// Hover cursor.
setPointer(event);
const hovering = raycaster.intersectObjects(pickMeshes, false).length > 0;
renderer.domElement.style.cursor = hovering ? "grab" : "default";
});
function endPointer(event) {
draggingCrate = false;
orbitMode = null;
if (renderer.domElement.hasPointerCapture(event.pointerId)) {
renderer.domElement.releasePointerCapture(event.pointerId);
}
renderer.domElement.style.cursor = "default";
}
renderer.domElement.addEventListener("pointerup", endPointer);
renderer.domElement.addEventListener("pointercancel", endPointer);
renderer.domElement.addEventListener("contextmenu", event => {
event.preventDefault();
});
renderer.domElement.addEventListener(
"wheel",
event => {
event.preventDefault();
orbit.radius = THREE.MathUtils.clamp(
orbit.radius * Math.exp(event.deltaY * 0.001),
4.2,
15
);
applyCamera();
},
{ passive: false }
);
window.addEventListener("keydown", event => {
if (["INPUT", "TEXTAREA", "SELECT"].includes(event.target.tagName)) {
return;
}
const amount = event.shiftKey ? 0.25 : 0.10;
let changed = true;
switch (event.key) {
case "ArrowLeft":
selectedCargo.group.position.x -= amount;
break;
case "ArrowRight":
selectedCargo.group.position.x += amount;
break;
case "ArrowUp":
selectedCargo.group.position.z -= amount;
break;
case "ArrowDown":
selectedCargo.group.position.z += amount;
break;
default:
changed = false;
}
if (changed) {
event.preventDefault();
clampCrate(selectedCargo);
analysisDirty = true;
}
});
massSlider.addEventListener("input", () => {
selectedCargo.mass = Number(massSlider.value);
massValueElement.textContent = `${selectedCargo.mass} kg`;
drawMassLabel(selectedCargo);
analysisDirty = true;
});
function resetScene() {
for (const crate of cargo) {
crate.mass = crate.home.mass;
crate.group.position.copy(crate.home.position);
drawMassLabel(crate);
}
selectedCargo = cargo[1];
refreshSelection();
analysisDirty = true;
}
document.getElementById("reset").addEventListener("click", resetScene);
document.getElementById("tipTest").addEventListener("click", () => {
cargo[0].mass = 5;
cargo[1].mass = 300;
cargo[2].mass = 5;
cargo[0].group.position.set(-1.35, DECK_TOP, 0.45);
cargo[1].group.position.set(1.255, DECK_TOP, -0.52);
cargo[2].group.position.set(-1.43, DECK_TOP, -0.45);
for (const crate of cargo) drawMassLabel(crate);
selectedCargo = cargo[1];
refreshSelection();
analysisDirty = true;
});
document.querySelectorAll("[data-view]").forEach(button => {
button.addEventListener("click", () => {
const view = button.dataset.view;
if (view === "iso") {
orbit.target.set(0, 0.9, 0);
orbit.radius = 8.4;
orbit.theta = 0.72;
orbit.phi = 1.02;
} else if (view === "top") {
orbit.target.set(0, 0.6, 0);
orbit.radius = 8.8;
orbit.theta = 0;
orbit.phi = 0.10;
} else {
orbit.target.set(0, 1.0, 0);
orbit.radius = 8.0;
orbit.theta = 0;
orbit.phi = 1.34;
}
applyCamera();
});
});
window.addEventListener("resize", () => {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
});
// -------------------------------------------------------------------------
// Animation
// -------------------------------------------------------------------------
refreshSelection();
updateAnalysis();
const clock = new THREE.Clock();
function animate() {
requestAnimationFrame(animate);
const time = clock.getElapsedTime();
if (analysisDirty) updateAnalysis();
const pulse = 1 + Math.sin(time * 3.2) * 0.08;
comDot.scale.setScalar(pulse);
selectedCargo.mesh.updateWorldMatrix(true, false);
selectionHelper.setFromObject(selectedCargo.mesh);
renderer.render(scene, camera);
}
animate();
</script>
</body>
</html>
```