Prompt specification
Build or customize the Three.js 3D scene "Area rearrangement puzzle" 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: Area rearrangement puzzle
Category: Algorithms & Systems · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/area-rearrangement-puzzle-x1684
Scene Description Prompt:
Create a single self-contained HTML file using Three.js from cdnjs that shows area-preserving geometric dissections. Let users move and rotate a fixed set of polygon pieces into target silhouettes; validate coverage and overlap geometrically rather than accepting a visually approximate fit. Low-poly.
Working Three.js Starter (area-rearrangement-puzzle-x1684):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Polygon Area Lab</title>
<style>
:root {
color-scheme: dark;
--bg: #07111f;
--panel: rgba(10, 22, 39, 0.88);
--panel-border: rgba(139, 190, 224, 0.18);
--text: #e9f3ff;
--muted: #8fa8bf;
--accent: #64e1d0;
--accent-2: #ffd166;
--danger: #ff7185;
--success: #71e6a3;
}
* {
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;
}
button {
color: inherit;
font: inherit;
}
#app {
position: relative;
width: 100%;
height: 100%;
isolation: isolate;
}
#stage {
position: absolute;
inset: 0;
width: 100%;
height: 100%;
display: block;
touch-action: none;
outline: none;
}
.glass {
background: var(--panel);
border: 1px solid var(--panel-border);
box-shadow:
0 16px 45px rgba(0, 0, 0, 0.28),
inset 0 1px rgba(255, 255, 255, 0.035);
backdrop-filter: blur(16px);
-webkit-backdrop-filter: blur(16px);
}
header {
position: absolute;
top: 18px;
left: 18px;
right: 18px;
z-index: 5;
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 18px;
pointer-events: none;
}
.brand {
min-width: 230px;
padding: 14px 16px;
border-radius: 16px;
pointer-events: auto;
}
.eyebrow {
margin-bottom: 5px;
color: var(--accent);
font-size: 10px;
font-weight: 800;
letter-spacing: 0.18em;
text-transform: uppercase;
}
h1 {
margin: 0;
font-size: 21px;
font-weight: 760;
letter-spacing: -0.025em;
}
.subtitle {
margin-top: 5px;
color: var(--muted);
font-size: 12px;
}
.target-picker {
display: flex;
gap: 7px;
padding: 7px;
border-radius: 15px;
pointer-events: auto;
}
.target-button {
min-width: 132px;
padding: 9px 12px;
border: 1px solid transparent;
border-radius: 10px;
background: transparent;
color: var(--muted);
cursor: pointer;
transition: 160ms ease;
text-align: left;
}
.target-button:hover {
background: rgba(255, 255, 255, 0.05);
color: var(--text);
}
.target-button.active {
border-color: rgba(100, 225, 208, 0.38);
background: rgba(100, 225, 208, 0.1);
color: var(--text);
}
.target-button strong {
display: block;
font-size: 12px;
}
.target-button span {
display: block;
margin-top: 2px;
color: var(--muted);
font-size: 10px;
}
.info-card {
position: absolute;
top: 112px;
left: 18px;
z-index: 4;
width: 228px;
padding: 14px;
border-radius: 15px;
pointer-events: none;
}
.info-title {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 10px;
color: var(--muted);
font-size: 10px;
font-weight: 800;
letter-spacing: 0.12em;
text-transform: uppercase;
}
.lock {
color: var(--accent-2);
letter-spacing: 0;
}
.area-line {
display: flex;
align-items: baseline;
justify-content: space-between;
margin-bottom: 4px;
}
.area-line strong {
font-size: 19px;
}
.area-line span {
color: var(--muted);
font-size: 11px;
}
.area-note {
color: var(--muted);
font-size: 11px;
line-height: 1.45;
}
.status-card {
position: absolute;
left: 18px;
bottom: 18px;
z-index: 5;
width: 292px;
padding: 15px;
border-radius: 17px;
pointer-events: none;
}
.status-header {
display: flex;
align-items: center;
justify-content: space-between;
gap: 10px;
margin-bottom: 12px;
}
#status {
color: var(--accent-2);
font-size: 12px;
font-weight: 760;
line-height: 1.3;
}
#status.valid {
color: var(--success);
}
#status.invalid {
color: var(--danger);
}
.status-icon {
width: 25px;
height: 25px;
border: 1px solid currentColor;
border-radius: 50%;
display: grid;
place-items: center;
font-size: 12px;
flex: 0 0 auto;
}
.progress-track {
height: 5px;
overflow: hidden;
margin-bottom: 12px;
border-radius: 99px;
background: rgba(255, 255, 255, 0.08);
}
#progress {
width: 0;
height: 100%;
border-radius: inherit;
background: linear-gradient(90deg, var(--accent), #91a7ff);
transition: width 100ms linear;
}
.metrics {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 8px;
}
.metric {
padding: 8px 7px;
border: 1px solid rgba(255, 255, 255, 0.06);
border-radius: 10px;
background: rgba(255, 255, 255, 0.025);
}
.metric span {
display: block;
color: var(--muted);
font-size: 9px;
letter-spacing: 0.04em;
text-transform: uppercase;
}
.metric strong {
display: block;
margin-top: 4px;
font-size: 12px;
}
.control-dock {
position: absolute;
left: 50%;
bottom: 18px;
z-index: 6;
display: flex;
align-items: center;
gap: 7px;
padding: 8px;
border-radius: 16px;
transform: translateX(-50%);
white-space: nowrap;
}
.control-button {
min-height: 38px;
padding: 0 12px;
border: 1px solid rgba(255, 255, 255, 0.08);
border-radius: 10px;
background: rgba(255, 255, 255, 0.045);
cursor: pointer;
transition: 140ms ease;
}
.control-button:hover:not(:disabled) {
border-color: rgba(100, 225, 208, 0.4);
background: rgba(100, 225, 208, 0.1);
transform: translateY(-1px);
}
.control-button:disabled {
cursor: default;
opacity: 0.36;
}
.control-button.primary {
border-color: rgba(100, 225, 208, 0.35);
background: rgba(100, 225, 208, 0.13);
color: #b9fff5;
}
.dock-separator {
width: 1px;
height: 28px;
margin: 0 2px;
background: rgba(255, 255, 255, 0.09);
}
.help-card {
position: absolute;
right: 18px;
bottom: 18px;
z-index: 4;
width: 224px;
padding: 14px 15px;
border-radius: 16px;
color: var(--muted);
font-size: 11px;
line-height: 1.55;
pointer-events: none;
}
.help-card strong {
display: block;
margin-bottom: 5px;
color: var(--text);
font-size: 11px;
}
kbd {
padding: 1px 5px;
border: 1px solid rgba(255, 255, 255, 0.14);
border-bottom-color: rgba(255, 255, 255, 0.25);
border-radius: 4px;
background: rgba(255, 255, 255, 0.055);
color: var(--text);
font-family: inherit;
font-size: 10px;
}
.world-label {
position: absolute;
z-index: 2;
color: rgba(184, 213, 237, 0.48);
font-size: 10px;
font-weight: 800;
letter-spacing: 0.16em;
text-transform: uppercase;
pointer-events: none;
transform: translateX(-50%);
}
#source-label {
left: 25%;
top: 84px;
}
#target-label {
left: 72%;
top: 84px;
}
@media (max-width: 900px) {
.brand {
min-width: 0;
}
.brand .subtitle {
display: none;
}
.target-button {
min-width: 105px;
}
.info-card,
.help-card {
display: none;
}
.status-card {
width: 250px;
}
.control-dock {
right: 12px;
left: auto;
transform: none;
}
.control-button {
padding: 0 9px;
}
}
@media (max-width: 650px) {
header {
top: 10px;
right: 10px;
left: 10px;
flex-direction: column;
}
.brand {
padding: 10px 12px;
}
.brand h1 {
font-size: 17px;
}
.target-picker {
width: 100%;
}
.target-button {
flex: 1;
min-width: 0;
}
.status-card {
right: 10px;
bottom: 72px;
left: 10px;
width: auto;
padding: 11px;
}
.metrics {
gap: 5px;
}
.metric {
padding: 6px;
}
.control-dock {
right: 10px;
bottom: 10px;
left: 10px;
justify-content: center;
overflow-x: auto;
}
.control-button {
min-height: 34px;
padding: 0 9px;
font-size: 11px;
}
#source-label,
#target-label {
display: none;
}
}
</style>
</head>
<body>
<main id="app">
<canvas id="stage" tabindex="0" aria-label="Interactive polygon dissection workspace"></canvas>
<header>
<section class="brand glass">
<div class="eyebrow">Geometric dissection</div>
<h1>Polygon Area Lab</h1>
<div class="subtitle">Fixed pieces · rotation and translation only</div>
</section>
<nav class="target-picker glass" aria-label="Target silhouette">
<button class="target-button active" data-target="square">
<strong>4 × 4 square</strong>
<span>Area 16</span>
</button>
<button class="target-button" data-target="ribbon">
<strong>8 × 2 ribbon</strong>
<span>Area 16</span>
</button>
</nav>
</header>
<div id="source-label" class="world-label">Source tray</div>
<div id="target-label" class="world-label">Target silhouette</div>
<aside class="info-card glass">
<div class="info-title">
Area invariant
<span class="lock">Scale locked</span>
</div>
<div class="area-line">
<strong id="piece-area">16.000</strong>
<span>total piece area</span>
</div>
<div class="area-line">
<strong id="target-area">16.000</strong>
<span>target area</span>
</div>
<div class="area-note">
Every target has the same area as the original fixed collection.
</div>
</aside>
<section class="status-card glass" aria-live="polite">
<div class="status-header">
<div id="status">Coverage incomplete</div>
<div id="status-icon" class="status-icon">×</div>
</div>
<div class="progress-track">
<div id="progress"></div>
</div>
<div class="metrics">
<div class="metric">
<span>Coverage</span>
<strong id="coverage">0%</strong>
</div>
<div class="metric">
<span>Max overlap</span>
<strong id="overlap">0.000</strong>
</div>
<div class="metric">
<span>Outside</span>
<strong id="outside">16.000</strong>
</div>
</div>
</section>
<section class="control-dock glass" aria-label="Piece controls">
<button id="rotate-left" class="control-button" title="Rotate selected piece counterclockwise">
↶ 15°
</button>
<button id="rotate-right" class="control-button" title="Rotate selected piece clockwise">
↷ 15°
</button>
<div class="dock-separator"></div>
<button id="hint" class="control-button primary" title="Place the next piece into its exact solution position">
Next hint
</button>
<button id="reset" class="control-button" title="Return every piece to the source tray">
Reset
</button>
</section>
<aside class="help-card glass">
<strong>Controls</strong>
Drag to move. Select a piece and use the wheel, <kbd>Q</kbd>/<kbd>E</kbd>,
or the rotate buttons to rotate. Arrow keys nudge by 0.25;
hold <kbd>Shift</kbd> for finer steps.
</aside>
</main>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
// -------------------------------------------------------------------------
// Configuration and fixed pieces
// -------------------------------------------------------------------------
const canvas = document.querySelector("#stage");
const statusElement = document.querySelector("#status");
const statusIcon = document.querySelector("#status-icon");
const coverageElement = document.querySelector("#coverage");
const overlapElement = document.querySelector("#overlap");
const outsideElement = document.querySelector("#outside");
const progressElement = document.querySelector("#progress");
const pieceAreaElement = document.querySelector("#piece-area");
const targetAreaElement = document.querySelector("#target-area");
const rotateLeftButton = document.querySelector("#rotate-left");
const rotateRightButton = document.querySelector("#rotate-right");
const hintButton = document.querySelector("#hint");
const resetButton = document.querySelector("#reset");
const PI = Math.PI;
const AREA_EPSILON = 1e-5;
const CAMERA_CENTER_X = -1.15;
const CAMERA_CENTER_Y = 0;
const squareSize = 2;
const rectangleWidth = 2;
const rectangleHeight = 1;
const triangleLeg = Math.SQRT2;
const pieces = [
{
name: "Square A",
points: [
[-1, -1],
[1, -1],
[1, 1],
[-1, 1]
],
color: 0xf2a65a
},
{
name: "Square B",
points: [
[-1, -1],
[1, -1],
[1, 1],
[-1, 1]
],
color: 0xef6f6c
},
{
name: "Bar A",
points: [
[-1, -0.5],
[1, -0.5],
[1, 0.5],
[-1, 0.5]
],
color: 0x5cc8be
},
{
name: "Bar B",
points: [
[-1, -0.5],
[1, -0.5],
[1, 0.5],
[-1, 0.5]
],
color: 0x70a6e8
},
{
name: "Triangle A",
points: [
[0, 0],
[0, -triangleLeg],
[triangleLeg, 0]
],
color: 0xf3cf58
},
{
name: "Triangle B",
points: [
[0, 0],
[0, -triangleLeg],
[triangleLeg, 0]
],
color: 0x9b7ede
},
{
name: "Triangle C",
points: [
[0, 0],
[0, -triangleLeg],
[triangleLeg, 0]
],
color: 0x70c991
},
{
name: "Triangle D",
points: [
[0, 0],
[0, -triangleLeg],
[triangleLeg, 0]
],
color: 0xdf83b7
}
];
const sourceStates = [
{ x: -8.3, y: 2.1, angle: 0 },
{ x: -8.3, y: -1.2, angle: 0 },
{ x: -5.2, y: 1.8, angle: 0 },
{ x: -5.2, y: -0.35, angle: 0 },
{ x: -2.7, y: 2.0, angle: -0.15 },
{ x: -1.35, y: 1.15, angle: 0.25 },
{ x: -2.6, y: -0.4, angle: 0.15 },
{ x: -1.2, y: -1.35, angle: -0.2 }
];
const targetDefinitions = {
square: {
label: "4 × 4 square",
center: { x: 4, y: 0 },
width: 4,
height: 4
},
ribbon: {
label: "8 × 2 ribbon",
center: { x: 4, y: 0 },
width: 8,
height: 2
}
};
const solutionStates = {
square: [
{ x: 3, y: -1, angle: 0 },
{ x: 5, y: -1, angle: 0 },
{ x: 3, y: 0.5, angle: 0 },
{ x: 3, y: 1.5, angle: 0 },
{ x: 5, y: 1, angle: -PI / 4 },
{ x: 5, y: 1, angle: PI / 4 },
{ x: 5, y: 1, angle: (3 * PI) / 4 },
{ x: 5, y: 1, angle: (5 * PI) / 4 }
],
ribbon: [
{ x: 1, y: 0, angle: 0 },
{ x: 3, y: 0, angle: 0 },
{ x: 4.5, y: 0, angle: PI / 2 },
{ x: 5.5, y: 0, angle: PI / 2 },
{ x: 7, y: 0, angle: -PI / 4 },
{ x: 7, y: 0, angle: PI / 4 },
{ x: 7, y: 0, angle: (3 * PI) / 4 },
{ x: 7, y: 0, angle: (5 * PI) / 4 }
]
};
let currentTargetKey = "square";
let selectedIndex = -1;
let hintIndex = 0;
let dragging = null;
// -------------------------------------------------------------------------
// Three.js scene
// -------------------------------------------------------------------------
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x07111f);
scene.fog = new THREE.Fog(0x07111f, 24, 42);
const renderer = new THREE.WebGLRenderer({
canvas,
antialias: true,
alpha: false,
powerPreference: "high-performance"
});
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
const camera = new THREE.OrthographicCamera(-10, 10, 6, -6, 0.1, 100);
camera.position.set(CAMERA_CENTER_X, -5.7, 20);
camera.lookAt(CAMERA_CENTER_X, CAMERA_CENTER_Y, 0);
const ambientLight = new THREE.HemisphereLight(0xbde5ff, 0x142033, 1.75);
scene.add(ambientLight);
const keyLight = new THREE.DirectionalLight(0xfff0d6, 3.2);
keyLight.position.set(-5, -7, 15);
keyLight.castShadow = true;
keyLight.shadow.mapSize.set(2048, 2048);
keyLight.shadow.camera.left = -15;
keyLight.shadow.camera.right = 15;
keyLight.shadow.camera.top = 12;
keyLight.shadow.camera.bottom = -12;
keyLight.shadow.camera.near = 1;
keyLight.shadow.camera.far = 40;
keyLight.shadow.bias = -0.0005;
scene.add(keyLight);
const rimLight = new THREE.DirectionalLight(0x62b9ff, 1.5);
rimLight.position.set(10, 7, 9);
scene.add(rimLight);
const ground = new THREE.Mesh(
new THREE.PlaneGeometry(80, 80),
new THREE.MeshStandardMaterial({
color: 0x081526,
roughness: 0.96,
metalness: 0.02
})
);
ground.position.z = -0.36;
ground.receiveShadow = true;
scene.add(ground);
const grid = new THREE.GridHelper(80, 80, 0x29445d, 0x14283c);
grid.rotation.x = Math.PI / 2;
grid.position.z = -0.32;
grid.material.transparent = true;
grid.material.opacity = 0.42;
scene.add(grid);
const targetGroup = new THREE.Group();
scene.add(targetGroup);
const targetFillMaterial = new THREE.MeshStandardMaterial({
color: 0x102c43,
roughness: 0.88,
metalness: 0.08,
transparent: true,
opacity: 0.96
});
const targetEdgeMaterial = new THREE.LineBasicMaterial({
color: 0x64e1d0,
transparent: true,
opacity: 0.88
});
let targetMesh = null;
let targetEdge = null;
const pieceMeshes = [];
const pieceEdges = [];
const pieceStates = sourceStates.map((state) => ({ ...state }));
function makeShape(points) {
return new THREE.Shape(
points.map(([x, y]) => new THREE.Vector2(x, y))
);
}
function createPiece(piece, index) {
const shape = makeShape(piece.points);
const geometry = new THREE.ExtrudeGeometry(shape, {
depth: 0.22,
bevelEnabled: false,
steps: 1,
curveSegments: 1
});
const topMaterial = new THREE.MeshStandardMaterial({
color: piece.color,
roughness: 0.72,
metalness: 0.04,
flatShading: true
});
const sideMaterial = new THREE.MeshStandardMaterial({
color: new THREE.Color(piece.color).multiplyScalar(0.48),
roughness: 0.86,
metalness: 0.02,
flatShading: true
});
const mesh = new THREE.Mesh(geometry, [topMaterial, sideMaterial]);
mesh.castShadow = true;
mesh.receiveShadow = true;
mesh.userData.pieceIndex = index;
scene.add(mesh);
const edges = new THREE.LineSegments(
new THREE.EdgesGeometry(geometry, 18),
new THREE.LineBasicMaterial({
color: 0x101925,
transparent: true,
opacity: 0.9
})
);
mesh.add(edges);
pieceMeshes.push(mesh);
pieceEdges.push(edges);
updatePieceMesh(index);
}
pieces.forEach(createPiece);
// -------------------------------------------------------------------------
// Target construction
// -------------------------------------------------------------------------
function targetPolygon(definition) {
const halfWidth = definition.width / 2;
const halfHeight = definition.height / 2;
return [
{
x: definition.center.x - halfWidth,
y: definition.center.y - halfHeight
},
{
x: definition.center.x + halfWidth,
y: definition.center.y - halfHeight
},
{
x: definition.center.x + halfWidth,
y: definition.center.y + halfHeight
},
{
x: definition.center.x - halfWidth,
y: definition.center.y + halfHeight
}
];
}
function rebuildTarget() {
if (targetMesh) {
targetGroup.remove(targetMesh);
targetMesh.geometry.dispose();
}
if (targetEdge) {
targetGroup.remove(targetEdge);
targetEdge.geometry.dispose();
}
const definition = targetDefinitions[currentTargetKey];
const localPoints = [
[-definition.width / 2, -definition.height / 2],
[definition.width / 2, -definition.height / 2],
[definition.width / 2, definition.height / 2],
[-definition.width / 2, definition.height / 2]
];
const geometry = new THREE.ExtrudeGeometry(makeShape(localPoints), {
depth: 0.12,
bevelEnabled: false,
steps: 1,
curveSegments: 1
});
targetMesh = new THREE.Mesh(geometry, targetFillMaterial);
targetMesh.position.set(
definition.center.x,
definition.center.y,
-0.22
);
targetMesh.receiveShadow = true;
targetGroup.add(targetMesh);
targetEdge = new THREE.LineSegments(
new THREE.EdgesGeometry(geometry, 15),
targetEdgeMaterial
);
targetMesh.add(targetEdge);
document.querySelector("#target-label").textContent = definition.label;
targetAreaElement.textContent = polygonArea(
targetPolygon(definition)
).toFixed(3);
}
// -------------------------------------------------------------------------
// Exact polygon geometry
// -------------------------------------------------------------------------
function cross(ax, ay, bx, by) {
return ax * by - ay * bx;
}
function signedPolygonArea(polygon) {
let sum = 0;
for (let i = 0; i < polygon.length; i++) {
const a = polygon[i];
const b = polygon[(i + 1) % polygon.length];
sum += a.x * b.y - a.y * b.x;
}
return sum / 2;
}
function polygonArea(polygon) {
return Math.abs(signedPolygonArea(polygon));
}
function ensureCounterClockwise(polygon) {
return signedPolygonArea(polygon) < 0
? [...polygon].reverse()
: polygon;
}
function transformedPiecePolygon(index) {
const piece = pieces[index];
const state = pieceStates[index];
const cosine = Math.cos(state.angle);
const sine = Math.sin(state.angle);
const polygon = piece.points.map(([x, y]) => ({
x: state.x + x * cosine - y * sine,
y: state.y + x * sine + y * cosine
}));
return ensureCounterClockwise(polygon);
}
// Sutherland-Hodgman clipping against a convex, counter-clockwise polygon.
// Polygon areas are computed directly; no visual or raster approximation is used.
function intersectConvexPolygons(subject, clip) {
let output = subject.map((point) => ({ ...point }));
if (output.length === 0) {
return [];
}
for (let i = 0; i < clip.length; i++) {
if (output.length === 0) {
break;
}
const a = clip[i];
const b = clip[(i + 1) % clip.length];
const edgeX = b.x - a.x;
const edgeY = b.y - a.y;
const input = output;
output = [];
let previous = input[input.length - 1];
let previousDistance =
edgeX * (previous.y - a.y) -
edgeY * (previous.x - a.x);
let previousInside = previousDistance >= -AREA_EPSILON;
for (const current of input) {
const currentDistance =
edgeX * (current.y - a.y) -
edgeY * (current.x - a.x);
const currentInside = currentDistance >= -AREA_EPSILON;
if (currentInside !== previousInside) {
const denominator = previousDistance - currentDistance;
const t = Math.abs(denominator) > 1e-12
? previousDistance / denominator
: 0;
output.push({
x: previous.x + (current.x - previous.x) * t,
y: previous.y + (current.y - previous.y) * t
});
}
if (currentInside) {
output.push({ ...current });
}
previous = current;
previousDistance = currentDistance;
previousInside = currentInside;
}
}
return output;
}
function intersectionArea(a, b) {
const intersection = intersectConvexPolygons(a, b);
return intersection.length >= 3
? polygonArea(intersection)
: 0;
}
function validateGeometry() {
const definition = targetDefinitions[currentTargetKey];
const target = ensureCounterClockwise(targetPolygon(definition));
const targetArea = polygonArea(target);
const transformed = pieces.map((_, index) =>
transformedPiecePolygon(index)
);
const pieceAreas = pieces.map((piece, index) =>
polygonArea(transformed[index])
);
let placedArea = 0;
let outsideArea = 0;
transformed.forEach((polygon, index) => {
const inside = intersectionArea(polygon, target);
placedArea += inside;
outsideArea += Math.max(0, pieceAreas[index] - inside);
});
let largestOverlap = 0;
let overlappingPairCount = 0;
for (let i = 0; i < transformed.length; i++) {
for (let j = i + 1; j < transformed.length; j++) {
const overlap = intersectionArea(transformed[i], transformed[j]);
if (overlap > AREA_EPSILON) {
overlappingPairCount++;
}
largestOverlap = Math.max(largestOverlap, overlap);
}
}
const totalPieceArea = pieceAreas.reduce((sum, area) => sum + area, 0);
const areaInvariant = Math.abs(totalPieceArea - targetArea) <= AREA_EPSILON;
// With zero pairwise overlap, the sum of the piece/target intersection
// areas is exactly the union area inside the target. Therefore equality
// with the target area proves full coverage, not merely visual closeness.
const exactCoverage =
Math.abs(placedArea - targetArea) <= AREA_EPSILON;
const noOverlap = largestOverlap <= AREA_EPSILON;
const fullyInside = outsideArea <= AREA_EPSILON;
const valid =
areaInvariant &&
exactCoverage &&
noOverlap &&
fullyInside;
return {
valid,
areaInvariant,
targetArea,
totalPieceArea,
placedArea,
outsideArea,
largestOverlap,
overlappingPairCount,
exactCoverage,
noOverlap,
fullyInside
};
}
// -------------------------------------------------------------------------
// State and UI
// -------------------------------------------------------------------------
function updatePieceMesh(index) {
const mesh = pieceMeshes[index];
const state = pieceStates[index];
mesh.position.x = state.x;
mesh.position.y = state.y;
mesh.position.z = index === selectedIndex ? 0.36 : 0.12 + index * 0.002;
mesh.rotation.z = state.angle;
pieceEdges[index].material.color.set(
index === selectedIndex ? 0xbffff7 : 0x101925
);
pieceEdges[index].material.opacity = index === selectedIndex ? 1 : 0.88;
}
function updateAllPieceMeshes() {
pieces.forEach((_, index) => updatePieceMesh(index));
}
function updateValidation() {
const result = validateGeometry();
const percent = result.targetArea > 0
? (result.placedArea / result.targetArea) * 100
: 0;
coverageElement.textContent = `${Math.min(100, percent).toFixed(1)}%`;
overlapElement.textContent = result.largestOverlap.toFixed(3);
outsideElement.textContent = result.outsideArea.toFixed(3);
progressElement.style.width = `${Math.min(100, percent)}%`;
if (!result.areaInvariant) {
statusElement.textContent = "Area invariant failed";
statusElement.className = "invalid";
statusIcon.textContent = "!";
} else if (!result.noOverlap) {
statusElement.textContent =
`${result.overlappingPairCount} overlapping pair${result.overlappingPairCount === 1 ? "" : "s"}`;
statusElement.className = "invalid";
statusIcon.textContent = "!";
} else if (!result.exactCoverage) {
statusElement.textContent = "Coverage incomplete";
statusElement.className = "";
statusIcon.textContent = "×";
} else if (!result.fullyInside) {
statusElement.textContent = "Some pieces are outside";
statusElement.className = "invalid";
statusIcon.textContent = "!";
} else {
statusElement.textContent = "Exact dissection verified";
statusElement.className = "valid";
statusIcon.textContent = "✓";
}
rotateLeftButton.disabled = selectedIndex < 0;
rotateRightButton.disabled = selectedIndex < 0;
}
function selectPiece(index) {
selectedIndex = index;
updateAllPieceMeshes();
updateValidation();
}
function resetPieces() {
pieceStates.forEach((state, index) => {
Object.assign(state, sourceStates[index]);
});
selectedIndex = -1;
hintIndex = 0;
updateAllPieceMeshes();
updateValidation();
}
function rotateSelected(amount) {
if (selectedIndex < 0) {
return;
}
pieceStates[selectedIndex].angle += amount;
updatePieceMesh(selectedIndex);
updateValidation();
}
function nudgeSelected(dx, dy, fine = false) {
if (selectedIndex < 0) {
return;
}
const step = fine ? 0.05 : 0.25;
pieceStates[selectedIndex].x += dx * step;
pieceStates[selectedIndex].y += dy * step;
updatePieceMesh(selectedIndex);
updateValidation();
}
function placeNextHint() {
const solution = solutionStates[currentTargetKey];
if (hintIndex >= solution.length) {
hintIndex = 0;
}
const index = hintIndex;
Object.assign(pieceStates[index], solution[index]);
hintIndex++;
selectPiece(index);
updateValidation();
if (hintIndex >= solution.length) {
hintButton.textContent = "All pieces placed";
} else {
hintButton.textContent = `Next hint · ${hintIndex}/${solution.length}`;
}
}
function switchTarget(key) {
currentTargetKey = key;
hintIndex = 0;
hintButton.textContent = "Next hint";
document.querySelectorAll(".target-button").forEach((button) => {
button.classList.toggle("active", button.dataset.target === key);
});
rebuildTarget();
resetPieces();
}
// -------------------------------------------------------------------------
// Pointer interaction
// -------------------------------------------------------------------------
const raycaster = new THREE.Raycaster();
const pointer = new THREE.Vector2();
const dragPlane = new THREE.Plane(new THREE.Vector3(0, 0, 1), -0.58);
const dragPoint = new THREE.Vector3();
function updatePointer(event) {
const bounds = canvas.getBoundingClientRect();
pointer.x =
((event.clientX - bounds.left) / bounds.width) * 2 - 1;
pointer.y =
-((event.clientY - bounds.top) / bounds.height) * 2 + 1;
}
function pointerToDragPlane(event) {
updatePointer(event);
raycaster.setFromCamera(pointer, camera);
return raycaster.ray.intersectPlane(dragPlane, dragPoint);
}
canvas.addEventListener("pointerdown", (event) => {
if (event.button !== 0) {
return;
}
updatePointer(event);
raycaster.setFromCamera(pointer, camera);
const hits = raycaster.intersectObjects(pieceMeshes, false);
if (hits.length === 0) {
return;
}
const index = hits[0].object.userData.pieceIndex;
selectPiece(index);
if (pointerToDragPlane(event)) {
dragging = {
index,
offsetX: pieceStates[index].x - dragPoint.x,
offsetY: pieceStates[index].y - dragPoint.y
};
canvas.setPointerCapture(event.pointerId);
canvas.style.cursor = "grabbing";
event.preventDefault();
}
});
canvas.addEventListener("pointermove", (event) => {
if (!dragging) {
return;
}
if (pointerToDragPlane(event)) {
const state = pieceStates[dragging.index];
state.x = dragPoint.x + dragging.offsetX;
state.y = dragPoint.y + dragging.offsetY;
updatePieceMesh(dragging.index);
updateValidation();
}
});
function endDrag(event) {
if (!dragging) {
return;
}
dragging = null;
canvas.style.cursor = "default";
if (event && canvas.hasPointerCapture(event.pointerId)) {
canvas.releasePointerCapture(event.pointerId);
}
}
canvas.addEventListener("pointerup", endDrag);
canvas.addEventListener("pointercancel", endDrag);
canvas.addEventListener("contextmenu", (event) => event.preventDefault());
canvas.addEventListener(
"wheel",
(event) => {
if (selectedIndex < 0) {
return;
}
event.preventDefault();
const step = event.shiftKey
? PI / 180
: PI / 12;
rotateSelected(event.deltaY > 0 ? -step : step);
},
{ passive: false }
);
window.addEventListener("keydown", (event) => {
if (event.target instanceof HTMLInputElement ||
event.target instanceof HTMLTextAreaElement) {
return;
}
const key = event.key.toLowerCase();
const fine = event.shiftKey;
if (key === "q") {
event.preventDefault();
rotateSelected(-(fine ? PI / 180 : PI / 12));
} else if (key === "e") {
event.preventDefault();
rotateSelected(fine ? PI / 180 : PI / 12);
} else if (key === "arrowleft") {
event.preventDefault();
nudgeSelected(-1, 0, fine);
} else if (key === "arrowright") {
event.preventDefault();
nudgeSelected(1, 0, fine);
} else if (key === "arrowup") {
event.preventDefault();
nudgeSelected(0, 1, fine);
} else if (key === "arrowdown") {
event.preventDefault();
nudgeSelected(0, -1, fine);
}
});
rotateLeftButton.addEventListener("click", () =>
rotateSelected(-PI / 12)
);
rotateRightButton.addEventListener("click", () =>
rotateSelected(PI / 12)
);
hintButton.addEventListener("click", placeNextHint);
resetButton.addEventListener("click", resetPieces);
document.querySelectorAll(".target-button").forEach((button) => {
button.addEventListener("click", () => {
switchTarget(button.dataset.target);
});
});
// -------------------------------------------------------------------------
// Resize and initialization
// -------------------------------------------------------------------------
function resize() {
const width = window.innerWidth;
const height = window.innerHeight;
const aspect = width / height;
const desiredWidth = 21.5;
const desiredHeight = 12;
let viewWidth;
let viewHeight;
if (aspect >= desiredWidth / desiredHeight) {
viewHeight = desiredHeight;
viewWidth = viewHeight * aspect;
} else {
viewWidth = desiredWidth;
viewHeight = viewWidth / aspect;
}
camera.left = CAMERA_CENTER_X - viewWidth / 2;
camera.right = CAMERA_CENTER_X + viewWidth / 2;
camera.top = CAMERA_CENTER_Y + viewHeight / 2;
camera.bottom = CAMERA_CENTER_Y - viewHeight / 2;
camera.updateProjectionMatrix();
renderer.setSize(width, height, false);
}
window.addEventListener("resize", resize);
rebuildTarget();
resize();
const totalArea = pieces.reduce(
(sum, piece) => sum + polygonArea(
piece.points.map(([x, y]) => ({ x, y }))
),
0
);
pieceAreaElement.textContent = totalArea.toFixed(3);
updateValidation();
renderer.setAnimationLoop(() => renderer.render(scene, camera));
</script>
</body>
</html>
```