Prompt specification
Build or customize the Three.js 3D scene "Arrange a public event within a fixed square perimeter" 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: Arrange a public event within a fixed square perimeter
Category: Voxel Worlds · Style: Voxel 3D
License: MIT · Reference: https://three3d.app/scene/arrange-a-public-event-within-a-fixed-square-perimeter-x2848
Scene Description Prompt:
Create a single self-contained HTML file using Three.js from cdnjs that shows Plaza Mayor in Madrid. Let users place fictional booths and seating while preserving entrance passages and a circulation loop. Compare layouts by open area and route connectivity. Voxel style.
Working Three.js Starter (arrange-a-public-event-within-a-fixed-square-perimeter-x2848):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Plaza Mayor — Spatial Planner</title>
<style>
:root {
--ink: #24343a;
--muted: #66777d;
--paper: #f7f3ea;
--panel: rgba(250, 247, 239, 0.96);
--line: #d9d5ca;
--teal: #147d78;
--teal-soft: #d9efeb;
--blue: #3477a8;
--red: #b94b3f;
--gold: #d19a3a;
--shadow: 0 12px 35px rgba(37, 45, 47, 0.16);
}
* { box-sizing: border-box; }
html, body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: #d7e1df;
color: var(--ink);
font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
button, input { font: inherit; }
button { -webkit-tap-highlight-color: transparent; }
#scene {
position: fixed;
inset: 0;
}
#scene canvas {
display: block;
width: 100%;
height: 100%;
outline: none;
}
.panel {
position: fixed;
z-index: 10;
top: 14px;
bottom: 14px;
width: 316px;
padding: 18px;
overflow: auto;
border: 1px solid rgba(255, 255, 255, 0.68);
border-radius: 18px;
background: var(--panel);
box-shadow: var(--shadow);
backdrop-filter: blur(14px);
scrollbar-width: thin;
scrollbar-color: #bac4c1 transparent;
}
#planner { left: 14px; }
#compare {
right: 14px;
width: 330px;
}
.eyebrow {
margin: 0 0 5px;
color: var(--teal);
font-size: 11px;
font-weight: 800;
letter-spacing: 0.15em;
text-transform: uppercase;
}
h1 {
margin: 0;
font-family: Georgia, "Times New Roman", serif;
font-size: 28px;
font-weight: 700;
line-height: 1.04;
}
h2 {
margin: 0;
font-family: Georgia, "Times New Roman", serif;
font-size: 21px;
}
.subtitle {
margin: 8px 0 15px;
color: var(--muted);
font-size: 12px;
line-height: 1.45;
}
.section {
margin-top: 17px;
padding-top: 15px;
border-top: 1px solid var(--line);
}
.section-title {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 9px;
font-size: 11px;
font-weight: 800;
letter-spacing: 0.1em;
text-transform: uppercase;
}
.constraint {
display: flex;
gap: 9px;
align-items: flex-start;
margin-top: 13px;
padding: 10px 11px;
border: 1px solid #b9dcd6;
border-radius: 11px;
background: var(--teal-soft);
color: #285d58;
font-size: 11px;
line-height: 1.4;
}
.constraint-icon {
display: grid;
flex: 0 0 22px;
width: 22px;
height: 22px;
place-items: center;
border-radius: 7px;
background: var(--teal);
color: white;
font-size: 12px;
font-weight: 900;
}
.tool-grid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 8px;
}
.tool {
display: flex;
min-height: 55px;
align-items: center;
gap: 9px;
padding: 9px;
border: 1px solid var(--line);
border-radius: 11px;
background: #fffdf8;
color: var(--ink);
cursor: pointer;
text-align: left;
transition: 140ms ease;
}
.tool:hover {
border-color: #8ebbb5;
transform: translateY(-1px);
}
.tool.active {
border-color: var(--teal);
background: #e5f3ef;
box-shadow: inset 0 0 0 1px var(--teal);
}
.tool-icon {
display: grid;
flex: 0 0 31px;
width: 31px;
height: 31px;
place-items: center;
border-radius: 8px;
background: #ece9df;
font-size: 17px;
}
.tool.active .tool-icon { background: var(--teal); color: white; }
.tool strong {
display: block;
font-size: 12px;
}
.tool small {
display: block;
margin-top: 2px;
color: var(--muted);
font-size: 9px;
}
.button-row {
display: flex;
gap: 7px;
margin-top: 9px;
}
.btn {
min-height: 34px;
padding: 7px 10px;
border: 1px solid var(--line);
border-radius: 9px;
background: #fffdf8;
color: var(--ink);
cursor: pointer;
font-size: 11px;
font-weight: 700;
transition: 140ms ease;
}
.btn:hover { border-color: #9eb8b4; background: white; }
.btn:active { transform: translateY(1px); }
.btn.primary {
border-color: var(--teal);
background: var(--teal);
color: white;
}
.btn.danger { color: var(--red); }
.btn:disabled { opacity: 0.42; cursor: default; }
.selection-card {
min-height: 57px;
padding: 10px 11px;
border: 1px dashed #c6c8bf;
border-radius: 10px;
background: rgba(255, 255, 255, 0.45);
color: var(--muted);
font-size: 11px;
line-height: 1.45;
}
.selection-card strong { color: var(--ink); }
.preset-row, .slot-row {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 7px;
}
.slot {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 6px;
margin-top: 8px;
padding: 9px;
border: 1px solid var(--line);
border-radius: 10px;
background: rgba(255, 255, 255, 0.5);
}
.slot-name {
grid-column: 1 / -1;
margin-bottom: 1px;
font-size: 11px;
font-weight: 800;
}
.switch {
display: flex;
align-items: center;
justify-content: space-between;
gap: 10px;
font-size: 11px;
font-weight: 700;
}
.switch input {
width: 35px;
height: 19px;
accent-color: var(--teal);
}
.hero-metric {
margin-top: 15px;
padding: 15px;
border-radius: 13px;
background: var(--ink);
color: white;
}
.hero-metric .label {
color: #b7c8c6;
font-size: 10px;
font-weight: 800;
letter-spacing: 0.12em;
text-transform: uppercase;
}
.hero-metric .value {
margin-top: 4px;
font-family: Georgia, "Times New Roman", serif;
font-size: 30px;
}
.hero-metric .sub {
margin-top: 4px;
color: #b7c8c6;
font-size: 10px;
}
.metric-grid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 8px;
margin-top: 9px;
}
.metric {
padding: 11px;
border: 1px solid var(--line);
border-radius: 11px;
background: rgba(255, 255, 255, 0.5);
}
.metric span {
display: block;
color: var(--muted);
font-size: 9px;
font-weight: 800;
letter-spacing: 0.07em;
text-transform: uppercase;
}
.metric strong {
display: block;
margin-top: 4px;
font-size: 17px;
}
.good { color: var(--teal); }
.warning { color: var(--red); }
table {
width: 100%;
border-collapse: collapse;
font-size: 10px;
}
th, td {
padding: 9px 4px;
border-bottom: 1px solid var(--line);
text-align: right;
}
th:first-child, td:first-child { text-align: left; }
th { color: var(--muted); font-weight: 700; }
td.current { background: rgba(20, 125, 120, 0.07); font-weight: 800; }
td.best { color: var(--teal); font-weight: 900; }
.legend {
display: grid;
gap: 8px;
margin-top: 12px;
font-size: 10px;
color: var(--muted);
}
.legend-row {
display: flex;
align-items: center;
gap: 8px;
}
.swatch {
width: 15px;
height: 15px;
border-radius: 4px;
border: 1px solid rgba(0, 0, 0, 0.1);
}
.swatch.route { background: rgba(52, 119, 168, 0.35); }
.swatch.loop { background: rgba(20, 125, 120, 0.35); }
.swatch.booth { background: #b94b3f; }
.swatch.seat { background: #d19a3a; }
.key {
display: inline-block;
min-width: 19px;
padding: 2px 5px;
border: 1px solid #c8ccc7;
border-bottom-width: 2px;
border-radius: 4px;
background: white;
color: var(--ink);
font-size: 9px;
text-align: center;
}
.help {
margin-top: 12px;
color: var(--muted);
font-size: 10px;
line-height: 1.55;
}
.bottom-hint {
position: fixed;
z-index: 5;
left: 50%;
bottom: 15px;
max-width: min(560px, calc(100vw - 700px));
padding: 9px 14px;
transform: translateX(-50%);
border: 1px solid rgba(255, 255, 255, 0.7);
border-radius: 999px;
background: rgba(250, 247, 239, 0.9);
box-shadow: 0 8px 24px rgba(37, 45, 47, 0.12);
color: var(--muted);
font-size: 10px;
text-align: center;
pointer-events: none;
}
#toast {
position: fixed;
z-index: 30;
left: 50%;
top: 22px;
max-width: min(520px, calc(100vw - 40px));
padding: 10px 15px;
transform: translate(-50%, -20px);
border-radius: 10px;
background: var(--ink);
box-shadow: var(--shadow);
color: white;
font-size: 11px;
opacity: 0;
pointer-events: none;
transition: 180ms ease;
}
#toast.show { opacity: 1; transform: translate(-50%, 0); }
#toast.bad { background: #9a3d36; }
.mobile-bar {
position: fixed;
z-index: 20;
top: 10px;
left: 50%;
display: none;
gap: 6px;
padding: 5px;
transform: translateX(-50%);
border-radius: 11px;
background: rgba(250, 247, 239, 0.94);
box-shadow: var(--shadow);
}
.mobile-bar button {
border: 0;
border-radius: 8px;
padding: 8px 11px;
background: transparent;
color: var(--ink);
font-size: 11px;
font-weight: 800;
}
@media (max-width: 900px) {
#compare { width: 300px; }
.bottom-hint { display: none; }
}
@media (max-width: 760px) {
.panel {
top: 66px;
bottom: 10px;
max-height: calc(100vh - 76px);
transition: transform 180ms ease;
}
#planner {
left: 10px;
width: min(316px, calc(100vw - 20px));
transform: translateX(calc(-100% - 20px));
}
#planner.open { transform: translateX(0); }
#compare {
right: 10px;
width: min(330px, calc(100vw - 20px));
transform: translateX(calc(100% + 20px));
}
#compare.open { transform: translateX(0); }
.mobile-bar { display: flex; }
}
</style>
</head>
<body>
<div id="scene" aria-label="Interactive 3D model of Plaza Mayor"></div>
<nav class="mobile-bar" aria-label="Panels">
<button id="showPlanner">Planner</button>
<button id="showCompare">Compare</button>
</nav>
<aside id="planner" class="panel" aria-label="Layout planner">
<p class="eyebrow">Madrid · Spatial planner</p>
<h1>Plaza Mayor</h1>
<p class="subtitle">Place fictional market booths and seating in a voxel model of Madrid’s central square.</p>
<div class="constraint">
<span class="constraint-icon">✓</span>
<span><strong>Protected circulation is active.</strong><br>Entrance passages and the perimeter loop cannot be blocked.</span>
</div>
<section class="section">
<div class="section-title"><span>1 · Choose an object</span></div>
<div class="tool-grid">
<button class="tool active" data-tool="select">
<span class="tool-icon">↖</span>
<span><strong>Select</strong><small>Inspect an object</small></span>
</button>
<button class="tool" data-tool="booth">
<span class="tool-icon">▦</span>
<span><strong>Booth</strong><small>2.5 × 2.5 m</small></span>
</button>
<button class="tool" data-tool="seating">
<span class="tool-icon">▰</span>
<span><strong>Seating</strong><small>2.5 × 1.25 m</small></span>
</button>
<button class="tool" data-tool="move">
<span class="tool-icon">✥</span>
<span><strong>Move</strong><small>Relocate selection</small></span>
</button>
</div>
<div class="button-row">
<button class="btn" id="rotateBtn">Rotate · R</button>
<button class="btn danger" id="deleteBtn">Delete</button>
</div>
</section>
<section class="section">
<div class="section-title"><span>Selection</span></div>
<div class="selection-card" id="selectionInfo">Nothing selected. Choose <strong>Select</strong> and click an object.</div>
<div class="button-row">
<button class="btn" id="undoBtn">↶ Undo</button>
<button class="btn danger" id="clearBtn">Clear layout</button>
</div>
</section>
<section class="section">
<div class="section-title"><span>2 · Try a starting layout</span></div>
<div class="preset-row">
<button class="btn" data-preset="market">Market day</button>
<button class="btn" data-preset="cafe">Café corner</button>
<button class="btn" data-preset="minimal">Minimal</button>
<button class="btn" id="resetView">Reset view</button>
</div>
</section>
<section class="section">
<div class="section-title"><span>3 · Save comparison slots</span></div>
<div class="slot-row">
<div class="slot">
<div class="slot-name">Slot A</div>
<button class="btn" id="saveA">Save</button>
<button class="btn" id="loadA">Load</button>
</div>
<div class="slot">
<div class="slot-name">Slot B</div>
<button class="btn" id="saveB">Save</button>
<button class="btn" id="loadB">Load</button>
</div>
</div>
</section>
<section class="section">
<label class="switch">
<span>Show protected routes</span>
<input id="routeToggle" type="checkbox" checked />
</label>
</section>
</aside>
<aside id="compare" class="panel" aria-label="Layout comparison">
<p class="eyebrow">Live analysis</p>
<h2>Layout comparison</h2>
<p class="subtitle">Open area and circulation are calculated from each saved layout.</p>
<div class="hero-metric">
<div class="label">Current usable open area</div>
<div class="value" id="metricArea">—</div>
<div class="sub" id="metricOpenPct">— of gross plaza area</div>
</div>
<div class="metric-grid">
<div class="metric">
<span>Entrances</span>
<strong id="metricGates">—</strong>
</div>
<div class="metric">
<span>Loop intact</span>
<strong id="metricLoop">—</strong>
</div>
<div class="metric">
<span>Route connectivity</span>
<strong id="metricConnect">—</strong>
</div>
<div class="metric">
<span>Placed objects</span>
<strong id="metricObjects">—</strong>
</div>
</div>
<section class="section">
<div class="section-title"><span>Scenario matrix</span></div>
<table aria-label="Layout metrics">
<thead>
<tr>
<th>Metric</th>
<th>Current</th>
<th>A</th>
<th>B</th>
</tr>
</thead>
<tbody>
<tr>
<th>Open area</th>
<td class="current" id="currentArea">—</td>
<td id="areaA">—</td>
<td id="areaB">—</td>
</tr>
<tr>
<th>Open %</th>
<td class="current" id="currentOpen">—</td>
<td id="openA">—</td>
<td id="openB">—</td>
</tr>
<tr>
<th>Entrances</th>
<td class="current" id="currentGates">—</td>
<td id="gatesA">—</td>
<td id="gatesB">—</td>
</tr>
<tr>
<th>Loop</th>
<td class="current" id="currentLoop">—</td>
<td id="loopA">—</td>
<td id="loopB">—</td>
</tr>
<tr>
<th>Connectivity</th>
<td class="current" id="currentConnect">—</td>
<td id="connectA">—</td>
<td id="connectB">—</td>
</tr>
</tbody>
</table>
</section>
<section class="section">
<div class="section-title"><span>Map legend</span></div>
<div class="legend">
<div class="legend-row"><span class="swatch route"></span>Protected entrance passage</div>
<div class="legend-row"><span class="swatch loop"></span>Protected circulation loop</div>
<div class="legend-row"><span class="swatch booth"></span>Fictional market booth</div>
<div class="legend-row"><span class="swatch seat"></span>Fictional seating</div>
</div>
</section>
<p class="help">
<strong>Controls:</strong> drag to orbit, right-drag to pan, and scroll to zoom.
<span class="key">B</span> booth · <span class="key">S</span> seating ·
<span class="key">V</span> select · <span class="key">M</span> move ·
<span class="key">R</span> rotate.
</p>
</aside>
<div class="bottom-hint" id="bottomHint">Select an object, or choose Booth / Seating and click the plaza.</div>
<div id="toast" role="status" aria-live="polite"></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 layout geometry
// ------------------------------------------------------------
const WORLD = {
width: 42,
depth: 35.5,
metersPerUnit: 130 / 42,
snap: 0.5
};
const GROSS_AREA = WORLD.width * WORLD.depth * WORLD.metersPerUnit ** 2;
const ROUTE_CELL = 0.5;
const FLOOR_Y = 0.04;
const ENTRANCE_RECTS = [
{ minX: -1.6, maxX: 1.6, minZ: -WORLD.depth / 2, maxZ: -8.5 },
{ minX: -1.6, maxX: 1.6, minZ: 8.5, maxZ: WORLD.depth / 2 },
{ minX: -WORLD.width / 2, maxX: -11, minZ: -1.6, maxZ: 1.6 },
{ minX: 11, maxX: WORLD.width / 2, minZ: -1.6, maxZ: 1.6 }
];
const LOOP_RECTS = [
{ minX: -11, maxX: 11, minZ: -8.5, maxZ: -6.3 },
{ minX: -11, maxX: 11, minZ: 6.3, maxZ: 8.5 },
{ minX: -11, maxX: -8.8, minZ: -8.5, maxZ: 8.5 },
{ minX: 8.8, maxX: 11, minZ: -8.5, maxZ: 8.5 }
];
const STATUE_RECT = { minX: -1.65, maxX: 1.65, minZ: -1.65, maxZ: 1.65 };
const PRESETS = {
market: [
{ id: 1, type: "booth", x: -5, z: -3, rot: 0, color: 0 },
{ id: 2, type: "booth", x: 5, z: -3, rot: 0, color: 1 },
{ id: 3, type: "seating", x: -5, z: 3, rot: 0, color: 0 },
{ id: 4, type: "seating", x: 5, z: 3, rot: 0, color: 1 }
],
cafe: [
{ id: 11, type: "booth", x: -5, z: -3, rot: 0, color: 2 },
{ id: 12, type: "booth", x: 5, z: 3, rot: 0, color: 0 },
{ id: 13, type: "seating", x: 0, z: -4.7, rot: 0, color: 1 },
{ id: 14, type: "seating", x: 0, z: 4.7, rot: 0, color: 2 }
],
minimal: [
{ id: 21, type: "booth", x: -5, z: -3, rot: 0, color: 0 }
]
};
const scene = new THREE.Scene();
scene.background = new THREE.Color(0xd6e2df);
scene.fog = new THREE.Fog(0xd6e2df, 78, 135);
const camera = new THREE.OrthographicCamera(-30, 30, 25, -25, 0.1, 220);
const renderer = new THREE.WebGLRenderer({ antialias: true, alpha: false });
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;
document.querySelector("#scene").appendChild(renderer.domElement);
const hemi = new THREE.HemisphereLight(0xeaf5f1, 0x8c765d, 2.0);
scene.add(hemi);
const sun = new THREE.DirectionalLight(0xfff1d2, 3.4);
sun.position.set(-28, 48, 24);
sun.castShadow = true;
sun.shadow.mapSize.set(2048, 2048);
sun.shadow.camera.left = -40;
sun.shadow.camera.right = 40;
sun.shadow.camera.top = 40;
sun.shadow.camera.bottom = -40;
sun.shadow.camera.near = 1;
sun.shadow.camera.far = 100;
sun.shadow.bias = -0.0004;
scene.add(sun);
const fill = new THREE.DirectionalLight(0x94bfc4, 0.75);
fill.position.set(30, 20, -30);
scene.add(fill);
const material = (color, extra = {}) =>
new THREE.MeshStandardMaterial({ color, roughness: 0.78, metalness: 0.02, ...extra });
const MAT = {
base: material(0x8f8170),
floor: material(0xd8c8a7),
floorEdge: material(0xc1aa84),
brick: material(0xa94d3f),
brickDark: material(0x843c34),
cream: material(0xeee3ca),
window: material(0x34464b, { roughness: 0.45 }),
roof: material(0x665b51),
route: new THREE.MeshBasicMaterial({
color: 0x438bc0, transparent: true, opacity: 0.18,
depthWrite: false, side: THREE.DoubleSide
}),
loop: new THREE.MeshBasicMaterial({
color: 0x238d83, transparent: true, opacity: 0.19,
depthWrite: false, side: THREE.DoubleSide
}),
stone: material(0xb9aa95),
stoneLight: material(0xd0c1a8),
bronze: material(0x5e6b56, { roughness: 0.6 }),
wood: material(0xa96f38),
woodLight: material(0xc78c4d),
metal: material(0x3c4b4d, { metalness: 0.45 }),
creamWhite: material(0xfff5dc),
boothRed: material(0xb84437),
boothBlue: material(0x397f99),
boothGold: material(0xd59b36),
boothCream: material(0xf5e5be)
};
function box(parent, sx, sy, sz, x, y, z, mat, shadow = true) {
const mesh = new THREE.Mesh(new THREE.BoxGeometry(sx, sy, sz), mat);
mesh.position.set(x, y, z);
mesh.castShadow = shadow;
mesh.receiveShadow = true;
parent.add(mesh);
return mesh;
}
// ------------------------------------------------------------
// Plaza floor, protected circulation, and voxel architecture
// ------------------------------------------------------------
box(scene, WORLD.width + 4.8, 0.85, WORLD.depth + 4.8, 0, -0.55, 0, MAT.base);
const floor = box(
scene,
WORLD.width,
0.24,
WORLD.depth,
0,
-0.12,
0,
MAT.floor
);
floor.userData.isGround = true;
const tilePoints = [];
for (let x = -WORLD.width / 2; x <= WORLD.width / 2; x += 1) {
tilePoints.push(x, 0.012, -WORLD.depth / 2, x, 0.012, WORLD.depth / 2);
}
for (let z = -WORLD.depth / 2; z <= WORLD.depth / 2; z += 1) {
tilePoints.push(-WORLD.width / 2, 0.012, z, WORLD.width / 2, 0.012, z);
}
const tileGeometry = new THREE.BufferGeometry();
tileGeometry.setAttribute("position", new THREE.Float32BufferAttribute(tilePoints, 3));
const tileLines = new THREE.LineSegments(
tileGeometry,
new THREE.LineBasicMaterial({ color: 0xb6a78e, transparent: true, opacity: 0.22 })
);
scene.add(tileLines);
function addRouteRect(rect, mat, lineColor) {
const w = rect.maxX - rect.minX;
const d = rect.maxZ - rect.minZ;
const cx = (rect.minX + rect.maxX) / 2;
const cz = (rect.minZ + rect.maxZ) / 2;
const plane = new THREE.Mesh(new THREE.PlaneGeometry(w, d), mat);
plane.rotation.x = -Math.PI / 2;
plane.position.set(cx, 0.025, cz);
scene.add(plane);
const pts = [
new THREE.Vector3(rect.minX, 0.035, rect.minZ),
new THREE.Vector3(rect.maxX, 0.035, rect.minZ),
new THREE.Vector3(rect.maxX, 0.035, rect.maxZ),
new THREE.Vector3(rect.minX, 0.035, rect.maxZ)
];
const line = new THREE.LineLoop(
new THREE.BufferGeometry().setFromPoints(pts),
new THREE.LineBasicMaterial({ color: lineColor, transparent: true, opacity: 0.8 })
);
scene.add(line);
}
const routeLayer = new THREE.Group();
scene.add(routeLayer);
ENTRANCE_RECTS.forEach(r => addRouteRect(r, MAT.route, 0x3477a8));
LOOP_RECTS.forEach(r => addRouteRect(r, MAT.loop, 0x147d78));
function makeLabel(text, accent = "#147d78") {
const canvas = document.createElement("canvas");
canvas.width = 512;
canvas.height = 112;
const ctx = canvas.getContext("2d");
ctx.fillStyle = "rgba(250,247,239,0.95)";
ctx.fillRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = accent;
ctx.fillRect(0, 0, 18, canvas.height);
ctx.fillStyle = "#24343a";
ctx.font = "700 38px system-ui";
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.fillText(text, 266, 57);
const texture = new THREE.CanvasTexture(canvas);
texture.colorSpace = THREE.SRGBColorSpace;
const sprite = new THREE.Sprite(new THREE.SpriteMaterial({ map: texture }));
sprite.scale.set(4.1, 0.9, 1);
return sprite;
}
function createFacade(length, x, z, rotation, gateName) {
const group = new THREE.Group();
group.position.set(x, 0, z);
group.rotation.y = rotation;
scene.add(group);
const gap = 3.4;
const segments = [
{ start: -length / 2, end: -gap / 2 },
{ start: gap / 2, end: length / 2 }
];
for (const segment of segments) {
const len = segment.end - segment.start;
const center = (segment.start + segment.end) / 2;
box(group, len, 10.4, 2.3, center, 5.2, 0, MAT.brick);
for (const y of [3.45, 6.95, 10.3]) {
box(group, len + 0.08, 0.28, 2.42, center, y, 0, MAT.cream);
}
const modules = Math.max(2, Math.floor(len / 2.55));
const step = len / modules;
for (let i = 0; i < modules; i++) {
const ux = segment.start + step * (i + 0.5);
box(group, 1.28, 2.05, 0.1, ux, 1.45, 1.18, MAT.window, false);
box(group, 0.9, 0.48, 0.1, ux, 2.67, 1.18, MAT.window, false);
box(group, 0.26, 2.95, 0.16, segment.start + step * i, 1.65, 1.25, MAT.cream);
if (i % 2 === 0) {
for (const y of [5.15, 8.42]) {
box(group, 0.78, 1.28, 0.1, ux, y, 1.18, MAT.window, false);
box(group, 1.02, 0.18, 0.17, ux, y - 0.72, 1.25, MAT.cream);
box(group, 1.02, 0.18, 0.17, ux, y + 0.72, 1.25, MAT.cream);
}
}
}
box(group, len + 0.18, 0.42, 2.65, center, 10.72, 0, MAT.brickDark);
}
// Central arched gateway.
box(group, gap - 0.25, 3.55, 2.28, 0, 1.78, 0, MAT.window, false);
box(group, gap + 0.15, 0.32, 2.48, 0, 3.66, 0, MAT.cream);
box(group, 0.48, 3.7, 2.4, -gap / 2 - 0.2, 1.85, 0, MAT.brick);
box(group, 0.48, 3.7, 2.4, gap / 2 + 0.2, 1.85, 0, MAT.brick);
box(group, gap + 1.35, 3.0, 2.34, 0, 8.15, 0, MAT.brick);
box(group, gap + 1.6, 0.28, 2.5, 0, 6.85, 0, MAT.cream);
box(group, gap + 1.8, 0.42, 2.62, 0, 9.82, 0, MAT.brickDark);
box(group, gap + 2.2, 0.28, 2.75, 0, 10.2, 0, MAT.cream);
const label = makeLabel(gateName);
label.position.set(0, 4.15, 1.55);
label.scale.set(3.3, 0.72, 1);
group.add(label);
}
createFacade(WORLD.width, 0, -WORLD.depth / 2 - 1.15, 0, "CALLE DE MAYOR");
createFacade(WORLD.width, 0, WORLD.depth / 2 + 1.15, Math.PI, "CALLE DE SAL");
createFacade(WORLD.depth, -WORLD.width / 2 - 1.15, 0, -Math.PI / 2, "CALLE DE FELIPE III");
createFacade(WORLD.depth, WORLD.width / 2 + 1.15, 0, Math.PI / 2, "CALLE DE MAYOR");
// Corner towers.
for (const sx of [-1, 1]) {
for (const sz of [-1, 1]) {
const tower = new THREE.Group();
tower.position.set(
sx * (WORLD.width / 2 + 1.1),
0,
sz * (WORLD.depth / 2 + 1.1)
);
scene.add(tower);
box(tower, 5.2, 12.1, 5.2, 0, 6.05, 0, MAT.brick);
for (const y of [0.65, 3.65, 6.95, 10.2]) {
box(tower, 5.35, 0.25, 5.35, 0, y, 0, MAT.cream);
}
box(tower, 5.8, 0.55, 5.8, 0, 12.35, 0, MAT.brickDark);
box(tower, 4.7, 0.35, 4.7, 0, 12.8, 0, MAT.cream);
}
}
// Voxel equestrian monument at the center.
const monument = new THREE.Group();
scene.add(monument);
box(monument, 3.7, 0.32, 3.7, 0, 0.16, 0, MAT.stoneLight);
box(monument, 3.05, 0.32, 3.05, 0, 0.48, 0, MAT.stone);
box(monument, 2.25, 1.45, 2.25, 0, 1.34, 0, MAT.stoneLight);
box(monument, 1.8, 0.28, 1.8, 0, 2.18, 0, MAT.stone);
box(monument, 1.8, 0.9, 0.65, 0.05, 2.72, 0, MAT.bronze);
box(monument, 0.55, 1.25, 0.58, 0.82, 3.12, 0, MAT.bronze);
box(monument, 0.78, 0.48, 0.55, 1.03, 3.65, 0, MAT.bronze);
for (const x of [-0.58, 0.62]) {
for (const z of [-0.23, 0.23]) {
box(monument, 0.22, 1.05, 0.22, x, 2.13, z, MAT.bronze);
}
}
box(monument, 0.54, 1.05, 0.48, -0.2, 3.78, 0, MAT.bronze);
box(monument, 0.5, 0.43, 0.5, -0.2, 4.48, 0, MAT.bronze);
// ------------------------------------------------------------
// Application state
// ------------------------------------------------------------
let items = structuredClone(PRESETS.market);
let selectedId = null;
let activeTool = "select";
let pendingRotation = 0;
let pendingMove = null;
let nextId = Math.max(...items.map(i => i.id)) + 1;
let undoStack = [];
let ghost = null;
let selectionHelper = null;
let toastTimer = null;
let slots = {
a: structuredClone(PRESETS.market),
b: structuredClone(PRESETS.cafe)
};
try {
const stored = JSON.parse(localStorage.getItem("plaza-mayor-layout-slots"));
if (stored?.a && stored?.b) slots = stored;
} catch (_) {}
const itemLayer = new THREE.Group();
scene.add(itemLayer);
const boothPalettes = [
[MAT.boothRed, MAT.boothCream],
[MAT.boothBlue, MAT.boothCream],
[MAT.boothGold, MAT.boothCream]
];
function itemDimensions(type, rot = 0) {
let w = type === "booth" ? 2.5 : 2.5;
let d = type === "booth" ? 2.5 : 1.25;
if (rot % 2 === 1) [w, d] = [d, w];
return { w, d };
}
function footprint(item) {
const dims = itemDimensions(item.type, item.rot);
return {
minX: item.x - dims.w / 2,
maxX: item.x + dims.w / 2,
minZ: item.z - dims.d / 2,
maxZ: item.z + dims.d / 2
};
}
function rectsOverlap(a, b) {
return (
a.minX < b.maxX - 0.001 &&
a.maxX > b.minX + 0.001 &&
a.minZ < b.maxZ - 0.001 &&
a.maxZ > b.minZ + 0.001
);
}
function validateCandidate(candidate, ignoredId = null) {
const rect = footprint(candidate);
const halfW = (rect.maxX - rect.minX) / 2;
const halfD = (rect.maxZ - rect.minZ) / 2;
if (
candidate.x - halfW < -WORLD.width / 2 ||
candidate.x + halfW > WORLD.width / 2 ||
candidate.z - halfD < -WORLD.depth / 2 ||
candidate.z + halfD > WORLD.depth / 2
) {
return { ok: false, reason: "That object would extend beyond the plaza floor." };
}
if (ENTRANCE_RECTS.some(r => rectsOverlap(rect, r))) {
return { ok: false, reason: "Keep the entrance passages clear." };
}
if (LOOP_RECTS.some(r => rectsOverlap(rect, r))) {
return { ok: false, reason: "Keep the circulation loop clear." };
}
if (rectsOverlap(rect, STATUE_RECT)) {
return { ok: false, reason: "The central monument must remain unobstructed." };
}
for (const item of items) {
if (item.id === ignoredId) continue;
if (rectsOverlap(rect, footprint(item))) {
return { ok: false, reason: "That position overlaps another object." };
}
}
return { ok: true, reason: "" };
}
function makeBoothSign(text) {
const canvas = document.createElement("canvas");
canvas.width = 256;
canvas.height = 80;
const ctx = canvas.getContext("2d");
ctx.fillStyle = "#fff4d7";
ctx.fillRect(0, 0, 256, 80);
ctx.fillStyle = "#9f3e34";
ctx.fillRect(0, 0, 14, 80);
ctx.fillStyle = "#28383c";
ctx.font = "700 31px system-ui";
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.fillText(text, 139, 42);
const texture = new THREE.CanvasTexture(canvas);
texture.colorSpace = THREE.SRGBColorSpace;
return new THREE.Mesh(
new THREE.PlaneGeometry(1.42, 0.44),
new THREE.MeshBasicMaterial({ map: texture })
);
}
function createItemModel(item) {
const root = new THREE.Group();
root.position.set(item.x, FLOOR_Y, item.z);
root.rotation.y = item.rot * Math.PI / 2;
root.userData.itemId = item.id;
if (item.type === "booth") {
const palette = boothPalettes[item.color % boothPalettes.length];
box(root, 2.35, 0.16, 2.2, 0, 0.08, 0, MAT.wood);
box(root, 1.95, 0.95, 1.15, 0, 0.62, 0.46, palette[0]);
box(root, 2.12, 0.14, 1.35, 0, 1.16, 0.46, MAT.creamWhite);
for (const x of [-0.95, 0.95]) {
for (const z of [-0.9, 0.9]) {
box(root, 0.13, 2.32, 0.13, x, 1.27, z, MAT.woodLight);
}
}
for (let i = 0; i < 6; i++) {
const x = -1.08 + i * 0.432;
box(root, 0.43, 0.25, 2.25, x, 2.48, 0, i % 2 ? MAT.boothCream : palette[0]);
}
box(root, 2.62, 0.18, 2.55, 0, 2.66, 0, palette[0]);
const sign = makeBoothSign(`BOOTH ${String(item.id).padStart(2, "0")}`);
sign.position.set(0, 2.05, 1.015);
root.add(sign);
box(root, 0.55, 0.55, 0.42, -0.58, 1.52, 0.45, MAT.boothGold);
box(root, 0.42, 0.42, 0.42, 0.45, 1.5, 0.45, MAT.boothGold);
} else {
// Bench slats.
for (let i = 0; i < 3; i++) {
box(root, 2.2, 0.12, 0.19, 0, 0.63, -0.37 + i * 0.22, MAT.woodLight);
}
box(root, 2.2, 0.65, 0.13, 0, 1.0, -0.5, MAT.wood);
for (const x of [-0.82, 0.82]) {
box(root, 0.13, 0.65, 0.55, x, 0.33, -0.25, MAT.metal);
}
// Small café table and stools.
box(root, 0.58, 0.12, 0.58, 0.42, 0.86, 0.32, MAT.woodLight);
box(root, 0.13, 0.78, 0.13, 0.42, 0.43, 0.32, MAT.metal);
for (const x of [-0.02, 0.87]) {
box(root, 0.4, 0.13, 0.4, x, 0.47, 0.32, MAT.boothGold);
box(root, 0.13, 0.42, 0.13, x, 0.22, 0.32, MAT.metal);
}
}
return root;
}
function clearSelectionHelper() {
if (selectionHelper) {
scene.remove(selectionHelper);
selectionHelper.geometry.dispose();
selectionHelper.material.dispose();
selectionHelper = null;
}
}
function rebuildItems() {
while (itemLayer.children.length) {
const child = itemLayer.children[0];
itemLayer.remove(child);
child.traverse(node => {
if (node.geometry) node.geometry.dispose();
});
}
for (const item of items) itemLayer.add(createItemModel(item));
clearSelectionHelper();
const selected = items.find(i => i.id === selectedId);
if (selected) {
const model = itemLayer.children.find(c => c.userData.itemId === selected.id);
if (model) {
selectionHelper = new THREE.BoxHelper(model, 0x167e78);
selectionHelper.material.depthTest = false;
selectionHelper.renderOrder = 10;
scene.add(selectionHelper);
}
}
}
function makeGhost(type, rot) {
if (ghost) {
scene.remove(ghost);
ghost.traverse(node => {
if (node.geometry) node.geometry.dispose();
if (node.material) node.material.dispose();
});
}
const dims = itemDimensions(type, rot);
const group = new THREE.Group();
group.rotation.y = rot * Math.PI / 2;
const fillMat = new THREE.MeshBasicMaterial({
color: 0x1e9c83,
transparent: true,
opacity: 0.35,
depthWrite: false
});
const edgeMat = new THREE.MeshBasicMaterial({
color: 0x0f6d62,
transparent: true,
opacity: 0.75,
depthWrite: false
});
const slab = new THREE.Mesh(new THREE.BoxGeometry(dims.w, 0.07, dims.d), fillMat);
slab.position.y = 0.06;
group.add(slab);
const outline = new THREE.LineSegments(
new THREE.EdgesGeometry(new THREE.BoxGeometry(dims.w, type === "booth" ? 2.5 : 0.9, dims.d)),
new THREE.LineBasicMaterial({ color: 0x0f6d62 })
);
outline.position.y = type === "booth" ? 1.25 : 0.45;
group.add(outline);
group.userData.fillMat = fillMat;
group.userData.edgeMat = edgeMat;
ghost = group;
scene.add(ghost);
}
function setGhostValidity(valid) {
if (!ghost) return;
const color = valid ? 0x168878 : 0xc44b42;
ghost.userData.fillMat.color.setHex(color);
ghost.userData.edgeMat.color.setHex(color);
}
function setTool(tool) {
activeTool = tool;
pendingMove = null;
pendingRotation = 0;
if (tool === "move") {
const selected = items.find(i => i.id === selectedId);
if (!selected) {
toast("Select an object first, then choose Move.");
activeTool = "select";
} else {
pendingMove = { id: selected.id, type: selected.type, rot: selected.rot };
pendingRotation = selected.rot;
makeGhost(selected.type, pendingRotation);
}
}
document.querySelectorAll("[data-tool]").forEach(button => {
button.classList.toggle("active", button.dataset.tool === activeTool);
});
renderer.domElement.style.cursor =
activeTool === "select" ? "default" : "crosshair";
const hints = {
select: "Select an object, or choose Booth / Seating and click the plaza.",
booth: "Click an open plaza area to place a booth. Protected routes turn red.",
seating: "Click an open plaza area to place seating. Protected routes turn red.",
move: "Click a new valid position to move the selected object."
};
document.querySelector("#bottomHint").textContent = hints[activeTool];
}
function selectItem(id) {
selectedId = id;
rebuildItems();
updateSelectionInfo();
}
function updateSelectionInfo() {
const el = document.querySelector("#selectionInfo");
const item = items.find(i => i.id === selectedId);
if (!item) {
el.innerHTML = "Nothing selected. Choose <strong>Select</strong> and click an object.";
return;
}
const dims = itemDimensions(item.type, item.rot);
el.innerHTML =
`<strong>${item.type === "booth" ? "Market booth" : "Café seating"} #${item.id}</strong><br>` +
`Footprint ${dims.w.toFixed(2)} × ${dims.d.toFixed(2)} m · ` +
`position (${item.x.toFixed(1)}, ${item.z.toFixed(1)})`;
}
function pushHistory() {
undoStack.push(structuredClone(items));
if (undoStack.length > 30) undoStack.shift();
}
function toast(message, bad = false) {
const el = document.querySelector("#toast");
el.textContent = message;
el.classList.toggle("bad", bad);
el.classList.add("show");
clearTimeout(toastTimer);
toastTimer = setTimeout(() => el.classList.remove("show"), 2400);
}
function addItem(candidate) {
const validation = validateCandidate(candidate);
if (!validation.ok) {
toast(validation.reason, true);
return false;
}
pushHistory();
candidate.id = nextId++;
items.push(candidate);
rebuildItems();
updateMetrics();
toast(`${candidate.type === "booth" ? "Booth" : "Seating"} placed.`);
return true;
}
function moveSelected(candidate) {
const current = items.find(i => i.id === pendingMove?.id);
if (!current) return;
const validation = validateCandidate(candidate, current.id);
if (!validation.ok) {
toast(validation.reason, true);
return;
}
pushHistory();
current.x = candidate.x;
current.z = candidate.z;
current.rot = candidate.rot;
selectedId = current.id;
rebuildItems();
updateMetrics();
toast("Object moved.");
}
function rotateSelection() {
if (pendingMove) {
pendingRotation = (pendingRotation + 1) % 2;
makeGhost(pendingMove.type, pendingRotation);
return;
}
const item = items.find(i => i.id === selectedId);
if (!item) return;
const candidate = { ...item, rot: (item.rot + 1) % 2 };
const validation = validateCandidate(candidate, item.id);
if (!validation.ok) {
toast(validation.reason, true);
return;
}
pushHistory();
item.rot = candidate.rot;
rebuildItems();
updateMetrics();
}
function deleteSelection() {
const item = items.find(i => i.id === selectedId);
if (!item) return;
pushHistory();
items = items.filter(i => i.id !== selectedId);
selectedId = null;
pendingMove = null;
rebuildItems();
updateSelectionInfo();
updateMetrics();
toast("Object removed.");
}
function undo() {
if (!undoStack.length) return;
items = undoStack.pop();
selectedId = null;
pendingMove = null;
nextId = Math.max(0, ...items.map(i => i.id)) + 1;
rebuildItems();
updateSelectionInfo();
updateMetrics();
toast("Last change undone.");
}
function clearLayout() {
if (!items.length) return;
pushHistory();
items = [];
selectedId = null;
pendingMove = null;
rebuildItems();
updateSelectionInfo();
updateMetrics();
toast("Layout cleared. Protected routes remain open.");
}
function loadPreset(name) {
pushHistory();
items = structuredClone(PRESETS[name]);
selectedId = null;
pendingMove = null;
nextId = Math.max(0, ...items.map(i => i.id)) + 1;
rebuildItems();
updateSelectionInfo();
updateMetrics();
toast(`${name[0].toUpperCase() + name.slice(1)} layout loaded.`);
}
// ------------------------------------------------------------
// Area and route connectivity calculations
// ------------------------------------------------------------
function computeMetrics(layout) {
const m2 = WORLD.metersPerUnit ** 2;
let occupied = 0;
for (const item of layout) {
const dims = itemDimensions(item.type, item.rot);
occupied += dims.w * dims.d * m2;
}
occupied +=
(STATUE_RECT.maxX - STATUE_RECT.minX) *
(STATUE_RECT.maxZ - STATUE_RECT.minZ) * m2;
const openArea = Math.max(0, GROSS_AREA - occupied);
const openPercent = openArea / GROSS_AREA * 100;
const nx = Math.ceil(WORLD.width / ROUTE_CELL);
const nz = Math.ceil(WORLD.depth / ROUTE_CELL);
const blocked = new Uint8Array(nx * nz);
const ringMask = new Uint8Array(nx * nz);
const itemRects = layout.map(footprint);
let passable = 0;
let ringCells = 0;
for (let iz = 0; iz < nz; iz++) {
for (let ix = 0; ix < nx; ix++) {
const x = -WORLD.width / 2 + (ix + 0.5) * ROUTE_CELL;
const z = -WORLD.depth / 2 + (iz + 0.5) * ROUTE_CELL;
const index = iz * nx + ix;
if (LOOP_RECTS.some(r => rectsOverlap({ minX: x, maxX: x, minZ: z, maxZ: z }, r))) {
ringMask[index] = 1;
ringCells++;
}
const isBlocked =
rectsOverlap({ minX: x, maxX: x, minZ: z, maxZ: z }, STATUE_RECT) ||
itemRects.some(r => rectsOverlap({ minX: x, maxX: x, minZ: z, maxZ: z }, r));
blocked[index] = isBlocked ? 1 : 0;
if (!isBlocked) passable++;
}
}
const starts = [
Math.floor(nx / 2),
(nz - 1) * nx + Math.floor(nx / 2),
Math.floor(nz / 2),
Math.floor(nz / 2) * nx + nx - 1
];
const union = new Uint8Array(nx * nz);
const gateVisits = [];
for (const start of starts) {
const visited = new Uint8Array(nx * nz);
const queue = new Int32Array(nx * nz);
let head = 0;
let tail = 0;
queue[tail++] = start;
visited[start] = 1;
while (head < tail) {
const index = queue[head++];
const ix = index % nx;
const iz = Math.floor(index / nx);
const neighbors = [];
if (ix > 0) neighbors.push(index - 1);
if (ix < nx - 1) neighbors.push(index + 1);
if (iz > 0) neighbors.push(index - nx);
if (iz < nz - 1) neighbors.push(index + nx);
for (const n of neighbors) {
if (!visited[n] && !blocked[n]) {
visited[n] = 1;
queue[tail++] = n;
}
}
}
let reachesRing = false;
for (let i = 0; i < visited.length; i++) {
if (visited[i]) union[i] = 1;
if (visited[i] && ringMask[i]) reachesRing = true;
}
gateVisits.push(reachesRing);
}
let reachable = 0;
let reachableRing = 0;
let freeRing = 0;
for (let i = 0; i < union.length; i++) {
if (union[i]) reachable++;
if (ringMask[i]) {
if (!blocked[i]) freeRing++;
if (union[i]) reachableRing++;
}
}
const connectedGates = gateVisits.filter(Boolean).length;
const connectivity = passable ? reachable / passable * 100 : 100;
const loopIntegrity = ringCells ? freeRing / ringCells * 100 : 100;
return {
openArea,
openPercent,
connectedGates,
totalGates: 4,
connectivity,
loopIntegrity,
objects: layout.length,
reachableRing,
ringCells
};
}
const formatNumber = value => Math.round(value).toLocaleString("en-US");
const formatPercent = value => `${value.toFixed(1)}%`;
function updateMetrics() {
const current = computeMetrics(items);
const a = computeMetrics(slots.a);
const b = computeMetrics(slots.b);
document.querySelector("#metricArea").textContent = `${formatNumber(current.openArea)} m²`;
document.querySelector("#metricOpenPct").textContent =
`${formatPercent(current.openPercent)} of gross plaza area`;
document.querySelector("#metricGates").textContent =
`${current.connectedGates}/4`;
document.querySelector("#metricGates").className =
current.connectedGates === 4 ? "good" : "warning";
document.querySelector("#metricLoop").textContent =
formatPercent(current.loopIntegrity);
document.querySelector("#metricLoop").className =
current.loopIntegrity >= 99.9 ? "good" : "warning";
document.querySelector("#metricConnect").textContent =
formatPercent(current.connectivity);
document.querySelector("#metricConnect").className =
current.connectivity >= 99.9 ? "good" : "warning";
document.querySelector("#metricObjects").textContent = current.objects;
const set = (id, value) => {
document.querySelector(id).textContent = value;
};
set("#currentArea", `${formatNumber(current.openArea)} m²`);
set("#currentOpen", formatPercent(current.openPercent));
set("#currentGates", `${current.connectedGates}/4`);
set("#currentLoop", formatPercent(current.loopIntegrity));
set("#currentConnect", formatPercent(current.connectivity));
set("#areaA", `${formatNumber(a.openArea)} m²`);
set("#openA", formatPercent(a.openPercent));
set("#gatesA", `${a.connectedGates}/4`);
set("#loopA", formatPercent(a.loopIntegrity));
set("#connectA", formatPercent(a.connectivity));
set("#areaB", `${formatNumber(b.openArea)} m²`);
set("#openB", formatPercent(b.openPercent));
set("#gatesB", `${b.connectedGates}/4`);
set("#loopB", formatPercent(b.loopIntegrity));
set("#connectB", formatPercent(b.connectivity));
const bestOpen = Math.max(current.openArea, a.openArea, b.openArea);
const bestConnect = Math.max(current.connectivity, a.connectivity, b.connectivity);
document.querySelector("#currentArea").classList.toggle("best", current.openArea === bestOpen);
document.querySelector("#areaA").classList.toggle("best", a.openArea === bestOpen);
document.querySelector("#areaB").classList.toggle("best", b.openArea === bestOpen);
document.querySelector("#currentConnect").classList.toggle("best", current.connectivity === bestConnect);
document.querySelector("#connectA").classList.toggle("best", a.connectivity === bestConnect);
document.querySelector("#connectB").classList.toggle("best", b.connectivity === bestConnect);
}
function saveSlot(slot) {
slots[slot] = structuredClone(items);
try {
localStorage.setItem("plaza-mayor-layout-slots", JSON.stringify(slots));
} catch (_) {}
updateMetrics();
toast(`Current layout saved to slot ${slot.toUpperCase()}.`);
}
function loadSlot(slot) {
pushHistory();
items = structuredClone(slots[slot]);
selectedId = null;
pendingMove = null;
nextId = Math.max(0, ...items.map(i => i.id)) + 1;
rebuildItems();
updateSelectionInfo();
updateMetrics();
toast(`Slot ${slot.toUpperCase()} loaded.`);
}
// ------------------------------------------------------------
// Custom camera controls: orbit, pan, zoom
// ------------------------------------------------------------
const controls = {
target: new THREE.Vector3(0, 1.7, 0),
azimuth: 0.72,
polar: 0.82,
zoom: 1,
dragging: false,
button: 0,
startX: 0,
startY: 0,
lastX: 0,
lastY: 0,
moved: false
};
function updateCamera() {
const radius = 70;
const sinPolar = Math.sin(controls.polar);
camera.position.set(
controls.target.x + Math.sin(controls.azimuth) * sinPolar * radius,
controls.target.y + Math.sin(controls.polar) * radius,
controls.target.z + Math.cos(controls.azimuth) * sinPolar * radius
);
camera.lookAt(controls.target);
camera.zoom = controls.zoom;
camera.updateProjectionMatrix();
}
function resetCamera() {
controls.target.set(0, 1.7, 0);
controls.azimuth = 0.72;
controls.polar = 0.82;
controls.zoom = 1;
updateCamera();
}
function panCamera(dx, dy) {
const right = new THREE.Vector3();
camera.getWorldDirection(right);
right.y = 0;
right.normalize();
const forward = controls.target.clone().sub(camera.position);
forward.y = 0;
forward.normalize();
const scale = 48 / camera.zoom / renderer.domElement.clientHeight * 1.25;
controls.target.addScaledVector(right, -dx * scale);
controls.target.addScaledVector(forward, dy * scale);
updateCamera();
}
renderer.domElement.addEventListener("contextmenu", e => e.preventDefault());
renderer.domElement.addEventListener("pointerdown", event => {
controls.dragging = true;
controls.button = event.button;
controls.startX = controls.lastX = event.clientX;
controls.startY = controls.lastY = event.clientY;
controls.moved = false;
renderer.domElement.setPointerCapture(event.pointerId);
});
renderer.domElement.addEventListener("pointermove", event => {
const dx = event.clientX - controls.lastX;
const dy = event.clientY - controls.lastY;
controls.lastX = event.clientX;
controls.lastY = event.clientY;
if (controls.dragging) {
const totalDistance = Math.hypot(
event.clientX - controls.startX,
event.clientY - controls.startY
);
if (totalDistance > 4) controls.moved = true;
if (controls.moved) {
if (controls.button === 0) {
controls.azimuth -= dx * 0.006;
controls.polar = THREE.MathUtils.clamp(
controls.polar - dy * 0.005,
0.32,
1.22
);
updateCamera();
} else {
panCamera(dx, dy);
}
}
}
updateGhostFromPointer(event);
});
renderer.domElement.addEventListener("pointerup", event => {
const wasClick =
controls.dragging &&
!controls.moved &&
controls.button === 0 &&
Math.hypot(
event.clientX - controls.startX,
event.clientY - controls.startY
) < 5;
controls.dragging = false;
if (renderer.domElement.hasPointerCapture(event.pointerId)) {
renderer.domElement.releasePointerCapture(event.pointerId);
}
if (wasClick) handleSceneClick(event);
});
renderer.domElement.addEventListener("pointercancel", () => {
controls.dragging = false;
});
renderer.domElement.addEventListener("wheel", event => {
event.preventDefault();
controls.zoom = THREE.MathUtils.clamp(
controls.zoom * (event.deltaY > 0 ? 0.92 : 1.08),
0.62,
2.4
);
updateCamera();
}, { passive: false });
// ------------------------------------------------------------
// Picking and placement
// ------------------------------------------------------------
const raycaster = new THREE.Raycaster();
const pointer = new THREE.Vector2();
function pointerToNDC(event) {
const rect = renderer.domElement.getBoundingClientRect();
pointer.x = ((event.clientX - rect.left) / rect.width) * 2 - 1;
pointer.y = -((event.clientY - rect.top) / rect.height) * 2 + 1;
raycaster.setFromCamera(pointer, camera);
}
function groundPoint(event) {
pointerToNDC(event);
const hit = raycaster.intersectObject(floor, false)[0];
return hit ? hit.point : null;
}
function updateGhostFromPointer(event) {
if (activeTool !== "booth" && activeTool !== "seating" && activeTool !== "move") {
return;
}
const point = groundPoint(event);
if (!point) {
if (ghost) ghost.visible = false;
return;
}
const type = activeTool === "move"
? pendingMove?.type
: activeTool;
if (!type) return;
const x = Math.round(point.x / WORLD.snap) * WORLD.snap;
const z = Math.round(point.z / WORLD.snap) * WORLD.snap;
const candidate = { type, x, z, rot: pendingRotation };
const validation = validateCandidate(
candidate,
activeTool === "move" ? pendingMove.id : null
);
if (ghost && (ghost.userData.type !== type || ghost.userData.rot !== pendingRotation)) {
makeGhost(type, pendingRotation);
}
if (ghost) {
ghost.visible = true;
ghost.position.set(x, FLOOR_Y, z);
ghost.userData.type = type;
ghost.userData.rot = pendingRotation;
setGhostValidity(validation.ok);
}
}
function findItemId(object) {
let current = object;
while (current) {
if (current.userData?.itemId !== undefined) return current.userData.itemId;
current = current.parent;
}
return null;
}
function handleSceneClick(event) {
if (activeTool === "select") {
pointerToNDC(event);
const hit = raycaster.intersectObjects(itemLayer.children, true)[0];
if (hit) {
const id = findItemId(hit.object);
if (id !== null) selectItem(id);
} else {
selectedId = null;
pendingMove = null;
rebuildItems();
updateSelectionInfo();
}
return;
}
const point = groundPoint(event);
if (!point) return;
const x = Math.round(point.x / WORLD.snap) * WORLD.snap;
const z = Math.round(point.z / WORLD.snap) * WORLD.snap;
if (activeTool === "move" && pendingMove) {
moveSelected({ ...pendingMove, x, z, rot: pendingRotation });
} else if (activeTool === "booth" || activeTool === "seating") {
const color = Math.floor(Math.random() * boothPalettes.length);
addItem({ type: activeTool, x, z, rot: pendingRotation, color });
}
}
// ------------------------------------------------------------
// Interface events
// ------------------------------------------------------------
document.querySelectorAll("[data-tool]").forEach(button => {
button.addEventListener("click", () => setTool(button.dataset.tool));
});
document.querySelectorAll("[data-preset]").forEach(button => {
button.addEventListener("click", () => loadPreset(button.dataset.preset));
});
document.querySelector("#rotateBtn").addEventListener("click", rotateSelection);
document.querySelector("#deleteBtn").addEventListener("click", deleteSelection);
document.querySelector("#undoBtn").addEventListener("click", undo);
document.querySelector("#clearBtn").addEventListener("click", clearLayout);
document.querySelector("#resetView").addEventListener("click", resetCamera);
document.querySelector("#saveA").addEventListener("click", () => saveSlot("a"));
document.querySelector("#saveB").addEventListener("click", () => saveSlot("b"));
document.querySelector("#loadA").addEventListener("click", () => loadSlot("a"));
document.querySelector("#loadB").addEventListener("click", () => loadSlot("b"));
document.querySelector("#routeToggle").addEventListener("change", event => {
routeLayer.visible = event.target.checked;
});
window.addEventListener("keydown", event => {
if (event.target.matches("input, textarea, select")) return;
if ((event.ctrlKey || event.metaKey) && event.key.toLowerCase() === "z") {
event.preventDefault();
undo();
return;
}
switch (event.key.toLowerCase()) {
case "b": setTool("booth"); break;
case "s": setTool("seating"); break;
case "v": setTool("select"); break;
case "m": setTool("move"); break;
case "r": rotateSelection(); break;
case "delete":
case "backspace": deleteSelection(); break;
case "escape":
setTool("select");
break;
}
});
document.querySelector("#showPlanner").addEventListener("click", () => {
document.querySelector("#planner").classList.toggle("open");
document.querySelector("#compare").classList.remove("open");
});
document.querySelector("#showCompare").addEventListener("click", () => {
document.querySelector("#compare").classList.toggle("open");
document.querySelector("#planner").classList.remove("open");
});
// ------------------------------------------------------------
// Resize and render loop
// ------------------------------------------------------------
function resize() {
const width = window.innerWidth;
const height = window.innerHeight;
const aspect = width / height;
const viewHeight = Math.max(52, 49 / aspect);
camera.left = -viewHeight * aspect / 2;
camera.right = viewHeight * aspect / 2;
camera.top = viewHeight / 2;
camera.bottom = -viewHeight / 2;
camera.updateProjectionMatrix();
renderer.setSize(width, height);
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
updateCamera();
}
window.addEventListener("resize", resize);
function animate() {
requestAnimationFrame(animate);
if (selectionHelper) selectionHelper.update();
renderer.render(scene, camera);
}
rebuildItems();
updateSelectionInfo();
updateMetrics();
setTool("select");
resize();
animate();
</script>
</body>
</html>
```