Prompt specification
Build or customize the Three.js 3D scene "Open-plan space allocation game" 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: Open-plan space allocation game
Category: Architecture & Cities · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/open-plan-space-allocation-game-x0220
Scene Description Prompt:
I'd like to see this as a low-poly Three.js scene: open-plan space allocation game. Build a flexible room where users position rugs and furniture for quiet study, play, and meals; show activity footprints and flag overlap with the main corridor. Use cdnjs and return one self-contained HTML file.
Working Three.js Starter (open-plan-space-allocation-game-x0220):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>OpenPlan — Room Allocation</title>
<style>
:root {
--ink: #183b37;
--muted: #6f817d;
--panel: rgba(255, 255, 252, 0.94);
--line: rgba(24, 59, 55, 0.12);
--green: #2f7d70;
--green-dark: #205f55;
--study: #4779e8;
--play: #e85f91;
--meal: #ef9d3f;
--danger: #dc4b4b;
--shadow: 0 18px 50px rgba(40, 67, 60, 0.14);
}
* { box-sizing: border-box; }
html, body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: #e8eee9;
color: var(--ink);
font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
button, select { font: inherit; }
button {
color: inherit;
cursor: pointer;
}
#scene {
position: fixed;
inset: 0;
}
#scene canvas {
display: block;
width: 100%;
height: 100%;
touch-action: none;
outline: none;
}
.topbar {
position: fixed;
z-index: 20;
top: 16px;
left: 18px;
right: 18px;
min-height: 66px;
padding: 10px 12px 10px 16px;
display: flex;
align-items: center;
gap: 16px;
border: 1px solid rgba(255,255,255,.72);
border-radius: 20px;
background: rgba(250, 252, 248, .9);
box-shadow: var(--shadow);
backdrop-filter: blur(16px);
}
.brand {
display: flex;
align-items: center;
gap: 11px;
min-width: 220px;
}
.brand-mark {
position: relative;
width: 38px;
height: 38px;
border-radius: 12px;
background: var(--ink);
overflow: hidden;
}
.brand-mark::before,
.brand-mark::after {
content: "";
position: absolute;
border-radius: 3px;
background: #b8ddd0;
transform: rotate(-8deg);
}
.brand-mark::before {
width: 17px;
height: 26px;
left: 7px;
top: 7px;
}
.brand-mark::after {
width: 9px;
height: 20px;
right: 6px;
top: 4px;
background: #f0b05a;
}
.brand h1 {
margin: 0;
font-size: 18px;
line-height: 1.05;
letter-spacing: -.03em;
}
.brand p {
margin: 4px 0 0;
color: var(--muted);
font-size: 11px;
font-weight: 650;
letter-spacing: .08em;
text-transform: uppercase;
}
.top-actions {
margin-left: auto;
display: flex;
align-items: center;
gap: 8px;
}
.tool-button {
min-height: 40px;
padding: 0 13px;
border: 1px solid var(--line);
border-radius: 12px;
background: #fff;
font-size: 12px;
font-weight: 750;
transition: .18s ease;
}
.tool-button:hover {
transform: translateY(-1px);
border-color: rgba(24,59,55,.25);
box-shadow: 0 5px 14px rgba(24,59,55,.08);
}
.tool-button.active {
color: #fff;
border-color: var(--green);
background: var(--green);
}
.status-pill {
padding: 9px 12px;
border-radius: 999px;
color: var(--green-dark);
background: #dff1e8;
font-size: 11px;
font-weight: 800;
white-space: nowrap;
}
.status-pill.warning {
color: #963737;
background: #fde1df;
}
.panel {
position: fixed;
z-index: 15;
top: 96px;
bottom: 18px;
width: 276px;
padding: 18px;
overflow: auto;
border: 1px solid rgba(255,255,255,.78);
border-radius: 22px;
background: var(--panel);
box-shadow: var(--shadow);
backdrop-filter: blur(16px);
scrollbar-width: thin;
}
#catalog { left: 18px; }
#dashboard { right: 18px; width: 292px; }
.eyebrow {
margin: 0 0 5px;
color: var(--green);
font-size: 10px;
font-weight: 850;
letter-spacing: .15em;
text-transform: uppercase;
}
.panel h2 {
margin: 0;
font-size: 22px;
line-height: 1.1;
letter-spacing: -.04em;
}
.panel-intro {
margin: 8px 0 16px;
color: var(--muted);
font-size: 12px;
line-height: 1.55;
}
.section-title {
display: flex;
align-items: center;
justify-content: space-between;
margin: 18px 0 9px;
font-size: 11px;
font-weight: 850;
letter-spacing: .08em;
text-transform: uppercase;
}
.section-title span:last-child {
color: var(--muted);
font-size: 10px;
font-weight: 650;
letter-spacing: 0;
text-transform: none;
}
.catalog-list {
display: grid;
gap: 8px;
}
.catalog-card {
width: 100%;
display: grid;
grid-template-columns: 39px 1fr;
align-items: center;
gap: 10px;
padding: 9px;
text-align: left;
border: 1px solid var(--line);
border-radius: 14px;
background: rgba(255,255,255,.88);
transition: transform .16s ease, box-shadow .16s ease, border-color .16s ease;
user-select: none;
touch-action: none;
}
.catalog-card:hover {
transform: translateY(-2px);
border-color: rgba(24,59,55,.25);
box-shadow: 0 7px 18px rgba(24,59,55,.09);
}
.catalog-card:active { cursor: grabbing; }
.catalog-icon {
width: 39px;
height: 39px;
display: grid;
place-items: center;
border-radius: 12px;
background: #edf3ef;
font-size: 19px;
}
.catalog-name {
display: block;
font-size: 12px;
font-weight: 800;
}
.catalog-meta {
display: block;
margin-top: 3px;
color: var(--muted);
font-size: 10px;
}
.tiny-dot {
display: inline-block;
width: 6px;
height: 6px;
margin-right: 5px;
border-radius: 50%;
vertical-align: 1px;
}
.panel-footer {
display: flex;
gap: 7px;
margin-top: 14px;
}
.panel-footer button {
flex: 1;
padding: 9px 8px;
border: 1px solid var(--line);
border-radius: 11px;
background: #fff;
font-size: 10px;
font-weight: 800;
}
.hint-box {
margin-top: 14px;
padding: 11px;
border-radius: 13px;
color: #56706a;
background: #edf4f0;
font-size: 10px;
line-height: 1.55;
}
.score-row {
display: grid;
grid-template-columns: 78px 1fr;
align-items: center;
gap: 14px;
margin-top: 16px;
padding: 12px;
border: 1px solid var(--line);
border-radius: 17px;
background: #fff;
}
.score-ring {
--score: 0;
width: 72px;
height: 72px;
display: grid;
place-items: center;
border-radius: 50%;
background: conic-gradient(var(--green) calc(var(--score) * 1%), #e6ede8 0);
}
.score-ring::before {
content: "";
grid-area: 1 / 1;
width: 56px;
height: 56px;
border-radius: 50%;
background: white;
}
.score-value {
z-index: 1;
grid-area: 1 / 1;
font-size: 18px;
font-weight: 900;
letter-spacing: -.05em;
}
.score-copy strong {
display: block;
font-size: 13px;
}
.score-copy span {
display: block;
margin-top: 4px;
color: var(--muted);
font-size: 10px;
line-height: 1.45;
}
.objective {
margin: 11px 0;
padding: 10px 11px;
border: 1px solid var(--line);
border-radius: 13px;
background: rgba(255,255,255,.75);
}
.objective-top {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 7px;
font-size: 11px;
font-weight: 800;
}
.objective-top span:last-child {
color: var(--muted);
font-size: 10px;
font-weight: 650;
}
.bar {
height: 6px;
overflow: hidden;
border-radius: 99px;
background: #e5ebe7;
}
.bar-fill {
width: 0;
height: 100%;
border-radius: inherit;
transition: width .25s ease, background .2s ease;
}
.corridor-card {
margin-top: 13px;
padding: 12px;
border: 1px solid #cfe3da;
border-radius: 14px;
background: #edf7f1;
}
.corridor-card.conflict {
border-color: #f0c4c0;
background: #fff0ee;
}
.corridor-title {
display: flex;
align-items: center;
gap: 7px;
font-size: 11px;
font-weight: 850;
}
.corridor-title i {
width: 9px;
height: 9px;
border-radius: 50%;
background: var(--green);
}
.corridor-card.conflict .corridor-title i { background: var(--danger); }
.corridor-card p {
margin: 6px 0 0;
color: var(--muted);
font-size: 10px;
line-height: 1.45;
}
.warning-list {
display: grid;
gap: 4px;
margin-top: 7px;
color: #a33d3d;
font-size: 10px;
font-weight: 700;
}
.selection-empty {
padding: 12px;
border: 1px dashed rgba(24,59,55,.2);
border-radius: 14px;
color: var(--muted);
font-size: 11px;
line-height: 1.5;
text-align: center;
}
.selection-content {
padding: 12px;
border: 1px solid var(--line);
border-radius: 15px;
background: #fff;
}
.selection-content.conflict {
border-color: #efc2bf;
background: #fff9f8;
}
.selection-name {
font-size: 13px;
font-weight: 850;
}
.selection-meta {
margin-top: 4px;
color: var(--muted);
font-size: 10px;
}
.field-label {
display: block;
margin: 12px 0 5px;
color: var(--muted);
font-size: 9px;
font-weight: 850;
letter-spacing: .08em;
text-transform: uppercase;
}
select {
width: 100%;
height: 38px;
padding: 0 10px;
color: var(--ink);
border: 1px solid var(--line);
border-radius: 10px;
background: #f7faf7;
font-size: 11px;
font-weight: 750;
}
.selection-actions {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 7px;
margin-top: 10px;
}
.selection-actions button {
padding: 9px 6px;
border: 1px solid var(--line);
border-radius: 10px;
background: #f8faf8;
font-size: 10px;
font-weight: 800;
}
.selection-actions .delete {
color: #a44040;
background: #fff2f0;
}
#toast {
position: fixed;
z-index: 50;
left: 50%;
bottom: 24px;
max-width: min(460px, calc(100vw - 30px));
padding: 11px 16px;
border-radius: 999px;
color: #fff;
background: var(--ink);
box-shadow: 0 12px 32px rgba(24,59,55,.24);
font-size: 11px;
font-weight: 750;
text-align: center;
opacity: 0;
pointer-events: none;
transform: translate(-50%, 12px);
transition: .22s ease;
}
#toast.show {
opacity: 1;
transform: translate(-50%, 0);
}
#toast.warning { background: #a84747; }
#dragGhost {
position: fixed;
z-index: 100;
display: none;
min-width: 120px;
padding: 10px 13px;
border: 1px solid rgba(255,255,255,.4);
border-radius: 13px;
color: #fff;
background: rgba(24,59,55,.92);
box-shadow: 0 10px 26px rgba(24,59,55,.2);
font-size: 11px;
font-weight: 800;
pointer-events: none;
transform: translate(14px, 14px);
}
#dragGhost span {
margin-right: 7px;
font-size: 16px;
}
.mobile-only { display: none; }
[hidden] { display: none !important; }
@media (max-width: 1100px) {
#catalog { width: 238px; }
#dashboard { width: 258px; }
.brand { min-width: 175px; }
.tool-button { padding: 0 10px; }
.status-pill { display: none; }
}
@media (max-width: 760px) {
.topbar {
top: 10px;
left: 10px;
right: 10px;
min-height: 58px;
padding: 8px 9px 8px 11px;
}
.brand { min-width: 0; }
.brand-mark { width: 34px; height: 34px; }
.brand h1 { font-size: 15px; }
.brand p { display: none; }
.top-actions { gap: 5px; }
.tool-button { min-height: 36px; padding: 0 9px; font-size: 10px; }
#footprintBtn .button-label,
#resetViewBtn .button-label { display: none; }
.mobile-only { display: inline-block; }
#catalog {
top: auto;
left: 10px;
right: 10px;
bottom: 10px;
width: auto;
max-height: 214px;
padding: 13px;
border-radius: 18px;
}
#catalog h2 { font-size: 18px; }
#catalog .panel-intro,
#catalog .section-title,
#catalog .hint-box,
#catalog .panel-footer { display: none; }
.catalog-list {
display: flex;
overflow-x: auto;
padding-bottom: 3px;
}
.catalog-card {
min-width: 170px;
}
#dashboard {
top: 78px;
right: 10px;
bottom: auto;
width: min(285px, calc(100vw - 20px));
max-height: calc(100vh - 92px);
transform: translateX(calc(100% + 24px));
transition: transform .22s ease;
}
#dashboard.open { transform: translateX(0); }
#toast { bottom: 235px; }
}
</style>
</head>
<body>
<div id="scene"></div>
<header class="topbar">
<div class="brand">
<div class="brand-mark" aria-hidden="true"></div>
<div>
<h1>OpenPlan</h1>
<p>Room allocation studio</p>
</div>
</div>
<div class="top-actions">
<button class="tool-button active" id="footprintBtn" aria-pressed="true">
◫ <span class="button-label">Footprints</span>
</button>
<button class="tool-button" id="viewBtn">Plan view</button>
<button class="tool-button" id="resetViewBtn" title="Reset camera">
↺ <span class="button-label">Reset view</span>
</button>
<button class="tool-button mobile-only" id="briefBtn">Brief</button>
<div class="status-pill" id="roomStatus">Room in progress</div>
</div>
</header>
<aside class="panel" id="catalog">
<p class="eyebrow">Furniture library</p>
<h2>Build your zones</h2>
<p class="panel-intro">
Drag a piece into the room, then drag it around. Every footprint shows its activity area.
</p>
<div class="section-title">
<span>Place a piece</span>
<span>Drag to canvas</span>
</div>
<div class="catalog-list" id="catalogList"></div>
<div class="panel-footer">
<button id="resetRoomBtn">Reset sample</button>
<button id="clearRoomBtn">Clear all</button>
</div>
<div class="hint-box">
<strong>Controls:</strong> drag furniture to move it. Drag empty floor to orbit,
right-drag to pan, scroll to zoom, and use the arrow keys for precise placement.
</div>
</aside>
<aside class="panel" id="dashboard">
<p class="eyebrow">Today's brief</p>
<h2>Space allocation</h2>
<p class="panel-intro">
Balance three everyday activities while keeping the main circulation route open.
</p>
<div class="score-row">
<div class="score-ring" id="scoreRing">
<div class="score-value" id="scoreValue">0%</div>
</div>
<div class="score-copy">
<strong id="scoreTitle">Getting started</strong>
<span>Footprint coverage across study, play, and meals.</span>
</div>
</div>
<div class="section-title">
<span>Activity goals</span>
<span>Footprint area</span>
</div>
<div class="objective">
<div class="objective-top">
<span><i class="tiny-dot" style="background:var(--study)"></i>Quiet study</span>
<span id="studyValue">0 / 10 m²</span>
</div>
<div class="bar"><div class="bar-fill" id="studyBar" style="background:var(--study)"></div></div>
</div>
<div class="objective">
<div class="objective-top">
<span><i class="tiny-dot" style="background:var(--play)"></i>Play</span>
<span id="playValue">0 / 8 m²</span>
</div>
<div class="bar"><div class="bar-fill" id="playBar" style="background:var(--play)"></div></div>
</div>
<div class="objective">
<div class="objective-top">
<span><i class="tiny-dot" style="background:var(--meal)"></i>Meals</span>
<span id="mealValue">0 / 10 m²</span>
</div>
<div class="bar"><div class="bar-fill" id="mealBar" style="background:var(--meal)"></div></div>
</div>
<div class="corridor-card" id="corridorCard">
<div class="corridor-title"><i></i><span id="corridorTitle">Main corridor is clear</span></div>
<p id="corridorCopy">Keep the central 1.8 m-wide route free of activity footprints.</p>
<div class="warning-list" id="warningList"></div>
</div>
<div class="section-title">
<span>Selected piece</span>
<span id="selectedPosition">None</span>
</div>
<div class="selection-empty" id="selectionEmpty">
Select furniture in the room to edit its activity or rotate it.
</div>
<div class="selection-content" id="selectionContent" hidden>
<div class="selection-name" id="selectedName"></div>
<div class="selection-meta" id="selectedMeta"></div>
<label class="field-label" for="zoneSelect">Activity footprint</label>
<select id="zoneSelect">
<option value="study">Quiet study</option>
<option value="play">Play</option>
<option value="meal">Meals</option>
</select>
<div class="selection-actions">
<button id="rotateBtn">↻ Rotate 90°</button>
<button class="delete" id="deleteBtn">Delete</button>
</div>
</div>
</aside>
<div id="toast"></div>
<div id="dragGhost"></div>
<script type="module">
import * as THREE from "https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
const ROOM_WIDTH = 18;
const ROOM_DEPTH = 12;
const CORRIDOR_WIDTH = 1.8;
const ACTIVITY_COLORS = {
study: 0x4779e8,
play: 0xe85f91,
meal: 0xef9d3f
};
const ACTIVITY_NAMES = {
study: "Quiet study",
play: "Play",
meal: "Meals"
};
const GOALS = {
study: 10,
play: 8,
meal: 10
};
const CATALOG = [
{ id: "quietRug", name: "Quiet rug", icon: "▰", model: "quietRug", activity: "study", w: 4.0, d: 3.0, h: .12 },
{ id: "studyDesk", name: "Study desk", icon: "▤", model: "studyDesk", activity: "study", w: 2.4, d: 1.6, h: 1.25 },
{ id: "readingChair", name: "Reading chair", icon: "▣", model: "readingChair", activity: "study", w: 1.35, d: 1.35, h: 1.25 },
{ id: "playRug", name: "Play rug", icon: "◆", model: "playRug", activity: "play", w: 3.6, d: 2.8, h: .12 },
{ id: "playBlocks", name: "Block shelf", icon: "▥", model: "playBlocks", activity: "play", w: 1.8, d: 1.4, h: 1.15 },
{ id: "mealRug", name: "Meal rug", icon: "◇", model: "mealRug", activity: "meal", w: 3.8, d: 2.8, h: .12 },
{ id: "diningTable", name: "Dining table", icon: "▬", model: "diningTable", activity: "meal", w: 3.2, d: 2.2, h: 1.05 },
{ id: "diningBench", name: "Dining bench", icon: "▱", model: "diningBench", activity: "meal", w: 2.4, d: 1.0, h: .9 }
];
const scene = new THREE.Scene();
scene.background = new THREE.Color(0xe8eee9);
scene.fog = new THREE.Fog(0xe8eee9, 28, 52);
const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.08;
renderer.domElement.setAttribute("aria-label", "Interactive 3D room allocation scene");
document.getElementById("scene").appendChild(renderer.domElement);
const camera = new THREE.PerspectiveCamera(
43,
window.innerWidth / window.innerHeight,
.1,
100
);
const cameraState = {
yaw: .67,
pitch: .82,
distance: 20,
target: new THREE.Vector3(0, .15, 0),
top: false
};
const hemi = new THREE.HemisphereLight(0xf6fbff, 0x9d8f79, 2.2);
scene.add(hemi);
const sun = new THREE.DirectionalLight(0xfff4df, 3.1);
sun.position.set(8, 15, 10);
sun.castShadow = true;
sun.shadow.mapSize.set(2048, 2048);
sun.shadow.camera.left = -14;
sun.shadow.camera.right = 14;
sun.shadow.camera.top = 12;
sun.shadow.camera.bottom = -12;
sun.shadow.camera.near = 1;
sun.shadow.camera.far = 40;
sun.shadow.bias = -.0004;
scene.add(sun);
const fill = new THREE.DirectionalLight(0xbcd8ff, .8);
fill.position.set(-8, 7, -4);
scene.add(fill);
const raycaster = new THREE.Raycaster();
const pointer = new THREE.Vector2();
const groundPlane = new THREE.Plane(new THREE.Vector3(0, 1, 0), 0);
const itemStates = new Map();
const itemMeshes = [];
let itemCounter = 0;
let selectedItem = null;
let footprintVisible = true;
let catalogDrag = null;
let canvasDrag = null;
let previewMesh = null;
let toastTimer = null;
const catalogList = document.getElementById("catalogList");
const toast = document.getElementById("toast");
const dragGhost = document.getElementById("dragGhost");
function makeMaterial(color, options = {}) {
return new THREE.MeshStandardMaterial({
color,
roughness: options.roughness ?? .82,
metalness: options.metalness ?? 0,
flatShading: true,
transparent: options.transparent ?? false,
opacity: options.opacity ?? 1,
side: options.side ?? THREE.FrontSide,
depthWrite: options.depthWrite ?? true
});
}
function addBox(parent, w, h, d, color, x = 0, y = 0, z = 0, options = {}) {
const mesh = new THREE.Mesh(
new THREE.BoxGeometry(w, h, d),
makeMaterial(color, options)
);
mesh.position.set(x, y, z);
mesh.castShadow = options.castShadow ?? true;
mesh.receiveShadow = options.receiveShadow ?? true;
parent.add(mesh);
return mesh;
}
function addCylinder(parent, radiusTop, radiusBottom, height, color, x = 0, y = 0, z = 0, segments = 8) {
const mesh = new THREE.Mesh(
new THREE.CylinderGeometry(radiusTop, radiusBottom, height, segments),
makeMaterial(color)
);
mesh.position.set(x, y, z);
mesh.castShadow = true;
mesh.receiveShadow = true;
parent.add(mesh);
return mesh;
}
function roundedRect(ctx, x, y, w, h, r) {
ctx.beginPath();
ctx.moveTo(x + r, y);
ctx.arcTo(x + w, y, x + w, y + h, r);
ctx.arcTo(x + w, y + h, x, y + h, r);
ctx.arcTo(x, y + h, x, y, r);
ctx.arcTo(x, y, x + w, y, r);
ctx.closePath();
}
function makeTextSprite(text, accent = "#2f7d70") {
const canvas = document.createElement("canvas");
canvas.width = 768;
canvas.height = 112;
const ctx = canvas.getContext("2d");
ctx.clearRect(0, 0, canvas.width, canvas.height);
roundedRect(ctx, 8, 8, 752, 96, 24);
ctx.fillStyle = "rgba(255,255,255,.96)";
ctx.fill();
ctx.strokeStyle = accent;
ctx.lineWidth = 5;
ctx.stroke();
ctx.fillStyle = "#183b37";
ctx.font = "800 34px system-ui, sans-serif";
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.fillText(text.toUpperCase(), 384, 57);
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.9, .43, 1);
sprite.renderOrder = 20;
return sprite;
}
function makeWarningSprite() {
const canvas = document.createElement("canvas");
canvas.width = 128;
canvas.height = 128;
const ctx = canvas.getContext("2d");
ctx.beginPath();
ctx.arc(64, 64, 53, 0, Math.PI * 2);
ctx.fillStyle = "#dc4b4b";
ctx.fill();
ctx.lineWidth = 8;
ctx.strokeStyle = "#fff";
ctx.stroke();
ctx.fillStyle = "#fff";
ctx.font = "900 76px system-ui";
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.fillText("!", 64, 65);
const texture = new THREE.CanvasTexture(canvas);
texture.colorSpace = THREE.SRGBColorSpace;
const sprite = new THREE.Sprite(new THREE.SpriteMaterial({
map: texture,
transparent: true,
depthTest: false,
depthWrite: false
}));
sprite.scale.set(.48, .48, 1);
sprite.position.y = .43;
sprite.renderOrder = 30;
return sprite;
}
function createRoom() {
const floor = addBox(
scene, ROOM_WIDTH, .22, ROOM_DEPTH, 0xe4dccb,
0, -.11, 0, { castShadow: false }
);
floor.receiveShadow = true;
addBox(scene, ROOM_WIDTH + .35, .25, ROOM_DEPTH + .35, 0xb8b09e, 0, -.27, 0);
const seamPositions = [];
for (let x = -8; x <= 8; x += 1) {
seamPositions.push(x, .008, -5.95, x, .008, 5.95);
}
for (let z = -5; z <= 5; z += 1) {
seamPositions.push(-8.95, .008, z, 8.95, .008, z);
}
const seamGeometry = new THREE.BufferGeometry();
seamGeometry.setAttribute("position", new THREE.Float32BufferAttribute(seamPositions, 3));
scene.add(new THREE.LineSegments(
seamGeometry,
new THREE.LineBasicMaterial({ color: 0xcdbfab, transparent: true, opacity: .38 })
));
const wallMaterial = 0xf1eee6;
addBox(scene, ROOM_WIDTH + .2, 3.25, .18, wallMaterial, 0, 1.55, -6.05);
addBox(scene, .18, 3.25, ROOM_DEPTH + .1, wallMaterial, -9.05, 1.55, 0);
addBox(scene, ROOM_WIDTH, .13, .08, 0xaab6ad, 0, .08, -5.92);
addBox(scene, .08, .13, ROOM_DEPTH, 0xaab6ad, -8.92, .08, 0);
const windowGroup = new THREE.Group();
windowGroup.position.set(-4.7, 1.85, -5.91);
scene.add(windowGroup);
const glass = addBox(windowGroup, 3.1, 1.45, .07, 0xa9cbd2, 0, 0, 0, { castShadow: false });
glass.material.emissive.setHex(0x355c63);
glass.material.emissiveIntensity = .22;
addBox(windowGroup, .09, 1.6, .13, 0xffffff, 0, 0, .06);
addBox(windowGroup, 3.25, .09, .13, 0xffffff, 0, 0, .06);
addBox(windowGroup, 3.4, .10, .28, 0xd2c7b5, 0, -.79, .1);
const door = new THREE.Group();
door.position.set(5.5, 1.36, -5.91);
scene.add(door);
addBox(door, 1.55, 2.72, .08, 0xc9b79d, 0, 0, 0);
addBox(door, 1.22, 1.03, .04, 0xe8dfcf, -.1, .55, .07);
addBox(door, 1.22, 1.03, .04, 0xe8dfcf, -.1, -.55, .07);
addBox(door, .08, .25, .08, 0x5f6f68, .5, 0, .11);
const art = new THREE.Group();
art.position.set(1.25, 1.75, -5.89);
scene.add(art);
addBox(art, 1.45, 1.05, .08, 0x9d8068, 0, 0, 0);
addBox(art, 1.2, .82, .04, 0xf4dfbd, 0, 0, .07);
addBox(art, .58, .46, .05, 0x82b6ad, -.2, .03, .11);
const shelf = new THREE.Group();
shelf.position.set(-8.82, 1.85, -2.8);
scene.add(shelf);
addBox(shelf, .25, .08, 2.5, 0x9d8068, 0, 0, 0);
addBox(shelf, .25, .08, 2.5, 0x9d8068, 0, .65, 0);
for (let i = 0; i < 6; i++) {
const colors = [0xe0a45c, 0x7ea89e, 0xd17e87, 0x7386ac, 0xd7cda8, 0x6d9e8d];
addBox(shelf, .18, .42 + (i % 2) * .12, .25, colors[i], -.02, .29, -.9 + i * .36);
}
const plant = new THREE.Group();
plant.position.set(-8.1, 0, -4.85);
scene.add(plant);
addCylinder(plant, .38, .28, .62, 0xc17d58, 0, .31, 0, 7);
addCylinder(plant, .045, .055, 1.35, 0x647d4d, 0, 1.05, 0, 6);
const leafGeometry = new THREE.ConeGeometry(.23, .8, 5);
const leafColors = [0x557b55, 0x6f9362, 0x456e50];
for (let i = 0; i < 7; i++) {
const leaf = new THREE.Mesh(leafGeometry, makeMaterial(leafColors[i % 3]));
const angle = i * 2.4;
leaf.position.set(Math.cos(angle) * .24, .85 + i * .12, Math.sin(angle) * .24);
leaf.rotation.z = Math.cos(angle) * .72;
leaf.rotation.x = Math.sin(angle) * .72;
leaf.castShadow = true;
plant.add(leaf);
}
const corridor = new THREE.Mesh(
new THREE.PlaneGeometry(ROOM_WIDTH - .2, CORRIDOR_WIDTH),
makeMaterial(0xa9c8bf, {
transparent: true,
opacity: .52,
depthWrite: false,
side: THREE.DoubleSide
})
);
corridor.rotation.x = -Math.PI / 2;
corridor.position.y = .014;
corridor.renderOrder = 1;
scene.add(corridor);
for (const z of [-CORRIDOR_WIDTH / 2, CORRIDOR_WIDTH / 2]) {
const geometry = new THREE.BufferGeometry().setFromPoints([
new THREE.Vector3(-8.85, .025, z),
new THREE.Vector3(8.85, .025, z)
]);
const line = new THREE.Line(
geometry,
new THREE.LineDashedMaterial({
color: 0x47776e,
dashSize: .38,
gapSize: .2,
transparent: true,
opacity: .75
})
);
line.computeLineDistances();
scene.add(line);
}
const labelCanvas = document.createElement("canvas");
labelCanvas.width = 1024;
labelCanvas.height = 128;
const ctx = labelCanvas.getContext("2d");
ctx.fillStyle = "rgba(35,92,81,.82)";
ctx.font = "800 48px system-ui";
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.fillText("MAIN CORRIDOR • KEEP CLEAR", 512, 64);
const labelTexture = new THREE.CanvasTexture(labelCanvas);
labelTexture.colorSpace = THREE.SRGBColorSpace;
const floorLabel = new THREE.Mesh(
new THREE.PlaneGeometry(4.5, .56),
new THREE.MeshBasicMaterial({
map: labelTexture,
transparent: true,
depthWrite: false,
side: THREE.DoubleSide
})
);
floorLabel.rotation.x = -Math.PI / 2;
floorLabel.position.set(-2.3, .028, 0);
scene.add(floorLabel);
const arrowShape = new THREE.Shape();
arrowShape.moveTo(-.38, -.18);
arrowShape.lineTo(.06, -.18);
arrowShape.lineTo(.06, -.34);
arrowShape.lineTo(.43, 0);
arrowShape.lineTo(.06, .34);
arrowShape.lineTo(.06, .18);
arrowShape.lineTo(-.38, .18);
arrowShape.closePath();
for (const x of [-6.6, -3.8, 3.8, 6.6]) {
const arrow = new THREE.Mesh(
new THREE.ShapeGeometry(arrowShape),
new THREE.MeshBasicMaterial({
color: 0x5d8f84,
transparent: true,
opacity: .55,
depthWrite: false,
side: THREE.DoubleSide
})
);
arrow.rotation.x = -Math.PI / 2;
arrow.position.set(x, .03, 0);
scene.add(arrow);
}
}
function buildModel(def, parent) {
const w = def.w;
const d = def.d;
if (def.model === "quietRug") {
addBox(parent, w - .12, .035, d - .12, 0xaec8c2, 0, .025, 0, { castShadow: false });
for (let i = 0; i < 5; i++) {
addBox(parent, .08, .012, d - .42, 0x739b91, -w * .36 + i * w * .18, .052, 0, { castShadow: false });
}
addBox(parent, w - .5, .012, .12, 0xe2e9dc, 0, .052, d * .28, { castShadow: false });
}
if (def.model === "studyDesk") {
addBox(parent, 2.15, .13, .82, 0xc99b69, 0, .88, -.28);
for (const x of [-.88, .88]) {
for (const z of [-.57, .02]) {
addBox(parent, .09, .78, .09, 0x4c5d57, x, .43, z);
}
}
addBox(parent, .72, .12, .68, 0x4f7f79, 0, .48, .48);
addBox(parent, .72, .65, .11, 0x3f6e69, 0, .78, .77);
for (const x of [-.27, .27]) {
addBox(parent, .07, .39, .07, 0x42544f, x, .25, .48);
}
addBox(parent, .42, .035, .28, 0xe8dfcd, .25, .97, -.3, { castShadow: false });
addBox(parent, .36, .025, .23, 0x7899a4, -.5, .97, -.28, { castShadow: false });
}
if (def.model === "readingChair") {
addBox(parent, .84, .18, .78, 0xcb6f68, 0, .48, .02);
addBox(parent, .84, .72, .16, 0xb45d59, 0, .78, -.34);
addBox(parent, .14, .48, .78, 0xb45d59, -.4, .62, .02);
addBox(parent, .14, .48, .78, 0xb45d59, .4, .62, .02);
for (const x of [-.31, .31]) {
for (const z of [-.27, .27]) {
addBox(parent, .07, .36, .07, 0x4b554f, x, .2, z);
}
}
}
if (def.model === "playRug") {
addBox(parent, w - .12, .035, d - .12, 0xe5b3bf, 0, .025, 0, { castShadow: false });
const colors = [0xf1d58d, 0x8cb8b1, 0x7186b6, 0xef927e];
for (let i = 0; i < 4; i++) {
const patch = addBox(
parent, .58, .015, .58, colors[i],
-w * .3 + i * .55, .055, -.45 + (i % 2) * .65,
{ castShadow: false }
);
patch.rotation.y = Math.PI / 4;
}
}
if (def.model === "playBlocks") {
addBox(parent, 1.35, .1, .62, 0xa97752, 0, .36, -.2);
addBox(parent, 1.35, .1, .62, 0xa97752, 0, .75, -.2);
addBox(parent, .1, .52, .62, 0x936541, -.65, .55, -.2);
addBox(parent, .1, .52, .62, 0x936541, .65, .55, -.2);
const blockColors = [0xe36e69, 0x679db2, 0xe7b453, 0x7db18d, 0x927db3];
for (let i = 0; i < 5; i++) {
addBox(
parent, .28, .28, .28, blockColors[i],
-.4 + i * .2, .58 + (i % 2) * .32, -.18,
{ roughness: .75 }
);
}
const ball = new THREE.Mesh(
new THREE.IcosahedronGeometry(.24, 0),
makeMaterial(0xe28d5b)
);
ball.position.set(.48, .25, .42);
ball.castShadow = true;
parent.add(ball);
}
if (def.model === "mealRug") {
addBox(parent, w - .12, .035, d - .12, 0xe8d2ad, 0, .025, 0, { castShadow: false });
const diamonds = [
[-.95, -.55, 0xe59a4d], [0, -.55, 0x7da69b],
[.95, -.55, 0xd8796e], [-.48, .62, 0xd8796e],
[.48, .62, 0x7da69b]
];
for (const [x, z, color] of diamonds) {
const mesh = addBox(parent, .48, .014, .48, color, x, .056, z, { castShadow: false });
mesh.rotation.y = Math.PI / 4;
}
}
if (def.model === "diningTable") {
addBox(parent, 2.55, .14, 1.28, 0xb9895f, 0, .86, 0);
for (const x of [-1.03, 1.03]) {
for (const z of [-.46, .46]) {
addBox(parent, .1, .75, .1, 0x5d675e, x, .43, z);
}
}
addBox(parent, .62, .06, .42, 0xf0e5d1, -.45, .96, 0);
addCylinder(parent, .16, .18, .05, 0xd99a6f, .5, .96, .08, 10);
addCylinder(parent, .08, .1, .28, 0x8db0a6, .5, 1.12, .08, 8);
}
if (def.model === "diningBench") {
addBox(parent, 2.18, .17, .68, 0xc49364, 0, .49, 0);
for (const x of [-.83, .83]) {
addBox(parent, .1, .4, .48, 0x5e675f, x, .22, 0);
}
}
}
function effectiveDimensions(item) {
return item.rotation % 180 === 0
? { w: item.def.w, d: item.def.d }
: { w: item.def.d, d: item.def.w };
}
function clearGroup(group) {
while (group.children.length) {
const child = group.children.pop();
child.traverse?.(object => {
object.geometry?.dispose?.();
if (object.material) {
const materials = Array.isArray(object.material) ? object.material : [object.material];
for (const material of materials) {
material.map?.dispose?.();
material.dispose?.();
}
}
});
group.remove(child);
}
}
function rebuildFootprint(item) {
clearGroup(item.footprintGroup);
const { w, d } = effectiveDimensions(item);
const plane = new THREE.Mesh(
new THREE.PlaneGeometry(w, d),
makeMaterial(ACTIVITY_COLORS[item.activity], {
transparent: true,
opacity: .2,
depthWrite: false,
side: THREE.DoubleSide
})
);
plane.rotation.x = -Math.PI / 2;
plane.position.y = .052;
plane.renderOrder = 3;
item.footprintGroup.add(plane);
const points = [
new THREE.Vector3(-w / 2, .059, -d / 2),
new THREE.Vector3(w / 2, .059, -d / 2),
new THREE.Vector3(w / 2, .059, d / 2),
new THREE.Vector3(-w / 2, .059, d / 2),
new THREE.Vector3(-w / 2, .059, -d / 2)
];
const border = new THREE.Line(
new THREE.BufferGeometry().setFromPoints(points),
new THREE.LineBasicMaterial({
color: ACTIVITY_COLORS[item.activity],
transparent: true,
opacity: .85
})
);
border.renderOrder = 4;
item.footprintGroup.add(border);
item.footprintPlane = plane;
item.footprintBorder = border;
}
function updateItemLabel(item) {
if (!item.label) return;
const oldMaterial = item.label.material;
oldMaterial.map?.dispose?.();
oldMaterial.dispose?.();
item.label = makeTextSprite(
`${ACTIVITY_NAMES[item.activity]} · ${item.def.name}`,
`#${ACTIVITY_COLORS[item.activity].toString(16).padStart(6, "0")}`
);
item.label.position.y = item.def.h + .65;
item.root.add(item.label);
}
function createItem(def, x, z) {
const id = `item-${++itemCounter}`;
const root = new THREE.Group();
const model = new THREE.Group();
const footprintGroup = new THREE.Group();
root.add(model);
root.add(footprintGroup);
root.position.set(x, 0, z);
scene.add(root);
buildModel(def, model);
model.traverse(object => {
if (object.isMesh) {
object.userData.itemId = id;
itemMeshes.push(object);
}
});
const warning = new THREE.Group();
const marker = new THREE.Mesh(
new THREE.OctahedronGeometry(.18, 0),
makeMaterial(0xdc4b4b, { emissive: 0x7a1616, emissiveIntensity: .3 })
);
warning.add(marker);
warning.add(makeWarningSprite());
warning.position.y = def.h + .2;
warning.visible = false;
root.add(warning);
const item = {
id,
def,
root,
model,
footprintGroup,
warning,
marker,
activity: def.activity,
rotation: 0,
invalid: false
};
itemStates.set(id, item);
rebuildFootprint(item);
updateItemLabel(item);
return item;
}
function removeItem(item) {
if (!item) return;
itemMeshes.splice(0, itemMeshes.length, ...itemMeshes.filter(mesh => mesh.userData.itemId !== item.id));
scene.remove(item.root);
itemStates.delete(item.id);
if (selectedItem === item) selectItem(null);
}
function clearAllItems() {
for (const item of [...itemStates.values()]) removeItem(item);
}
function getRect(item) {
const { w, d } = effectiveDimensions(item);
return {
x1: item.root.position.x - w / 2,
x2: item.root.position.x + w / 2,
z1: item.root.position.z - d / 2,
z2: item.root.position.z + d / 2
};
}
function overlapsCorridor(rect) {
const corridorMin = -CORRIDOR_WIDTH / 2;
const corridorMax = CORRIDOR_WIDTH / 2;
return rect.z1 < corridorMax && rect.z2 > corridorMin;
}
function intersectionArea(a, b) {
const width = Math.max(0, Math.min(a.x2, b.x2) - Math.max(a.x1, b.x1));
const depth = Math.max(0, Math.min(a.z2, b.z2) - Math.max(a.z1, b.z1));
return width * depth;
}
function unionArea(rectangles) {
if (!rectangles.length) return 0;
const xs = [...new Set(rectangles.flatMap(rect => [rect.x1, rect.x2]))].sort((a, b) => a - b);
let area = 0;
for (let i = 0; i < xs.length - 1; i++) {
const x0 = xs[i];
const x1 = xs[i + 1];
const middle = (x0 + x1) / 2;
const intervals = rectangles
.filter(rect => rect.x1 <= middle && rect.x2 >= middle)
.map(rect => [rect.z1, rect.z2])
.sort((a, b) => a[0] - b[0]);
if (!intervals.length) continue;
let currentStart = intervals[0][0];
let currentEnd = intervals[0][1];
for (let j = 1; j < intervals.length; j++) {
const [start, end] = intervals[j];
if (start > currentEnd) {
area += (x1 - x0) * (currentEnd - currentStart);
currentStart = start;
currentEnd = end;
} else {
currentEnd = Math.max(currentEnd, end);
}
}
area += (x1 - x0) * (currentEnd - currentStart);
}
return area;
}
function updateItemVisual(item) {
const rect = getRect(item);
item.invalid = overlapsCorridor(rect);
const color = item.invalid ? 0xdc4b4b : ACTIVITY_COLORS[item.activity];
const isSelected = selectedItem === item;
if (item.footprintPlane) {
item.footprintPlane.material.color.setHex(color);
item.footprintPlane.material.opacity = item.invalid ? .36 : isSelected ? .32 : .19;
}
if (item.footprintBorder) {
item.footprintBorder.material.color.setHex(item.invalid ? 0xdc4b4b : isSelected ? 0x173a36 : color);
item.footprintBorder.material.opacity = isSelected ? 1 : .82;
}
item.footprintGroup.visible = footprintVisible || item.invalid;
item.warning.visible = item.invalid;
if (item.label) item.label.visible = isSelected;
}
function computeStats() {
const areas = { study: 0, play: 0, meal: 0 };
const invalidItems = [];
const byActivity = { study: [], play: [], meal: [] };
for (const item of itemStates.values()) {
const rect = getRect(item);
if (overlapsCorridor(rect)) {
invalidItems.push(item);
} else {
byActivity[item.activity].push(rect);
}
}
for (const activity of Object.keys(areas)) {
areas[activity] = unionArea(byActivity[activity]);
}
const totalPossible = Object.values(GOALS).reduce((sum, goal) => sum + goal, 0);
const achieved = Object.keys(GOALS).reduce(
(sum, activity) => sum + Math.min(areas[activity], GOALS[activity]),
0
);
const score = Math.round((achieved / totalPossible) * 100);
return { areas, invalidItems, score };
}
function updateUI(stats) {
document.getElementById("scoreValue").textContent = `${stats.score}%`;
document.getElementById("scoreRing").style.setProperty("--score", stats.score);
const allComplete = Object.keys(GOALS).every(activity => stats.areas[activity] >= GOALS[activity]);
document.getElementById("scoreTitle").textContent = allComplete
? "Brief complete"
: stats.score > 0 ? "Good progress" : "Getting started";
for (const activity of Object.keys(GOALS)) {
const value = stats.areas[activity];
const percent = Math.min(100, (value / GOALS[activity]) * 100);
document.getElementById(`${activity}Value`).textContent =
`${Math.min(value, GOALS[activity]).toFixed(1)} / ${GOALS[activity]} m²`;
document.getElementById(`${activity}Bar`).style.width = `${percent}%`;
}
const corridorCard = document.getElementById("corridorCard");
const status = document.getElementById("roomStatus");
const warningList = document.getElementById("warningList");
corridorCard.classList.toggle("conflict", stats.invalidItems.length > 0);
status.classList.toggle("warning", stats.invalidItems.length > 0);
if (stats.invalidItems.length) {
document.getElementById("corridorTitle").textContent = `${stats.invalidItems.length} corridor conflict${stats.invalidItems.length > 1 ? "s" : ""}`;
document.getElementById("corridorCopy").textContent = "Red footprints overlap the main circulation route.";
warningList.innerHTML = stats.invalidItems
.slice(0, 3)
.map(item => `<div>⚠ ${item.def.name} overlaps corridor</div>`)
.join("") +
(stats.invalidItems.length > 3 ? `<div>+ ${stats.invalidItems.length - 3} more</div>` : "");
status.textContent = `${stats.invalidItems.length} corridor conflict${stats.invalidItems.length > 1 ? "s" : ""}`;
} else {
document.getElementById("corridorTitle").textContent = "Main corridor is clear";
document.getElementById("corridorCopy").textContent = "Keep the central 1.8 m-wide route free of activity footprints.";
warningList.innerHTML = "";
status.textContent = allComplete ? "All briefs met" : "Room in progress";
}
if (selectedItem) {
document.getElementById("selectedPosition").textContent =
`${selectedItem.root.position.x.toFixed(1)}, ${selectedItem.root.position.z.toFixed(1)} m`;
document.getElementById("selectedName").textContent = selectedItem.def.name;
document.getElementById("selectedMeta").textContent =
`${ACTIVITY_NAMES[selectedItem.activity]} · ${selectedItem.rotation}°${selectedItem.invalid ? " · Corridor conflict" : ""}`;
document.getElementById("zoneSelect").value = selectedItem.activity;
document.getElementById("selectionContent").classList.toggle("conflict", selectedItem.invalid);
} else {
document.getElementById("selectedPosition").textContent = "None";
}
}
function refreshAll() {
for (const item of itemStates.values()) updateItemVisual(item);
updateUI(computeStats());
}
function selectItem(item) {
selectedItem = item;
document.getElementById("selectionEmpty").hidden = !!item;
document.getElementById("selectionContent").hidden = !item;
refreshAll();
}
function clampItemPosition(item, x, z) {
const { w, d } = effectiveDimensions(item);
item.root.position.x = THREE.MathUtils.clamp(x, -ROOM_WIDTH / 2 + w / 2 + .06, ROOM_WIDTH / 2 - w / 2 - .06);
item.root.position.z = THREE.MathUtils.clamp(z, -ROOM_DEPTH / 2 + d / 2 + .06, ROOM_DEPTH / 2 - d / 2 - .06);
}
function rotateSelected() {
if (!selectedItem) return;
selectedItem.rotation = (selectedItem.rotation + 90) % 360;
selectedItem.model.rotation.y = selectedItem.rotation * Math.PI / 180;
rebuildFootprint(selectedItem);
refreshAll();
showToast(`${selectedItem.def.name} rotated 90°`);
}
function deleteSelected() {
if (!selectedItem) return;
const name = selectedItem.def.name;
removeItem(selectedItem);
refreshAll();
showToast(`${name} removed`);
}
function findOpenSpot(def) {
const candidates = [];
const existing = [...itemStates.values()].map(getRect);
for (let x = -7.8; x <= 7.8; x += .6) {
for (let z = -4.8; z <= 4.8; z += .6) {
const rect = {
x1: x - def.w / 2,
x2: x + def.w / 2,
z1: z - def.d / 2,
z2: z + def.d / 2
};
if (rect.x1 < -8.9 || rect.x2 > 8.9 || rect.z1 < -5.9 || rect.z2 > 5.9) continue;
if (overlapsCorridor(rect)) continue;
let overlap = 0;
for (const other of existing) overlap += intersectionArea(rect, other);
candidates.push({ x, z, overlap });
}
}
candidates.sort((a, b) => a.overlap - b.overlap || Math.abs(a.x) - Math.abs(b.x));
return candidates[0] || { x: 0, z: 3.2 };
}
function addItem(def, x = null, z = null, notify = true) {
if (x === null || z === null) {
const spot = findOpenSpot(def);
x = spot.x;
z = spot.z;
}
const item = createItem(def, x, z);
clampItemPosition(item, x, z);
refreshAll();
if (notify) {
const rect = getRect(item);
showToast(
overlapsCorridor(rect)
? `${def.name} placed — corridor overlap flagged`
: `${def.name} added to the room`,
overlapsCorridor(rect) ? "warning" : ""
);
}
return item;
}
function showToast(message, type = "") {
clearTimeout(toastTimer);
toast.textContent = message;
toast.className = type;
toast.classList.add("show");
toastTimer = setTimeout(() => toast.classList.remove("show"), 2600);
}
function applyCamera() {
if (cameraState.top) {
camera.position.set(
cameraState.target.x,
cameraState.target.y + cameraState.distance,
cameraState.target.z + .01
);
} else {
const sinPitch = Math.sin(cameraState.pitch);
camera.position.set(
cameraState.target.x + cameraState.distance * sinPitch * Math.sin(cameraState.yaw),
cameraState.target.y + cameraState.distance * Math.cos(cameraState.pitch),
cameraState.target.z + cameraState.distance * sinPitch * Math.cos(cameraState.yaw)
);
}
camera.lookAt(cameraState.target);
}
function resetCamera() {
cameraState.yaw = .67;
cameraState.pitch = .82;
cameraState.distance = 20;
cameraState.target.set(0, .15, 0);
cameraState.top = false;
document.getElementById("viewBtn").textContent = "Plan view";
applyCamera();
}
function getGroundPoint(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 point = new THREE.Vector3();
return raycaster.ray.intersectPlane(groundPlane, point) ? point : null;
}
function pickItem(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 hit = raycaster.intersectObjects(itemMeshes, false)[0];
return hit ? itemStates.get(hit.object.userData.itemId) : null;
}
function isCanvasAt(x, y) {
const element = document.elementFromPoint(x, y);
return element === renderer.domElement;
}
function makePreview(def) {
if (previewMesh) {
scene.remove(previewMesh);
previewMesh.geometry.dispose();
previewMesh.material.dispose();
}
previewMesh = new THREE.Mesh(
new THREE.PlaneGeometry(def.w, def.d),
makeMaterial(0x2f7d70, {
transparent: true,
opacity: .27,
depthWrite: false,
side: THREE.DoubleSide
})
);
previewMesh.rotation.x = -Math.PI / 2;
previewMesh.position.y = .065;
previewMesh.visible = false;
previewMesh.renderOrder = 8;
scene.add(previewMesh);
}
function renderCatalog() {
catalogList.innerHTML = "";
for (const def of CATALOG) {
const button = document.createElement("button");
button.type = "button";
button.className = "catalog-card";
button.dataset.id = def.id;
button.innerHTML = `
<span class="catalog-icon" style="background:${hexToCss(ACTIVITY_COLORS[def.activity])}1c">${def.icon}</span>
<span>
<span class="catalog-name">${def.name}</span>
<span class="catalog-meta">
<i class="tiny-dot" style="background:${hexToCss(ACTIVITY_COLORS[def.activity])}"></i>
${ACTIVITY_NAMES[def.activity]} · ${def.w.toFixed(1)} × ${def.d.toFixed(1)} m
</span>
</span>
`;
button.addEventListener("pointerdown", event => {
if (event.button !== 0) return;
event.preventDefault();
startCatalogDrag(def, event);
});
button.addEventListener("keydown", event => {
if (event.key === "Enter" || event.key === " ") {
event.preventDefault();
addItem(def);
}
});
catalogList.appendChild(button);
}
}
function hexToCss(hex) {
return `#${hex.toString(16).padStart(6, "0")}`;
}
function startCatalogDrag(def, event) {
catalogDrag = {
def,
startX: event.clientX,
startY: event.clientY,
moved: false
};
dragGhost.innerHTML = `<span>${def.icon}</span>${def.name}`;
dragGhost.style.display = "block";
dragGhost.style.left = `${event.clientX}px`;
dragGhost.style.top = `${event.clientY}px`;
makePreview(def);
}
window.addEventListener("pointermove", event => {
if (!catalogDrag) return;
const dx = event.clientX - catalogDrag.startX;
const dy = event.clientY - catalogDrag.startY;
if (Math.hypot(dx, dy) > 5) catalogDrag.moved = true;
dragGhost.style.left = `${event.clientX}px`;
dragGhost.style.top = `${event.clientY}px`;
if (isCanvasAt(event.clientX, event.clientY)) {
const point = getGroundPoint(event.clientX, event.clientY);
if (point && previewMesh) {
const rect = {
x1: point.x - catalogDrag.def.w / 2,
x2: point.x + catalogDrag.def.w / 2,
z1: point.z - catalogDrag.def.d / 2,
z2: point.z + catalogDrag.def.d / 2
};
const conflict = overlapsCorridor(rect);
previewMesh.material.color.setHex(conflict ? 0xdc4b4b : ACTIVITY_COLORS[catalogDrag.def.activity]);
previewMesh.position.set(point.x, .065, point.z);
previewMesh.visible = true;
}
} else if (previewMesh) {
previewMesh.visible = false;
}
});
window.addEventListener("pointerup", event => {
if (!catalogDrag) return;
const drag = catalogDrag;
catalogDrag = null;
dragGhost.style.display = "none";
if (previewMesh) previewMesh.visible = false;
if (isCanvasAt(event.clientX, event.clientY)) {
const point = getGroundPoint(event.clientX, event.clientY);
if (point) addItem(drag.def, point.x, point.z);
} else if (!drag.moved) {
addItem(drag.def);
}
});
renderer.domElement.addEventListener("pointerdown", event => {
if (event.button === 0) {
const item = pickItem(event.clientX, event.clientY);
if (item) {
selectItem(item);
const point = getGroundPoint(event.clientX, event.clientY);
canvasDrag = {
type: "item",
item,
offsetX: point ? item.root.position.x - point.x : 0,
offsetZ: point ? item.root.position.z - point.z : 0,
lastX: event.clientX,
lastY: event.clientY
};
} else {
canvasDrag = {
type: "orbit",
lastX: event.clientX,
lastY: event.clientY
};
}
} else {
canvasDrag = {
type: "pan",
lastX: event.clientX,
lastY: event.clientY
};
}
renderer.domElement.setPointerCapture(event.pointerId);
event.preventDefault();
});
renderer.domElement.addEventListener("pointermove", event => {
if (!canvasDrag) return;
const dx = event.clientX - canvasDrag.lastX;
const dy = event.clientY - canvasDrag.lastY;
canvasDrag.lastX = event.clientX;
canvasDrag.lastY = event.clientY;
if (canvasDrag.type === "item") {
const point = getGroundPoint(event.clientX, event.clientY);
if (point) {
const x = Math.round((point.x + canvasDrag.offsetX) * 20) / 20;
const z = Math.round((point.z + canvasDrag.offsetZ) * 20) / 20;
clampItemPosition(canvasDrag.item, x, z);
refreshAll();
}
}
if (canvasDrag.type === "orbit" && !cameraState.top) {
cameraState.yaw -= dx * .006;
cameraState.pitch = THREE.MathUtils.clamp(cameraState.pitch + dy * .004, .38, 1.25);
applyCamera();
}
if (canvasDrag.type === "pan") {
const scale = cameraState.distance * .0015;
const forward = new THREE.Vector3();
camera.getWorldDirection(forward);
forward.y = 0;
forward.normalize();
const right = new THREE.Vector3().crossVectors(forward, new THREE.Vector3(0, 1, 0)).normalize();
cameraState.target.addScaledVector(right, -dx * scale);
cameraState.target.addScaledVector(forward, dy * scale);
cameraState.target.x = THREE.MathUtils.clamp(cameraState.target.x, -6, 6);
cameraState.target.z = THREE.MathUtils.clamp(cameraState.target.z, -5, 5);
applyCamera();
}
});
function endCanvasDrag(event) {
if (canvasDrag?.type === "item") refreshAll();
canvasDrag = null;
if (event?.pointerId !== undefined && renderer.domElement.hasPointerCapture(event.pointerId)) {
renderer.domElement.releasePointerCapture(event.pointerId);
}
}
renderer.domElement.addEventListener("pointerup", endCanvasDrag);
renderer.domElement.addEventListener("pointercancel", endCanvasDrag);
renderer.domElement.addEventListener("contextmenu", event => event.preventDefault());
renderer.domElement.addEventListener("wheel", event => {
event.preventDefault();
cameraState.distance = THREE.MathUtils.clamp(
cameraState.distance + event.deltaY * .012,
10,
31
);
applyCamera();
}, { passive: false });
renderer.domElement.addEventListener("dblclick", resetCamera);
document.getElementById("footprintBtn").addEventListener("click", () => {
footprintVisible = !footprintVisible;
const button = document.getElementById("footprintBtn");
button.classList.toggle("active", footprintVisible);
button.setAttribute("aria-pressed", String(footprintVisible));
refreshAll();
showToast(footprintVisible ? "Activity footprints shown" : "Activity footprints hidden");
});
document.getElementById("viewBtn").addEventListener("click", () => {
cameraState.top = !cameraState.top;
cameraState.distance = cameraState.top ? 22 : 20;
document.getElementById("viewBtn").textContent = cameraState.top ? "3D view" : "Plan view";
applyCamera();
});
document.getElementById("resetViewBtn").addEventListener("click", resetCamera);
document.getElementById("rotateBtn").addEventListener("click", rotateSelected);
document.getElementById("deleteBtn").addEventListener("click", deleteSelected);
document.getElementById("zoneSelect").addEventListener("change", event => {
if (!selectedItem) return;
selectedItem.activity = event.target.value;
rebuildFootprint(selectedItem);
updateItemLabel(selectedItem);
refreshAll();
showToast(`${selectedItem.def.name} assigned to ${ACTIVITY_NAMES[selectedItem.activity]}`);
});
function resetSampleRoom() {
clearAllItems();
addItem(CATALOG.find(def => def.id === "studyDesk"), -4.7, -3.55, false);
addItem(CATALOG.find(def => def.id === "playRug"), 3.8, 3.25, false);
addItem(CATALOG.find(def => def.id === "diningTable"), 3.5, -3.45, false);
selectItem(null);
showToast("Sample room restored");
}
document.getElementById("resetRoomBtn").addEventListener("click", resetSampleRoom);
document.getElementById("clearRoomBtn").addEventListener("click", () => {
clearAllItems();
selectItem(null);
showToast("Room cleared — drag pieces in from the library");
});
document.getElementById("briefBtn").addEventListener("click", () => {
document.getElementById("dashboard").classList.toggle("open");
});
document.addEventListener("keydown", event => {
if (event.target.matches("input, select, textarea")) return;
if (event.key === "Escape") {
selectItem(null);
return;
}
if (!selectedItem) return;
const step = event.shiftKey ? .75 : .25;
let moved = false;
if (event.key === "ArrowLeft") {
clampItemPosition(selectedItem, selectedItem.root.position.x - step, selectedItem.root.position.z);
moved = true;
}
if (event.key === "ArrowRight") {
clampItemPosition(selectedItem, selectedItem.root.position.x + step, selectedItem.root.position.z);
moved = true;
}
if (event.key === "ArrowUp") {
clampItemPosition(selectedItem, selectedItem.root.position.x, selectedItem.root.position.z - step);
moved = true;
}
if (event.key === "ArrowDown") {
clampItemPosition(selectedItem, selectedItem.root.position.x, selectedItem.root.position.z + step);
moved = true;
}
if (moved) {
event.preventDefault();
refreshAll();
}
if (event.key.toLowerCase() === "r") {
event.preventDefault();
rotateSelected();
}
if (event.key === "Delete" || event.key === "Backspace") {
event.preventDefault();
deleteSelected();
}
});
window.addEventListener("resize", () => {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
});
createRoom();
renderCatalog();
resetSampleRoom();
applyCamera();
const clock = new THREE.Clock();
function animate() {
requestAnimationFrame(animate);
const elapsed = clock.getElapsedTime();
for (const item of itemStates.values()) {
if (item.invalid) {
item.marker.rotation.y = elapsed * 1.6;
item.marker.position.y = Math.sin(elapsed * 3.2) * .04;
}
if (item === selectedItem && item.footprintPlane) {
item.footprintPlane.material.opacity = .28 + Math.sin(elapsed * 2.8) * .06;
}
}
renderer.render(scene, camera);
}
animate();
</script>
</body>
</html>
```