Prompt specification
Build or customize the Three.js 3D scene "Triangle and rectangle dissection 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: Triangle and rectangle dissection tray
Category: Algorithms & Systems · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/triangle-and-rectangle-dissection-tray-x1681
Scene Description Prompt:
Create a single self-contained HTML file using Three.js from cdnjs that shows area-preserving geometric dissections. Build a triangle cut into a few movable pieces beside a target rectangle-like arrangement; preserve exact piece dimensions and verify no overlap in the final assembly. Low-poly.
Working Three.js Starter (triangle-and-rectangle-dissection-tray-x1681):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Area-Locked Geometric Dissection</title>
<style>
:root {
color-scheme: dark;
--bg: #09111e;
--panel: rgba(13, 24, 41, 0.88);
--border: rgba(148, 177, 214, 0.2);
--text: #eef5ff;
--muted: #9eb0c8;
--cyan: #58e0d0;
--orange: #ffb45b;
--violet: #8994ff;
--green: #72f0ad;
--red: #ff7d8d;
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: var(--bg);
color: var(--text);
font-family:
Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
#viewport,
#viewport canvas {
position: absolute;
inset: 0;
width: 100%;
height: 100%;
display: block;
touch-action: none;
}
.hud {
position: absolute;
inset: 0;
pointer-events: none;
}
.panel {
position: absolute;
pointer-events: auto;
border: 1px solid var(--border);
border-radius: 16px;
background: var(--panel);
box-shadow: 0 18px 50px rgba(0, 0, 0, 0.28);
backdrop-filter: blur(16px);
-webkit-backdrop-filter: blur(16px);
}
.intro {
top: 18px;
left: 18px;
width: min(380px, calc(100vw - 36px));
padding: 18px 20px;
}
.eyebrow {
margin-bottom: 7px;
color: var(--cyan);
font-size: 11px;
font-weight: 800;
letter-spacing: 0.18em;
text-transform: uppercase;
}
h1 {
margin: 0;
font-size: clamp(21px, 2.4vw, 31px);
line-height: 1.05;
letter-spacing: -0.035em;
}
.intro p {
margin: 12px 0 0;
color: var(--muted);
font-size: 13px;
line-height: 1.55;
}
.equation {
display: flex;
align-items: center;
gap: 8px;
margin-top: 14px;
padding: 10px 12px;
border: 1px solid rgba(88, 224, 208, 0.18);
border-radius: 10px;
background: rgba(88, 224, 208, 0.06);
color: #dffcf8;
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 12px;
}
.key {
display: inline-block;
padding: 2px 6px;
border: 1px solid rgba(255, 255, 255, 0.2);
border-bottom-width: 2px;
border-radius: 5px;
background: rgba(255, 255, 255, 0.07);
color: #fff;
font-size: 10px;
line-height: 1.4;
}
.verification {
top: 18px;
right: 18px;
width: min(315px, calc(100vw - 36px));
padding: 16px;
}
.verification h2 {
margin: 0 0 12px;
font-size: 12px;
letter-spacing: 0.12em;
text-transform: uppercase;
}
.verdict {
padding: 12px;
border: 1px solid rgba(158, 176, 200, 0.16);
border-radius: 11px;
background: rgba(255, 255, 255, 0.035);
}
.verdict.valid {
border-color: rgba(114, 240, 173, 0.34);
background: rgba(114, 240, 173, 0.08);
}
.verdict.invalid {
border-color: rgba(255, 125, 141, 0.28);
background: rgba(255, 125, 141, 0.055);
}
#verdictTitle {
color: var(--muted);
font-size: 12px;
font-weight: 800;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.valid #verdictTitle {
color: var(--green);
}
.invalid #verdictTitle {
color: #ffc2ca;
}
#verdictDetail {
margin-top: 5px;
color: var(--muted);
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 11px;
line-height: 1.45;
}
.checks {
display: grid;
gap: 7px;
margin-top: 12px;
}
.check {
display: flex;
justify-content: space-between;
gap: 12px;
padding-bottom: 7px;
border-bottom: 1px solid rgba(255, 255, 255, 0.055);
color: var(--muted);
font-size: 11px;
}
.check b {
color: #dbe7f7;
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-weight: 600;
text-align: right;
}
.check b.ok {
color: var(--green);
}
.check b.no {
color: #ff9ca8;
}
.controls {
left: 50%;
bottom: 18px;
width: min(760px, calc(100vw - 36px));
padding: 12px;
transform: translateX(-50%);
display: flex;
align-items: center;
justify-content: center;
flex-wrap: wrap;
gap: 8px;
}
button {
appearance: none;
border: 1px solid rgba(255, 255, 255, 0.13);
border-radius: 9px;
padding: 10px 13px;
background: rgba(255, 255, 255, 0.055);
color: var(--text);
font: inherit;
font-size: 12px;
font-weight: 700;
cursor: pointer;
transition:
transform 120ms ease,
background 120ms ease,
border-color 120ms ease;
}
button:hover {
transform: translateY(-1px);
border-color: rgba(255, 255, 255, 0.28);
background: rgba(255, 255, 255, 0.095);
}
button:active {
transform: translateY(0);
}
button:disabled {
opacity: 0.35;
cursor: default;
transform: none;
}
button.primary {
border-color: rgba(88, 224, 208, 0.35);
background: rgba(88, 224, 208, 0.14);
color: #dffffb;
}
button.rotate {
border-color: rgba(255, 180, 91, 0.3);
background: rgba(255, 180, 91, 0.1);
}
.divider {
width: 1px;
height: 28px;
margin: 0 2px;
background: var(--border);
}
.toggle {
display: flex;
align-items: center;
gap: 7px;
padding: 0 5px;
color: var(--muted);
font-size: 11px;
cursor: pointer;
user-select: none;
}
.toggle input {
accent-color: var(--cyan);
}
.selection {
position: absolute;
left: 18px;
bottom: 18px;
max-width: 250px;
padding: 12px 14px;
color: var(--muted);
font-size: 11px;
line-height: 1.5;
}
.selection strong {
display: block;
margin-bottom: 3px;
color: var(--text);
font-size: 12px;
}
.world-label {
position: absolute;
left: 0;
top: 0;
pointer-events: none;
padding: 4px 7px;
border: 1px solid rgba(255, 255, 255, 0.13);
border-radius: 6px;
background: rgba(8, 15, 27, 0.78);
color: #dce9f8;
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 10px;
white-space: nowrap;
transform: translate(-50%, -50%);
box-shadow: 0 4px 16px rgba(0, 0, 0, 0.25);
}
.world-label.title {
padding: 6px 9px;
border-color: rgba(88, 224, 208, 0.25);
color: var(--cyan);
font-family: inherit;
font-size: 10px;
font-weight: 800;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.world-label.dimension {
color: #b9c9dd;
}
@media (max-width: 800px) {
.intro {
width: calc(100vw - 36px);
padding: 13px 15px;
}
.intro p,
.equation {
display: none;
}
.verification {
top: 102px;
left: 18px;
right: auto;
width: 250px;
padding: 12px;
}
.checks {
display: none;
}
.selection {
display: none;
}
.controls {
gap: 6px;
padding: 9px;
}
button {
padding: 9px 10px;
font-size: 11px;
}
.divider {
display: none;
}
}
</style>
</head>
<body>
<div id="viewport"></div>
<div class="hud">
<section class="panel intro">
<div class="eyebrow">Area-locked dissection lab</div>
<h1>One triangle.<br>Three rigid pieces.</h1>
<p>
Drag pieces onto the target. Use <span class="key">R</span> or the
rotate button to turn the selected piece. Right-drag empty space to
orbit; scroll to zoom.
</p>
<div class="equation">
½ × 6 × 6 = 18 = 6 × 3
</div>
</section>
<section class="panel verification">
<h2>Assembly verification</h2>
<div id="verdict" class="verdict">
<div id="verdictTitle">Ready to assemble</div>
<div id="verdictDetail">0 / 3 pieces at target</div>
</div>
<div class="checks">
<div class="check">
<span>Piece areas</span>
<b id="areaCheck">18.000000 / 18</b>
</div>
<div class="check">
<span>Maximum overlap</span>
<b id="overlapCheck">0.000000 u²</b>
</div>
<div class="check">
<span>Target boundary</span>
<b id="boundaryCheck">Not assembled</b>
</div>
<div class="check">
<span>Piece placement</span>
<b id="positionCheck">0 / 3 exact</b>
</div>
</div>
</section>
<section class="panel selection" id="selectionInfo">
<strong>No piece selected</strong>
Click a colored piece to select it.
</section>
<section class="panel controls">
<button id="solveButton" class="primary">Show solution</button>
<button id="resetButton">Reset triangle</button>
<span class="divider"></span>
<button id="rotateButton" class="rotate" disabled>
Rotate selected 90°
</button>
<button id="verifyButton">Verify fit</button>
<label class="toggle">
<input id="guidesToggle" type="checkbox" checked>
Target guides
</label>
</section>
</div>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
// -------------------------------------------------------------------------
// Constants and scene
// -------------------------------------------------------------------------
const SOURCE_OFFSET = { x: -9, z: -3 };
const TARGET_OFFSET = { x: 0, z: -1.5 };
const PIECE_HEIGHT = 0.42;
const PIECE_Y = 0.15;
const EPSILON = 1e-7;
const viewport = document.getElementById("viewport");
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x09111e);
scene.fog = new THREE.Fog(0x09111e, 26, 52);
const camera = new THREE.OrthographicCamera(-10, 10, 8, -8, 0.1, 100);
const renderer = new THREE.WebGLRenderer({
antialias: true,
alpha: false
});
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.12;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
viewport.appendChild(renderer.domElement);
scene.add(new THREE.HemisphereLight(0xb8d8ff, 0x243044, 1.65));
const keyLight = new THREE.DirectionalLight(0xffffff, 2.5);
keyLight.position.set(-7, 15, 10);
keyLight.castShadow = true;
keyLight.shadow.mapSize.set(2048, 2048);
keyLight.shadow.camera.left = -15;
keyLight.shadow.camera.right = 15;
keyLight.shadow.camera.top = 13;
keyLight.shadow.camera.bottom = -13;
keyLight.shadow.camera.near = 1;
keyLight.shadow.camera.far = 40;
keyLight.shadow.bias = -0.0005;
scene.add(keyLight);
const rimLight = new THREE.DirectionalLight(0x5fe1d1, 1.1);
rimLight.position.set(9, 7, -9);
scene.add(rimLight);
const ground = new THREE.Mesh(
new THREE.PlaneGeometry(42, 30),
new THREE.MeshStandardMaterial({
color: 0x0b1423,
roughness: 0.94,
metalness: 0.02
})
);
ground.rotation.x = -Math.PI / 2;
ground.position.y = -0.035;
ground.receiveShadow = true;
scene.add(ground);
const grid = new THREE.GridHelper(36, 36, 0x29415e, 0x1b2c42);
grid.position.y = 0.005;
grid.material.transparent = true;
grid.material.opacity = 0.22;
scene.add(grid);
// -------------------------------------------------------------------------
// Geometry helpers
// -------------------------------------------------------------------------
function cross2(a, b) {
return a.x * b.z - a.z * b.x;
}
function subtract2(a, b) {
return { x: a.x - b.x, z: a.z - b.z };
}
function polygonArea(points) {
let sum = 0;
for (let i = 0; i < points.length; i++) {
const a = points[i];
const b = points[(i + 1) % points.length];
sum += a.x * b.z - a.z * b.x;
}
return Math.abs(sum * 0.5);
}
function polygonCentroid(points) {
const total = { x: 0, z: 0 };
for (const p of points) {
total.x += p.x;
total.z += p.z;
}
return {
x: total.x / points.length,
z: total.z / points.length
};
}
/**
* Creates a flat-shaded prism from a convex polygon in the XZ plane.
* Polygon vertices are expected to be counter-clockwise in X/Z.
*/
function createPrismGeometry(points, height) {
const count = points.length;
const positions = [];
for (const p of points) positions.push(p.x, 0, p.z);
for (const p of points) positions.push(p.x, height, p.z);
const center = polygonCentroid(points);
positions.push(center.x, 0, center.z);
positions.push(center.x, height, center.z);
const bottomCenter = count * 2;
const topCenter = count * 2 + 1;
const indices = [];
for (let i = 0; i < count; i++) {
const j = (i + 1) % count;
// Bottom and top faces.
indices.push(bottomCenter, i, j);
indices.push(topCenter, count + j, count + i);
// Side walls.
indices.push(i, count + i, count + j);
indices.push(i, count + j, j);
}
const indexed = new THREE.BufferGeometry();
indexed.setAttribute(
"position",
new THREE.Float32BufferAttribute(positions, 3)
);
indexed.setIndex(indices);
const geometry = indexed.toNonIndexed();
indexed.dispose();
geometry.computeVertexNormals();
return geometry;
}
function makeBoard(points, offset, color, height = 0.09) {
const group = new THREE.Group();
group.position.set(offset.x, 0, offset.z);
const geometry = createPrismGeometry(points, height);
const mesh = new THREE.Mesh(
geometry,
new THREE.MeshStandardMaterial({
color,
roughness: 0.82,
metalness: 0.08,
flatShading: true
})
);
mesh.receiveShadow = true;
group.add(mesh);
const edge = new THREE.LineSegments(
new THREE.EdgesGeometry(geometry, 18),
new THREE.LineBasicMaterial({
color: 0x607b9d,
transparent: true,
opacity: 0.75
})
);
group.add(edge);
scene.add(group);
return group;
}
function addLineSegments(points, color, opacity = 1) {
const geometry = new THREE.BufferGeometry().setFromPoints(
points.map((p) => new THREE.Vector3(p.x, p.y ?? 0.12, p.z))
);
const line = new THREE.LineSegments(
geometry,
new THREE.LineBasicMaterial({
color,
transparent: opacity < 1,
opacity
})
);
scene.add(line);
return line;
}
function addDimension(a, b, tick, color = 0x7690ad) {
const main = [
{ x: a.x, y: 0.12, z: a.z },
{ x: b.x, y: 0.12, z: b.z }
];
const ticks = [
{
x: a.x - tick.x,
y: 0.12,
z: a.z - tick.z
},
{
x: a.x + tick.x,
y: 0.12,
z: a.z + tick.z
},
{
x: b.x - tick.x,
y: 0.12,
z: b.z - tick.z
},
{
x: b.x + tick.x,
y: 0.12,
z: b.z + tick.z
}
];
addLineSegments([...main, ...ticks], color, 0.8);
}
// Source and target boards.
const sourceBoardPoints = [
{ x: 0, z: 0 },
{ x: 6, z: 0 },
{ x: 0, z: 6 }
];
const targetBoardPoints = [
{ x: 0, z: 0 },
{ x: 6, z: 0 },
{ x: 6, z: 3 },
{ x: 0, z: 3 }
];
makeBoard(sourceBoardPoints, SOURCE_OFFSET, 0x17243a, 0.085);
makeBoard(targetBoardPoints, TARGET_OFFSET, 0x102a32, 0.095);
// -------------------------------------------------------------------------
// The exact three-piece dissection
// -------------------------------------------------------------------------
const pieces = [
{
id: "square",
name: "Square piece",
description: "3 × 3 square · area 9",
color: 0xffb45b,
local: [
{ x: -1.5, z: -1.5 },
{ x: 1.5, z: -1.5 },
{ x: 1.5, z: 1.5 },
{ x: -1.5, z: 1.5 }
],
source: {
x: SOURCE_OFFSET.x + 1.5,
z: SOURCE_OFFSET.z + 1.5,
angle: 0
},
target: {
x: TARGET_OFFSET.x + 1.5,
z: TARGET_OFFSET.z + 1.5,
angle: 0
},
quarterTurnSymmetry: true
},
{
id: "lower-triangle",
name: "Lower triangle",
description: "Right triangle · legs 3 and 3 · area 4.5",
color: 0x3dd6c6,
local: [
{ x: -1, z: -1 },
{ x: 2, z: -1 },
{ x: -1, z: 2 }
],
source: {
x: SOURCE_OFFSET.x + 4,
z: SOURCE_OFFSET.z + 1,
angle: 0
},
target: {
x: TARGET_OFFSET.x + 4,
z: TARGET_OFFSET.z + 1,
angle: 0
},
quarterTurnSymmetry: false
},
{
id: "upper-triangle",
name: "Upper triangle",
description: "Right triangle · legs 3 and 3 · area 4.5",
color: 0x8994ff,
local: [
{ x: -1, z: -1 },
{ x: 2, z: -1 },
{ x: -1, z: 2 }
],
source: {
x: SOURCE_OFFSET.x + 1,
z: SOURCE_OFFSET.z + 4,
angle: 0
},
target: {
x: TARGET_OFFSET.x + 5,
z: TARGET_OFFSET.z + 2,
angle: Math.PI
},
quarterTurnSymmetry: false
}
];
for (const piece of pieces) {
piece.area = polygonArea(piece.local);
piece.group = new THREE.Group();
piece.group.position.set(
piece.source.x,
PIECE_Y,
piece.source.z
);
piece.group.rotation.y = piece.source.angle;
const geometry = createPrismGeometry(piece.local, PIECE_HEIGHT);
piece.mesh = new THREE.Mesh(
geometry,
new THREE.MeshStandardMaterial({
color: piece.color,
roughness: 0.63,
metalness: 0.06,
flatShading: true
})
);
piece.mesh.castShadow = true;
piece.mesh.receiveShadow = true;
piece.mesh.userData.piece = piece;
piece.group.add(piece.mesh);
piece.edge = new THREE.LineSegments(
new THREE.EdgesGeometry(geometry, 18),
new THREE.LineBasicMaterial({
color: 0x101827,
transparent: true,
opacity: 0.95
})
);
piece.group.add(piece.edge);
scene.add(piece.group);
}
// Target ghost guides use the exact final polygon coordinates.
const targetGhostPolygons = [
[
{ x: 0, z: 0 },
{ x: 3, z: 0 },
{ x: 3, z: 3 },
{ x: 0, z: 3 }
],
[
{ x: 3, z: 0 },
{ x: 6, z: 0 },
{ x: 3, z: 3 }
],
[
{ x: 6, z: 3 },
{ x: 3, z: 3 },
{ x: 6, z: 0 }
]
];
const targetGuides = new THREE.Group();
targetGuides.position.set(
TARGET_OFFSET.x,
0.105,
TARGET_OFFSET.z
);
targetGhostPolygons.forEach((polygon, index) => {
const geometry = createPrismGeometry(polygon, 0.025);
const mesh = new THREE.Mesh(
geometry,
new THREE.MeshBasicMaterial({
color: pieces[index].color,
transparent: true,
opacity: 0.085,
depthWrite: false
})
);
targetGuides.add(mesh);
const outline = new THREE.LineSegments(
new THREE.EdgesGeometry(geometry, 18),
new THREE.LineBasicMaterial({
color: pieces[index].color,
transparent: true,
opacity: 0.35,
depthWrite: false
})
);
targetGuides.add(outline);
});
scene.add(targetGuides);
// -------------------------------------------------------------------------
// Dimension annotations
// -------------------------------------------------------------------------
addDimension(
{ x: SOURCE_OFFSET.x, z: SOURCE_OFFSET.z - 0.58 },
{ x: SOURCE_OFFSET.x + 6, z: SOURCE_OFFSET.z - 0.58 },
{ x: 0, z: 0.16 },
0x839ab7
);
addDimension(
{ x: SOURCE_OFFSET.x - 0.52, z: SOURCE_OFFSET.z },
{ x: SOURCE_OFFSET.x - 0.52, z: SOURCE_OFFSET.z + 6 },
{ x: 0.16, z: 0 },
0x839ab7
);
addDimension(
{ x: TARGET_OFFSET.x, z: TARGET_OFFSET.z - 0.62 },
{ x: TARGET_OFFSET.x + 6, z: TARGET_OFFSET.z - 0.62 },
{ x: 0, z: 0.16 },
0x58e0d0
);
addDimension(
{ x: TARGET_OFFSET.x - 0.52, z: TARGET_OFFSET.z },
{ x: TARGET_OFFSET.x - 0.52, z: TARGET_OFFSET.z + 3 },
{ x: 0.16, z: 0 },
0x58e0d0
);
const worldLabels = [];
function addWorldLabel(text, position, className = "") {
const element = document.createElement("div");
element.className = `world-label ${className}`;
element.textContent = text;
document.body.appendChild(element);
worldLabels.push({
element,
position: new THREE.Vector3(position.x, position.y, position.z)
});
}
addWorldLabel(
"SOURCE TRIANGLE · 6 × 6",
{ x: -7.5, y: 0.55, z: 3.55 },
"title"
);
addWorldLabel(
"TARGET RECTANGLE · 6 × 3",
{ x: 3, y: 0.55, z: 2.05 },
"title"
);
addWorldLabel(
"6.00",
{ x: -6, y: 0.2, z: -3.7 },
"dimension"
);
addWorldLabel(
"6.00",
{ x: -9.7, y: 0.2, z: 0 },
"dimension"
);
addWorldLabel(
"6.00",
{ x: 3, y: 0.2, z: -2.25 },
"dimension"
);
addWorldLabel(
"3.00",
{ x: -0.7, y: 0.2, z: 0 },
"dimension"
);
// -------------------------------------------------------------------------
// Exact polygon overlap calculation
// -------------------------------------------------------------------------
/**
* Clips a convex subject polygon against a convex CCW clip polygon.
* The signed/absolute area of the result is their overlap area.
*/
function clipPolygon(subject, clip) {
let output = subject.slice();
for (let i = 0; i < clip.length && output.length; i++) {
const a = clip[i];
const b = clip[(i + 1) % clip.length];
const edge = subtract2(b, a);
const input = output;
output = [];
for (let j = 0; j < input.length; j++) {
const p = input[j];
const q = input[(j + 1) % input.length];
const pInside =
cross2(edge, subtract2(p, a)) >= -EPSILON;
const qInside =
cross2(edge, subtract2(q, a)) >= -EPSILON;
if (pInside && qInside) {
output.push(q);
} else if (pInside && !qInside) {
output.push(intersection(p, q, a, b));
} else if (!pInside && qInside) {
output.push(intersection(p, q, a, b));
output.push(q);
}
}
}
return output;
}
function intersection(p, q, a, b) {
const d = subtract2(q, p);
const e = subtract2(b, a);
const denominator = cross2(d, e);
if (Math.abs(denominator) < EPSILON) return p;
const t = cross2(subtract2(a, p), e) / denominator;
return {
x: p.x + d.x * t,
z: p.z + d.z * t
};
}
function currentPolygon(piece) {
const angle = piece.group.rotation.y;
const c = Math.cos(angle);
const s = Math.sin(angle);
const position = piece.group.position;
return piece.local.map((point) => ({
x: position.x + c * point.x + s * point.z,
z: position.z - s * point.x + c * point.z
}));
}
function normalizedAngle(angle) {
return Math.atan2(Math.sin(angle), Math.cos(angle));
}
function angleDistance(a, b) {
return Math.abs(normalizedAngle(a - b));
}
function placementAngleError(piece) {
const targetAngle = piece.target.angle;
if (piece.quarterTurnSymmetry) {
let best = Infinity;
for (let turn = 0; turn < 4; turn++) {
best = Math.min(
best,
angleDistance(
piece.group.rotation.y,
targetAngle + turn * Math.PI / 2
)
);
}
return best;
}
return angleDistance(piece.group.rotation.y, targetAngle);
}
const targetRectangleWorld = [
{ x: 0, z: -1.5 },
{ x: 6, z: -1.5 },
{ x: 6, z: 1.5 },
{ x: 0, z: 1.5 }
];
function insideTarget(polygon) {
return polygon.every(
(p) =>
p.x >= -EPSILON &&
p.x <= 6 + EPSILON &&
p.z >= -1.5 - EPSILON &&
p.z <= 1.5 + EPSILON
);
}
const verdict = document.getElementById("verdict");
const verdictTitle = document.getElementById("verdictTitle");
const verdictDetail = document.getElementById("verdictDetail");
const areaCheck = document.getElementById("areaCheck");
const overlapCheck = document.getElementById("overlapCheck");
const boundaryCheck = document.getElementById("boundaryCheck");
const positionCheck = document.getElementById("positionCheck");
function setCheck(element, text, ok) {
element.textContent = text;
element.classList.toggle("ok", ok);
element.classList.toggle("no", !ok);
}
function verifyAssembly() {
const polygons = pieces.map(currentPolygon);
let totalArea = 0;
let placedCount = 0;
let allContained = true;
let maxOverlap = 0;
for (const polygon of polygons) {
totalArea += polygonArea(polygon);
if (!insideTarget(polygon)) allContained = false;
}
for (const piece of pieces) {
const positionError = Math.hypot(
piece.group.position.x - piece.target.x,
piece.group.position.z - piece.target.z
);
if (
positionError < 0.035 &&
placementAngleError(piece) < 0.035
) {
placedCount++;
}
}
for (let i = 0; i < polygons.length; i++) {
for (let j = i + 1; j < polygons.length; j++) {
const overlap = polygonArea(
clipPolygon(polygons[i], polygons[j])
);
maxOverlap = Math.max(maxOverlap, overlap);
}
}
const areaConserved = Math.abs(totalArea - 18) < 1e-6;
const noOverlap = maxOverlap < 1e-6;
const valid =
placedCount === pieces.length &&
areaConserved &&
noOverlap &&
allContained;
verdict.classList.toggle("valid", valid);
verdict.classList.toggle("invalid", !valid);
if (valid) {
verdictTitle.textContent = "PASS — exact assembly";
verdictDetail.textContent =
"All 3 rigid pieces fill the 6 × 3 target with zero overlap.";
} else {
verdictTitle.textContent = "Not yet assembled";
verdictDetail.textContent =
`${placedCount} / 3 pieces at exact target transforms`;
}
setCheck(
areaCheck,
`${totalArea.toFixed(6)} / 18`,
areaConserved
);
setCheck(
overlapCheck,
`${maxOverlap.toFixed(6)} u²`,
noOverlap
);
setCheck(
boundaryCheck,
allContained ? "All inside" : "Outside target",
allContained
);
setCheck(
positionCheck,
`${placedCount} / 3 exact`,
placedCount === 3
);
return valid;
}
// -------------------------------------------------------------------------
// Selection, rotation and animation
// -------------------------------------------------------------------------
let selectedPiece = null;
function selectPiece(piece) {
selectedPiece = piece;
for (const p of pieces) {
p.edge.material.color.set(
p === selectedPiece ? 0xfff4b0 : 0x101827
);
p.edge.material.opacity = p === selectedPiece ? 1 : 0.9;
}
const rotateButton = document.getElementById("rotateButton");
rotateButton.disabled = !selectedPiece;
const selectionInfo = document.getElementById("selectionInfo");
if (selectedPiece) {
selectionInfo.innerHTML =
`<strong>${selectedPiece.name}</strong>` +
`${selectedPiece.description}<br>` +
`Rotation: ${Math.round(
normalizedAngle(selectedPiece.group.rotation.y) *
180 /
Math.PI
)}°`;
} else {
selectionInfo.innerHTML =
"<strong>No piece selected</strong>Click a colored piece to select it.";
}
}
const animations = [];
function animatePiece(piece, destination, duration = 700) {
const from = {
x: piece.group.position.x,
z: piece.group.position.z,
angle: piece.group.rotation.y
};
// Remove any older animation for this piece.
for (let i = animations.length - 1; i >= 0; i--) {
if (animations[i].piece === piece) animations.splice(i, 1);
}
animations.push({
piece,
from,
to: destination,
start: performance.now(),
duration
});
}
function animateAll(destinationKey) {
animations.length = 0;
for (const piece of pieces) {
const destination = piece[destinationKey];
animatePiece(piece, {
x: destination.x,
z: destination.z,
angle: destination.angle
});
}
pendingVerification = destinationKey === "target";
}
let pendingVerification = false;
function rotateSelected() {
if (!selectedPiece) return;
selectedPiece.group.rotation.y += Math.PI / 2;
pendingVerification = false;
selectPiece(selectedPiece);
verifyAssembly();
}
// -------------------------------------------------------------------------
// Camera: implemented directly, without external controls
// -------------------------------------------------------------------------
const cameraState = {
center: new THREE.Vector3(-1.5, 0, 0),
azimuth: 0,
elevation: 0.91,
radius: 22,
zoom: 1
};
function updateCamera() {
const { center, azimuth, elevation, radius } = cameraState;
const horizontal = Math.cos(elevation) * radius;
camera.position.set(
center.x + Math.sin(azimuth) * horizontal,
center.y + Math.sin(elevation) * radius,
center.z + Math.cos(azimuth) * horizontal
);
camera.lookAt(center);
camera.zoom = cameraState.zoom;
camera.updateProjectionMatrix();
camera.updateMatrixWorld();
}
function resize() {
const width = window.innerWidth;
const height = window.innerHeight;
const aspect = width / height;
const halfHeight = Math.max(6.9, 8.8 / aspect);
camera.left = -halfHeight * aspect;
camera.right = halfHeight * aspect;
camera.top = halfHeight;
camera.bottom = -halfHeight;
camera.updateProjectionMatrix();
renderer.setSize(width, height);
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
}
window.addEventListener("resize", resize);
resize();
updateCamera();
// -------------------------------------------------------------------------
// Pointer interaction: piece dragging and camera orbit
// -------------------------------------------------------------------------
const raycaster = new THREE.Raycaster();
const pointer = new THREE.Vector2();
const dragPlane = new THREE.Plane(
new THREE.Vector3(0, 1, 0),
-(PIECE_Y + PIECE_HEIGHT * 0.5)
);
const intersectionPoint = new THREE.Vector3();
let draggingPiece = null;
let orbiting = false;
let dragOffset = { x: 0, z: 0 };
let lastPointer = { x: 0, y: 0 };
function updatePointer(event) {
const rect = renderer.domElement.getBoundingClientRect();
pointer.x =
((event.clientX - rect.left) / rect.width) * 2 - 1;
pointer.y =
-((event.clientY - rect.top) / rect.height) * 2 + 1;
raycaster.setFromCamera(pointer, camera);
}
renderer.domElement.addEventListener(
"contextmenu",
(event) => event.preventDefault()
);
renderer.domElement.addEventListener("pointerdown", (event) => {
updatePointer(event);
lastPointer = { x: event.clientX, y: event.clientY };
const hits = raycaster.intersectObjects(
pieces.map((piece) => piece.mesh),
false
);
if (event.button === 0 && hits.length && !event.shiftKey) {
draggingPiece = hits[0].object.userData.piece;
selectPiece(draggingPiece);
pendingVerification = false;
dragPlane.constant =
-(draggingPiece.group.position.y + PIECE_HEIGHT * 0.5);
if (
raycaster.ray.intersectPlane(
dragPlane,
intersectionPoint
)
) {
dragOffset = {
x: draggingPiece.group.position.x - intersectionPoint.x,
z: draggingPiece.group.position.z - intersectionPoint.z
};
}
renderer.domElement.setPointerCapture(event.pointerId);
event.preventDefault();
} else {
orbiting = true;
renderer.domElement.setPointerCapture(event.pointerId);
}
});
renderer.domElement.addEventListener("pointermove", (event) => {
if (draggingPiece) {
updatePointer(event);
if (
raycaster.ray.intersectPlane(
dragPlane,
intersectionPoint
)
) {
draggingPiece.group.position.x = THREE.MathUtils.clamp(
intersectionPoint.x + dragOffset.x,
-13,
9
);
draggingPiece.group.position.z = THREE.MathUtils.clamp(
intersectionPoint.z + dragOffset.z,
-8,
7
);
}
} else if (orbiting) {
const dx = event.clientX - lastPointer.x;
const dy = event.clientY - lastPointer.y;
cameraState.azimuth -= dx * 0.006;
cameraState.elevation = THREE.MathUtils.clamp(
cameraState.elevation + dy * 0.005,
0.38,
1.35
);
lastPointer = { x: event.clientX, y: event.clientY };
updateCamera();
}
});
renderer.domElement.addEventListener("pointerup", (event) => {
if (draggingPiece) {
const piece = draggingPiece;
draggingPiece = null;
const positionError = Math.hypot(
piece.group.position.x - piece.target.x,
piece.group.position.z - piece.target.z
);
const angleError = placementAngleError(piece);
// Magnetic snapping when the piece is close to its intended transform.
if (positionError < 0.62 && angleError < 0.22) {
animatePiece(piece, piece.target, 320);
pendingVerification = true;
} else {
verifyAssembly();
}
}
orbiting = false;
if (renderer.domElement.hasPointerCapture(event.pointerId)) {
renderer.domElement.releasePointerCapture(event.pointerId);
}
});
renderer.domElement.addEventListener(
"pointercancel",
() => {
draggingPiece = null;
orbiting = false;
}
);
renderer.domElement.addEventListener(
"wheel",
(event) => {
event.preventDefault();
cameraState.zoom = THREE.MathUtils.clamp(
cameraState.zoom * Math.exp(-event.deltaY * 0.001),
0.65,
1.9
);
updateCamera();
},
{ passive: false }
);
window.addEventListener("keydown", (event) => {
if (event.key.toLowerCase() === "r") {
rotateSelected();
}
});
// -------------------------------------------------------------------------
// UI actions
// -------------------------------------------------------------------------
document
.getElementById("solveButton")
.addEventListener("click", () => {
animateAll("target");
});
document
.getElementById("resetButton")
.addEventListener("click", () => {
pendingVerification = false;
animateAll("source");
});
document
.getElementById("rotateButton")
.addEventListener("click", rotateSelected);
document
.getElementById("verifyButton")
.addEventListener("click", verifyAssembly);
document
.getElementById("guidesToggle")
.addEventListener("change", (event) => {
targetGuides.visible = event.target.checked;
});
verifyAssembly();
// -------------------------------------------------------------------------
// Animation and render loop
// -------------------------------------------------------------------------
function updateAnimations(now) {
let allComplete = true;
for (let i = animations.length - 1; i >= 0; i--) {
const animation = animations[i];
const raw =
(now - animation.start) / animation.duration;
const t = THREE.MathUtils.clamp(raw, 0, 1);
const eased = 1 - Math.pow(1 - t, 3);
animation.piece.group.position.x = THREE.MathUtils.lerp(
animation.from.x,
animation.to.x,
eased
);
animation.piece.group.position.z = THREE.MathUtils.lerp(
animation.from.z,
animation.to.z,
eased
);
animation.piece.group.rotation.y = THREE.MathUtils.lerp(
animation.from.angle,
animation.to.angle,
eased
);
if (t < 1) {
allComplete = false;
} else {
animations.splice(i, 1);
}
}
if (allComplete && pendingVerification) {
pendingVerification = false;
verifyAssembly();
}
}
const projected = new THREE.Vector3();
function updateWorldLabels() {
const width = window.innerWidth;
const height = window.innerHeight;
for (const label of worldLabels) {
projected.copy(label.position).project(camera);
const visible =
projected.z >= -1 &&
projected.z <= 1 &&
Math.abs(projected.x) <= 1.1 &&
Math.abs(projected.y) <= 1.1;
label.element.style.display = visible ? "block" : "none";
if (visible) {
const x = (projected.x * 0.5 + 0.5) * width;
const y = (-projected.y * 0.5 + 0.5) * height;
label.element.style.left = `${x}px`;
label.element.style.top = `${y}px`;
}
}
}
function animate(now) {
requestAnimationFrame(animate);
updateAnimations(now);
updateWorldLabels();
renderer.render(scene, camera);
}
requestAnimationFrame(animate);
</script>
</body>
</html>
```