Prompt specification
Build or customize the Three.js 3D scene "Playroom miniature city building" 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: Playroom miniature city building
Category: Voxel Worlds · Style: Voxel 3D
License: MIT · Reference: https://three3d.app/scene/playroom-miniature-city-building-x0351
Scene Description Prompt:
Create a single self-contained HTML file using Three.js from cdnjs that shows a voxel toy city being assembled on a playroom rug. Include small houses, one bridge, and a tower built from compatible flat panels. Selecting a building unfolds its panels into a matching arrangement beside the assembled model. Use colored edge markers to show which edges meet, and keep panel sizes unchanged during folding. Leave the other buildings assembled so the room still reads as a miniature city. A toy storage box and a few loose pieces can sit at the rug's edge. Make the folding order clear and prevent panels from intersecting as they move between flat and spatial configurations.
Working Three.js Starter (playroom-miniature-city-building-x0351):
```html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Little City, Big Fold</title>
<style>
:root {
--ink: #24343b;
--muted: #66757b;
--paper: rgba(255, 252, 244, 0.93);
--line: rgba(36, 52, 59, 0.13);
--accent: #e86f51;
--teal: #3f8f8a;
--shadow: 0 18px 45px rgba(46, 54, 52, 0.15);
}
* { box-sizing: border-box; }
html, body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: #e9e0d1;
color: var(--ink);
font-family: Inter, ui-sans-serif, system-ui, -apple-system,
BlinkMacSystemFont, "Segoe UI", sans-serif;
}
button { font: inherit; }
#app, #scene {
position: fixed;
inset: 0;
}
#scene canvas {
display: block;
width: 100%;
height: 100%;
touch-action: none;
cursor: grab;
}
#scene canvas.dragging { cursor: grabbing; }
.ui {
position: fixed;
inset: 0;
pointer-events: none;
z-index: 5;
}
.card {
background: var(--paper);
border: 1px solid rgba(255,255,255,0.72);
box-shadow: var(--shadow);
backdrop-filter: blur(14px);
-webkit-backdrop-filter: blur(14px);
border-radius: 18px;
}
#titleCard {
position: absolute;
top: 22px;
left: 22px;
width: min(360px, calc(100vw - 44px));
padding: 18px 20px 17px;
}
.eyebrow {
display: flex;
align-items: center;
gap: 8px;
margin-bottom: 6px;
color: var(--teal);
font-size: 10px;
font-weight: 800;
letter-spacing: 0.16em;
text-transform: uppercase;
}
.eyebrow::before {
content: "";
width: 18px;
height: 3px;
border-radius: 3px;
background: var(--accent);
}
h1 {
margin: 0;
font-size: clamp(24px, 3vw, 34px);
line-height: 1;
letter-spacing: -0.045em;
}
#titleCard p {
margin: 9px 0 0;
color: var(--muted);
font-size: 12px;
line-height: 1.55;
}
#toolbar {
position: absolute;
top: 22px;
right: 22px;
display: flex;
flex-wrap: wrap;
justify-content: flex-end;
gap: 8px;
max-width: min(520px, calc(100vw - 44px));
pointer-events: auto;
}
.tool {
appearance: none;
border: 1px solid rgba(36,52,59,0.12);
background: rgba(255,252,244,0.91);
color: var(--ink);
padding: 10px 13px;
border-radius: 12px;
box-shadow: 0 8px 20px rgba(46,54,52,0.10);
cursor: pointer;
font-size: 12px;
font-weight: 750;
transition: transform .16s ease, background .16s ease, opacity .16s ease;
}
.tool:hover:not(:disabled) {
transform: translateY(-2px);
background: #fffdf7;
}
.tool:disabled {
opacity: .42;
cursor: default;
}
.tool.active {
color: white;
background: var(--teal);
border-color: var(--teal);
}
#selectionCard {
position: absolute;
left: 22px;
bottom: 22px;
width: min(390px, calc(100vw - 44px));
padding: 17px 18px 16px;
transition: opacity .2s ease;
}
.selection-top {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 14px;
}
#buildingName {
margin: 0;
font-size: 20px;
letter-spacing: -.025em;
}
#panelCount {
flex: 0 0 auto;
padding: 5px 8px;
border-radius: 8px;
background: #edf2ef;
color: #49635e;
font-size: 10px;
font-weight: 800;
letter-spacing: .08em;
text-transform: uppercase;
}
#statusText {
min-height: 34px;
margin: 7px 0 12px;
color: var(--muted);
font-size: 12px;
line-height: 1.45;
}
#progressTrack {
height: 5px;
overflow: hidden;
border-radius: 10px;
background: #e7e4dc;
}
#progressFill {
width: 0;
height: 100%;
border-radius: inherit;
background: linear-gradient(90deg, var(--accent), #f3b54b);
transition: width .08s linear;
}
#steps {
display: grid;
grid-template-columns: repeat(4, 1fr);
gap: 5px;
margin-top: 12px;
}
.step {
min-width: 0;
padding: 7px 4px;
border-radius: 8px;
background: #efede6;
color: #8a9293;
text-align: center;
font-size: 9px;
font-weight: 800;
letter-spacing: .025em;
transition: color .2s ease, background .2s ease;
}
.step.current {
color: white;
background: var(--accent);
}
.step.done {
color: #356c67;
background: #dcece7;
}
#legend {
position: absolute;
right: 22px;
bottom: 22px;
width: min(285px, calc(100vw - 44px));
padding: 15px 16px;
color: var(--muted);
font-size: 11px;
line-height: 1.55;
}
#legend strong {
display: block;
margin-bottom: 4px;
color: var(--ink);
font-size: 12px;
}
.legend-row {
display: flex;
align-items: center;
gap: 9px;
margin-top: 8px;
}
.swatch {
width: 26px;
height: 7px;
border-radius: 5px;
background: linear-gradient(90deg, #e86554, #51a89e, #657ac8);
}
#gestureHint {
position: absolute;
left: 50%;
bottom: 25px;
transform: translateX(-50%);
padding: 8px 12px;
border-radius: 999px;
background: rgba(36,52,59,.78);
color: rgba(255,255,255,.92);
font-size: 10px;
font-weight: 700;
letter-spacing: .04em;
opacity: .88;
white-space: nowrap;
}
#hoverTip {
position: fixed;
z-index: 20;
display: none;
pointer-events: none;
padding: 7px 9px;
border-radius: 8px;
background: rgba(36,52,59,.9);
color: white;
font-size: 10px;
font-weight: 700;
box-shadow: 0 5px 15px rgba(0,0,0,.18);
transform: translate(12px, 12px);
}
@media (max-width: 760px) {
#titleCard {
top: 12px;
left: 12px;
width: calc(100vw - 24px);
padding: 13px 15px;
}
#titleCard p { display: none; }
#toolbar {
top: 101px;
left: 12px;
right: 12px;
max-width: none;
justify-content: flex-start;
}
.tool { padding: 8px 10px; font-size: 10px; }
#selectionCard {
left: 12px;
bottom: 12px;
width: calc(100vw - 24px);
padding: 13px 14px;
}
#legend, #gestureHint { display: none; }
}
</style>
</head>
<body>
<div id="app">
<div id="scene"></div>
<div class="ui">
<section id="titleCard" class="card">
<div class="eyebrow">Interactive voxel playroom</div>
<h1>Little City,<br>Big Fold</h1>
<p>
Pick a house, bridge, or tower. Its matching panels unfold into a
flat set while the rest of the city stays built.
</p>
</section>
<nav id="toolbar" aria-label="Scene controls">
<button id="foldBtn" class="tool" disabled>Fold back</button>
<button id="guidesBtn" class="tool active">Edge guides</button>
<button id="resetBtn" class="tool">Reset view</button>
</nav>
<section id="selectionCard" class="card">
<div class="selection-top">
<h2 id="buildingName">Choose a building</h2>
<span id="panelCount">0 panels</span>
</div>
<div id="statusText">
Click any colored building. The numbered order shows how its
panels safely lift, turn flat, and settle into the matching layout.
</div>
<div id="progressTrack"><div id="progressFill"></div></div>
<div id="steps">
<div class="step">Lift clear</div>
<div class="step">Separate</div>
<div class="step">Turn flat</div>
<div class="step">Seat in net</div>
</div>
</section>
<aside id="legend" class="card">
<strong>How the flat set works</strong>
Every colored edge marker has a matching partner. Guides connect the
paired edges, while the numbered badge shows the active fold order.
<div class="legend-row"><span class="swatch"></span> Paired edge colors</div>
</aside>
<div id="gestureHint">
DRAG TO ORBIT · RIGHT-DRAG TO PAN · SCROLL TO ZOOM
</div>
</div>
<div id="hoverTip"></div>
</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 renderer
// -------------------------------------------------------------------------
const PANEL_SIZE = 0.76;
const PANEL_THICKNESS = 0.12;
const PANEL_SPACING = 0.82;
const BASE_Y = 0.08;
const LIFT = 0.75;
const sceneHost = document.getElementById("scene");
const scene = new THREE.Scene();
scene.background = new THREE.Color(0xe9e0d1);
scene.fog = new THREE.Fog(0xe9e0d1, 30, 58);
const camera = new THREE.PerspectiveCamera(
43,
innerWidth / innerHeight,
0.1,
100
);
const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setSize(innerWidth, innerHeight);
renderer.setPixelRatio(Math.min(devicePixelRatio, 2));
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.08;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
sceneHost.appendChild(renderer.domElement);
const clock = new THREE.Clock();
// -------------------------------------------------------------------------
// Custom camera controls: orbit, pan and zoom, implemented without addons.
// -------------------------------------------------------------------------
const controls = {
target: new THREE.Vector3(0, 0.15, 0),
theta: 0.06,
phi: 0.79,
radius: 19.5,
home: {
target: new THREE.Vector3(0, 0.15, 0),
theta: 0.06,
phi: 0.79,
radius: 19.5
}
};
function updateCamera() {
const s = Math.sin(controls.phi);
camera.position.set(
controls.target.x + controls.radius * s * Math.sin(controls.theta),
controls.target.y + controls.radius * Math.cos(controls.phi),
controls.target.z + controls.radius * s * Math.cos(controls.theta)
);
camera.lookAt(controls.target);
}
updateCamera();
// -------------------------------------------------------------------------
// Lights and room
// -------------------------------------------------------------------------
scene.add(new THREE.HemisphereLight(0xfff6e6, 0x8c9b96, 2.0));
const sun = new THREE.DirectionalLight(0xfff1d9, 3.1);
sun.position.set(-8, 15, 9);
sun.castShadow = true;
sun.shadow.mapSize.set(2048, 2048);
sun.shadow.camera.left = -16;
sun.shadow.camera.right = 16;
sun.shadow.camera.top = 14;
sun.shadow.camera.bottom = -14;
sun.shadow.camera.near = 1;
sun.shadow.camera.far = 38;
sun.shadow.bias = -0.00035;
sun.shadow.normalBias = 0.025;
scene.add(sun);
const fill = new THREE.DirectionalLight(0xb9d9e4, 0.8);
fill.position.set(10, 8, -8);
scene.add(fill);
const floor = new THREE.Mesh(
new THREE.PlaneGeometry(45, 34),
new THREE.MeshStandardMaterial({
color: 0xd8cbb6,
roughness: 0.92
})
);
floor.rotation.x = -Math.PI / 2;
floor.position.y = -0.045;
floor.receiveShadow = true;
scene.add(floor);
const backWall = new THREE.Mesh(
new THREE.BoxGeometry(34, 10, 0.24),
new THREE.MeshStandardMaterial({
color: 0xe5ded2,
roughness: 0.95
})
);
backWall.position.set(0, 4.9, -11.5);
backWall.receiveShadow = true;
scene.add(backWall);
const baseboard = new THREE.Mesh(
new THREE.BoxGeometry(34, 0.32, 0.32),
new THREE.MeshStandardMaterial({ color: 0xf5f0e7, roughness: 0.8 })
);
baseboard.position.set(0, 0.12, -11.3);
scene.add(baseboard);
// A simple playroom window.
const windowGroup = new THREE.Group();
windowGroup.position.set(-7.2, 5.0, -11.34);
scene.add(windowGroup);
const windowSky = new THREE.Mesh(
new THREE.PlaneGeometry(3.9, 2.65),
new THREE.MeshStandardMaterial({
color: 0x9dcbd7,
emissive: 0x416b74,
emissiveIntensity: 0.12,
roughness: 0.6
})
);
windowGroup.add(windowSky);
const frameMat = new THREE.MeshStandardMaterial({
color: 0xf8f2e8,
roughness: 0.72
});
const framePieces = [
[4.2, 0.16, 0.12, 0, 1.42, 0.06],
[4.2, 0.16, 0.12, 0, -1.42, 0.06],
[0.16, 3.0, 0.12, -2.08, 0, 0.06],
[0.16, 3.0, 0.12, 2.08, 0, 0.06],
[0.11, 2.8, 0.12, 0, 0, 0.08],
[4.1, 0.11, 0.12, 0, 0, 0.08]
];
for (const [w, h, d, x, y, z] of framePieces) {
const m = new THREE.Mesh(new THREE.BoxGeometry(w, h, d), frameMat);
m.position.set(x, y, z);
m.castShadow = true;
windowGroup.add(m);
}
// A pair of simple framed pictures.
function addWallArt(x, y, color) {
const art = new THREE.Group();
art.position.set(x, y, -11.31);
const backing = new THREE.Mesh(
new THREE.BoxGeometry(1.7, 2.1, 0.09),
new THREE.MeshStandardMaterial({ color: 0xf7f0e4, roughness: 0.8 })
);
const picture = new THREE.Mesh(
new THREE.BoxGeometry(1.28, 1.65, 0.06),
new THREE.MeshStandardMaterial({ color, roughness: 0.85 })
);
picture.position.z = 0.08;
art.add(backing, picture);
scene.add(art);
}
addWallArt(7.8, 5.1, 0xe59b76);
addWallArt(9.8, 4.7, 0x75aaa4);
// -------------------------------------------------------------------------
// Rug and a small river beneath the bridge
// -------------------------------------------------------------------------
function roundedRectPath(ctx, x, y, w, h, r) {
ctx.beginPath();
ctx.moveTo(x + r, y);
ctx.lineTo(x + w - r, y);
ctx.quadraticCurveTo(x + w, y, x + w, y + r);
ctx.lineTo(x + w, y + h - r);
ctx.quadraticCurveTo(x + w, y + h, x + w - r, y + h);
ctx.lineTo(x + r, y + h);
ctx.quadraticCurveTo(x, y + h, x, y + h - r);
ctx.lineTo(x, y + r);
ctx.quadraticCurveTo(x, y, x + r, y);
ctx.closePath();
}
function makeRugTexture() {
const canvas = document.createElement("canvas");
canvas.width = 1024;
canvas.height = 666;
const ctx = canvas.getContext("2d");
ctx.clearRect(0, 0, canvas.width, canvas.height);
roundedRectPath(ctx, 8, 8, 1008, 650, 58);
ctx.fillStyle = "#d8caa8";
ctx.fill();
roundedRectPath(ctx, 28, 28, 968, 610, 44);
ctx.strokeStyle = "#6d9d98";
ctx.lineWidth = 16;
ctx.stroke();
roundedRectPath(ctx, 48, 48, 928, 570, 32);
ctx.strokeStyle = "rgba(255,255,255,.36)";
ctx.lineWidth = 3;
ctx.setLineDash([13, 10]);
ctx.stroke();
ctx.setLineDash([]);
const colors = ["#e9b28f", "#8db8af", "#e4c869", "#aab8c9"];
for (let row = 0; row < 5; row++) {
for (let col = 0; col < 8; col++) {
ctx.save();
ctx.translate(125 + col * 108, 113 + row * 105);
ctx.rotate(Math.PI / 4);
ctx.globalAlpha = 0.17;
ctx.fillStyle = colors[(row + col) % colors.length];
ctx.fillRect(-15, -15, 30, 30);
ctx.restore();
}
}
ctx.globalAlpha = 0.13;
ctx.fillStyle = "#fff8e8";
for (let i = 0; i < 44; i++) {
const x = 90 + (i * 193) % 850;
const y = 90 + (i * 83) % 480;
ctx.beginPath();
ctx.arc(x, y, 3, 0, Math.PI * 2);
ctx.fill();
}
const texture = new THREE.CanvasTexture(canvas);
texture.colorSpace = THREE.SRGBColorSpace;
texture.anisotropy = Math.min(8, renderer.capabilities.getMaxAnisotropy());
return texture;
}
const rug = new THREE.Mesh(
new THREE.PlaneGeometry(20, 13),
new THREE.MeshStandardMaterial({
map: makeRugTexture(),
transparent: true,
alphaTest: 0.03,
roughness: 0.95
})
);
rug.rotation.x = -Math.PI / 2;
rug.position.y = -0.005;
rug.receiveShadow = true;
scene.add(rug);
function roundedRectShape(w, h, r) {
const shape = new THREE.Shape();
const x = -w / 2;
const y = -h / 2;
shape.moveTo(x + r, y);
shape.lineTo(x + w - r, y);
shape.quadraticCurveTo(x + w, y, x + w, y + r);
shape.lineTo(x + w, y + h - r);
shape.quadraticCurveTo(x + w, y + h, x + w - r, y + h);
shape.lineTo(x + r, y + h);
shape.quadraticCurveTo(x, y + h, x, y + h - r);
shape.lineTo(x, y + r);
shape.quadraticCurveTo(x, y, x + r, y);
return shape;
}
const river = new THREE.Mesh(
new THREE.ShapeGeometry(roundedRectShape(8.5, 1.5, 0.35)),
new THREE.MeshStandardMaterial({
color: 0x73b5bd,
roughness: 0.75
})
);
river.rotation.x = -Math.PI / 2;
river.position.set(0, 0.012, -0.2);
river.receiveShadow = true;
scene.add(river);
// -------------------------------------------------------------------------
// Shared panel geometry
// -------------------------------------------------------------------------
const panelGeometry = new THREE.BoxGeometry(
PANEL_SIZE,
PANEL_SIZE,
PANEL_THICKNESS
);
const panelEdgesGeometry = new THREE.EdgesGeometry(panelGeometry);
const panelEdgeMaterial = new THREE.LineBasicMaterial({
color: 0x42545a,
transparent: true,
opacity: 0.28
});
const horizontalQuaternion = new THREE.Quaternion().setFromEuler(
new THREE.Euler(-Math.PI / 2, 0, 0)
);
const qFront = new THREE.Quaternion();
const qBack = new THREE.Quaternion().setFromAxisAngle(
new THREE.Vector3(0, 1, 0), Math.PI
);
const qRight = new THREE.Quaternion().setFromAxisAngle(
new THREE.Vector3(0, 1, 0), Math.PI / 2
);
const qLeft = new THREE.Quaternion().setFromAxisAngle(
new THREE.Vector3(0, 1, 0), -Math.PI / 2
);
const buildings = [];
const allPanels = [];
const panelMeshes = [];
let selectedBuilding = null;
let hoveredPanel = null;
let showGuides = true;
// -------------------------------------------------------------------------
// Labels
// -------------------------------------------------------------------------
function roundedRectCanvas(ctx, x, y, w, h, r) {
ctx.beginPath();
ctx.moveTo(x + r, y);
ctx.lineTo(x + w - r, y);
ctx.quadraticCurveTo(x + w, y, x + w, y + r);
ctx.lineTo(x + w, y + h - r);
ctx.quadraticCurveTo(x + w, y + h, x + w - r, y + h);
ctx.lineTo(x + r, y + h);
ctx.quadraticCurveTo(x, y + h, x, y + h - r);
ctx.lineTo(x, y + r);
ctx.quadraticCurveTo(x, y, x + r, y);
ctx.closePath();
}
function createLabel(text, accent = "#3f8f8a", subtext = "") {
const canvas = document.createElement("canvas");
canvas.width = 512;
canvas.height = 128;
const ctx = canvas.getContext("2d");
roundedRectCanvas(ctx, 8, 8, 496, 112, 28);
ctx.fillStyle = "rgba(255,252,244,.95)";
ctx.fill();
ctx.strokeStyle = accent;
ctx.lineWidth = 6;
ctx.stroke();
ctx.fillStyle = accent;
ctx.beginPath();
ctx.arc(46, 64, 13, 0, Math.PI * 2);
ctx.fill();
ctx.textAlign = "left";
ctx.textBaseline = "middle";
ctx.fillStyle = "#24343b";
ctx.font = "800 38px system-ui, sans-serif";
ctx.fillText(text, 76, subtext ? 50 : 64);
if (subtext) {
ctx.fillStyle = "#718087";
ctx.font = "700 22px system-ui, sans-serif";
ctx.fillText(subtext, 76, 86);
}
const texture = new THREE.CanvasTexture(canvas);
texture.colorSpace = THREE.SRGBColorSpace;
const material = new THREE.SpriteMaterial({
map: texture,
transparent: true,
depthTest: false,
depthWrite: false
});
const sprite = new THREE.Sprite(material);
sprite.scale.set(2.15, 0.54, 1);
sprite.renderOrder = 7;
return sprite;
}
// -------------------------------------------------------------------------
// Buildings and panels
// -------------------------------------------------------------------------
function createBuilding({
name,
description,
x,
z,
netX,
netZ,
accent
}) {
const building = {
name,
description,
x,
z,
netX,
netZ,
accent,
group: new THREE.Group(),
panels: [],
pairs: [],
mode: "assembled",
anim: null,
flatLabel: null,
phaseAngle: Math.random() * Math.PI * 2
};
building.group.position.set(x, 0, z);
scene.add(building.group);
buildings.push(building);
return building;
}
function addPanel(
building,
position,
quaternion,
color,
category,
assemblyOrder,
escape = new THREE.Vector3(0, 0, 1)
) {
const root = new THREE.Group();
root.position.copy(position);
root.quaternion.copy(quaternion);
const material = new THREE.MeshStandardMaterial({
color,
roughness: 0.72,
metalness: 0.0
});
const mesh = new THREE.Mesh(panelGeometry, material);
mesh.castShadow = true;
mesh.receiveShadow = true;
const edges = new THREE.LineSegments(
panelEdgesGeometry,
panelEdgeMaterial
);
root.add(mesh, edges);
const panel = {
building,
root,
mesh,
material,
edges,
assembledPos: position.clone(),
assembledQuat: quaternion.clone(),
flatPos: new THREE.Vector3(),
flatQuat: horizontalQuaternion.clone(),
category,
assemblyOrder,
escape: escape.clone(),
markers: [],
number: 0,
originalIndex: allPanels.length
};
mesh.userData.panel = panel;
building.group.add(root);
building.panels.push(panel);
allPanels.push(panel);
panelMeshes.push(mesh);
return panel;
}
function addFootprint(building, colors, roofColor) {
for (let iz = -1; iz <= 1; iz++) {
for (let ix = -1; ix <= 1; ix++) {
addPanel(
building,
new THREE.Vector3(
ix * PANEL_SPACING,
BASE_Y,
iz * PANEL_SPACING
),
horizontalQuaternion,
colors[(ix + iz + 2) % colors.length],
"base",
0,
new THREE.Vector3(0, 0, 1)
);
}
}
}
function addHouseWalls(building, layers, wallColors, roofColor) {
const face = PANEL_SPACING + PANEL_SIZE / 2 + 0.03;
const wallBottom = BASE_Y + PANEL_THICKNESS / 2 + 0.01;
const wallCenter = wallBottom + PANEL_SIZE / 2;
for (let layer = 0; layer < layers; layer++) {
const y = wallCenter + layer * PANEL_SIZE;
const order = 1 + layer * 0.1;
for (let ix = -1; ix <= 1; ix++) {
addPanel(
building,
new THREE.Vector3(ix * PANEL_SPACING, y, face),
qFront,
wallColors[(ix + layer + 2) % wallColors.length],
"wall",
order,
new THREE.Vector3(0, 0, 1)
);
addPanel(
building,
new THREE.Vector3(ix * PANEL_SPACING, y, -face),
qBack,
wallColors[(ix + layer + 1) % wallColors.length],
"wall",
order,
new THREE.Vector3(0, 0, -1)
);
}
addPanel(
building,
new THREE.Vector3(face, y, 0),
qRight,
wallColors[(layer + 1) % wallColors.length],
"wall",
order,
new THREE.Vector3(1, 0, 0)
);
addPanel(
building,
new THREE.Vector3(-face, y, 0),
qLeft,
wallColors[layer % wallColors.length],
"wall",
order,
new THREE.Vector3(-1, 0, 0)
);
}
const roofY = wallCenter + (layers - 1) * PANEL_SIZE
+ PANEL_SIZE / 2 + 0.06;
for (let iz = -1; iz <= 1; iz++) {
for (let ix = -1; ix <= 1; ix++) {
addPanel(
building,
new THREE.Vector3(
ix * PANEL_SPACING,
roofY,
iz * PANEL_SPACING
),
horizontalQuaternion,
roofColor,
"roof",
3,
new THREE.Vector3(0, 1, 0)
);
}
}
}
const cottage = createBuilding({
name: "Rosewood Cottage",
description: "A coral-roofed home with two stacked wall courses.",
x: -5.25,
z: -3.65,
netX: -5.0,
netZ: 2.65,
accent: "#e86f51"
});
addFootprint(cottage, [0xf1d6a5, 0xf7e8c8], 0xdc715c);
addHouseWalls(
cottage,
2,
[0xf2d6a9, 0xf7ead1, 0xe9b8a7],
0xd96855
);
const littleHouse = createBuilding({
name: "Mint Cottage",
description: "A compact single-course house with a sunny roof.",
x: -0.7,
z: -4.55,
netX: -0.8,
netZ: 3.05,
accent: "#4d9b8f"
});
addFootprint(littleHouse, [0xc9ded2, 0xf3e7c9], 0xe5b84f);
addHouseWalls(
littleHouse,
1,
[0xbad7c9, 0xe4ead3, 0xf1d8b6],
0xe4b348
);
const tower = createBuilding({
name: "Blue Watchtower",
description: "Four high wall courses built from the same square panels.",
x: 4.65,
z: -3.25,
netX: 4.55,
netZ: 2.7,
accent: "#657ac8"
});
addFootprint(tower, [0xaabbd0, 0xd6e0e5], 0xe4b84f);
addHouseWalls(
tower,
4,
[0x708bc4, 0x9eb5d4, 0xe6dcc1, 0x7693c8],
0xe5b84f
);
const bridge = createBuilding({
name: "Rainbow Bridge",
description: "A deck, two side rails, and four supporting piers.",
x: 0,
z: -0.2,
netX: 0,
netZ: 3.05,
accent: "#df9a57"
});
// Bridge piers.
for (const px of [-1.64, 1.64]) {
for (const pz of [-0.41, 0.41]) {
addPanel(
bridge,
new THREE.Vector3(px, 0.49, pz),
pz > 0 ? qFront : qBack,
0x61748d,
"pier",
0,
new THREE.Vector3(0, 0, pz > 0 ? 1 : -1)
);
}
}
// Bridge deck.
for (let ix = 0; ix < 6; ix++) {
for (let iz = 0; iz < 2; iz++) {
addPanel(
bridge,
new THREE.Vector3(
(ix - 2.5) * PANEL_SPACING,
0.93,
(iz - 0.5) * PANEL_SPACING
),
horizontalQuaternion,
(ix + iz) % 2 ? 0xf0ba76 : 0xe9a961,
"deck",
1,
new THREE.Vector3(0, 1, 0)
);
}
}
// Bridge rails.
for (const side of [-1, 1]) {
for (let ix = 0; ix < 6; ix++) {
addPanel(
bridge,
new THREE.Vector3(
(ix - 2.5) * PANEL_SPACING,
1.31,
side * 0.86
),
side > 0 ? qFront : qBack,
side > 0 ? 0x4a9991 : 0x63aaa1,
"rail",
2,
new THREE.Vector3(0, 0, side)
);
}
}
// Building labels.
function placeLabel(label, { position }) {
label.position.copy(position);
return label;
}
cottage.group.add(
placeLabel(
createLabel("ROSEWOOD", "#e86f51", "COTTAGE"),
{ position: new THREE.Vector3(0, 2.35, 0) }
)
);
littleHouse.group.add(
placeLabel(
createLabel("MINT", "#4d9b8f", "COTTAGE"),
{ position: new THREE.Vector3(0, 1.85, 0) }
)
);
tower.group.add(
placeLabel(
createLabel("WATCHTOWER", "#657ac8", "4 COURSES"),
{ position: new THREE.Vector3(0, 3.85, 0) }
)
);
bridge.group.add(
placeLabel(
createLabel("RAINBOW", "#df9a57", "BRIDGE"),
{ position: new THREE.Vector3(0, 1.95, 0) }
)
);
// -------------------------------------------------------------------------
// Storage box and loose pieces at the rug edge
// -------------------------------------------------------------------------
const storage = new THREE.Group();
storage.position.set(8.05, 0, -4.65);
scene.add(storage);
const boxMat = new THREE.MeshStandardMaterial({
color: 0x5d91ad,
roughness: 0.76
});
const boxInsideMat = new THREE.MeshStandardMaterial({
color: 0x416f88,
roughness: 0.85
});
function boxPart(w, h, d, x, y, z, material = boxMat) {
const mesh = new THREE.Mesh(
new THREE.BoxGeometry(w, h, d),
material
);
mesh.position.set(x, y, z);
mesh.castShadow = true;
mesh.receiveShadow = true;
storage.add(mesh);
return mesh;
}
boxPart(2.55, 0.18, 1.75, 0, 0.12, 0, boxInsideMat);
boxPart(2.55, 1.05, 0.15, 0, 0.66, 0.86);
boxPart(2.55, 1.05, 0.15, 0, 0.66, -0.86);
boxPart(0.15, 1.05, 1.55, 1.22, 0.66, 0);
boxPart(0.15, 1.05, 1.55, -1.22, 0.66, 0);
const storageLabel = createLabel("BLOCKS", "#5d91ad", "TOY BOX");
storageLabel.scale.set(1.45, 0.36, 1);
storageLabel.position.set(0, 1.46, 0);
storage.add(storageLabel);
const looseColors = [0xe7a45e, 0x69aaa1, 0xe47b67, 0x8196c9, 0xe9d27b];
for (let i = 0; i < 5; i++) {
const loose = new THREE.Mesh(
panelGeometry,
new THREE.MeshStandardMaterial({
color: looseColors[i],
roughness: 0.75
})
);
const standing = i % 2 === 0;
if (standing) {
loose.rotation.set(0, (i - 2) * 0.23, 0);
} else {
loose.rotation.set(-Math.PI / 2, 0, (i - 2) * 0.4);
}
loose.position.set(
6.75 + (i % 3) * 0.42,
standing ? 0.43 : 0.08,
-3.65 + Math.floor(i / 3) * 0.52
);
loose.castShadow = true;
loose.receiveShadow = true;
scene.add(loose);
}
// -------------------------------------------------------------------------
// Edge matching: identify touching panel edges and assign paired colors.
// -------------------------------------------------------------------------
function edgeVector(slot) {
const h = PANEL_SIZE / 2;
switch (slot) {
case 0: return new THREE.Vector3(0, h, 0);
case 1: return new THREE.Vector3(h, 0, 0);
case 2: return new THREE.Vector3(0, -h, 0);
default: return new THREE.Vector3(-h, 0, 0);
}
}
function edgeMidpoint(panel, slot) {
return edgeVector(slot)
.applyQuaternion(panel.assembledQuat)
.add(panel.assembledPos);
}
function addEdgeMarker(panel, slot, color) {
const h = PANEL_SIZE / 2;
const horizontal = slot === 0 || slot === 2;
const marker = new THREE.Mesh(
new THREE.BoxGeometry(
horizontal ? PANEL_SIZE * 0.28 : 0.055,
horizontal ? 0.055 : PANEL_SIZE * 0.28,
0.055
),
new THREE.MeshBasicMaterial({ color })
);
if (slot === 0) marker.position.set(0, h, PANEL_THICKNESS / 2 + 0.03);
if (slot === 1) marker.position.set(h, 0, PANEL_THICKNESS / 2 + 0.03);
if (slot === 2) marker.position.set(0, -h, PANEL_THICKNESS / 2 + 0.03);
if (slot === 3) marker.position.set(-h, 0, PANEL_THICKNESS / 2 + 0.03);
panel.root.add(marker);
panel.markers[slot] = marker;
return marker;
}
function findEdgePairs(building) {
const candidates = new Map();
for (const panel of building.panels) {
for (let slot = 0; slot < 4; slot++) {
const a = edgeMidpoint(panel, slot);
let best = null;
let bestDistance = Infinity;
for (const other of building.panels) {
if (other === panel) continue;
for (let otherSlot = 0; otherSlot < 4; otherSlot++) {
const b = edgeMidpoint(other, otherSlot);
const distance = a.distanceTo(b);
if (distance < bestDistance) {
bestDistance = distance;
best = { panel: other, slot: otherSlot, distance };
}
}
}
if (best && best.distance < 0.14) {
candidates.set(`${panel.originalIndex}:${slot}`, {
panel,
slot,
other: best.panel,
otherSlot: best.slot,
distance: best.distance
});
}
}
}
const used = new Set();
const pairs = [];
const sorted = [...candidates.values()].sort((a, b) => a.distance - b.distance);
for (const candidate of sorted) {
const aKey = `${candidate.panel.originalIndex}:${candidate.slot}`;
const bKey = `${candidate.other.originalIndex}:${candidate.otherSlot}`;
const reverse = candidates.get(bKey);
if (used.has(aKey) || used.has(bKey)) continue;
if (!reverse || reverse.other !== candidate.panel || reverse.otherSlot !== candidate.slot) {
continue;
}
used.add(aKey);
used.add(bKey);
const color = new THREE.Color().setHSL(
(pairs.length * 0.61803398875) % 1,
0.72,
0.53
);
const pair = {
panelA: candidate.panel,
slotA: candidate.slot,
panelB: candidate.other,
slotB: candidate.otherSlot,
color,
markerA: null,
markerB: null
};
pair.markerA = addEdgeMarker(candidate.panel, candidate.slot, color);
pair.markerB = addEdgeMarker(candidate.other, candidate.otherSlot, color);
pairs.push(pair);
}
building.pairs = pairs;
}
buildings.forEach(findEdgePairs);
// -------------------------------------------------------------------------
// Ghost assembled model and guide-line geometry
// -------------------------------------------------------------------------
for (const building of buildings) {
const ghost = new THREE.Group();
ghost.position.set(building.x, 0, building.z);
const ghostMat = new THREE.MeshBasicMaterial({
color: 0x789096,
transparent: true,
opacity: 0.095,
depthWrite: false
});
const ghostEdgeMat = new THREE.LineBasicMaterial({
color: 0x667b80,
transparent: true,
opacity: 0.25
});
for (const panel of building.panels) {
const mesh = new THREE.Mesh(panelGeometry, ghostMat);
mesh.position.copy(panel.assembledPos);
mesh.quaternion.copy(panel.assembledQuat);
const edges = new THREE.LineSegments(
panelEdgesGeometry,
ghostEdgeMat
);
edges.position.copy(mesh.position);
edges.quaternion.copy(mesh.quaternion);
ghost.add(mesh, edges);
}
ghost.visible = false;
scene.add(ghost);
building.ghost = ghost;
const positions = new Float32Array(building.pairs.length * 6);
const colors = new Float32Array(building.pairs.length * 6);
for (let i = 0; i < building.pairs.length; i++) {
const pair = building.pairs[i];
const c = pair.color;
for (let j = 0; j < 2; j++) {
colors[i * 6 + j * 3] = c.r;
colors[i * 6 + j * 3 + 1] = c.g;
colors[i * 6 + j * 3 + 2] = c.b;
}
}
const geometry = new THREE.BufferGeometry();
geometry.setAttribute(
"position",
new THREE.BufferAttribute(positions, 3).setUsage(THREE.DynamicDrawUsage)
);
geometry.setAttribute(
"color",
new THREE.BufferAttribute(colors, 3)
);
const material = new THREE.LineBasicMaterial({
vertexColors: true,
transparent: true,
opacity: 0.42,
depthTest: false,
depthWrite: false
});
const lines = new THREE.LineSegments(geometry, material);
lines.renderOrder = 8;
lines.frustumCulled = false;
lines.visible = false;
scene.add(lines);
building.guideLines = lines;
}
// -------------------------------------------------------------------------
// Flat layouts
// -------------------------------------------------------------------------
for (const building of buildings) {
const unfoldPanels = [...building.panels].sort((a, b) => {
if (b.assemblyOrder !== a.assemblyOrder) {
return b.assemblyOrder - a.assemblyOrder;
}
return a.originalIndex - b.originalIndex;
});
const count = unfoldPanels.length;
const cols = Math.min(10, Math.max(4, Math.ceil(Math.sqrt(count * 1.45))));
const rows = Math.ceil(count / cols);
const spacing = PANEL_SIZE + 0.12;
unfoldPanels.forEach((panel, index) => {
const col = index % cols;
const row = Math.floor(index / cols);
panel.number = index + 1;
panel.flatPos.set(
building.netX - building.x
+ (col - (cols - 1) / 2) * spacing,
BASE_Y,
building.netZ - building.z
+ (row - (rows - 1) / 2) * spacing
);
});
building.unfoldPanels = unfoldPanels;
building.foldPanels = [...building.panels].sort((a, b) => {
if (a.assemblyOrder !== b.assemblyOrder) {
return a.assemblyOrder - b.assemblyOrder;
}
return a.originalIndex - b.originalIndex;
});
building.laneY =
Math.max(...building.panels.map(p => p.assembledPos.y))
+ LIFT + 1.65;
const flatLabel = createLabel(
building.name.toUpperCase(),
building.accent,
"FLAT MATCHING SET"
);
flatLabel.scale.set(2.7, 0.58, 1);
flatLabel.position.set(
building.netX,
0.42,
building.netZ - rows * spacing / 2 - 0.38
);
flatLabel.visible = false;
scene.add(flatLabel);
building.flatLabel = flatLabel;
}
// -------------------------------------------------------------------------
// Number badge for the currently moving panel
// -------------------------------------------------------------------------
const badgeCanvas = document.createElement("canvas");
badgeCanvas.width = 128;
badgeCanvas.height = 128;
const badgeCtx = badgeCanvas.getContext("2d");
const badgeTexture = new THREE.CanvasTexture(badgeCanvas);
badgeTexture.colorSpace = THREE.SRGBColorSpace;
const badgeSprite = new THREE.Sprite(
new THREE.SpriteMaterial({
map: badgeTexture,
transparent: true,
depthTest: false,
depthWrite: false
})
);
badgeSprite.scale.set(0.48, 0.48, 1);
badgeSprite.renderOrder = 20;
badgeSprite.visible = false;
scene.add(badgeSprite);
let badgeNumber = -1;
function setBadge(number) {
if (number === badgeNumber) return;
badgeNumber = number;
badgeCtx.clearRect(0, 0, 128, 128);
badgeCtx.fillStyle = "rgba(36,52,59,.94)";
badgeCtx.beginPath();
badgeCtx.arc(64, 64, 46, 0, Math.PI * 2);
badgeCtx.fill();
badgeCtx.strokeStyle = "#fff8e9";
badgeCtx.lineWidth = 6;
badgeCtx.stroke();
badgeCtx.fillStyle = "#fff8e9";
badgeCtx.font = "900 50px system-ui, sans-serif";
badgeCtx.textAlign = "center";
badgeCtx.textBaseline = "middle";
badgeCtx.fillText(String(number), 64, 67);
badgeTexture.needsUpdate = true;
}
// -------------------------------------------------------------------------
// Safe unfold / fold animation
//
// Every panel follows a collision-safe route:
// 1. the whole structure lifts clear;
// 2. one panel at a time rises above all stationary panels;
// 3. it travels through a high, dedicated lane;
// 4. it turns flat and lowers into a non-overlapping grid cell.
//
// Reassembly reverses the process and inserts base panels first,
// walls next, and roofs/decks last.
// -------------------------------------------------------------------------
function setPanelTransform(panel, position, quaternion) {
panel.root.position.copy(position);
panel.root.quaternion.copy(quaternion);
}
function beginUnfold(building) {
if (building.mode === "unfolding") return;
building.mode = "unfolding";
building.ghost.visible = true;
const now = performance.now() * 0.001;
const stagger = building.panels.length > 45 ? 0.034 : 0.044;
const liftDuration = 0.78;
const panelDuration = 0.86;
building.anim = {
kind: "unfold",
start: now,
stagger,
liftDuration,
panelDuration,
total: liftDuration
+ (building.unfoldPanels.length - 1) * stagger
+ panelDuration,
activeIndex: -1,
step: 0
};
}
function snapToFlat(building) {
for (const panel of building.panels) {
setPanelTransform(panel, panel.flatPos, panel.flatQuat);
}
building.mode = "flat";
building.anim = null;
building.ghost.visible = true;
}
function beginFold(building, clearSelectionAtEnd = false) {
if (building.mode !== "flat") return;
building.mode = "folding";
building.ghost.visible = true;
const now = performance.now() * 0.001;
const stagger = building.panels.length > 45 ? 0.034 : 0.042;
const panelDuration = 0.94;
building.anim = {
kind: "fold",
start: now,
stagger,
panelDuration,
total: (building.foldPanels.length - 1) * stagger + panelDuration,
activeIndex: -1,
step: 0,
clearSelectionAtEnd
};
}
const tempA = new THREE.Vector3();
const tempB = new THREE.Vector3();
const tempC = new THREE.Vector3();
const tempQ = new THREE.Quaternion();
function lanePosition(building, index, panel) {
const angle = building.phaseAngle + index * 2.39996323;
const radius = 3.05 + (index % 7) * 0.39;
return tempC.set(
Math.cos(angle) * radius,
building.laneY,
Math.sin(angle) * radius
);
}
function updateUnfold(building, now) {
const anim = building.anim;
const t = now - anim.start;
if (t < anim.liftDuration) {
for (const panel of building.panels) {
setPanelTransform(
panel,
tempA.copy(panel.assembledPos).add(new THREE.Vector3(0, LIFT, 0)),
panel.assembledQuat
);
}
anim.activeIndex = -1;
anim.step = 0;
return;
}
let activeIndex = -1;
let activeU = 0;
building.unfoldPanels.forEach((panel, index) => {
const start = anim.liftDuration + index * anim.stagger;
const u = (t - start) / anim.panelDuration;
if (u <= 0) {
setPanelTransform(
panel,
tempA.copy(panel.assembledPos).add(new THREE.Vector3(0, LIFT, 0)),
panel.assembledQuat
);
return;
}
if (u >= 1) {
setPanelTransform(panel, panel.flatPos, panel.flatQuat);
return;
}
activeIndex = index;
activeU = u;
const p0 = tempA.copy(panel.assembledPos).add(new THREE.Vector3(0, LIFT, 0));
const p1 = p0.clone().add(new THREE.Vector3(0, 0.85, 0));
const p2 = lanePosition(building, index, panel).clone();
const p3 = panel.flatPos.clone();
p3.y = building.laneY;
const p4 = panel.flatPos.clone();
let position;
if (u < 0.14) {
position = tempB.copy(p0).lerp(p1, u / 0.14);
setPanelTransform(panel, position, panel.assembledQuat);
} else if (u < 0.38) {
position = tempB.copy(p1).lerp(p2, (u - 0.14) / 0.24);
setPanelTransform(panel, position, panel.assembledQuat);
} else if (u < 0.52) {
tempQ.copy(panel.assembledQuat).slerp(
panel.flatQuat,
(u - 0.38) / 0.14
);
setPanelTransform(panel, p2, tempQ);
} else if (u < 0.80) {
position = tempB.copy(p2).lerp(p3, (u - 0.52) / 0.28);
setPanelTransform(panel, position, panel.flatQuat);
} else {
position = tempB.copy(p3).lerp(p4, (u - 0.80) / 0.20);
setPanelTransform(panel, position, panel.flatQuat);
}
});
anim.activeIndex = activeIndex;
anim.step = activeIndex < 0 ? 0
: activeU < 0.38 ? 1
: activeU < 0.52 ? 2
: 3;
}
function updateFold(building, now) {
const anim = building.anim;
const t = now - anim.start;
let activeIndex = -1;
let activeU = 0;
building.foldPanels.forEach((panel, index) => {
const start = index * anim.stagger;
const u = (t - start) / anim.panelDuration;
if (u <= 0) {
setPanelTransform(panel, panel.flatPos, panel.flatQuat);
return;
}
if (u >= 1) {
setPanelTransform(panel, panel.assembledPos, panel.assembledQuat);
return;
}
activeIndex = index;
activeU = u;
const p0 = panel.flatPos.clone();
const p1 = p0.clone();
p1.y = building.laneY;
const p2 = lanePosition(building, index, panel).clone();
let approach = panel.assembledPos.clone();
let insertionY = panel.assembledPos.y;
if (panel.category === "base") {
approach.addScaledVector(panel.escape, 1.65);
} else if (panel.category === "wall" || panel.category === "rail") {
approach.addScaledVector(panel.escape, 1.65);
} else if (panel.category === "roof" || panel.category === "deck") {
insertionY += 0.70;
} else if (panel.category === "pier") {
insertionY += 0.80;
}
const p3 = approach.clone();
p3.y = building.laneY;
const p4 = approach.clone();
p4.y = insertionY;
const p5 = panel.assembledPos.clone();
let position;
if (u < 0.14) {
position = tempB.copy(p0).lerp(p1, u / 0.14);
setPanelTransform(panel, position, panel.flatQuat);
} else if (u < 0.34) {
position = tempB.copy(p1).lerp(p2, (u - 0.14) / 0.20);
setPanelTransform(panel, position, panel.flatQuat);
} else if (u < 0.50) {
tempQ.copy(panel.flatQuat).slerp(
panel.assembledQuat,
(u - 0.34) / 0.16
);
setPanelTransform(panel, p2, tempQ);
} else if (u < 0.70) {
position = tempB.copy(p2).lerp(p3, (u - 0.50) / 0.20);
setPanelTransform(panel, position, panel.assembledQuat);
} else if (u < 0.86) {
position = tempB.copy(p3).lerp(p4, (u - 0.70) / 0.16);
setPanelTransform(panel, position, panel.assembledQuat);
} else {
position = tempB.copy(p4).lerp(p5, (u - 0.86) / 0.14);
setPanelTransform(panel, position, panel.assembledQuat);
}
});
anim.activeIndex = activeIndex;
anim.step = activeIndex < 0 ? 0
: activeU < 0.34 ? 1
: activeU < 0.50 ? 2
: 3;
}
function updateAnimations(now) {
for (const building of buildings) {
if (!building.anim) continue;
if (building.anim.kind === "unfold") {
updateUnfold(building, now);
} else {
updateFold(building, now);
}
if (now - building.anim.start >= building.anim.total) {
const wasFolding = building.anim.kind === "fold";
const clearSelection = building.anim.clearSelectionAtEnd;
if (wasFolding) {
for (const panel of building.panels) {
setPanelTransform(
panel,
panel.assembledPos,
panel.assembledQuat
);
}
building.mode = "assembled";
building.ghost.visible = false;
building.anim = null;
if (clearSelection && selectedBuilding === building) {
selectedBuilding = null;
}
} else {
snapToFlat(building);
}
}
}
}
// -------------------------------------------------------------------------
// Edge guide lines
// -------------------------------------------------------------------------
const markerWorldA = new THREE.Vector3();
const markerWorldB = new THREE.Vector3();
function updateGuides() {
for (const building of buildings) {
const visible =
showGuides &&
selectedBuilding === building &&
building.mode !== "assembled";
building.guideLines.visible = visible;
if (!visible) continue;
const position = building.guideLines.geometry.attributes.position;
building.pairs.forEach((pair, index) => {
pair.markerA.getWorldPosition(markerWorldA);
pair.markerB.getWorldPosition(markerWorldB);
position.setXYZ(index * 2, markerWorldA.x, markerWorldA.y, markerWorldA.z);
position.setXYZ(index * 2 + 1, markerWorldB.x, markerWorldB.y, markerWorldB.z);
});
position.needsUpdate = true;
}
}
// -------------------------------------------------------------------------
// Selection and interaction
// -------------------------------------------------------------------------
function selectBuilding(building) {
if (building.mode === "unfolding" || building.mode === "folding") return;
if (selectedBuilding === building) {
if (building.mode === "flat") {
beginFold(building, true);
} else if (building.mode === "assembled") {
beginUnfold(building);
}
return;
}
const previous = selectedBuilding;
selectedBuilding = building;
if (previous && previous !== building) {
if (previous.mode === "unfolding") {
snapToFlat(previous);
}
if (previous.mode === "flat") {
beginFold(previous, false);
}
}
if (building.mode === "assembled") {
beginUnfold(building);
}
}
const raycaster = new THREE.Raycaster();
const pointer = new THREE.Vector2();
function hitPanel(clientX, clientY) {
const rect = renderer.domElement.getBoundingClientRect();
pointer.x = ((clientX - rect.left) / rect.width) * 2 - 1;
pointer.y = -((clientY - rect.top) / rect.height) * 2 + 1;
raycaster.setFromCamera(pointer, camera);
const hits = raycaster.intersectObjects(panelMeshes, false);
return hits.length ? hits[0].object.userData.panel : null;
}
function setHovered(panel) {
if (hoveredPanel === panel) return;
if (hoveredPanel) {
hoveredPanel.material.emissive.setHex(0x000000);
hoveredPanel.material.emissiveIntensity = 0;
}
hoveredPanel = panel;
if (hoveredPanel) {
hoveredPanel.material.emissive.setHex(0xfff1cf);
hoveredPanel.material.emissiveIntensity = 0.22;
}
}
const hoverTip = document.getElementById("hoverTip");
// -------------------------------------------------------------------------
// UI
// -------------------------------------------------------------------------
const buildingName = document.getElementById("buildingName");
const panelCount = document.getElementById("panelCount");
const statusText = document.getElementById("statusText");
const progressFill = document.getElementById("progressFill");
const stepElements = [...document.querySelectorAll(".step")];
const foldBtn = document.getElementById("foldBtn");
const guidesBtn = document.getElementById("guidesBtn");
const resetBtn = document.getElementById("resetBtn");
foldBtn.addEventListener("click", () => {
if (selectedBuilding && selectedBuilding.mode === "flat") {
beginFold(selectedBuilding, true);
}
});
guidesBtn.addEventListener("click", () => {
showGuides = !showGuides;
guidesBtn.classList.toggle("active", showGuides);
});
resetBtn.addEventListener("click", () => {
controls.target.copy(controls.home.target);
controls.theta = controls.home.theta;
controls.phi = controls.home.phi;
controls.radius = controls.home.radius;
updateCamera();
});
function updateUI() {
const building = selectedBuilding;
if (!building) {
buildingName.textContent = "Choose a building";
panelCount.textContent = "0 panels";
statusText.textContent =
"Click any colored building. The numbered order shows how its panels safely lift, turn flat, and settle into the matching layout.";
progressFill.style.width = "0%";
stepElements.forEach(el => el.className = "step");
foldBtn.disabled = true;
foldBtn.textContent = "Fold back";
return;
}
buildingName.textContent = building.name;
panelCount.textContent = `${building.panels.length} panels`;
const anim = building.anim;
if (building.mode === "unfolding" && anim) {
const t = Math.max(0, performance.now() * 0.001 - anim.start);
const progress = Math.min(1, t / anim.total);
const active = anim.activeIndex >= 0
? building.unfoldPanels[anim.activeIndex]
: null;
progressFill.style.width = `${progress * 100}%`;
if (!active) {
statusText.textContent =
"Stage 1 of 4 — lifting the complete structure clear of the rug before separating any panels.";
} else {
const action = anim.step === 1
? "separating it through a high, collision-free lane"
: anim.step === 2
? "turning the same square panel flat without changing its size"
: "lowering it into its matching grid cell";
statusText.textContent =
`Step ${anim.step + 1} of 4 — panel ${active.number} is ${action}.`;
}
stepElements.forEach((el, index) => {
el.className = "step";
if (index < anim.step) el.classList.add("done");
if (index === anim.step) el.classList.add("current");
});
foldBtn.disabled = true;
foldBtn.textContent = "Unfolding…";
} else if (building.mode === "folding" && anim) {
const t = Math.max(0, performance.now() * 0.001 - anim.start);
const progress = Math.min(1, t / anim.total);
const active = anim.activeIndex >= 0
? building.foldPanels[anim.activeIndex]
: null;
progressFill.style.width = `${progress * 100}%`;
statusText.textContent = active
? `Step ${anim.step + 1} of 4 — returning panel ${active.number} along its clear approach route.`
: "Preparing the flat set for a safe return.";
stepElements.forEach((el, index) => {
el.className = "step";
if (index < anim.step) el.classList.add("done");
if (index === anim.step) el.classList.add("current");
});
foldBtn.disabled = true;
foldBtn.textContent = "Folding…";
} else if (building.mode === "flat") {
progressFill.style.width = "100%";
statusText.textContent =
"The matching set is ready. Colored tabs and guides identify the edges that meet in the assembled model.";
stepElements.forEach(el => {
el.className = "step done";
});
foldBtn.disabled = false;
foldBtn.textContent = "Fold back";
} else {
progressFill.style.width = "0%";
statusText.textContent = building.description;
stepElements.forEach(el => el.className = "step");
foldBtn.disabled = true;
foldBtn.textContent = "Fold back";
}
}
// -------------------------------------------------------------------------
// Pointer controls and picking
// -------------------------------------------------------------------------
const canvas = renderer.domElement;
let pointerDown = false;
let pointerId = null;
let startX = 0;
let startY = 0;
let previousX = 0;
let previousY = 0;
let dragged = false;
canvas.addEventListener("contextmenu", event => event.preventDefault());
canvas.addEventListener("pointerdown", event => {
pointerDown = true;
pointerId = event.pointerId;
startX = previousX = event.clientX;
startY = previousY = event.clientY;
dragged = false;
canvas.setPointerCapture(event.pointerId);
canvas.classList.add("dragging");
hoverTip.style.display = "none";
});
canvas.addEventListener("pointermove", event => {
if (pointerDown && event.pointerId === pointerId) {
const dx = event.clientX - previousX;
const dy = event.clientY - previousY;
if (Math.hypot(event.clientX - startX, event.clientY - startY) > 5) {
dragged = true;
}
const panMode = event.button === 2 || event.shiftKey;
if (panMode) {
const right = new THREE.Vector3(
Math.cos(controls.theta),
0,
-Math.sin(controls.theta)
);
const forward = new THREE.Vector3(
-Math.sin(controls.theta),
0,
-Math.cos(controls.theta)
);
const scale = controls.radius * 0.0014;
controls.target.addScaledVector(right, -dx * scale);
controls.target.addScaledVector(forward, -dy * scale);
} else {
controls.theta -= dx * 0.006;
controls.phi = THREE.MathUtils.clamp(
controls.phi - dy * 0.005,
0.28,
1.38
);
}
previousX = event.clientX;
previousY = event.clientY;
updateCamera();
return;
}
const hit = hitPanel(event.clientX, event.clientY);
setHovered(hit);
if (hit) {
hoverTip.textContent = `${hit.building.name} · click to unfold`;
hoverTip.style.left = `${event.clientX}px`;
hoverTip.style.top = `${event.clientY}px`;
hoverTip.style.display = "block";
canvas.style.cursor = "pointer";
} else {
hoverTip.style.display = "none";
canvas.style.cursor = "grab";
}
});
canvas.addEventListener("pointerup", event => {
if (!pointerDown || event.pointerId !== pointerId) return;
pointerDown = false;
pointerId = null;
canvas.classList.remove("dragging");
if (!dragged) {
const hit = hitPanel(event.clientX, event.clientY);
if (hit) selectBuilding(hit.building);
}
});
canvas.addEventListener("pointercancel", () => {
pointerDown = false;
pointerId = null;
canvas.classList.remove("dragging");
});
canvas.addEventListener("pointerleave", () => {
if (!pointerDown) {
setHovered(null);
hoverTip.style.display = "none";
}
});
canvas.addEventListener("wheel", event => {
event.preventDefault();
controls.radius = THREE.MathUtils.clamp(
controls.radius * Math.exp(event.deltaY * 0.001),
8.5,
31
);
updateCamera();
}, { passive: false });
// -------------------------------------------------------------------------
// Resize and render loop
// -------------------------------------------------------------------------
addEventListener("resize", () => {
camera.aspect = innerWidth / innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(innerWidth, innerHeight);
renderer.setPixelRatio(Math.min(devicePixelRatio, 2));
});
function animate() {
requestAnimationFrame(animate);
const now = performance.now() * 0.001;
updateAnimations(now);
updateGuides();
let badgePanel = null;
if (selectedBuilding?.anim) {
const anim = selectedBuilding.anim;
if (anim.activeIndex >= 0) {
badgePanel = anim.kind === "unfold"
? selectedBuilding.unfoldPanels[anim.activeIndex]
: selectedBuilding.foldPanels[anim.activeIndex];
}
}
if (badgePanel) {
setBadge(badgePanel.number);
badgePanel.root.getWorldPosition(tempA);
tempA.y += 0.58;
badgeSprite.position.copy(tempA);
badgeSprite.visible = true;
} else {
badgeSprite.visible = false;
}
for (const building of buildings) {
building.flatLabel.visible =
selectedBuilding === building &&
building.mode !== "assembled";
}
updateUI();
renderer.render(scene, camera);
}
animate();
</script>
</body>
</html>
```