Prompt specification
Build or customize the Three.js 3D scene "Three Pieces One Cargo Tray" 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: Three Pieces One Cargo Tray
Category: Games & Play · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/three-pieces-one-cargo-tray-x3474
Scene Description Prompt:
Make a low-poly Three.js scene in a self-contained HTML file using cdnjs: three pieces one cargo tray. Create a small packing puzzle with three original polyomino pieces and one tray. Validate nonoverlap and boundary containment from occupied grid cells.
Working Three.js Starter (three-pieces-one-cargo-tray-x3474):
```html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Cargo 25 — Polyomino Packing Puzzle</title>
<style>
:root {
color-scheme: dark;
--bg: #071019;
--panel: #0c1721;
--panel-2: #101e2a;
--line: rgba(166, 204, 224, 0.14);
--text: #e7f1f5;
--muted: #8297a6;
--mint: #54d7b0;
--amber: #f4ba4b;
--red: #ff747c;
}
* { box-sizing: border-box; }
html, body {
margin: 0;
min-height: 100%;
background: var(--bg);
color: var(--text);
font-family:
Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
body { overflow: hidden; }
button { font: inherit; }
.app {
height: 100vh;
min-height: 650px;
display: grid;
grid-template-rows: 76px minmax(0, 1fr);
}
header {
display: flex;
align-items: center;
justify-content: space-between;
gap: 20px;
padding: 0 22px;
border-bottom: 1px solid var(--line);
background: rgba(7, 16, 25, 0.94);
z-index: 5;
}
.brand {
display: flex;
align-items: center;
gap: 13px;
min-width: 0;
}
.brand-mark {
width: 37px;
height: 37px;
position: relative;
flex: 0 0 auto;
transform: rotate(-8deg);
}
.brand-mark::before,
.brand-mark::after {
content: "";
position: absolute;
inset: 3px 10px 3px 3px;
border: 2px solid var(--mint);
border-radius: 3px;
transform: skewY(-12deg);
}
.brand-mark::after {
inset: 10px 3px 3px 10px;
border-color: var(--amber);
transform: skewY(12deg);
}
.brand h1 {
margin: 0;
font-size: 17px;
line-height: 1.05;
letter-spacing: 0.12em;
text-transform: uppercase;
}
.brand p {
margin: 5px 0 0;
color: var(--muted);
font-size: 11px;
letter-spacing: 0.08em;
}
.header-note {
color: var(--muted);
font-size: 11px;
letter-spacing: 0.1em;
text-transform: uppercase;
white-space: nowrap;
}
main {
min-height: 0;
display: grid;
grid-template-columns: minmax(0, 1fr) 370px;
gap: 12px;
padding: 12px;
}
.scene-card,
.panel {
border: 1px solid var(--line);
border-radius: 16px;
overflow: hidden;
background: var(--panel);
}
.scene-card {
position: relative;
min-width: 0;
min-height: 0;
background: #08131c;
}
#scene {
position: absolute;
inset: 0;
touch-action: none;
}
#scene canvas {
display: block;
width: 100%;
height: 100%;
outline: none;
}
.scene-top {
position: absolute;
top: 16px;
left: 16px;
right: 16px;
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 16px;
pointer-events: none;
}
.eyebrow {
color: var(--muted);
font-size: 10px;
font-weight: 750;
letter-spacing: 0.17em;
text-transform: uppercase;
}
.scene-title {
margin-top: 6px;
font-size: clamp(19px, 2.5vw, 30px);
font-weight: 760;
letter-spacing: -0.04em;
}
.scene-subtitle {
margin-top: 5px;
color: #9bb0bd;
font-size: 12px;
}
.status-badge {
display: inline-flex;
align-items: center;
gap: 8px;
min-height: 34px;
padding: 0 12px;
border: 1px solid var(--line);
border-radius: 999px;
background: rgba(7, 16, 25, 0.82);
color: #9eb0bc;
font-size: 10px;
font-weight: 800;
letter-spacing: 0.13em;
text-transform: uppercase;
backdrop-filter: blur(12px);
}
.status-badge::before {
content: "";
width: 7px;
height: 7px;
border-radius: 50%;
background: currentColor;
box-shadow: 0 0 12px currentColor;
}
.status-badge.loading { color: var(--amber); }
.status-badge.conflict { color: var(--red); }
.status-badge.secured { color: var(--mint); }
.scene-bottom {
position: absolute;
left: 16px;
right: 16px;
bottom: 14px;
display: flex;
justify-content: space-between;
align-items: flex-end;
gap: 14px;
pointer-events: none;
}
.instructions {
max-width: 450px;
padding: 10px 12px;
border: 1px solid var(--line);
border-radius: 10px;
background: rgba(7, 16, 25, 0.78);
color: #9bb0bd;
font-size: 11px;
line-height: 1.55;
backdrop-filter: blur(12px);
}
.instructions strong { color: var(--text); }
.camera-hint {
color: #718795;
font-size: 10px;
letter-spacing: 0.06em;
text-align: right;
white-space: nowrap;
}
#toast {
position: absolute;
left: 50%;
top: 76px;
max-width: min(480px, calc(100% - 32px));
padding: 11px 15px;
border: 1px solid var(--line);
border-radius: 10px;
background: rgba(12, 23, 33, 0.94);
color: var(--text);
font-size: 12px;
box-shadow: 0 16px 45px rgba(0, 0, 0, 0.35);
opacity: 0;
transform: translate(-50%, -8px);
transition: opacity 160ms ease, transform 160ms ease;
pointer-events: none;
backdrop-filter: blur(12px);
}
#toast.show {
opacity: 1;
transform: translate(-50%, 0);
}
#toast.good { border-color: rgba(84, 215, 176, 0.45); }
#toast.bad { border-color: rgba(255, 116, 124, 0.48); }
.panel {
min-height: 0;
overflow-y: auto;
padding: 18px;
scrollbar-width: thin;
scrollbar-color: #243746 transparent;
}
.panel-heading {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 12px;
}
.panel h2 {
margin: 5px 0 0;
font-size: 21px;
letter-spacing: -0.035em;
}
.selected-pill {
min-width: 76px;
padding: 8px 9px;
border: 1px solid var(--line);
border-radius: 9px;
color: var(--muted);
font-size: 10px;
text-align: center;
text-transform: uppercase;
letter-spacing: 0.1em;
}
.objective {
margin: 16px 0;
padding: 13px;
border: 1px solid rgba(84, 215, 176, 0.2);
border-radius: 11px;
background: linear-gradient(135deg, rgba(84, 215, 176, 0.08), transparent);
color: #a9bac4;
font-size: 12px;
line-height: 1.55;
}
.objective strong { color: var(--mint); }
.section-label {
display: flex;
align-items: center;
justify-content: space-between;
margin: 17px 0 9px;
color: var(--muted);
font-size: 10px;
font-weight: 800;
letter-spacing: 0.14em;
text-transform: uppercase;
}
.section-label span:last-child {
color: #607888;
font-weight: 650;
letter-spacing: 0.04em;
}
.piece-list {
display: grid;
gap: 8px;
}
.piece-card {
width: 100%;
display: grid;
grid-template-columns: 54px minmax(0, 1fr) auto;
align-items: center;
gap: 11px;
padding: 10px;
border: 1px solid var(--line);
border-radius: 11px;
background: rgba(16, 30, 42, 0.62);
color: var(--text);
text-align: left;
cursor: pointer;
transition: border-color 140ms ease, background 140ms ease, transform 140ms ease;
}
.piece-card:hover {
transform: translateY(-1px);
border-color: rgba(255, 255, 255, 0.22);
}
.piece-card.active {
border-color: color-mix(in srgb, var(--piece) 65%, transparent);
background: color-mix(in srgb, var(--piece) 8%, #101e2a);
}
.piece-mini {
width: 54px;
height: 48px;
display: grid;
place-items: center;
overflow: hidden;
}
.piece-mini svg {
max-width: 100%;
max-height: 100%;
}
.piece-name {
font-size: 13px;
font-weight: 780;
letter-spacing: 0.015em;
}
.piece-meta {
margin-top: 4px;
color: var(--muted);
font-size: 10px;
letter-spacing: 0.06em;
}
.piece-state {
padding: 5px 6px;
border-radius: 6px;
color: #8da2af;
background: rgba(255, 255, 255, 0.045);
font-size: 8px;
font-weight: 850;
letter-spacing: 0.09em;
text-transform: uppercase;
}
.piece-state.in { color: var(--mint); }
.piece-state.out { color: var(--red); }
.piece-state.conflict { color: var(--amber); }
.controls {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 8px;
margin-top: 13px;
}
.control-button {
min-height: 39px;
border: 1px solid var(--line);
border-radius: 9px;
background: #132330;
color: #c9d8df;
font-size: 11px;
font-weight: 750;
letter-spacing: 0.035em;
cursor: pointer;
transition: background 140ms ease, border-color 140ms ease;
}
.control-button:hover {
background: #19303f;
border-color: rgba(255, 255, 255, 0.2);
}
.control-button.primary {
color: #07130f;
border-color: var(--mint);
background: var(--mint);
}
.control-button.primary:hover { background: #6ce4c1; }
.telemetry {
margin-top: 17px;
padding-top: 1px;
border-top: 1px solid var(--line);
}
.grid-heading {
display: flex;
align-items: center;
justify-content: space-between;
margin: 15px 0 9px;
color: var(--muted);
font-size: 10px;
font-weight: 800;
letter-spacing: 0.14em;
text-transform: uppercase;
}
.grid-heading strong {
color: var(--text);
font-size: 12px;
letter-spacing: 0.04em;
}
.mini-grid {
display: grid;
grid-template-columns: repeat(5, 1fr);
gap: 5px;
width: 100%;
aspect-ratio: 1;
padding: 8px;
border: 1px solid var(--line);
border-radius: 11px;
background: #08131b;
}
.mini-cell {
position: relative;
border: 1px solid rgba(152, 191, 212, 0.09);
border-radius: 4px;
background: rgba(133, 172, 194, 0.035);
}
.mini-cell::after {
content: "";
position: absolute;
inset: 5px;
border-radius: 2px;
background: var(--cell-color);
opacity: 0.88;
}
.mini-cell.collision {
border-color: var(--red);
box-shadow: 0 0 0 1px var(--red), 0 0 13px rgba(255, 116, 124, 0.3);
}
.mini-cell.collision::after {
background:
repeating-linear-gradient(
45deg,
var(--cell-color) 0 4px,
rgba(255, 116, 124, 0.9) 4px 7px
);
opacity: 1;
}
.checks {
display: grid;
gap: 7px;
margin-top: 12px;
}
.check {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
padding: 9px 10px;
border: 1px solid var(--line);
border-radius: 8px;
color: var(--muted);
font-size: 10px;
}
.check strong {
color: #aebfc9;
font-size: 9px;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.check.pass strong { color: var(--mint); }
.check.fail strong { color: var(--red); }
.check.wait strong { color: var(--amber); }
#outcome {
min-height: 38px;
margin: 12px 0 0;
color: #91a6b3;
font-size: 11px;
line-height: 1.55;
}
.method-note {
margin: 14px 0 0;
padding-top: 12px;
border-top: 1px solid var(--line);
color: #607887;
font-size: 9px;
line-height: 1.55;
}
@media (max-width: 980px) {
body { overflow: auto; }
.app {
height: auto;
min-height: 100vh;
grid-template-rows: 70px auto;
}
main {
grid-template-columns: 1fr;
}
.scene-card {
height: 66vh;
min-height: 520px;
}
.panel {
overflow: visible;
}
}
@media (max-width: 560px) {
header { padding: 0 14px; }
.header-note { display: none; }
main { padding: 8px; gap: 8px; }
.scene-card { min-height: 500px; }
.scene-subtitle, .camera-hint { display: none; }
.scene-top { left: 12px; right: 12px; }
.panel { padding: 14px; }
}
</style>
</head>
<body>
<div class="app">
<header>
<div class="brand">
<div class="brand-mark" aria-hidden="true"></div>
<div>
<h1>Cargo 25</h1>
<p>Three forms. One tray. No collisions.</p>
</div>
</div>
<div class="header-note">Original polyomino packing study</div>
</header>
<main>
<section class="scene-card" aria-label="Interactive 3D packing puzzle">
<div id="scene"></div>
<div class="scene-top">
<div>
<div class="eyebrow">Packing bay / 01</div>
<div class="scene-title">Load the tray.</div>
<div class="scene-subtitle">Drag, rotate, and settle all 24 cargo cells.</div>
</div>
<div id="statusBadge" class="status-badge">Empty</div>
</div>
<div class="scene-bottom">
<div class="instructions">
<strong>Drag a piece</strong> into the tray.
Press <strong>R</strong> to rotate the selected piece.
Empty-space dragging orbits the camera.
</div>
<div class="camera-hint">Wheel to zoom · Double-click to reset view</div>
</div>
<div id="toast" role="status" aria-live="polite"></div>
</section>
<aside class="panel">
<div class="panel-heading">
<div>
<div class="eyebrow">Shipment manifest</div>
<h2>Three cargo forms</h2>
</div>
<div id="selectedPill" class="selected-pill">None</div>
</div>
<div class="objective">
Each form contains <strong>8 occupied cells</strong>. The tray holds 25
cells, so the three forms must fit without overlap, leaving exactly
<strong>one empty cell</strong>.
</div>
<div class="section-label">
<span>Cargo pieces</span>
<span>24 cells total</span>
</div>
<div id="pieceList" class="piece-list"></div>
<div class="controls">
<button id="rotateBtn" class="control-button">Rotate piece · R</button>
<button id="resetBtn" class="control-button">Return to dock</button>
<button id="demoBtn" class="control-button primary">Demo pack</button>
<button id="clearBtn" class="control-button">Clear tray</button>
</div>
<div class="telemetry">
<div class="grid-heading">
<span>Occupied-cell ledger</span>
<strong id="occupancy">0 / 25</strong>
</div>
<div id="miniGrid" class="mini-grid" aria-label="Occupied tray cells"></div>
<div class="checks">
<div id="boundaryCheck" class="check">
<span>Boundary containment</span>
<strong>Waiting</strong>
</div>
<div id="collisionCheck" class="check">
<span>Cell collisions</span>
<strong>Clear</strong>
</div>
<div id="cargoCheck" class="check">
<span>Forms stowed</span>
<strong>0 / 3</strong>
</div>
</div>
<p id="outcome" aria-live="polite"></p>
<p class="method-note">
Validation is calculated from integer grid occupancy: every occupied
cell is checked for tray boundaries and duplicate ownership before
the fit is accepted.
</p>
</div>
</aside>
</main>
</div>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
const sceneHost = document.getElementById("scene");
const pieceList = document.getElementById("pieceList");
const miniGrid = document.getElementById("miniGrid");
const occupancyLabel = document.getElementById("occupancy");
const boundaryCheck = document.getElementById("boundaryCheck");
const collisionCheck = document.getElementById("collisionCheck");
const cargoCheck = document.getElementById("cargoCheck");
const outcome = document.getElementById("outcome");
const statusBadge = document.getElementById("statusBadge");
const selectedPill = document.getElementById("selectedPill");
const toast = document.getElementById("toast");
const GRID_SIZE = 5;
const CELL = 1;
const HALF_GRID = (GRID_SIZE - 1) / 2;
const DOCK_Y = 0.09;
const TRAY_Y = 0.24;
// ----- Renderer, camera, and lighting ---------------------------------
const renderer = new THREE.WebGLRenderer({
antialias: true,
powerPreference: "high-performance"
});
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.08;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
sceneHost.appendChild(renderer.domElement);
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x08131c);
scene.fog = new THREE.Fog(0x08131c, 19, 35);
const camera = new THREE.OrthographicCamera(-8, 8, 6, -6, 0.1, 80);
const cameraState = {
yaw: 0.32,
pitch: 0.72,
zoom: 1,
target: new THREE.Vector3(0.35, 0.25, 0.65)
};
function updateCamera() {
const radius = 17;
const horizontal = radius * Math.cos(cameraState.pitch);
camera.position.set(
cameraState.target.x + Math.sin(cameraState.yaw) * horizontal,
cameraState.target.y + Math.sin(cameraState.pitch) * radius,
cameraState.target.z + Math.cos(cameraState.yaw) * horizontal
);
camera.lookAt(cameraState.target);
camera.zoom = cameraState.zoom;
camera.updateProjectionMatrix();
}
function resetCamera() {
cameraState.yaw = 0.32;
cameraState.pitch = 0.72;
cameraState.zoom = 1;
updateCamera();
}
const hemisphere = new THREE.HemisphereLight(0xc4e6ff, 0x16232d, 2.0);
scene.add(hemisphere);
const keyLight = new THREE.DirectionalLight(0xfff1d4, 3.0);
keyLight.position.set(-5, 10, 8);
keyLight.castShadow = true;
keyLight.shadow.mapSize.set(2048, 2048);
keyLight.shadow.camera.left = -13;
keyLight.shadow.camera.right = 13;
keyLight.shadow.camera.top = 11;
keyLight.shadow.camera.bottom = -11;
keyLight.shadow.camera.near = 1;
keyLight.shadow.camera.far = 32;
keyLight.shadow.bias = -0.0004;
scene.add(keyLight);
const rimLight = new THREE.DirectionalLight(0x65c9ff, 1.5);
rimLight.position.set(8, 5, -7);
scene.add(rimLight);
// ----- Low-poly environment -------------------------------------------
const groundMaterial = new THREE.MeshStandardMaterial({
color: 0x071018,
roughness: 0.96,
metalness: 0.02
});
const ground = new THREE.Mesh(new THREE.PlaneGeometry(50, 50), groundMaterial);
ground.rotation.x = -Math.PI / 2;
ground.position.y = -0.12;
ground.receiveShadow = true;
scene.add(ground);
const platformMaterial = new THREE.MeshStandardMaterial({
color: 0x10202b,
roughness: 0.88,
metalness: 0.12,
flatShading: true
});
const platform = new THREE.Mesh(
new THREE.CylinderGeometry(9.3, 9.3, 0.16, 8),
platformMaterial
);
platform.position.set(0.35, -0.01, 0.65);
platform.scale.z = 0.64;
platform.receiveShadow = true;
scene.add(platform);
const dockMaterial = new THREE.MeshStandardMaterial({
color: 0x142633,
roughness: 0.75,
metalness: 0.2,
flatShading: true
});
function addDock(x, z, width, depth) {
const dock = new THREE.Mesh(
new THREE.BoxGeometry(width, 0.1, depth),
dockMaterial
);
dock.position.set(x, 0.035, z);
dock.receiveShadow = true;
scene.add(dock);
}
addDock(-4.5, 0.2, 5.35, 2.35);
addDock(5.3, 0.5, 5.35, 3.35);
addDock(0.4, 3.7, 4.35, 2.35);
function makeDockLabel(text, color, x, z) {
const canvas = document.createElement("canvas");
canvas.width = 512;
canvas.height = 160;
const ctx = canvas.getContext("2d");
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = "rgba(7, 16, 25, 0.88)";
ctx.strokeStyle = color;
ctx.lineWidth = 5;
ctx.beginPath();
ctx.roundRect(8, 8, 496, 144, 24);
ctx.fill();
ctx.stroke();
ctx.fillStyle = color;
ctx.font = "800 42px system-ui";
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.fillText(text, 256, 82);
const texture = new THREE.CanvasTexture(canvas);
texture.colorSpace = THREE.SRGBColorSpace;
const sprite = new THREE.Sprite(
new THREE.SpriteMaterial({
map: texture,
transparent: true,
depthWrite: false
})
);
sprite.position.set(x, 0.52, z);
sprite.scale.set(1.45, 0.45, 1);
scene.add(sprite);
}
makeDockLabel("01 / KITE", "#f4ba4b", -4.5, 1.63);
makeDockLabel("02 / RELAY", "#43c9c4", 5.3, 2.42);
makeDockLabel("03 / BRACE", "#ef737c", 0.4, 5.08);
// ----- Cargo tray -------------------------------------------------------
const tray = new THREE.Group();
scene.add(tray);
const trayBaseMaterial = new THREE.MeshStandardMaterial({
color: 0x263945,
roughness: 0.64,
metalness: 0.48,
flatShading: true
});
const trayWallMaterial = new THREE.MeshStandardMaterial({
color: 0x38505e,
roughness: 0.52,
metalness: 0.55,
flatShading: true,
emissive: 0x000000,
emissiveIntensity: 0.35
});
const trayBase = new THREE.Mesh(
new THREE.BoxGeometry(5.55, 0.18, 5.55),
trayBaseMaterial
);
trayBase.position.y = 0.045;
trayBase.castShadow = true;
trayBase.receiveShadow = true;
tray.add(trayBase);
const tileMaterials = [
new THREE.MeshStandardMaterial({
color: 0x1b2d37,
roughness: 0.82,
metalness: 0.16
}),
new THREE.MeshStandardMaterial({
color: 0x203541,
roughness: 0.82,
metalness: 0.16
})
];
const tileGeometry = new THREE.BoxGeometry(0.94, 0.07, 0.94);
for (let row = 0; row < GRID_SIZE; row++) {
for (let col = 0; col < GRID_SIZE; col++) {
const tile = new THREE.Mesh(
tileGeometry,
tileMaterials[(row + col) % 2]
);
tile.position.set(col - HALF_GRID, 0.17, row - HALF_GRID);
tile.receiveShadow = true;
tray.add(tile);
}
}
const wallGeometryLong = new THREE.BoxGeometry(5.72, 0.56, 0.18);
const wallGeometryShort = new THREE.BoxGeometry(0.18, 0.56, 5.36);
const northWall = new THREE.Mesh(wallGeometryLong, trayWallMaterial);
northWall.position.set(0, 0.36, -2.62);
northWall.castShadow = true;
tray.add(northWall);
const southWall = northWall.clone();
southWall.position.z = 2.62;
tray.add(southWall);
const eastWall = new THREE.Mesh(wallGeometryShort, trayWallMaterial);
eastWall.position.set(2.62, 0.36, 0);
eastWall.castShadow = true;
tray.add(eastWall);
const westWall = eastWall.clone();
westWall.position.x = -2.62;
tray.add(westWall);
const cornerGeometry = new THREE.CylinderGeometry(0.13, 0.13, 0.59, 6);
const cornerMaterial = new THREE.MeshStandardMaterial({
color: 0x76909c,
roughness: 0.48,
metalness: 0.65,
flatShading: true
});
for (const x of [-2.62, 2.62]) {
for (const z of [-2.62, 2.62]) {
const corner = new THREE.Mesh(cornerGeometry, cornerMaterial);
corner.position.set(x, 0.37, z);
corner.castShadow = true;
tray.add(corner);
}
}
// ----- Original polyomino cargo forms ----------------------------------
const pieces = [
{
id: "kite",
name: "Kite",
code: "K-08",
color: 0xf4ba4b,
topColor: 0xffd67c,
cells: [
[0, 0], [1, 0], [2, 0], [3, 0], [4, 0],
[0, 1], [1, 1], [2, 1]
],
home: { x: -6.5, z: -0.3 },
solution: { col: 0, row: 0 }
},
{
id: "relay",
name: "Relay",
code: "R-08",
color: 0x43c9c4,
topColor: 0x7ce7df,
cells: [
[3, 0], [4, 0],
[0, 1], [1, 1], [2, 1], [3, 1], [4, 1],
[4, 2]
],
home: { x: 3.3, z: -0.5 },
solution: { col: 0, row: 1 }
},
{
id: "brace",
name: "Brace",
code: "B-08",
color: 0xef737c,
topColor: 0xff9ca3,
cells: [
[0, 0], [1, 0], [2, 0], [3, 0],
[0, 1], [1, 1], [2, 1], [3, 1]
],
home: { x: -1.6, z: 3.2 },
solution: { col: 0, row: 3 }
}
];
const bodyGeometry = new THREE.BoxGeometry(0.84, 0.46, 0.84);
const topGeometry = new THREE.BoxGeometry(0.64, 0.06, 0.64);
const edgeGeometry = new THREE.EdgesGeometry(bodyGeometry, 20);
let selectedId = "kite";
let hitMeshes = [];
function normalizeCells(cells) {
const minX = Math.min(...cells.map(cell => cell[0]));
const minY = Math.min(...cells.map(cell => cell[1]));
return cells.map(([x, y]) => [x - minX, y - minY]);
}
function createPiece(piece) {
piece.originalCells = piece.cells.map(cell => [...cell]);
piece.anchor = null;
piece.group = new THREE.Group();
piece.group.userData.pieceId = piece.id;
piece.bodyMaterial = new THREE.MeshStandardMaterial({
color: piece.color,
roughness: 0.58,
metalness: 0.18,
flatShading: true,
emissive: piece.color,
emissiveIntensity: 0.025
});
piece.topMaterial = new THREE.MeshStandardMaterial({
color: piece.topColor,
roughness: 0.5,
metalness: 0.12,
flatShading: true,
emissive: piece.topColor,
emissiveIntensity: 0.02
});
scene.add(piece.group);
rebuildPiece(piece);
piece.group.position.set(piece.home.x, DOCK_Y, piece.home.z);
}
function rebuildPiece(piece) {
piece.group.clear();
const edgeMaterial = new THREE.LineBasicMaterial({
color: 0x10202a,
transparent: true,
opacity: 0.55
});
for (const [col, row] of piece.cells) {
const body = new THREE.Mesh(bodyGeometry, piece.bodyMaterial);
body.position.set(col, 0.25, row);
body.castShadow = true;
body.receiveShadow = true;
body.userData.pieceId = piece.id;
piece.group.add(body);
const top = new THREE.Mesh(topGeometry, piece.topMaterial);
top.position.set(col, 0.505, row);
top.castShadow = true;
top.userData.pieceId = piece.id;
piece.group.add(top);
const edge = new THREE.LineSegments(edgeGeometry, edgeMaterial);
edge.position.copy(body.position);
piece.group.add(edge);
hitMeshes.push(body, top);
}
}
for (const piece of pieces) createPiece(piece);
function averageLocalOffset(piece) {
const sum = piece.cells.reduce(
(total, [col, row]) => {
total.x += col;
total.z += row;
return total;
},
{ x: 0, z: 0 }
);
return {
x: sum.x / piece.cells.length,
z: sum.z / piece.cells.length
};
}
function rotateCellsAroundPivot(cells) {
const width = Math.max(...cells.map(cell => cell[0])) + 1;
const height = Math.max(...cells.map(cell => cell[1])) + 1;
const pivot = cells
.map(cell => ({ x: cell[0], y: cell[1] }))
.sort((a, b) => {
const da = Math.hypot(
a.x - (width - 1) / 2,
a.y - (height - 1) / 2
);
const db = Math.hypot(
b.x - (width - 1) / 2,
b.y - (height - 1) / 2
);
return da - db || a.y - b.y || a.x - b.x;
})[0];
const transformed = cells.map(([x, y]) => [
pivot.x - (y - pivot.y),
pivot.y + (x - pivot.x)
]);
const normalized = normalizeCells(transformed);
const minX = Math.min(...transformed.map(cell => cell[0]));
const minY = Math.min(...transformed.map(cell => cell[1]));
return {
cells: normalized,
shift: {
x: pivot.x - minX,
y: pivot.y - minY
}
};
}
function rotateSelected() {
const piece = pieces.find(item => item.id === selectedId);
if (!piece) return;
cancelTween(piece);
const result = rotateCellsAroundPivot(piece.cells);
piece.cells = result.cells;
rebuildPiece(piece);
if (piece.anchor) {
piece.anchor.col += result.shift.x;
piece.anchor.row += result.shift.y;
piece.group.position.set(
piece.anchor.col - HALF_GRID,
TRAY_Y,
piece.anchor.row - HALF_GRID
);
} else {
piece.group.position.x += result.shift.x;
piece.group.position.z += result.shift.y;
}
updateValidation();
showToast(`${piece.name} rotated`, "good");
}
// ----- Grid-cell validation ---------------------------------------------
function validate() {
const ownership = new Map();
const outsideCells = [];
const inBounds = new Map();
const pieceOutside = new Set();
const pieceConflicts = new Set();
for (const piece of pieces) {
if (!piece.anchor) continue;
for (const [col, row] of piece.cells) {
const gridCol = piece.anchor.col + col;
const gridRow = piece.anchor.row + row;
const key = `${gridCol},${gridRow}`;
if (!ownership.has(key)) ownership.set(key, []);
ownership.get(key).push(piece.id);
const inside =
gridCol >= 0 &&
gridCol < GRID_SIZE &&
gridRow >= 0 &&
gridRow < GRID_SIZE;
if (inside) {
if (!inBounds.has(key)) inBounds.set(key, []);
inBounds.get(key).push(piece.id);
} else {
outsideCells.push({ col: gridCol, row: gridRow, pieceId: piece.id });
pieceOutside.add(piece.id);
}
}
}
const collisionKeys = [];
for (const [key, owners] of ownership) {
if (owners.length > 1) {
collisionKeys.push(key);
owners.forEach(id => pieceConflicts.add(id));
}
}
const docked = pieces.filter(piece => !piece.anchor).length;
const stowed = pieces.filter(
piece => piece.anchor && !pieceOutside.has(piece.id)
).length;
const solved =
stowed === pieces.length &&
outsideCells.length === 0 &&
collisionKeys.length === 0;
return {
ownership,
inBounds,
outsideCells,
collisionKeys,
pieceOutside,
pieceConflicts,
docked,
stowed,
solved
};
}
function cssColor(value) {
return `#${value.toString(16).padStart(6, "0")}`;
}
function pieceSvg(cells) {
const width = Math.max(...cells.map(cell => cell[0])) + 1;
const height = Math.max(...cells.map(cell => cell[1])) + 1;
const color = cssColor(
pieces.find(piece => piece.id === selectedId)?.color ?? 0xffffff
);
const rects = cells.map(([col, row]) => {
const x = col * 10 + 1;
const y = row * 10 + 1;
return `<rect x="${x}" y="${y}" width="8" height="8" rx="1.5" fill="${color}"/>`;
}).join("");
return `
<svg viewBox="0 0 ${width * 10} ${height * 10}" aria-hidden="true">
${rects}
</svg>
`;
}
function updatePieceCards(result) {
for (const piece of pieces) {
const card = document.querySelector(`[data-piece-card="${piece.id}"]`);
if (!card) continue;
card.classList.toggle("active", piece.id === selectedId);
card.style.setProperty("--piece", cssColor(piece.color));
card.querySelector(".piece-mini").innerHTML = pieceSvg(piece.cells);
const state = card.querySelector(".piece-state");
let label = "Docked";
let stateClass = "";
if (piece.anchor) {
if (result.pieceConflicts.has(piece.id)) {
label = "Conflict";
stateClass = "conflict";
} else if (result.pieceOutside.has(piece.id)) {
label = "Outside";
stateClass = "out";
} else {
label = "In tray";
stateClass = "in";
}
}
state.textContent = label;
state.className = `piece-state ${stateClass}`;
}
}
function updateMiniGrid(result) {
const cells = [];
for (let row = 0; row < GRID_SIZE; row++) {
for (let col = 0; col < GRID_SIZE; col++) {
const key = `${col},${row}`;
const owners = result.inBounds.get(key) ?? [];
const piece = owners.length
? pieces.find(item => item.id === owners[0])
: null;
const classes = ["mini-cell"];
if (owners.length > 1) classes.push("collision");
cells.push(`
<div
class="${classes.join(" ")}"
style="--cell-color:${piece ? cssColor(piece.color) : "transparent"}"
title="${owners.length ? owners.join(", ") : "Empty cell"}"
></div>
`);
}
}
miniGrid.innerHTML = cells.join("");
}
function setCheck(element, state, label) {
element.className = `check ${state}`;
element.querySelector("strong").textContent = label;
}
function updateValidation() {
const result = validate();
occupancyLabel.textContent = `${result.inBounds.size} / ${GRID_SIZE * GRID_SIZE}`;
if (result.docked > 0) {
setCheck(
boundaryCheck,
"wait",
`${result.docked} waiting`
);
} else if (result.outsideCells.length > 0) {
setCheck(
boundaryCheck,
"fail",
`${result.outsideCells.length} outside`
);
} else {
setCheck(boundaryCheck, "pass", "Contained");
}
setCheck(
collisionCheck,
result.collisionKeys.length ? "fail" : "pass",
result.collisionKeys.length
? `${result.collisionKeys.length} overlap${result.collisionKeys.length === 1 ? "" : "s"}`
: "Clear"
);
setCheck(
cargoCheck,
result.stowed === 3 ? "pass" : "wait",
`${result.stowed} / 3`
);
statusBadge.className = "status-badge";
if (result.solved) {
statusBadge.textContent = "Secured";
statusBadge.classList.add("secured");
outcome.textContent =
"All 24 cargo cells are contained and collision-free. The tray is ready to seal.";
trayWallMaterial.emissive.setHex(0x0b5b4a);
} else {
trayWallMaterial.emissive.setHex(0x000000);
if (result.collisionKeys.length) {
statusBadge.textContent = "Conflict";
statusBadge.classList.add("conflict");
outcome.textContent =
"Two or more forms claim the same grid cell. Move the highlighted cargo to clear the overlap.";
} else if (result.outsideCells.length) {
statusBadge.textContent = "Out of bounds";
statusBadge.classList.add("conflict");
outcome.textContent =
"At least one occupied cell extends beyond the tray. Pull the offending form inward.";
} else if (result.stowed > 0) {
statusBadge.textContent = "Loading";
statusBadge.classList.add("loading");
outcome.textContent =
"The current forms fit. Bring the remaining cargo into the tray without creating a collision.";
} else {
statusBadge.textContent = "Empty";
outcome.textContent =
"Choose a cargo form and drag it from its dock into the tray.";
}
}
updatePieceCards(result);
updateMiniGrid(result);
}
pieceList.innerHTML = pieces.map(piece => `
<button
class="piece-card"
data-piece-card="${piece.id}"
style="--piece:${cssColor(piece.color)}"
>
<span class="piece-mini"></span>
<span>
<span class="piece-name">${piece.name}</span>
<span class="piece-meta">${piece.code} · 8 CELLS</span>
</span>
<span class="piece-state">Docked</span>
</button>
`).join("");
pieceList.addEventListener("click", event => {
const card = event.target.closest("[data-piece-card]");
if (!card) return;
selectedId = card.dataset.pieceCard;
selectedPill.textContent = pieces.find(piece => piece.id === selectedId).name;
updateValidation();
});
// ----- Simple position tweens -------------------------------------------
const tweens = new WeakMap();
function cancelTween(piece) {
tweens.delete(piece);
}
function tweenPiece(piece, target, duration = 500) {
cancelTween(piece);
tweens.set(piece, {
start: piece.group.position.clone(),
end: new THREE.Vector3(target.x, target.y, target.z),
started: performance.now(),
duration
});
}
function updateTweens(now) {
for (const piece of pieces) {
const tween = tweens.get(piece);
if (!tween) continue;
const t = Math.min(1, (now - tween.started) / tween.duration);
const eased = 1 - Math.pow(1 - t, 3);
piece.group.position.lerpVectors(tween.start, tween.end, eased);
if (t >= 1) tweens.delete(piece);
}
}
// ----- Pointer interaction and custom camera controls --------------------
const raycaster = new THREE.Raycaster();
const pointer = new THREE.Vector2();
const dragPlane = new THREE.Plane(new THREE.Vector3(0, 1, 0), 0);
const planePoint = new THREE.Vector3();
let drag = null;
let orbit = null;
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 getPlanePoint(event) {
updatePointer(event);
return raycaster.ray.intersectPlane(dragPlane, planePoint)
? planePoint.clone()
: null;
}
renderer.domElement.addEventListener("pointerdown", event => {
if (event.button !== 0) return;
updatePointer(event);
const hits = raycaster.intersectObjects(hitMeshes, false);
if (hits.length) {
const pieceId = hits[0].object.userData.pieceId;
const piece = pieces.find(item => item.id === pieceId);
if (!piece) return;
selectedId = piece.id;
selectedPill.textContent = piece.name;
updateValidation();
dragPlane.set(
new THREE.Vector3(0, 1, 0),
-hits[0].point.y
);
const point = getPlanePoint(event);
if (!point) return;
const average = averageLocalOffset(piece);
const visualCenter = {
x: piece.group.position.x + average.x,
z: piece.group.position.z + average.z
};
drag = {
piece,
pointerId: event.pointerId,
startX: event.clientX,
startY: event.clientY,
moved: false,
offsetX: point.x - visualCenter.x,
offsetZ: point.z - visualCenter.z
};
renderer.domElement.setPointerCapture(event.pointerId);
renderer.domElement.style.cursor = "grabbing";
event.preventDefault();
} else {
orbit = {
pointerId: event.pointerId,
lastX: event.clientX,
lastY: event.clientY
};
renderer.domElement.setPointerCapture(event.pointerId);
renderer.domElement.style.cursor = "grabbing";
}
});
renderer.domElement.addEventListener("pointermove", event => {
if (drag && event.pointerId === drag.pointerId) {
const movement = Math.hypot(
event.clientX - drag.startX,
event.clientY - drag.startY
);
if (!drag.moved && movement < 4) return;
drag.moved = true;
const point = getPlanePoint(event);
if (!point) return;
const piece = drag.piece;
const average = averageLocalOffset(piece);
const desiredAnchorX =
point.x - drag.offsetX - average.x;
const desiredAnchorZ =
point.z - drag.offsetZ - average.z;
const col = THREE.MathUtils.clamp(
Math.round(desiredAnchorX + HALF_GRID),
-3,
GRID_SIZE + 3
);
const row = THREE.MathUtils.clamp(
Math.round(desiredAnchorZ + HALF_GRID),
-3,
GRID_SIZE + 3
);
cancelTween(piece);
piece.anchor = { col, row };
piece.group.position.set(
col - HALF_GRID,
TRAY_Y,
row - HALF_GRID
);
updateValidation();
return;
}
if (orbit && event.pointerId === orbit.pointerId) {
const dx = event.clientX - orbit.lastX;
const dy = event.clientY - orbit.lastY;
cameraState.yaw -= dx * 0.006;
cameraState.pitch = THREE.MathUtils.clamp(
cameraState.pitch + dy * 0.0045,
0.48,
1.18
);
orbit.lastX = event.clientX;
orbit.lastY = event.clientY;
updateCamera();
}
});
function finishPointer(event) {
if (drag && event.pointerId === drag.pointerId) {
if (drag.moved) {
const result = validate();
if (result.solved) {
showToast("Cargo secured. One cell remains empty.", "good");
} else if (result.collisionKeys.length) {
showToast("Cell collision detected.", "bad");
} else if (result.outsideCells.length) {
showToast("Some cargo is outside the tray.", "bad");
} else {
showToast(`${drag.piece.name} stowed without a collision.`, "good");
}
}
drag = null;
}
if (orbit && event.pointerId === orbit.pointerId) orbit = null;
if (renderer.domElement.hasPointerCapture(event.pointerId)) {
renderer.domElement.releasePointerCapture(event.pointerId);
}
renderer.domElement.style.cursor = "default";
}
renderer.domElement.addEventListener("pointerup", finishPointer);
renderer.domElement.addEventListener("pointercancel", finishPointer);
renderer.domElement.addEventListener("wheel", event => {
event.preventDefault();
cameraState.zoom = THREE.MathUtils.clamp(
cameraState.zoom * Math.exp(-event.deltaY * 0.001),
0.68,
1.65
);
updateCamera();
}, { passive: false });
renderer.domElement.addEventListener("dblclick", resetCamera);
renderer.domElement.addEventListener("contextmenu", event => event.preventDefault());
window.addEventListener("keydown", event => {
if (event.key.toLowerCase() === "r") {
event.preventDefault();
rotateSelected();
}
});
// ----- Panel actions -----------------------------------------------------
document.getElementById("rotateBtn").addEventListener("click", rotateSelected);
document.getElementById("resetBtn").addEventListener("click", () => {
const piece = pieces.find(item => item.id === selectedId);
if (!piece) return;
piece.anchor = null;
piece.cells = piece.originalCells.map(cell => [...cell]);
rebuildPiece(piece);
tweenPiece(piece, {
x: piece.home.x,
y: DOCK_Y,
z: piece.home.z
});
updateValidation();
showToast(`${piece.name} returned to its dock.`, "good");
});
document.getElementById("clearBtn").addEventListener("click", () => {
for (const piece of pieces) {
piece.anchor = null;
piece.cells = piece.originalCells.map(cell => [...cell]);
rebuildPiece(piece);
tweenPiece(piece, {
x: piece.home.x,
y: DOCK_Y,
z: piece.home.z
});
}
updateValidation();
showToast("Tray cleared.", "good");
});
document.getElementById("demoBtn").addEventListener("click", () => {
for (const piece of pieces) {
piece.cells = piece.originalCells.map(cell => [...cell]);
piece.anchor = { ...piece.solution };
rebuildPiece(piece);
tweenPiece(piece, {
x: piece.anchor.col - HALF_GRID,
y: TRAY_Y,
z: piece.anchor.row - HALF_GRID
}, 650);
}
updateValidation();
showToast("Demo manifest loaded and secured.", "good");
});
let toastTimer;
function showToast(message, type = "") {
clearTimeout(toastTimer);
toast.textContent = message;
toast.className = `show ${type}`;
toastTimer = setTimeout(() => {
toast.className = "";
}, 2200);
}
// ----- Resize and render loop --------------------------------------------
function resize() {
const width = Math.max(1, sceneHost.clientWidth);
const height = Math.max(1, sceneHost.clientHeight);
const aspect = width / height;
renderer.setSize(width, height, false);
const halfHeight = Math.max(6.2, 8.7 / aspect);
camera.left = -halfHeight * aspect;
camera.right = halfHeight * aspect;
camera.top = halfHeight;
camera.bottom = -halfHeight;
camera.updateProjectionMatrix();
}
new ResizeObserver(resize).observe(sceneHost);
resize();
resetCamera();
updateValidation();
renderer.setAnimationLoop(now => {
updateTweens(now);
// Selected cargo receives a restrained emissive lift.
for (const piece of pieces) {
const selected = piece.id === selectedId;
piece.bodyMaterial.emissiveIntensity = selected ? 0.13 : 0.025;
piece.topMaterial.emissiveIntensity = selected ? 0.09 : 0.02;
}
renderer.render(scene, camera);
});
</script>
</body>
</html>
```