Prompt specification
Build or customize the Three.js 3D scene "Corner-first puzzle assembly" 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: Corner-first puzzle assembly
Category: Games & Play · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/corner-first-puzzle-assembly-x0342
Scene Description Prompt:
Build a self-contained HTML scene with Three.js from cdnjs featuring jigsaw puzzle boundaries. Animate the four corners and border pieces assembling around an empty interior; highlight how flat edges constrain placement before any printed image information appears. Low-poly.
Technical checks: Fit all four corners flush against their neighbors without overlaps or unintended gaps. Keep the middle empty during corner assembly and reveal the completed print at the end.
Return one complete HTML document that works with the cdnjs Three.js r160 module inside a sandbox with scripts allowed. Make the requested subject visible at the default camera. Use procedural assets and local button handlers. Do not use native form submission, pointer lock, external assets or runtime requests other than Three.js.
Working Three.js Starter (corner-first-puzzle-assembly-x0342):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Flat Edge / Jigsaw Assembly Lab</title>
<style>
:root {
color-scheme: dark;
--panel: rgba(16, 28, 34, 0.86);
--line: rgba(196, 235, 229, 0.18);
--text: #eef8f4;
--muted: #9eb7b3;
--cyan: #63eadb;
--amber: #ffc66d;
--pass: #88f0b1;
--fail: #ff7e7e;
}
* { box-sizing: border-box; }
html, body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: #17252b;
color: var(--text);
font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
}
canvas {
display: block;
width: 100%;
height: 100%;
touch-action: none;
}
#hud {
position: fixed;
inset: 0;
pointer-events: none;
}
.panel {
position: absolute;
border: 1px solid var(--line);
background: var(--panel);
box-shadow: 0 18px 50px rgba(0, 0, 0, 0.24);
backdrop-filter: blur(12px);
-webkit-backdrop-filter: blur(12px);
}
#title {
top: 22px;
left: 22px;
width: min(390px, calc(100vw - 44px));
padding: 17px 19px 16px;
border-radius: 16px;
}
.eyebrow {
color: var(--cyan);
font-size: 11px;
font-weight: 800;
letter-spacing: 0.17em;
text-transform: uppercase;
}
h1 {
margin: 7px 0 8px;
font-size: clamp(21px, 3vw, 31px);
line-height: 1.05;
letter-spacing: -0.035em;
}
#intro {
margin: 0;
color: var(--muted);
font-size: 13px;
line-height: 1.5;
}
#diagnostics {
top: 22px;
right: 22px;
width: 254px;
padding: 15px 16px;
border-radius: 16px;
}
#status {
display: flex;
align-items: center;
gap: 8px;
margin-bottom: 12px;
color: var(--pass);
font-size: 12px;
font-weight: 850;
letter-spacing: 0.08em;
text-transform: uppercase;
}
#status::before {
content: "";
width: 9px;
height: 9px;
border-radius: 50%;
background: currentColor;
box-shadow: 0 0 16px currentColor;
}
#status.fail { color: var(--fail); }
#status.moving { color: var(--amber); }
.metric {
display: flex;
justify-content: space-between;
gap: 18px;
padding: 7px 0;
border-top: 1px solid rgba(255, 255, 255, 0.07);
color: var(--muted);
font-size: 12px;
}
.metric b {
color: var(--text);
font-variant-numeric: tabular-nums;
}
#lesson {
left: 50%;
bottom: 22px;
width: min(620px, calc(100vw - 44px));
padding: 15px 18px;
border-radius: 16px;
transform: translateX(-50%);
}
#step {
color: var(--amber);
font-size: 11px;
font-weight: 850;
letter-spacing: 0.13em;
text-transform: uppercase;
}
#instruction {
margin-top: 5px;
font-size: 15px;
font-weight: 720;
line-height: 1.35;
}
.legend {
display: flex;
flex-wrap: wrap;
gap: 8px 18px;
margin-top: 11px;
color: var(--muted);
font-size: 11px;
}
.legend span {
display: inline-flex;
align-items: center;
gap: 7px;
}
.swatch {
width: 22px;
height: 3px;
border-radius: 4px;
background: var(--cyan);
box-shadow: 0 0 8px rgba(99, 234, 219, 0.45);
}
.swatch.amber {
background: var(--amber);
box-shadow: 0 0 8px rgba(255, 198, 109, 0.4);
}
#controls {
position: absolute;
right: 22px;
bottom: 22px;
display: flex;
gap: 9px;
pointer-events: auto;
}
button {
min-height: 42px;
padding: 0 15px;
border: 1px solid rgba(255, 255, 255, 0.16);
border-radius: 12px;
background: rgba(20, 37, 43, 0.92);
color: var(--text);
font: inherit;
font-size: 12px;
font-weight: 800;
letter-spacing: 0.03em;
cursor: pointer;
box-shadow: 0 10px 25px rgba(0, 0, 0, 0.2);
}
button:hover {
border-color: var(--cyan);
color: var(--cyan);
}
button:focus-visible {
outline: 2px solid var(--cyan);
outline-offset: 3px;
}
#cornerNote {
position: absolute;
left: 22px;
bottom: 22px;
width: min(260px, calc(100vw - 44px));
padding: 13px 15px;
border-radius: 14px;
color: var(--muted);
font-size: 11px;
line-height: 1.45;
}
#cornerNote strong {
display: block;
margin-bottom: 3px;
color: var(--text);
font-size: 12px;
}
@media (max-width: 820px) {
#diagnostics {
top: auto;
right: 14px;
bottom: 116px;
width: 215px;
padding: 11px 13px;
}
#title {
top: 14px;
left: 14px;
}
#lesson {
bottom: 14px;
}
#cornerNote {
display: none;
}
#controls {
right: 14px;
bottom: 142px;
}
.metric {
padding: 5px 0;
font-size: 11px;
}
}
</style>
</head>
<body>
<div id="hud">
<section id="title" class="panel">
<div class="eyebrow">Spatial reasoning / puzzle lab</div>
<h1>Flat Edge Assembly</h1>
<p id="intro">Observe the straight outer boundaries first. Then watch four corner pieces and four border pieces lock around an intentionally empty center.</p>
</section>
<section id="diagnostics" class="panel" aria-live="polite">
<div id="status">Checking geometry</div>
<div class="metric"><span>Paired jigsaw seams</span><b id="seamMetric">—</b></div>
<div class="metric"><span>Area closure</span><b id="areaMetric">—</b></div>
<div class="metric"><span>Grid overlaps / gaps</span><b id="overlapMetric">—</b></div>
<div class="metric"><span>Corner rise</span><b id="riseMetric">—</b></div>
</section>
<section id="lesson" class="panel" aria-live="polite">
<div id="step">Step 1 / Read the boundary</div>
<div id="instruction">Cyan marks flat edges: they must sit flush against the board.</div>
<div class="legend">
<span><i class="swatch"></i>Flat outer edge</span>
<span><i class="swatch amber"></i>Curved internal jigsaw boundary</span>
<span>Printed artwork appears only after assembly</span>
</div>
</section>
<aside id="cornerNote" class="panel">
<strong>Corner-fit inspection</strong>
Every corner uses the same seam coordinates as its neighboring border piece. All eight pieces settle to one elevation, preventing lifted corners or corner openings.
</aside>
<nav id="controls" aria-label="Scene controls">
<button id="replay" type="button">Replay assembly</button>
<button id="view" type="button">Top view</button>
</nav>
</div>
<script type="module">
import * as THREE from "https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
const viewport = { width: innerWidth, height: innerHeight };
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x17252b);
scene.fog = new THREE.Fog(0x17252b, 20, 38);
const renderer = new THREE.WebGLRenderer({ antialias: true, alpha: false });
renderer.setPixelRatio(Math.min(devicePixelRatio, 2));
renderer.setSize(viewport.width, viewport.height);
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.08;
document.body.prepend(renderer.domElement);
const camera = new THREE.PerspectiveCamera(42, viewport.width / viewport.height, 0.1, 80);
const orbit = {
theta: 0.62,
phi: 0.91,
radius: 17.5,
target: new THREE.Vector3(0, 0.25, 0)
};
const desiredOrbit = { ...orbit, target: orbit.target.clone() };
function updateCamera() {
camera.position.setFromSphericalCoords(orbit.radius, orbit.phi, orbit.theta);
camera.position.add(orbit.target);
camera.lookAt(orbit.target);
}
updateCamera();
scene.add(new THREE.HemisphereLight(0xcdeee8, 0x344047, 2.1));
const key = new THREE.DirectionalLight(0xfff0cf, 3.2);
key.position.set(-7, 12, 8);
key.castShadow = true;
key.shadow.mapSize.set(2048, 2048);
key.shadow.camera.left = -12;
key.shadow.camera.right = 12;
key.shadow.camera.top = 12;
key.shadow.camera.bottom = -12;
key.shadow.camera.near = 1;
key.shadow.camera.far = 35;
key.shadow.bias = -0.00035;
scene.add(key);
const rim = new THREE.DirectionalLight(0x73d8df, 1.35);
rim.position.set(8, 7, -9);
scene.add(rim);
const ground = new THREE.Mesh(
new THREE.PlaneGeometry(60, 60),
new THREE.MeshStandardMaterial({ color: 0x1e3035, roughness: 1, flatShading: true })
);
ground.rotation.x = -Math.PI / 2;
ground.position.y = -0.17;
ground.receiveShadow = true;
scene.add(ground);
const BOARD_TOP = 0.14;
const DEPTH = 0.28;
const BODY_Y = BOARD_TOP + DEPTH / 2;
const OUTER = 4;
const INNER = 2.35;
const SPLIT = 1.2;
const boardMaterial = new THREE.MeshStandardMaterial({
color: 0x294047,
roughness: 0.92,
metalness: 0.02,
flatShading: true
});
function addBoardSlab(w, d, x, z) {
const slab = new THREE.Mesh(new THREE.BoxGeometry(w, 0.28, d), boardMaterial);
slab.position.set(x, 0, z);
slab.castShadow = true;
slab.receiveShadow = true;
scene.add(slab);
}
const boardOuter = 4.55;
const boardHole = 2.52;
const band = boardOuter - boardHole;
addBoardSlab(boardOuter * 2, band, 0, -(boardOuter + boardHole) / 2);
addBoardSlab(boardOuter * 2, band, 0, (boardOuter + boardHole) / 2);
addBoardSlab(band, boardHole * 2, -(boardOuter + boardHole) / 2, 0);
addBoardSlab(band, boardHole * 2, (boardOuter + boardHole) / 2, 0);
const rockMaterial = new THREE.MeshStandardMaterial({
color: 0x49636a,
roughness: 1,
flatShading: true
});
const rockPositions = [
[-5.8, -0.02, -4.8, 0.42], [5.8, -0.05, -4.5, 0.36],
[-6.1, -0.03, 4.8, 0.32], [5.9, -0.02, 5.0, 0.44],
[-5.7, -0.08, 0.1, 0.25], [6.0, -0.06, 0.4, 0.24]
];
for (const [x, y, z, s] of rockPositions) {
const rock = new THREE.Mesh(new THREE.IcosahedronGeometry(s, 0), rockMaterial);
rock.position.set(x, y, z);
rock.scale.y = 0.72;
rock.rotation.set(0.2, x * 0.8, 0.1);
rock.castShadow = true;
rock.receiveShadow = true;
scene.add(rock);
}
const pt = (x, y) => ({ x, y });
const corners = [
{ o: pt(-OUTER, -OUTER), a: pt(-SPLIT, -OUTER), b: pt(-OUTER, -SPLIT), i: pt(-INNER, -INNER), side: "top-left" },
{ o: pt( OUTER, -OUTER), a: pt( OUTER, -SPLIT), b: pt( SPLIT, -OUTER), i: pt( INNER, -INNER), side: "top-right" },
{ o: pt( OUTER, OUTER), a: pt( SPLIT, OUTER), b: pt( OUTER, SPLIT), i: pt( INNER, INNER), side: "bottom-right" },
{ o: pt(-OUTER, OUTER), a: pt(-OUTER, SPLIT), b: pt(-SPLIT, OUTER), i: pt(-INNER, INNER), side: "bottom-left" }
];
function makeSeam(start, end, towardCorner) {
const dx = end.x - start.x;
const dy = end.y - start.y;
const length = Math.hypot(dx, dy);
let nx = -dy / length;
let ny = dx / length;
const midX = (start.x + end.x) / 2;
const midY = (start.y + end.y) / 2;
if (nx * (towardCorner.x - midX) + ny * (towardCorner.y - midY) < 0) {
nx *= -1;
ny *= -1;
}
const profile = [
[0.00, 0.00],
[0.14, 0.08],
[0.28, -0.12],
[0.36, 0.42],
[0.48, 0.42],
[0.60, -0.12],
[0.70, 0.08],
[1.00, 0.00]
];
const amplitude = 0.75;
return profile.map(([t, f]) => ({
x: start.x + dx * t + nx * amplitude * f,
y: start.y + dy * t + ny * amplitude * f
}));
}
const seams = corners.map(c => ({
a: makeSeam(c.a, c.i, c.o),
b: makeSeam(c.b, c.i, c.o)
}));
const polygons = [];
const pieces = [];
function polygonArea(poly) {
let sum = 0;
for (let k = 0; k < poly.length; k++) {
const a = poly[k];
const b = poly[(k + 1) % poly.length];
sum += a.x * b.y - b.x * a.y;
}
return sum / 2;
}
for (let i = 0; i < 4; i++) {
const c = corners[i];
const reverseB = seams[i].b.slice().reverse();
const poly = [c.o, ...seams[i].a, ...reverseB.slice(1)];
polygons.push({ type: "corner", index: i, poly, outerEdges: [[c.o, c.a], [c.b, c.o]] });
}
for (let i = 0; i < 4; i++) {
const next = (i + 1) % 4;
const reverseA = seams[i].a.slice().reverse();
const poly = [corners[i].a, ...seams[next].b, corners[i].i, ...reverseA.slice(1)];
polygons.push({
type: "border",
index: i,
poly,
outerEdges: [[corners[i].a, corners[next].b]],
innerEdges: [[corners[next].i, corners[i].i]]
});
}
function createArtworkTexture() {
const canvas = document.createElement("canvas");
canvas.width = canvas.height = 1024;
const ctx = canvas.getContext("2d");
const sky = ctx.createLinearGradient(0, 0, 0, 1024);
sky.addColorStop(0, "#f6dc9a");
sky.addColorStop(0.48, "#e99972");
sky.addColorStop(1, "#315f6c");
ctx.fillStyle = sky;
ctx.fillRect(0, 0, 1024, 1024);
ctx.fillStyle = "#ffe3a0";
ctx.beginPath();
ctx.arc(740, 240, 105, 0, Math.PI * 2);
ctx.fill();
const mountains = [
[[0, 640], [180, 365], [360, 640], "#654f6b"],
[[130, 650], [430, 285], [705, 650], "#495a70"],
[[460, 650], [735, 350], [1024, 650], "#354e62"],
[[640, 660], [880, 430], [1024, 565], [1024, 660], "#2f485a"]
];
for (const polygon of mountains) {
ctx.beginPath();
polygon.forEach(([x, y], index) => index ? ctx.lineTo(x, y) : ctx.moveTo(x, y));
ctx.closePath();
ctx.fillStyle = polygon === mountains[0] ? "#654f6b" :
polygon === mountains[1] ? "#495a70" :
polygon === mountains[2] ? "#354e62" : "#2f485a";
ctx.fill();
}
ctx.fillStyle = "#3f7780";
ctx.beginPath();
ctx.moveTo(0, 620);
ctx.lineTo(1024, 620);
ctx.lineTo(1024, 1024);
ctx.lineTo(0, 1024);
ctx.closePath();
ctx.fill();
const reflections = [
[[0, 690], [320, 690], [225, 815], [0, 885]],
[[420, 705], [875, 705], [760, 825], [500, 805]],
[[90, 875], [650, 875], [480, 1024], [190, 1024]]
];
reflections.forEach((poly, index) => {
ctx.beginPath();
poly.forEach(([x, y], i) => i ? ctx.lineTo(x, y) : ctx.moveTo(x, y));
ctx.closePath();
ctx.fillStyle = ["#73a1a2", "#619194", "#89aaa5"][index];
ctx.fill();
});
ctx.fillStyle = "rgba(20, 43, 49, 0.82)";
ctx.beginPath();
ctx.moveTo(0, 1024);
ctx.lineTo(0, 910);
ctx.lineTo(155, 850);
ctx.lineTo(315, 935);
ctx.lineTo(500, 1024);
ctx.closePath();
ctx.fill();
ctx.fillStyle = "rgba(245, 247, 226, 0.95)";
ctx.font = "800 52px system-ui, sans-serif";
ctx.textAlign = "center";
ctx.fillText("CONNECTED", 512, 945);
ctx.font = "600 24px system-ui, sans-serif";
ctx.fillText("FLAT EDGE • CURVED FIT", 512, 985);
const texture = new THREE.CanvasTexture(canvas);
texture.colorSpace = THREE.SRGBColorSpace;
texture.anisotropy = Math.min(8, renderer.capabilities.getMaxAnisotropy());
return texture;
}
const artwork = createArtworkTexture();
const capCorner = new THREE.MeshStandardMaterial({
color: 0xf2e6ca,
roughness: 0.88,
metalness: 0,
flatShading: true
});
const capBorder = new THREE.MeshStandardMaterial({
color: 0xe8ddc1,
roughness: 0.92,
metalness: 0,
flatShading: true
});
const sideMaterial = new THREE.MeshStandardMaterial({
color: 0xb8a77e,
roughness: 0.96,
metalness: 0,
flatShading: true
});
const outlineMaterial = new THREE.LineBasicMaterial({
color: 0x30464a,
transparent: true,
opacity: 0.42
});
const flatMaterial = new THREE.LineBasicMaterial({
color: 0x63eadb,
transparent: true,
opacity: 0.98
});
const innerMaterial = new THREE.LineBasicMaterial({
color: 0xffc66d,
transparent: true,
opacity: 0.88
});
const targetLineMaterial = new THREE.LineBasicMaterial({
color: 0x8cecdf,
transparent: true,
opacity: 0.66
});
function makeShape(poly) {
return new THREE.Shape(poly.map(p => new THREE.Vector2(p.x, p.y)));
}
function lineFromPoints(points, material, y = 0) {
const geometry = new THREE.BufferGeometry().setFromPoints(
points.map(p => new THREE.Vector3(p.x, y, p.y))
);
return new THREE.LineLoop(geometry, material);
}
function segmentsFromPairs(pairs, material, y = 0) {
const positions = [];
for (const [a, b] of pairs) {
positions.push(a.x, y, a.y, b.x, y, b.y);
}
const geometry = new THREE.BufferGeometry();
geometry.setAttribute("position", new THREE.Float32BufferAttribute(positions, 3));
return new THREE.LineSegments(geometry, material);
}
const targetGroup = new THREE.Group();
scene.add(targetGroup);
for (const item of polygons) {
const shape = makeShape(item.poly);
const geometry = new THREE.ExtrudeGeometry(shape, {
depth: DEPTH,
steps: 1,
bevelEnabled: false,
curveSegments: 1
});
geometry.rotateX(Math.PI / 2);
geometry.translate(0, DEPTH / 2, 0);
const group = new THREE.Group();
const body = new THREE.Mesh(
geometry,
item.type === "corner" ? [capCorner, sideMaterial] : [capBorder, sideMaterial]
);
body.castShadow = true;
body.receiveShadow = true;
group.add(body);
const outline = lineFromPoints(item.poly, outlineMaterial, DEPTH / 2 + 0.012);
group.add(outline);
const flatEdges = segmentsFromPairs(item.outerEdges, flatMaterial, DEPTH / 2 + 0.018);
group.add(flatEdges);
if (item.innerEdges?.length) {
group.add(segmentsFromPairs(item.innerEdges, innerMaterial, DEPTH / 2 + 0.016));
}
const overlayGeometry = new THREE.ShapeGeometry(shape);
const positions = overlayGeometry.attributes.position;
const uvs = new Float32Array(positions.count * 2);
for (let i = 0; i < positions.count; i++) {
uvs[i * 2] = positions.getX(i) / (OUTER * 2) + 0.5;
uvs[i * 2 + 1] = positions.getY(i) / (OUTER * 2) + 0.5;
}
overlayGeometry.setAttribute("uv", new THREE.BufferAttribute(uvs, 2));
overlayGeometry.rotateX(Math.PI / 2);
const overlayMaterial = new THREE.MeshStandardMaterial({
map: artwork,
transparent: true,
opacity: 0,
roughness: 0.9,
metalness: 0,
depthWrite: false,
polygonOffset: true,
polygonOffsetFactor: -2,
polygonOffsetUnits: -2
});
const overlay = new THREE.Mesh(overlayGeometry, overlayMaterial);
overlay.position.y = DEPTH / 2 + 0.009;
overlay.renderOrder = 2;
group.add(overlay);
const ghostGeometry = new THREE.ShapeGeometry(shape);
ghostGeometry.rotateX(Math.PI / 2);
const ghostMaterial = new THREE.MeshBasicMaterial({
color: 0x63eadb,
transparent: true,
opacity: 0.035,
depthWrite: false,
side: THREE.DoubleSide
});
const ghost = new THREE.Mesh(ghostGeometry, ghostMaterial);
ghost.position.y = BOARD_TOP + 0.006;
targetGroup.add(ghost);
const targetLine = lineFromPoints(item.poly, targetLineMaterial, BOARD_TOP + 0.014);
targetGroup.add(targetLine);
let startOffset;
let startRotation;
if (item.type === "corner") {
const c = corners[item.index];
const length = Math.hypot(c.o.x, c.o.y);
startOffset = new THREE.Vector3(c.o.x / length * 3.15, 1.75, c.o.y / length * 3.15);
startRotation = new THREE.Euler(
(item.index % 2 ? -1 : 1) * 0.09,
(item.index < 2 ? 1 : -1) * 0.28,
(item.index % 2 ? 1 : -1) * 0.07
);
} else {
const normals = [
new THREE.Vector3(0, 0, -1),
new THREE.Vector3(1, 0, 0),
new THREE.Vector3(0, 0, 1),
new THREE.Vector3(-1, 0, 0)
];
startOffset = normals[item.index].clone().multiplyScalar(3.2);
startOffset.y = 1.15;
startRotation = new THREE.Euler(
0.04,
(item.index % 2 ? 1 : -1) * 0.22,
(item.index < 2 ? 1 : -1) * 0.05
);
}
group.position.copy(startOffset);
group.rotation.copy(startRotation);
scene.add(group);
pieces.push({
group,
overlay,
overlayMaterial,
body,
outline,
flatEdges,
item,
startOffset,
startRotation
});
}
const markerMaterial = new THREE.MeshBasicMaterial({
color: 0xffc66d,
transparent: true,
opacity: 0.9
});
for (const c of corners) {
const marker = new THREE.Mesh(new THREE.TorusGeometry(0.15, 0.025, 4, 4), markerMaterial);
marker.rotation.x = Math.PI / 2;
marker.position.set(c.i.x, BOARD_TOP + 0.028, c.i.y);
scene.add(marker);
}
function pointInPolygon(point, poly) {
let inside = false;
for (let i = 0, j = poly.length - 1; i < poly.length; j = i++) {
const a = poly[i];
const b = poly[j];
const intersects = ((a.y > point.y) !== (b.y > point.y)) &&
(point.x < (b.x - a.x) * (point.y - a.y) / ((b.y - a.y) || 1e-12) + a.x);
if (intersects) inside = !inside;
}
return inside;
}
function pointSegmentDistance(p, a, b) {
const dx = b.x - a.x;
const dy = b.y - a.y;
const denominator = dx * dx + dy * dy;
const t = denominator ? THREE.MathUtils.clamp(((p.x - a.x) * dx + (p.y - a.y) * dy) / denominator, 0, 1) : 0;
return Math.hypot(p.x - (a.x + t * dx), p.y - (a.y + t * dy));
}
function distanceToPolygon(point, poly) {
let distance = Infinity;
for (let i = 0; i < poly.length; i++) {
distance = Math.min(distance, pointSegmentDistance(point, poly[i], poly[(i + 1) % poly.length]));
}
return distance;
}
function samePoint(a, b) {
return Math.abs(a.x - b.x) < 1e-7 && Math.abs(a.y - b.y) < 1e-7;
}
function findSequence(poly, sequence) {
outer: for (let start = 0; start < poly.length; start++) {
for (let j = 0; j < sequence.length; j++) {
if (!samePoint(poly[(start + j) % poly.length], sequence[j])) continue outer;
}
return start;
}
return -1;
}
function runGeometryTests() {
const expectedArea = OUTER * OUTER * 2 - Math.pow(INNER * 2, 2);
const actualArea = polygons.reduce((sum, item) => sum + Math.abs(polygonArea(item.poly)), 0);
const areaError = Math.abs(actualArea - expectedArea);
let pairedSeams = 0;
for (let i = 0; i < 4; i++) {
const corner = polygons[i].poly;
const sameSide = polygons[i + 4].poly;
const previousSide = polygons[(i + 3) % 4 + 4].poly;
const aForward = findSequence(corner, seams[i].a);
const aReverse = findSequence(sameSide, seams[i].a.slice().reverse());
const bReverse = findSequence(corner, seams[i].b.slice().reverse());
const bForward = findSequence(previousSide, seams[i].b);
if (aForward >= 0 && aReverse >= 0 && bReverse >= 0 && bForward >= 0) pairedSeams += 2;
}
let overlaps = 0;
let gaps = 0;
let sampled = 0;
const divisions = 67;
for (let gx = 0; gx < divisions; gx++) {
for (let gy = 0; gy < divisions; gy++) {
const p = pt(-3.97 + 7.94 * gx / (divisions - 1), -3.97 + 7.94 * gy / (divisions - 1));
if (Math.abs(p.x) < INNER && Math.abs(p.y) < INNER) continue;
let nearBoundary = false;
for (const item of polygons) {
if (distanceToPolygon(p, item.poly) < 0.012) {
nearBoundary = true;
break;
}
}
if (nearBoundary) continue;
sampled++;
let count = 0;
for (const item of polygons) if (pointInPolygon(p, item.poly)) count++;
if (count > 1) overlaps++;
if (count === 0) gaps++;
}
}
return {
pass: pairedSeams === 8 && areaError < 1e-5 && overlaps === 0 && gaps === 0 && sampled > 1000,
pairedSeams,
areaError,
actualArea,
expectedArea,
overlaps,
gaps,
sampled
};
}
const staticTest = runGeometryTests();
const statusElement = document.getElementById("status");
const seamMetric = document.getElementById("seamMetric");
const areaMetric = document.getElementById("areaMetric");
const overlapMetric = document.getElementById("overlapMetric");
const riseMetric = document.getElementById("riseMetric");
function showDiagnostics(test) {
seamMetric.textContent = `${test.pairedSeams} / 8`;
areaMetric.textContent = `${test.actualArea.toFixed(2)} u²`;
overlapMetric.textContent = `${test.overlaps} / ${test.gaps}`;
}
showDiagnostics(staticTest);
statusElement.textContent = staticTest.pass ? "Fit check / pass" : "Fit check / failed";
statusElement.classList.toggle("fail", !staticTest.pass);
const stepElement = document.getElementById("step");
const instructionElement = document.getElementById("instruction");
const clamp01 = value => THREE.MathUtils.clamp(value, 0, 1);
const smooth = value => {
const t = clamp01(value);
return t * t * (3 - 2 * t);
};
let timeline = 0;
let playing = true;
let lastTime = performance.now();
let topView = false;
function updateScene(time) {
for (const piece of pieces) {
const isCorner = piece.item.type === "corner";
const start = isCorner ? 1.12 : 1.82;
const duration = isCorner ? 1.72 : 1.68;
const progress = smooth((time - start) / duration);
piece.group.position.set(
piece.startOffset.x * (1 - progress),
BODY_Y + piece.startOffset.y * (1 - progress),
piece.startOffset.z * (1 - progress)
);
piece.group.rotation.set(
piece.startRotation.x * (1 - progress),
piece.startRotation.y * (1 - progress),
piece.startRotation.z * (1 - progress)
);
if (progress >= 1) {
piece.group.position.set(0, BODY_Y, 0);
piece.group.rotation.set(0, 0, 0);
}
}
const reveal = smooth((time - 4.08) / 1.08);
for (const piece of pieces) piece.overlayMaterial.opacity = reveal;
const guideFade = time < 3.55 ? 1 : 1 - smooth((time - 3.55) / 0.8);
targetLineMaterial.opacity = 0.12 + guideFade * 0.54;
flatMaterial.opacity = 0.35 + guideFade * 0.63;
innerMaterial.opacity = 0.28 + guideFade * 0.60;
markerMaterial.opacity = 0.25 + guideFade * 0.65;
targetGroup.children.forEach(child => {
if (child.material) child.material.opacity = child.material === targetLineMaterial
? targetLineMaterial.opacity
: 0.035 * guideFade;
});
if (time < 1.12) {
stepElement.textContent = "Step 1 / Read the boundary";
instructionElement.textContent = "Cyan marks flat edges: they must sit flush against the board.";
} else if (time < 3.5) {
stepElement.textContent = "Step 2 / Assemble corners, then borders";
instructionElement.textContent = "The curved seams pair tabs and blanks; the flat edges constrain orientation.";
} else if (time < 4.08) {
stepElement.textContent = "Step 3 / Inspect the empty center";
instructionElement.textContent = "All four corners sit flush. No piece overlaps or leaves a corner opening.";
} else if (time < 5.16) {
stepElement.textContent = "Step 4 / Reveal the print";
instructionElement.textContent = "Only after the geometry locks does the printed artwork appear.";
} else {
stepElement.textContent = "Complete / geometrically connected";
instructionElement.textContent = "Eight exact seam pairs, one elevation, zero overlap: the frame is assembled.";
}
const cornerPieces = pieces.filter(piece => piece.item.type === "corner");
const settled = cornerPieces.filter(piece =>
Math.abs(piece.group.position.x) < 0.0001 &&
Math.abs(piece.group.position.z) < 0.0001 &&
Math.abs(piece.group.position.y - BODY_Y) < 0.0001
).length;
const maximumRise = Math.max(...pieces.map(piece => Math.abs(piece.group.position.y - BODY_Y)));
riseMetric.textContent = `${maximumRise.toFixed(3)}`;
if (time >= 3.5) {
statusElement.textContent = staticTest.pass && settled === 4 ? "Assembly / pass" : "Assembly / check";
statusElement.classList.toggle("fail", !(staticTest.pass && settled === 4));
statusElement.classList.remove("moving");
} else {
statusElement.textContent = "Assembly / moving";
statusElement.classList.add("moving");
statusElement.classList.remove("fail");
}
}
function replay() {
timeline = 0;
playing = true;
lastTime = performance.now();
updateScene(0);
}
document.getElementById("replay").addEventListener("click", replay);
document.getElementById("view").addEventListener("click", event => {
topView = !topView;
if (topView) {
desiredOrbit.theta = 0;
desiredOrbit.phi = 0.10;
desiredOrbit.radius = 15.5;
} else {
desiredOrbit.theta = 0.62;
desiredOrbit.phi = 0.91;
desiredOrbit.radius = 17.5;
}
event.currentTarget.textContent = topView ? "Isometric view" : "Top view";
});
let dragging = false;
let dragX = 0;
let dragY = 0;
renderer.domElement.addEventListener("pointerdown", event => {
dragging = true;
dragX = event.clientX;
dragY = event.clientY;
renderer.domElement.setPointerCapture(event.pointerId);
});
renderer.domElement.addEventListener("pointermove", event => {
if (!dragging) return;
const dx = event.clientX - dragX;
const dy = event.clientY - dragY;
dragX = event.clientX;
dragY = event.clientY;
orbit.theta -= dx * 0.006;
orbit.phi = THREE.MathUtils.clamp(orbit.phi - dy * 0.005, 0.08, 1.38);
desiredOrbit.theta = orbit.theta;
desiredOrbit.phi = orbit.phi;
});
function endDrag(event) {
dragging = false;
if (renderer.domElement.hasPointerCapture(event.pointerId)) {
renderer.domElement.releasePointerCapture(event.pointerId);
}
}
renderer.domElement.addEventListener("pointerup", endDrag);
renderer.domElement.addEventListener("pointercancel", endDrag);
renderer.domElement.addEventListener("wheel", event => {
event.preventDefault();
orbit.radius = THREE.MathUtils.clamp(orbit.radius + event.deltaY * 0.012, 10, 27);
desiredOrbit.radius = orbit.radius;
}, { passive: false });
window.addEventListener("resize", () => {
viewport.width = innerWidth;
viewport.height = innerHeight;
camera.aspect = viewport.width / viewport.height;
camera.updateProjectionMatrix();
renderer.setPixelRatio(Math.min(devicePixelRatio, 2));
renderer.setSize(viewport.width, viewport.height);
});
function animate(now) {
requestAnimationFrame(animate);
const dt = Math.min((now - lastTime) / 1000, 0.05);
lastTime = now;
if (playing) {
timeline += dt;
if (timeline >= 5.16) playing = false;
}
updateScene(timeline);
orbit.theta += (desiredOrbit.theta - orbit.theta) * 0.12;
orbit.phi += (desiredOrbit.phi - orbit.phi) * 0.12;
orbit.radius += (desiredOrbit.radius - orbit.radius) * 0.12;
updateCamera();
renderer.render(scene, camera);
}
updateScene(0);
requestAnimationFrame(animate);
if (!staticTest.pass) {
console.error("Jigsaw geometry validation failed", staticTest);
} else {
console.info("Jigsaw geometry validation passed", staticTest);
}
</script>
</body>
</html>
```