Prompt specification
Build or customize the Three.js 3D scene "Rectangle packing 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: Rectangle packing tray
Category: Algorithms & Systems · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/rectangle-packing-tray-x1709
Scene Description Prompt:
Make a standalone HTML scene with Three.js from cdnjs that depicts geometric packing within a bounded container. Build a bounded tray with a few differently sized rectangular blocks and visible unused space; allow only nonoverlapping placements and preserve each block's dimensions. Low-poly.
Working Three.js Starter (rectangle-packing-tray-x1709):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Bounded Geometric Packing</title>
<style>
:root {
color-scheme: dark;
--panel: rgba(13, 22, 35, 0.86);
--border: rgba(164, 204, 229, 0.18);
--text: #eaf6ff;
--muted: #9eb4c7;
--accent: #68e6b2;
--danger: #ff7185;
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: #0b1220;
font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
#scene {
position: fixed;
inset: 0;
}
canvas {
display: block;
width: 100%;
height: 100%;
touch-action: none;
}
.ui {
position: fixed;
inset: 0;
pointer-events: none;
}
.panel {
position: absolute;
background: var(--panel);
border: 1px solid var(--border);
border-radius: 14px;
box-shadow: 0 16px 45px rgba(0, 0, 0, 0.28);
backdrop-filter: blur(12px);
}
.intro {
top: 22px;
left: 22px;
width: min(350px, calc(100vw - 44px));
padding: 18px 20px;
}
.eyebrow {
margin: 0 0 7px;
color: var(--accent);
font-size: 11px;
font-weight: 800;
letter-spacing: 0.18em;
text-transform: uppercase;
}
h1 {
margin: 0;
color: var(--text);
font-size: clamp(23px, 3vw, 31px);
line-height: 1.05;
letter-spacing: -0.04em;
}
.intro p {
margin: 10px 0 14px;
color: var(--muted);
font-size: 13px;
line-height: 1.5;
}
.metrics {
display: flex;
flex-wrap: wrap;
gap: 7px;
}
.metric {
padding: 6px 9px;
border: 1px solid var(--border);
border-radius: 999px;
color: #cce2f2;
font-size: 11px;
white-space: nowrap;
}
.controls {
top: 22px;
right: 22px;
width: 245px;
padding: 13px;
pointer-events: auto;
}
.button-row {
display: flex;
gap: 8px;
}
button {
flex: 1;
min-height: 38px;
padding: 9px 10px;
border: 1px solid rgba(139, 208, 231, 0.22);
border-radius: 9px;
background: rgba(103, 230, 178, 0.12);
color: var(--text);
font: inherit;
font-size: 12px;
font-weight: 750;
cursor: pointer;
transition:
background 150ms ease,
transform 150ms ease,
border-color 150ms ease;
}
button:hover {
background: rgba(103, 230, 178, 0.22);
border-color: rgba(103, 230, 178, 0.55);
transform: translateY(-1px);
}
button:active {
transform: translateY(0);
}
#status {
min-height: 34px;
margin-top: 10px;
padding: 8px 9px;
border-radius: 8px;
background: rgba(255, 255, 255, 0.045);
color: var(--muted);
font-size: 11px;
line-height: 1.4;
}
#status[data-tone="good"] {
color: #8ef1c6;
background: rgba(104, 230, 178, 0.1);
}
#status[data-tone="bad"] {
color: #ff9aaa;
background: rgba(255, 113, 133, 0.1);
}
.inventory {
top: 178px;
right: 22px;
width: 245px;
padding: 14px;
}
.inventory-title {
margin: 0 0 10px;
color: var(--muted);
font-size: 10px;
font-weight: 800;
letter-spacing: 0.15em;
text-transform: uppercase;
}
.item {
display: grid;
grid-template-columns: 10px 1fr auto;
align-items: center;
gap: 8px;
padding: 6px 0;
border-top: 1px solid rgba(255, 255, 255, 0.055);
color: #d9e9f4;
font-size: 11px;
}
.item:first-of-type {
border-top: 0;
}
.swatch {
width: 8px;
height: 8px;
border-radius: 2px;
box-shadow: 0 0 10px currentColor;
}
.dimensions {
color: var(--muted);
font-variant-numeric: tabular-nums;
font-size: 10px;
}
.hint {
left: 22px;
bottom: 22px;
padding: 10px 13px;
color: var(--muted);
font-size: 11px;
line-height: 1.55;
}
.hint strong {
color: var(--text);
font-weight: 700;
}
#toast {
position: fixed;
left: 50%;
bottom: 24px;
max-width: calc(100vw - 36px);
padding: 11px 16px;
border: 1px solid rgba(104, 230, 178, 0.3);
border-radius: 999px;
background: rgba(13, 22, 35, 0.94);
color: #bff8df;
box-shadow: 0 12px 35px rgba(0, 0, 0, 0.35);
font-size: 12px;
font-weight: 700;
opacity: 0;
pointer-events: none;
transform: translate(-50%, 12px);
transition:
opacity 180ms ease,
transform 180ms ease;
}
#toast.visible {
opacity: 1;
transform: translate(-50%, 0);
}
#toast.bad {
border-color: rgba(255, 113, 133, 0.4);
color: #ffafbb;
}
@media (max-width: 760px) {
.inventory {
display: none;
}
.controls {
top: auto;
right: 14px;
bottom: 14px;
width: 220px;
}
.intro {
top: 14px;
left: 14px;
width: min(320px, calc(100vw - 28px));
}
.hint {
display: none;
}
#toast {
bottom: 122px;
}
}
</style>
</head>
<body>
<div id="scene"></div>
<div class="ui">
<section class="panel intro">
<p class="eyebrow">Bounded packing study</p>
<h1>Geometric Tray</h1>
<p>
Drag the blocks to rearrange the packing. Every block keeps its exact
dimensions, and overlapping placements are automatically rejected.
</p>
<div class="metrics">
<span class="metric">12 × 8 unit tray</span>
<span class="metric" id="occupancy">32% occupied</span>
</div>
</section>
<section class="panel controls">
<div class="button-row">
<button id="resetButton" type="button">Reset</button>
<button id="scatterButton" type="button">Scatter</button>
</div>
<div id="status" data-tone="neutral">
Six fixed-size blocks are ready to rearrange.
</div>
</section>
<section class="panel inventory">
<p class="inventory-title">Blocks · width × height × depth</p>
<div id="inventoryList"></div>
</section>
<section class="panel hint">
<strong>Drag a block</strong> to place it ·
<strong>Drag the background</strong> to orbit ·
<strong>Scroll</strong> to zoom
</section>
</div>
<div id="toast" role="status" aria-live="polite"></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 statusElement = document.getElementById("status");
const occupancyElement = document.getElementById("occupancy");
const inventoryElement = document.getElementById("inventoryList");
const toastElement = document.getElementById("toast");
const TRAY = {
width: 12,
depth: 8,
wallThickness: 0.3,
wallHeight: 1.1
};
const FLOOR_TOP = 0.08;
const INNER_WIDTH = TRAY.width - TRAY.wallThickness * 2;
const INNER_DEPTH = TRAY.depth - TRAY.wallThickness * 2;
const OVERLAP_EPSILON = 0.008;
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x0b1220);
scene.fog = new THREE.Fog(0x0b1220, 30, 58);
const camera = new THREE.PerspectiveCamera(
42,
innerWidth / innerHeight,
0.1,
100
);
const renderer = new THREE.WebGLRenderer({
antialias: true,
powerPreference: "high-performance"
});
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(innerWidth, innerHeight);
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.05;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
sceneHost.appendChild(renderer.domElement);
const hemisphere = new THREE.HemisphereLight(0xd9efff, 0x263448, 2.15);
scene.add(hemisphere);
const keyLight = new THREE.DirectionalLight(0xfff3dc, 3.1);
keyLight.position.set(8, 14, 9);
keyLight.castShadow = true;
keyLight.shadow.mapSize.set(2048, 2048);
keyLight.shadow.camera.left = -15;
keyLight.shadow.camera.right = 15;
keyLight.shadow.camera.top = 15;
keyLight.shadow.camera.bottom = -15;
keyLight.shadow.camera.near = 1;
keyLight.shadow.camera.far = 40;
keyLight.shadow.bias = -0.00035;
scene.add(keyLight);
const fillLight = new THREE.DirectionalLight(0x6fa9ff, 1.1);
fillLight.position.set(-9, 7, -6);
scene.add(fillLight);
const blocks = [];
const pickableObjects = [];
const wallMeshes = [];
function makeMaterial(color, options = {}) {
return new THREE.MeshStandardMaterial({
color,
roughness: 0.72,
metalness: 0.04,
flatShading: true,
...options
});
}
// Ground beneath the tray.
const ground = new THREE.Mesh(
new THREE.PlaneGeometry(80, 80),
makeMaterial(0x101a29, { roughness: 0.95 })
);
ground.rotation.x = -Math.PI / 2;
ground.position.y = -0.31;
ground.receiveShadow = true;
scene.add(ground);
// Dark structural tray base.
const base = new THREE.Mesh(
new THREE.BoxGeometry(
TRAY.width + 0.35,
0.3,
TRAY.depth + 0.35
),
makeMaterial(0x172537, { roughness: 0.85 })
);
base.position.y = -0.15;
base.castShadow = true;
base.receiveShadow = true;
scene.add(base);
// Slightly lighter interior floor.
const floor = new THREE.Mesh(
new THREE.BoxGeometry(INNER_WIDTH, FLOOR_TOP, INNER_DEPTH),
makeMaterial(0x24404b, { roughness: 0.9 })
);
floor.position.y = FLOOR_TOP * 0.5;
floor.receiveShadow = true;
scene.add(floor);
// Grid makes the unused floor area easy to read.
const gridPositions = [];
for (let x = -INNER_WIDTH / 2; x <= INNER_WIDTH / 2 + 0.001; x += 1) {
gridPositions.push(
x, FLOOR_TOP + 0.006, -INNER_DEPTH / 2,
x, FLOOR_TOP + 0.006, INNER_DEPTH / 2
);
}
for (let z = -INNER_DEPTH / 2; z <= INNER_DEPTH / 2 + 0.001; z += 1) {
gridPositions.push(
-INNER_WIDTH / 2, FLOOR_TOP + 0.006, z,
INNER_WIDTH / 2, FLOOR_TOP + 0.006, z
);
}
const gridGeometry = new THREE.BufferGeometry();
gridGeometry.setAttribute(
"position",
new THREE.Float32BufferAttribute(gridPositions, 3)
);
const grid = new THREE.LineSegments(
gridGeometry,
new THREE.LineBasicMaterial({
color: 0x89b7c7,
transparent: true,
opacity: 0.19
})
);
scene.add(grid);
function addWall(width, height, depth, x, z) {
const wall = new THREE.Mesh(
new THREE.BoxGeometry(width, height, depth),
makeMaterial(0x30475d, { roughness: 0.78 })
);
wall.position.set(x, FLOOR_TOP + height / 2, z);
wall.castShadow = true;
wall.receiveShadow = true;
scene.add(wall);
wallMeshes.push(wall);
pickableObjects.push(wall);
const edges = new THREE.LineSegments(
new THREE.EdgesGeometry(wall.geometry),
new THREE.LineBasicMaterial({
color: 0x8cb2c8,
transparent: true,
opacity: 0.24
})
);
edges.position.copy(wall.position);
scene.add(edges);
}
// Four walls form the hard packing boundary.
addWall(
TRAY.wallThickness,
TRAY.wallHeight,
TRAY.depth,
-TRAY.width / 2 + TRAY.wallThickness / 2,
0
);
addWall(
TRAY.wallThickness,
TRAY.wallHeight,
TRAY.depth,
TRAY.width / 2 - TRAY.wallThickness / 2,
0
);
addWall(
TRAY.width,
TRAY.wallHeight,
TRAY.wallThickness,
0,
-TRAY.depth / 2 + TRAY.wallThickness / 2
);
addWall(
TRAY.width,
TRAY.wallHeight,
TRAY.wallThickness,
0,
TRAY.depth / 2 - TRAY.wallThickness / 2
);
const blockDefinitions = [
{
name: "Slab",
w: 3.2,
h: 1.5,
d: 2.1,
color: 0xf0a35b,
position: [-3.45, -1.75]
},
{
name: "Beam",
w: 2.4,
h: 1.0,
d: 3.0,
color: 0x5ca9e8,
position: [0.35, -2.1]
},
{
name: "Cube",
w: 1.5,
h: 2.0,
d: 1.5,
color: 0xa58bea,
position: [3.55, -2.25]
},
{
name: "Plank",
w: 2.8,
h: 0.8,
d: 1.3,
color: 0x68c99b,
position: [-3.8, 1.45]
},
{
name: "Tile",
w: 2.0,
h: 0.65,
d: 2.0,
color: 0xe8ca62,
position: [-0.85, 1.45]
},
{
name: "Pillar",
w: 1.2,
h: 1.2,
d: 2.6,
color: 0xe57c9c,
position: [3.55, 1.15]
}
];
function createBlock(definition) {
const group = new THREE.Group();
group.position.set(
definition.position[0],
FLOOR_TOP,
definition.position[1]
);
const geometry = new THREE.BoxGeometry(
definition.w,
definition.h,
definition.d
);
const material = makeMaterial(definition.color);
const body = new THREE.Mesh(geometry, material);
body.position.y = definition.h / 2;
body.castShadow = true;
body.receiveShadow = true;
body.userData.block = group;
const edgeMaterial = new THREE.LineBasicMaterial({
color: 0xd4f1ff,
transparent: true,
opacity: 0.5
});
const edges = new THREE.LineSegments(
new THREE.EdgesGeometry(geometry),
edgeMaterial
);
edges.position.y = definition.h / 2;
group.add(body, edges);
group.userData = {
name: definition.name,
size: new THREE.Vector3(
definition.w,
definition.h,
definition.d
),
color: definition.color,
body,
material,
edgeMaterial,
initialX: definition.position[0],
initialZ: definition.position[1]
};
blocks.push(group);
pickableObjects.push(body);
scene.add(group);
}
blockDefinitions.forEach(createBlock);
// Inventory panel.
inventoryElement.innerHTML = blocks.map((block) => {
const data = block.userData;
const color = `#${new THREE.Color(data.color).getHexString()}`;
return `
<div class="item">
<span
class="swatch"
style="background:${color};color:${color}"
></span>
<span>${data.name}</span>
<span class="dimensions">
${data.size.x.toFixed(1)} × ${data.size.y.toFixed(1)} × ${data.size.z.toFixed(1)}
</span>
</div>
`;
}).join("");
function updateOccupancy() {
const usedArea = blocks.reduce(
(sum, block) =>
sum + block.userData.size.x * block.userData.size.z,
0
);
const totalArea = INNER_WIDTH * INNER_DEPTH;
const occupiedPercent = Math.round((usedArea / totalArea) * 100);
occupancyElement.textContent =
`${occupiedPercent}% occupied · ${100 - occupiedPercent}% open`;
}
updateOccupancy();
// Custom orbit controls, implemented without Three.js addons.
const cameraTarget = new THREE.Vector3(0, 0.65, 0);
let cameraTheta = 0.78;
let cameraPhi = 0.78;
let cameraRadius = 19;
function updateCamera() {
const sinPhi = Math.sin(cameraPhi);
camera.position.set(
cameraTarget.x +
cameraRadius * sinPhi * Math.sin(cameraTheta),
cameraTarget.y +
cameraRadius * Math.cos(cameraPhi),
cameraTarget.z +
cameraRadius * sinPhi * Math.cos(cameraTheta)
);
camera.lookAt(cameraTarget);
camera.updateMatrixWorld();
}
updateCamera();
const raycaster = new THREE.Raycaster();
const pointer = new THREE.Vector2();
const dragPlane = new THREE.Plane(
new THREE.Vector3(0, 1, 0),
-FLOOR_TOP
);
const planeIntersection = new THREE.Vector3();
let interactionMode = null;
let activePointerId = null;
let orbitLastX = 0;
let orbitLastY = 0;
let dragState = null;
let toastTimer = null;
function setPointerFromEvent(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 setStatus(message, tone = "neutral") {
statusElement.textContent = message;
statusElement.dataset.tone = tone;
}
function showToast(message, bad = false) {
clearTimeout(toastTimer);
toastElement.textContent = message;
toastElement.classList.toggle("bad", bad);
toastElement.classList.add("visible");
toastTimer = setTimeout(() => {
toastElement.classList.remove("visible");
}, 1900);
}
function boundsForSize(size) {
return {
minX: -INNER_WIDTH / 2 + size.x / 2,
maxX: INNER_WIDTH / 2 - size.x / 2,
minZ: -INNER_DEPTH / 2 + size.z / 2,
maxZ: INNER_DEPTH / 2 - size.z / 2
};
}
function rectanglesOverlap(a, b) {
const overlapX =
Math.abs(a.x - b.x) <
(a.size.x + b.size.x) / 2 - OVERLAP_EPSILON;
const overlapZ =
Math.abs(a.z - b.z) <
(a.size.z + b.size.z) / 2 - OVERLAP_EPSILON;
return overlapX && overlapZ;
}
function isValidPosition(block, x, z) {
const size = block.userData.size;
const bounds = boundsForSize(size);
if (
x < bounds.minX ||
x > bounds.maxX ||
z < bounds.minZ ||
z > bounds.maxZ
) {
return false;
}
for (const other of blocks) {
if (other === block) continue;
if (
rectanglesOverlap(
{ x, z, size },
{
x: other.position.x,
z: other.position.z,
size: other.userData.size
}
)
) {
return false;
}
}
return true;
}
function setBlockPreview(block, valid) {
const data = block.userData;
if (valid) {
data.material.color.setHex(0x53e5a9);
data.material.emissive.setHex(0x073b28);
data.edgeMaterial.color.setHex(0xd8fff1);
data.edgeMaterial.opacity = 1;
} else {
data.material.color.setHex(0xff5d76);
data.material.emissive.setHex(0x460b18);
data.edgeMaterial.color.setHex(0xffc2cc);
data.edgeMaterial.opacity = 1;
}
}
function restoreBlockAppearance(block) {
const data = block.userData;
data.material.color.setHex(data.color);
data.material.emissive.setHex(0x000000);
data.edgeMaterial.color.setHex(0xd4f1ff);
data.edgeMaterial.opacity = 0.5;
}
renderer.domElement.addEventListener("pointerdown", (event) => {
if (event.pointerType === "mouse" && event.button !== 0) return;
setPointerFromEvent(event);
activePointerId = event.pointerId;
const intersections = raycaster.intersectObjects(
pickableObjects,
false
);
const firstHit = intersections[0];
const block = firstHit?.object.userData.block;
if (block) {
if (!raycaster.ray.intersectPlane(dragPlane, planeIntersection)) {
return;
}
dragState = {
block,
offsetX: block.position.x - planeIntersection.x,
offsetZ: block.position.z - planeIntersection.z,
originalX: block.position.x,
originalZ: block.position.z,
valid: true
};
interactionMode = "drag";
setStatus(
`Moving ${block.userData.name}. Release over open space.`,
"neutral"
);
} else {
interactionMode = "orbit";
orbitLastX = event.clientX;
orbitLastY = event.clientY;
}
renderer.domElement.setPointerCapture(event.pointerId);
});
renderer.domElement.addEventListener("pointermove", (event) => {
if (activePointerId !== event.pointerId) return;
if (interactionMode === "drag" && dragState) {
setPointerFromEvent(event);
if (!raycaster.ray.intersectPlane(dragPlane, planeIntersection)) {
return;
}
const block = dragState.block;
const size = block.userData.size;
const bounds = boundsForSize(size);
const x = THREE.MathUtils.clamp(
planeIntersection.x + dragState.offsetX,
bounds.minX,
bounds.maxX
);
const z = THREE.MathUtils.clamp(
planeIntersection.z + dragState.offsetZ,
bounds.minZ,
bounds.maxZ
);
const valid = isValidPosition(block, x, z);
block.position.x = x;
block.position.z = z;
dragState.valid = valid;
setBlockPreview(block, valid);
if (valid) {
setStatus(
`Valid position for ${block.userData.name}. Release to place.`,
"good"
);
} else {
setStatus(
`Collision detected for ${block.userData.name}. Release to cancel.`,
"bad"
);
}
} else if (interactionMode === "orbit") {
const deltaX = event.clientX - orbitLastX;
const deltaY = event.clientY - orbitLastY;
orbitLastX = event.clientX;
orbitLastY = event.clientY;
cameraTheta -= deltaX * 0.006;
cameraPhi = THREE.MathUtils.clamp(
cameraPhi + deltaY * 0.006,
0.32,
1.36
);
updateCamera();
}
});
function finishPointerInteraction(event, cancelled = false) {
if (activePointerId !== event.pointerId) return;
if (dragState) {
const block = dragState.block;
if (cancelled || !dragState.valid) {
block.position.x = dragState.originalX;
block.position.z = dragState.originalZ;
restoreBlockAppearance(block);
setStatus(
`Placement rejected: ${block.userData.name} overlaps another block or the boundary.`,
"bad"
);
showToast("Placement rejected — no overlap allowed.", true);
} else {
restoreBlockAppearance(block);
setStatus(
`${block.userData.name} placed. Unused tray space is preserved.`,
"good"
);
showToast(`${block.userData.name} placed successfully.`);
}
dragState = null;
}
if (renderer.domElement.hasPointerCapture(event.pointerId)) {
renderer.domElement.releasePointerCapture(event.pointerId);
}
interactionMode = null;
activePointerId = null;
}
renderer.domElement.addEventListener("pointerup", (event) => {
finishPointerInteraction(event, false);
});
renderer.domElement.addEventListener("pointercancel", (event) => {
finishPointerInteraction(event, true);
});
renderer.domElement.addEventListener(
"wheel",
(event) => {
event.preventDefault();
cameraRadius = THREE.MathUtils.clamp(
cameraRadius + event.deltaY * 0.012,
12,
30
);
updateCamera();
},
{ passive: false }
);
function resetLayout() {
for (const block of blocks) {
const data = block.userData;
block.position.x = data.initialX;
block.position.z = data.initialZ;
restoreBlockAppearance(block);
}
setStatus("Original collision-free arrangement restored.", "good");
showToast("Layout reset.");
}
function scatterLayout() {
// Place larger blocks first, checking each candidate against
// all already-placed rectangles.
const orderedBlocks = [...blocks].sort(
(a, b) =>
b.userData.size.x * b.userData.size.z -
a.userData.size.x * a.userData.size.z
);
const placed = [];
const newPositions = new Map();
for (const block of orderedBlocks) {
const size = block.userData.size;
const bounds = boundsForSize(size);
let chosen = null;
for (let attempt = 0; attempt < 5000; attempt++) {
const x =
bounds.minX +
Math.random() * (bounds.maxX - bounds.minX);
const z =
bounds.minZ +
Math.random() * (bounds.maxZ - bounds.minZ);
const candidate = { x, z, size };
const collides = placed.some((other) =>
rectanglesOverlap(candidate, other)
);
if (!collides) {
chosen = candidate;
break;
}
}
// Deterministic fallback if random attempts fail.
if (!chosen) {
for (
let x = bounds.minX;
x <= bounds.maxX && !chosen;
x += 0.2
) {
for (
let z = bounds.minZ;
z <= bounds.maxZ;
z += 0.2
) {
const candidate = { x, z, size };
const collides = placed.some((other) =>
rectanglesOverlap(candidate, other)
);
if (!collides) {
chosen = candidate;
break;
}
}
}
}
if (!chosen) {
setStatus("Unable to find a collision-free scatter.", "bad");
showToast("Scatter failed; keeping the current layout.", true);
return;
}
placed.push(chosen);
newPositions.set(block, chosen);
}
for (const [block, position] of newPositions) {
block.position.x = position.x;
block.position.z = position.z;
restoreBlockAppearance(block);
}
setStatus(
"Scattered into a new collision-free arrangement. Unused space remains visible.",
"good"
);
showToast("Collision-free layout generated.");
}
document
.getElementById("resetButton")
.addEventListener("click", resetLayout);
document
.getElementById("scatterButton")
.addEventListener("click", scatterLayout);
window.addEventListener("keydown", (event) => {
if (event.key.toLowerCase() === "r") {
resetLayout();
} else if (event.key.toLowerCase() === "s") {
scatterLayout();
} else if (event.key === "Escape" && dragState) {
const pointerEvent = new PointerEvent("pointercancel", {
pointerId: activePointerId
});
finishPointerInteraction(pointerEvent, true);
}
});
window.addEventListener("resize", () => {
camera.aspect = innerWidth / innerHeight;
camera.updateProjectionMatrix();
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(innerWidth, innerHeight);
});
renderer.setAnimationLoop(() => {
renderer.render(scene, camera);
});
</script>
</body>
</html>
```