Prompt specification
Build or customize the Three.js 3D scene "Balance a neighborhood event with everyday access" 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: Balance a neighborhood event with everyday access
Category: Architecture & Cities · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/balance-a-neighborhood-event-with-everyday-access-x2728
Scene Description Prompt:
Create a single self-contained HTML file using Three.js from cdnjs that shows Getsemaní in Cartagena. Let users place temporary seating and performance space in a schematic square. Preserve residential entrances and compare circulation before and during the fictional event. Low-poly.
Working Three.js Starter (balance-a-neighborhood-event-with-everyday-access-x2728):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Getsemaní Temporary Event Planner</title>
<style>
:root {
--ink: #17343a;
--muted: #64777a;
--paper: #f7f8f4;
--line: #dce4df;
--green: #167d68;
--green-soft: #e4f3ed;
--amber: #dd8b24;
--amber-soft: #fff1dc;
--red: #c74f48;
--red-soft: #fbe8e5;
--blue: #277c91;
--shadow: 0 12px 35px rgba(28, 52, 55, 0.12);
}
* { box-sizing: border-box; }
html, body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
color: var(--ink);
background: #dce3de;
}
button, input { font: inherit; }
button {
color: inherit;
cursor: pointer;
}
#app {
width: 100%;
height: 100%;
display: grid;
grid-template-columns: 326px minmax(0, 1fr);
grid-template-rows: 66px minmax(0, 1fr);
}
header {
grid-column: 1 / -1;
display: flex;
align-items: center;
justify-content: space-between;
gap: 20px;
padding: 0 22px;
background: rgba(250, 251, 247, 0.97);
border-bottom: 1px solid var(--line);
z-index: 20;
}
.brand {
display: flex;
align-items: center;
gap: 12px;
min-width: 0;
}
.brand-mark {
width: 34px;
height: 34px;
flex: 0 0 auto;
display: grid;
place-items: center;
color: white;
background: var(--green);
border-radius: 9px 9px 9px 2px;
font-weight: 800;
letter-spacing: -1px;
box-shadow: 0 5px 14px rgba(22, 125, 104, 0.24);
}
.brand h1 {
margin: 0;
font-size: 16px;
line-height: 1.1;
letter-spacing: -0.02em;
}
.brand p {
margin: 3px 0 0;
color: var(--muted);
font-size: 11px;
}
.header-right {
display: flex;
align-items: center;
gap: 14px;
}
.event-chip {
padding: 7px 11px;
border: 1px solid #ecd6b5;
border-radius: 999px;
color: #8a5a22;
background: #fff7e9;
font-size: 11px;
font-weight: 700;
white-space: nowrap;
}
.segmented {
display: flex;
padding: 4px;
gap: 3px;
background: #e9eeea;
border-radius: 11px;
}
.segmented button {
border: 0;
border-radius: 8px;
padding: 8px 13px;
background: transparent;
color: #637275;
font-size: 12px;
font-weight: 700;
transition: 150ms ease;
}
.segmented button:hover { color: var(--ink); }
.segmented button.active {
color: var(--ink);
background: white;
box-shadow: 0 2px 8px rgba(36, 60, 62, 0.11);
}
aside {
position: relative;
z-index: 10;
overflow-y: auto;
padding: 18px 17px 24px;
background: rgba(250, 251, 247, 0.98);
border-right: 1px solid var(--line);
box-shadow: 7px 0 25px rgba(39, 65, 65, 0.05);
}
aside::-webkit-scrollbar { width: 7px; }
aside::-webkit-scrollbar-thumb { background: #cad4cf; border-radius: 8px; }
.section {
padding: 16px 0;
border-bottom: 1px solid var(--line);
}
.section:first-child { padding-top: 3px; }
.section:last-child { border-bottom: 0; }
.eyebrow {
margin: 0 0 6px;
color: var(--green);
font-size: 10px;
font-weight: 800;
letter-spacing: 0.13em;
text-transform: uppercase;
}
h2 {
margin: 0;
font-size: 18px;
letter-spacing: -0.025em;
}
.section > p {
margin: 7px 0 0;
color: var(--muted);
font-size: 12px;
line-height: 1.55;
}
.tools {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 9px;
margin-top: 13px;
}
.tool {
position: relative;
min-height: 82px;
padding: 12px 11px;
text-align: left;
background: white;
border: 1px solid var(--line);
border-radius: 12px;
transition: 160ms ease;
}
.tool:hover {
border-color: #aebfb7;
transform: translateY(-1px);
}
.tool.active {
border-color: var(--green);
background: var(--green-soft);
box-shadow: inset 0 0 0 1px var(--green);
}
.tool-icon {
width: 28px;
height: 28px;
display: grid;
place-items: center;
margin-bottom: 9px;
color: var(--green);
background: #edf4ef;
border-radius: 8px;
font-weight: 900;
}
.tool.stage .tool-icon {
color: #7b51a0;
background: #f1eafa;
}
.tool strong {
display: block;
font-size: 12px;
}
.tool small {
display: block;
margin-top: 3px;
color: var(--muted);
font-size: 10px;
}
.minor-actions {
display: grid;
grid-template-columns: repeat(4, 1fr);
gap: 6px;
margin-top: 9px;
}
.minor-actions button {
min-height: 36px;
padding: 7px 4px;
border: 1px solid var(--line);
border-radius: 9px;
background: white;
font-size: 10px;
font-weight: 700;
}
.minor-actions button:hover { background: #eff3ef; }
.minor-actions button.active { color: white; background: var(--green); border-color: var(--green); }
.constraint {
margin-top: 12px;
padding: 11px;
display: flex;
gap: 10px;
border: 1px solid #cde2da;
border-radius: 11px;
background: #eff8f3;
}
.constraint-icon {
width: 23px;
height: 23px;
flex: 0 0 auto;
display: grid;
place-items: center;
color: white;
background: var(--green);
border-radius: 50%;
font-size: 12px;
font-weight: 900;
}
.constraint strong {
display: block;
font-size: 11px;
}
.constraint p {
margin: 3px 0 0;
color: #5d7470;
font-size: 10px;
line-height: 1.45;
}
.toggle-list {
display: grid;
gap: 9px;
margin-top: 12px;
}
.toggle {
display: flex;
align-items: center;
justify-content: space-between;
gap: 10px;
color: #405b60;
font-size: 12px;
cursor: pointer;
}
.toggle span {
display: flex;
align-items: center;
gap: 8px;
}
.swatch {
width: 10px;
height: 10px;
border-radius: 3px;
}
.toggle input {
width: 16px;
height: 16px;
accent-color: var(--green);
}
.metrics {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 8px;
margin-top: 13px;
}
.metric {
min-height: 72px;
padding: 11px;
background: white;
border: 1px solid var(--line);
border-radius: 11px;
}
.metric small {
display: block;
color: var(--muted);
font-size: 9px;
font-weight: 800;
letter-spacing: 0.07em;
text-transform: uppercase;
}
.metric strong {
display: block;
margin-top: 6px;
font-size: 18px;
letter-spacing: -0.04em;
}
.metric.during { background: #fff9ef; border-color: #efdfc1; }
.summary-line {
margin-top: 10px;
padding: 10px 11px;
display: flex;
justify-content: space-between;
gap: 8px;
border-radius: 10px;
background: #edf2ef;
color: #52686b;
font-size: 10px;
}
.summary-line strong { color: var(--ink); }
.footnote {
margin: 13px 0 0;
color: #82908e;
font-size: 9px;
line-height: 1.55;
}
#viewport {
position: relative;
min-width: 0;
min-height: 0;
overflow: hidden;
background: #dce3de;
}
#scene {
display: block;
width: 100%;
height: 100%;
touch-action: none;
outline: none;
}
.view-label {
position: absolute;
z-index: 4;
top: 16px;
left: 16px;
padding: 9px 12px;
border: 1px solid rgba(255,255,255,0.68);
border-radius: 11px;
background: rgba(250, 252, 248, 0.88);
box-shadow: 0 7px 20px rgba(40, 65, 66, 0.1);
pointer-events: none;
backdrop-filter: blur(8px);
}
.view-label.during { left: calc(50% + 16px); }
.view-label.full.during { left: 16px; }
.view-label strong {
display: block;
font-size: 12px;
letter-spacing: -0.01em;
}
.view-label span {
display: block;
margin-top: 2px;
color: var(--muted);
font-size: 9px;
}
#divider {
position: absolute;
z-index: 3;
top: 0;
bottom: 0;
left: 50%;
width: 1px;
background: rgba(44, 73, 72, 0.2);
pointer-events: none;
}
#divider::after {
content: "DURING →";
position: absolute;
top: 16px;
left: 8px;
padding: 5px 7px;
color: #85601d;
background: #fff3dc;
border: 1px solid #ead4ac;
border-radius: 7px;
font-size: 8px;
font-weight: 900;
letter-spacing: 0.08em;
}
.help {
position: absolute;
z-index: 4;
left: 16px;
bottom: 15px;
padding: 8px 10px;
color: #536b6d;
background: rgba(250, 252, 248, 0.84);
border: 1px solid rgba(255,255,255,0.7);
border-radius: 9px;
font-size: 9px;
pointer-events: none;
backdrop-filter: blur(7px);
}
.legend {
position: absolute;
z-index: 4;
right: 15px;
bottom: 15px;
display: flex;
gap: 10px;
padding: 8px 10px;
color: #536b6d;
background: rgba(250, 252, 248, 0.84);
border: 1px solid rgba(255,255,255,0.7);
border-radius: 9px;
font-size: 9px;
pointer-events: none;
backdrop-filter: blur(7px);
}
.legend span {
display: flex;
align-items: center;
gap: 5px;
}
.legend i {
width: 13px;
height: 3px;
display: inline-block;
border-radius: 2px;
}
#toast {
position: absolute;
z-index: 12;
left: 50%;
bottom: 54px;
max-width: min(480px, calc(100% - 30px));
transform: translate(-50%, 12px);
padding: 10px 14px;
color: white;
background: #244a4c;
border-radius: 10px;
box-shadow: var(--shadow);
font-size: 11px;
font-weight: 700;
text-align: center;
opacity: 0;
pointer-events: none;
transition: 180ms ease;
}
#toast.show { opacity: 1; transform: translate(-50%, 0); }
#toast.error { background: #9c403b; }
#toast.success { background: #176f5e; }
@media (max-width: 920px) {
#app { grid-template-columns: 276px minmax(0, 1fr); }
.event-chip { display: none; }
aside { padding-left: 14px; padding-right: 14px; }
}
@media (max-width: 700px) {
#app { grid-template-columns: 238px minmax(0, 1fr); }
header { padding: 0 12px; }
.brand p { display: none; }
.segmented button { padding: 7px 8px; }
.legend { display: none; }
.view-label { padding: 7px 9px; }
.view-label strong { font-size: 10px; }
}
</style>
</head>
<body>
<div id="app">
<header>
<div class="brand">
<div class="brand-mark">G</div>
<div>
<h1>Getsemaní / Temporary Event Planner</h1>
<p>Cartagena de Indias, Colombia · Schematic spatial study</p>
</div>
</div>
<div class="header-right">
<div class="event-chip">FICTIONAL EVENT · RONDA DE CUMBIA · 18:00–22:00</div>
<div class="segmented" id="viewButtons">
<button data-view="before">Before</button>
<button data-view="compare" class="active">Compare</button>
<button data-view="during">During</button>
</div>
</div>
</header>
<aside>
<section class="section">
<p class="eyebrow">Temporary program</p>
<h2>Test the square</h2>
<p>Place seating modules and a performance platform on the plaza. The event is fictional and no permanent works are proposed.</p>
<div class="tools">
<button class="tool" data-tool="seating">
<span class="tool-icon">▦</span>
<strong>Seating module</strong>
<small>12 places · 4.2 × 4.2 m</small>
</button>
<button class="tool stage" data-tool="stage">
<span class="tool-icon">◆</span>
<strong>Performance space</strong>
<small>8 × 5 m platform</small>
</button>
</div>
<div class="minor-actions">
<button id="rotateButton" title="Rotate 90 degrees (R)">Rotate</button>
<button id="selectButton" title="Select and remove objects">Select</button>
<button id="undoButton" title="Undo the last placement">Undo</button>
<button id="clearButton" title="Remove all temporary objects">Clear</button>
</div>
<div class="constraint">
<div class="constraint-icon">✓</div>
<div>
<strong>Residential access is protected</strong>
<p>A 2.8 m clearance zone is reserved at every residence entrance. Temporary modules cannot overlap these zones or existing plaza objects.</p>
</div>
</div>
</section>
<section class="section">
<p class="eyebrow">Map layers</p>
<div class="toggle-list">
<label class="toggle">
<span><i class="swatch" style="background:#277c91"></i>Residential entrances</span>
<input id="layerEntrances" type="checkbox" checked>
</label>
<label class="toggle">
<span><i class="swatch" style="background:#dd8b24"></i>Circulation routes</span>
<input id="layerRoutes" type="checkbox" checked>
</label>
<label class="toggle">
<span><i class="swatch" style="background:#9ba89d"></i>Built context</span>
<input id="layerContext" type="checkbox" checked>
</label>
</div>
</section>
<section class="section">
<p class="eyebrow">Comparison</p>
<h2>Circulation impact</h2>
<div class="metrics">
<div class="metric">
<small>Before · clear area</small>
<strong id="beforeArea">—</strong>
</div>
<div class="metric during">
<small>During · clear area</small>
<strong id="duringArea">—</strong>
</div>
</div>
<div class="summary-line">
<span>Routes changed</span>
<strong id="routeSummary">0 of 4</strong>
</div>
<div class="summary-line">
<span>Entrances protected</span>
<strong id="entranceSummary">14 of 14</strong>
</div>
<div class="summary-line">
<span>Temporary seating</span>
<strong id="seatSummary">0 places</strong>
</div>
<p class="footnote">Routes are schematic pedestrian paths recalculated around temporary footprints. This is not a surveyed, accessibility-certified, or capacity study.</p>
</section>
</aside>
<main id="viewport">
<div id="divider"></div>
<div id="beforeLabel" class="view-label">
<strong>BEFORE · Existing square</strong>
<span id="beforeMeta">Calculating circulation…</span>
</div>
<div id="duringLabel" class="view-label during">
<strong>DURING · Fictional event</strong>
<span id="duringMeta">Place temporary elements on this side</span>
</div>
<div class="help">Drag: orbit · Right-drag: pan · Wheel: zoom · R: rotate · Delete: remove</div>
<div class="legend">
<span><i style="background:#38a7bd"></i>Existing route</span>
<span><i style="background:#ee9a2f"></i>Event route</span>
<span><i style="background:#3ca477"></i>Valid placement</span>
</div>
<div id="toast" role="status" aria-live="polite"></div>
</main>
</div>
<script type="module">
import * as THREE from 'https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js';
/* ---------- DOM and application state ---------- */
const viewport = document.getElementById('viewport');
const beforeLabel = document.getElementById('beforeLabel');
const duringLabel = document.getElementById('duringLabel');
const beforeMeta = document.getElementById('beforeMeta');
const duringMeta = document.getElementById('duringMeta');
const toast = document.getElementById('toast');
const divider = document.getElementById('divider');
const layerEntrances = document.getElementById('layerEntrances');
const layerRoutes = document.getElementById('layerRoutes');
const layerContext = document.getElementById('layerContext');
let viewMode = 'compare';
let activeTool = null;
let placementRotation = 0;
let selectedObject = null;
let selectionHelper = null;
let objectId = 0;
let toastTimer;
const objects = [];
const permanentObstacles = [];
const entrances = [];
const dimensions = {
seating: { w: 4.2, d: 4.2, label: 'Seating module' },
stage: { w: 8, d: 5, label: 'Performance space' }
};
function showToast(message, type = '') {
clearTimeout(toastTimer);
toast.textContent = message;
toast.className = `show ${type}`;
toastTimer = setTimeout(() => {
toast.className = type;
}, 2600);
}
/* ---------- Renderer and scene ---------- */
const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.domElement.id = 'scene';
renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 2));
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.12;
viewport.prepend(renderer.domElement);
const scene = new THREE.Scene();
scene.background = new THREE.Color('#d9e2dc');
scene.fog = new THREE.Fog('#d9e2dc', 95, 155);
const camera = new THREE.OrthographicCamera(-40, 40, 30, -30, 0.1, 220);
const cameraTarget = new THREE.Vector3(0, 0, 0);
let cameraTheta = 0.74;
let cameraPhi = 0.83;
let cameraZoom = 1.03;
const hemi = new THREE.HemisphereLight('#edf8f3', '#829087', 2.2);
scene.add(hemi);
const sun = new THREE.DirectionalLight('#fff4dc', 3.2);
sun.position.set(-30, 48, 25);
sun.castShadow = true;
sun.shadow.mapSize.set(2048, 2048);
sun.shadow.camera.left = -52;
sun.shadow.camera.right = 52;
sun.shadow.camera.top = 45;
sun.shadow.camera.bottom = -45;
sun.shadow.camera.near = 1;
sun.shadow.camera.far = 110;
sun.shadow.bias = -0.00035;
scene.add(sun);
const contextGroup = new THREE.Group();
const entranceGroup = new THREE.Group();
const baselineRoutesGroup = new THREE.Group();
const eventRoutesGroup = new THREE.Group();
const temporaryGroup = new THREE.Group();
scene.add(contextGroup, entranceGroup, baselineRoutesGroup, eventRoutesGroup, temporaryGroup);
/* ---------- Materials and low-poly helpers ---------- */
const materialCache = new Map();
function stdMaterial(color, options = {}) {
const key = `${color}-${JSON.stringify(options)}`;
if (!materialCache.has(key)) {
materialCache.set(key, new THREE.MeshStandardMaterial({
color,
roughness: 0.9,
metalness: 0,
flatShading: true,
...options
}));
}
return materialCache.get(key);
}
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),
stdMaterial(color, options)
);
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 makeLabelSprite(text, options = {}) {
const canvas = document.createElement('canvas');
canvas.width = options.width || 256;
canvas.height = options.height || 72;
const ctx = canvas.getContext('2d');
ctx.clearRect(0, 0, canvas.width, canvas.height);
roundedRect(ctx, 4, 4, canvas.width - 8, canvas.height - 8, 13);
ctx.fillStyle = options.background || 'rgba(18,47,52,.90)';
ctx.fill();
ctx.strokeStyle = options.stroke || 'rgba(255,255,255,.55)';
ctx.lineWidth = 2;
ctx.stroke();
ctx.fillStyle = options.color || '#ffffff';
ctx.font = `${options.weight || 800} ${options.fontSize || 28}px system-ui, sans-serif`;
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
ctx.fillText(text, canvas.width / 2, canvas.height / 2 + 1);
const texture = new THREE.CanvasTexture(canvas);
texture.colorSpace = THREE.SRGBColorSpace;
const material = new THREE.SpriteMaterial({
map: texture,
transparent: true,
depthWrite: false
});
const sprite = new THREE.Sprite(material);
sprite.scale.set(options.scaleX || 2.0, options.scaleY || 0.56, 1);
sprite.renderOrder = 8;
return sprite;
}
function makeGroundLabel(text, x, z, width = 17) {
const canvas = document.createElement('canvas');
canvas.width = 1024;
canvas.height = 150;
const ctx = canvas.getContext('2d');
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = 'rgba(36,67,68,.66)';
ctx.font = '800 68px system-ui, sans-serif';
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
ctx.fillText(text, 512, 75);
const texture = new THREE.CanvasTexture(canvas);
texture.colorSpace = THREE.SRGBColorSpace;
const material = new THREE.MeshBasicMaterial({
map: texture,
transparent: true,
depthWrite: false
});
const mesh = new THREE.Mesh(new THREE.PlaneGeometry(width, width * 150 / 1024), material);
mesh.rotation.x = -Math.PI / 2;
mesh.position.set(x, 0.09, z);
contextGroup.add(mesh);
}
function addEntrance(x, z, outwardX, outwardZ, name) {
const id = entrances.length + 1;
const door = addBox(
entranceGroup,
outwardX ? 0.16 : 1.35,
2.75,
outwardX ? 1.35 : 0.16,
'#277c91',
x,
1.45,
z
);
const canopy = addBox(
entranceGroup,
outwardX ? 0.8 : 2.0,
0.15,
outwardX ? 2.0 : 0.8,
'#d7eee8',
x + outwardX * 0.28,
3.0,
z + outwardZ * 0.28
);
const clearX = x + outwardX * 1.45;
const clearZ = z + outwardZ * 1.45;
const radius = 2.8;
const fill = new THREE.Mesh(
new THREE.CircleGeometry(radius, 40),
new THREE.MeshBasicMaterial({
color: '#3ca9bd',
transparent: true,
opacity: 0.09,
depthWrite: false,
side: THREE.DoubleSide
})
);
fill.rotation.x = -Math.PI / 2;
fill.position.set(clearX, 0.105, clearZ);
entranceGroup.add(fill);
const ring = new THREE.Mesh(
new THREE.RingGeometry(radius - 0.09, radius, 40),
new THREE.MeshBasicMaterial({
color: '#3ca9bd',
transparent: true,
opacity: 0.68,
depthWrite: false,
side: THREE.DoubleSide
})
);
ring.rotation.x = -Math.PI / 2;
ring.position.set(clearX, 0.115, clearZ);
entranceGroup.add(ring);
const label = makeLabelSprite(`R${id}`, {
scaleX: 1.15,
scaleY: 0.43,
fontSize: 27,
background: 'rgba(39,124,145,.94)',
stroke: 'rgba(218,246,247,.9)'
});
label.position.set(x + outwardX * 0.6, 3.8, z + outwardZ * 0.6);
entranceGroup.add(label);
entrances.push({ id, name, x: clearX, z: clearZ, radius });
}
function makeBuilding(x, z, w, d, h, color, side) {
addBox(contextGroup, w, h, d, color, x, h / 2 + 0.08, z);
addBox(contextGroup, w + 0.45, 0.35, d + 0.45, '#f0e7d5', x, h + 0.23, z);
let outwardX = 0;
let outwardZ = 0;
let facadeX = x;
let facadeZ = z;
if (side === 'north') {
outwardZ = 1;
facadeZ = z + d / 2;
} else if (side === 'south') {
outwardZ = -1;
facadeZ = z - d / 2;
} else if (side === 'west') {
outwardX = 1;
facadeX = x + w / 2;
} else {
outwardX = -1;
facadeX = x - w / 2;
}
const along = side === 'north' || side === 'south' ? w : d;
const windowCount = Math.max(2, Math.floor(along / 3.3));
const levels = h > 12 ? 3 : 2;
for (let level = 0; level < levels; level++) {
const wy = 4.8 + level * 3.45;
if (wy > h - 0.5) continue;
for (let i = 0; i < windowCount; i++) {
const offset = -along / 2 + (i + 0.5) * along / windowCount;
const wx = outwardX ? facadeX + outwardX * 0.06 : x + offset;
const wz = outwardZ ? facadeZ + outwardZ * 0.06 : z + offset;
addBox(
contextGroup,
outwardX ? 0.13 : 1.35,
1.55,
outwardZ ? 0.13 : 1.35,
level % 2 ? '#466d75' : '#315965',
wx,
wy,
wz
);
if (level > 0) {
const bx = outwardX ? facadeX + outwardX * 0.45 : x + offset;
const bz = outwardZ ? facadeZ + outwardZ * 0.45 : z + offset;
addBox(
contextGroup,
outwardX ? 0.9 : 2.15,
0.14,
outwardZ ? 0.9 : 2.15,
'#f1e8d6',
bx,
wy - 1.05,
bz
);
addBox(
contextGroup,
outwardX ? 0.12 : 2.15,
0.65,
outwardZ ? 0.12 : 2.15,
'#f1e8d6',
bx + outwardX * 0.42,
wy - 0.72,
bz + outwardZ * 0.42
);
}
}
}
}
/* ---------- Ground, plaza and context ---------- */
addBox(contextGroup, 80, 0.8, 62, '#b8c3bd', 0, -0.48, 0);
addBox(contextGroup, 53, 0.12, 35, '#d8d4c7', 0, 0, 0);
addBox(contextGroup, 43, 0.10, 27, '#e7e2d4', 0, 0.075, 0);
const gridVertices = [];
for (let x = -21; x <= 21; x += 2) {
gridVertices.push(x, 0.135, -13, x, 0.135, 13);
}
for (let z = -13; z <= 13; z += 2) {
gridVertices.push(-21, 0.135, z, 21, 0.135, z);
}
const gridGeometry = new THREE.BufferGeometry();
gridGeometry.setAttribute('position', new THREE.Float32BufferAttribute(gridVertices, 3));
contextGroup.add(new THREE.LineSegments(
gridGeometry,
new THREE.LineBasicMaterial({ color: '#9ca99e', transparent: true, opacity: 0.25 })
));
makeGroundLabel('PLAZA DE GETSEMANÍ', 5.0, 10.6, 17);
const northColors = ['#d9a58e', '#e2c49d', '#b9cbc0', '#d8b8a0'];
const southColors = ['#a8c4c0', '#e6bd8f', '#d9a295', '#c7c59e'];
const westColors = ['#dfb995', '#b9c9bd', '#d3a29a'];
const eastColors = ['#d4be94', '#aac3be', '#dda18e'];
[-18, -6, 6, 18].forEach((x, i) => {
makeBuilding(x, -21.5, 10, 8, [11.5, 13.5, 12, 14][i], northColors[i], 'north');
addEntrance(x, -17.44, 0, 1, `North residence ${i + 1}`);
});
[-18, -6, 6, 18].forEach((x, i) => {
makeBuilding(x, 21.5, 10, 8, [12.5, 11.5, 14, 13][i], southColors[i], 'south');
addEntrance(x, 17.44, 0, -1, `South residence ${i + 1}`);
});
[-10, 0, 10].forEach((z, i) => {
makeBuilding(-29.5, z, 8, 8, [12, 14, 11.5][i], westColors[i], 'west');
addEntrance(-25.44, z, 1, 0, `West residence ${i + 1}`);
});
[-10, 0, 10].forEach((z, i) => {
makeBuilding(29.5, z, 8, 8, [13.5, 12, 14][i], eastColors[i], 'east');
addEntrance(25.44, z, -1, 0, `East residence ${i + 1}`);
});
/* Fountain */
const fountain = new THREE.Group();
fountain.position.set(-8, 0, 0);
const fountainBase = new THREE.Mesh(
new THREE.CylinderGeometry(2.9, 3.15, 0.45, 12),
stdMaterial('#c9c3b3')
);
fountainBase.position.y = 0.27;
fountainBase.castShadow = true;
fountainBase.receiveShadow = true;
fountain.add(fountainBase);
const fountainWater = new THREE.Mesh(
new THREE.CylinderGeometry(2.42, 2.42, 0.08, 12),
stdMaterial('#69aab0', { roughness: 0.35, metalness: 0.05 })
);
fountainWater.position.y = 0.53;
fountain.add(fountainWater);
const fountainCenter = new THREE.Mesh(
new THREE.CylinderGeometry(0.45, 0.75, 1.55, 8),
stdMaterial('#a99d87')
);
fountainCenter.position.y = 1.2;
fountainCenter.castShadow = true;
fountain.add(fountainCenter);
contextGroup.add(fountain);
permanentObstacles.push({ x: -8, z: 0, r: 2.9, label: 'the fountain' });
/* Kiosks */
function addKiosk(x, z, color) {
addBox(contextGroup, 2.2, 1.8, 1.8, color, x, 0.98, z);
addBox(contextGroup, 3.0, 0.22, 2.6, '#f4e7ca', x, 2.0, z);
addBox(contextGroup, 2.35, 0.7, 0.10, '#53767a', x, 1.15, z + 0.91);
permanentObstacles.push({ x, z, r: 1.35, label: 'the kiosk' });
}
addKiosk(15, -10, '#bd806e');
addKiosk(-16, 10, '#769891');
/* Trees */
function addTree(x, z, scale = 1) {
const trunk = new THREE.Mesh(
new THREE.CylinderGeometry(0.18 * scale, 0.26 * scale, 1.65 * scale, 7),
stdMaterial('#846c4e')
);
trunk.position.set(x, 0.9 * scale, z);
trunk.castShadow = true;
contextGroup.add(trunk);
const crown = new THREE.Mesh(
new THREE.ConeGeometry(1.25 * scale, 2.8 * scale, 7),
stdMaterial('#688e69')
);
crown.position.set(x, 2.55 * scale, z);
crown.rotation.y = x * 0.2;
crown.castShadow = true;
contextGroup.add(crown);
permanentObstacles.push({ x, z, r: 0.9 * scale, label: 'a tree' });
}
[
[-18, -7, 1], [18, -7, 0.95], [-18, 9, 0.9],
[18, 9, 1.05], [-2, -11, 0.82], [12, 11, 0.9]
].forEach(v => addTree(...v));
/* ---------- Temporary object models ---------- */
function createSeatingModule() {
const group = new THREE.Group();
const floor = addBox(group, 4.05, 0.035, 4.05, '#d8b16e', 0, 0.17, 0, { transparent: true, opacity: 0.22 });
floor.castShadow = false;
const seatGeometry = new THREE.BoxGeometry(0.62, 0.12, 0.58);
const backGeometry = new THREE.BoxGeometry(0.62, 0.70, 0.10);
const seatMaterial = stdMaterial('#e7a55d');
const backMaterial = stdMaterial('#b96e49');
const seats = new THREE.InstancedMesh(seatGeometry, seatMaterial, 12);
const backs = new THREE.InstancedMesh(backGeometry, backMaterial, 12);
seats.castShadow = true;
seats.receiveShadow = true;
backs.castShadow = true;
const dummy = new THREE.Object3D();
let index = 0;
for (let row = 0; row < 4; row++) {
for (let col = 0; col < 3; col++) {
const x = (col - 1) * 1.08;
const z = (row - 1.5) * 0.86;
dummy.position.set(x, 0.57, z);
dummy.updateMatrix();
seats.setMatrixAt(index, dummy.matrix);
dummy.position.set(x, 0.92, z - 0.24);
dummy.updateMatrix();
backs.setMatrixAt(index, dummy.matrix);
index++;
}
}
seats.instanceMatrix.needsUpdate = true;
backs.instanceMatrix.needsUpdate = true;
group.add(seats, backs);
const border = new THREE.LineLoop(
new THREE.BufferGeometry().setFromPoints([
new THREE.Vector3(-2.1, 0.19, -2.1),
new THREE.Vector3(2.1, 0.19, -2.1),
new THREE.Vector3(2.1, 0.19, 2.1),
new THREE.Vector3(-2.1, 0.19, 2.1)
]),
new THREE.LineBasicMaterial({ color: '#b7793f', transparent: true, opacity: 0.75 })
);
group.add(border);
return group;
}
function createStage() {
const group = new THREE.Group();
addBox(group, 8, 0.48, 5, '#8f684d', 0, 0.31, 0);
addBox(group, 7.9, 0.08, 4.9, '#bc8d5e', 0, 0.59, 0);
addBox(group, 7.1, 2.35, 0.18, '#59436c', 0, 1.77, -2.16);
addBox(group, 0.45, 1.15, 0.45, '#273a40', -3.45, 1.15, -1.9);
addBox(group, 0.45, 1.15, 0.45, '#273a40', 3.45, 1.15, -1.9);
const performanceRing = new THREE.Mesh(
new THREE.RingGeometry(0.72, 0.9, 20),
new THREE.MeshBasicMaterial({ color: '#f2cf80', side: THREE.DoubleSide })
);
performanceRing.rotation.x = -Math.PI / 2;
performanceRing.position.set(0, 0.66, 0.25);
group.add(performanceRing);
const border = new THREE.LineLoop(
new THREE.BufferGeometry().setFromPoints([
new THREE.Vector3(-4, 0.65, -2.5),
new THREE.Vector3(4, 0.65, -2.5),
new THREE.Vector3(4, 0.65, 2.5),
new THREE.Vector3(-4, 0.65, 2.5)
]),
new THREE.LineBasicMaterial({ color: '#77508f', transparent: true, opacity: 0.8 })
);
group.add(border);
return group;
}
function createTemporaryObject(type) {
const id = ++objectId;
const group = type === 'stage' ? createStage() : createSeatingModule();
group.userData.objectId = id;
const spec = dimensions[type];
const item = {
id,
type,
group,
x: 0,
z: 0,
rot: 0,
w: spec.w,
d: spec.d
};
return item;
}
/* ---------- Placement validation ---------- */
function rectCorners(rect) {
const c = Math.cos(rect.rot);
const s = Math.sin(rect.rot);
const ax = { x: c, z: -s };
const az = { x: s, z: c };
return [
[-1, -1], [1, -1], [1, 1], [-1, 1]
].map(([sx, sz]) => ({
x: rect.x + ax.x * sx * rect.w / 2 + az.x * sz * rect.d / 2,
z: rect.z + ax.z * sx * rect.w / 2 + az.z * sz * rect.d / 2
}));
}
function circleIntersectsRect(cx, cz, radius, rect, gap = 0) {
const c = Math.cos(rect.rot);
const s = Math.sin(rect.rot);
const dx = cx - rect.x;
const dz = cz - rect.z;
const localX = c * dx - s * dz;
const localZ = s * dx + c * dz;
const qx = Math.max(Math.abs(localX) - rect.w / 2, 0);
const qz = Math.max(Math.abs(localZ) - rect.d / 2, 0);
return qx * qx + qz * qz <= (radius + gap / 2) ** 2;
}
function rectsOverlap(a, b, gap = 0) {
const ca = Math.cos(a.rot), sa = Math.sin(a.rot);
const cb = Math.cos(b.rot), sb = Math.sin(b.rot);
const axes = [
{ x: ca, z: -sa },
{ x: sa, z: ca },
{ x: cb, z: -sb },
{ x: sb, z: cb }
];
const cornersA = rectCorners(a);
const cornersB = rectCorners(b);
for (const axis of axes) {
const project = corners => corners.reduce((min, p) => Math.min(min, p.x * axis.x + p.z * axis.z), Infinity);
const projectMax = corners => corners.reduce((max, p) => Math.max(max, p.x * axis.x + p.z * axis.z), -Infinity);
const minA = project(cornersA), maxA = projectMax(cornersA);
const minB = project(cornersB), maxB = projectMax(cornersB);
if (maxA + gap / 2 < minB - gap / 2 || maxB + gap / 2 < minA - gap / 2) {
return false;
}
}
return true;
}
function validatePlacement(type, x, z, rot, ignoreId = null) {
const spec = dimensions[type];
const rect = { x, z, rot, w: spec.w, d: spec.d };
const corners = rectCorners(rect);
if (corners.some(p => Math.abs(p.x) > 20.5 || Math.abs(p.z) > 12.5)) {
return { ok: false, reason: 'Outside the temporary placement boundary.' };
}
for (const entrance of entrances) {
if (circleIntersectsRect(entrance.x, entrance.z, entrance.radius, rect, 0.25)) {
return { ok: false, reason: `Blocks the protected clearance at residence R${entrance.id}.` };
}
}
for (const obstacle of permanentObstacles) {
if (circleIntersectsRect(obstacle.x, obstacle.z, obstacle.r, rect, 0.2)) {
return { ok: false, reason: `Overlaps ${obstacle.label}.` };
}
}
for (const other of objects) {
if (other.id === ignoreId) continue;
if (rectsOverlap(rect, other, 0.6)) {
return { ok: false, reason: 'Too close to another temporary module.' };
}
}
if (objects.length >= 24 && ignoreId === null) {
return { ok: false, reason: 'The temporary layout limit of 24 modules has been reached.' };
}
return { ok: true, reason: '' };
}
/* ---------- Placement ghost ---------- */
let ghost = null;
let ghostType = null;
function buildGhost(type) {
if (ghost) {
scene.remove(ghost);
}
ghostType = type;
ghost = new THREE.Group();
const spec = dimensions[type];
const fillMaterial = new THREE.MeshBasicMaterial({
color: '#3ca477',
transparent: true,
opacity: 0.25,
depthWrite: false,
side: THREE.DoubleSide
});
const plane = new THREE.Mesh(new THREE.PlaneGeometry(spec.w, spec.d), fillMaterial);
plane.rotation.x = -Math.PI / 2;
plane.position.y = 0.24;
ghost.add(plane);
if (type === 'stage') {
const block = addBox(ghost, spec.w, 0.45, spec.d, '#3ca477', 0, 0.35, 0, {
transparent: true,
opacity: 0.25,
depthWrite: false
});
block.castShadow = false;
} else {
for (let row = 0; row < 3; row++) {
for (let col = 0; col < 3; col++) {
const chair = addBox(ghost, 0.68, 0.12, 0.68, '#3ca477', (col - 1) * 1.05, 0.32, (row - 1) * 1.05, {
transparent: true,
opacity: 0.3,
depthWrite: false
});
chair.castShadow = false;
}
}
}
const outline = new THREE.LineLoop(
new THREE.BufferGeometry().setFromPoints([
new THREE.Vector3(-spec.w / 2, 0.26, -spec.d / 2),
new THREE.Vector3(spec.w / 2, 0.26, -spec.d / 2),
new THREE.Vector3(spec.w / 2, 0.26, spec.d / 2),
new THREE.Vector3(-spec.w / 2, 0.26, spec.d / 2)
]),
new THREE.LineBasicMaterial({ color: '#3ca477', transparent: true, opacity: 0.95 })
);
ghost.add(outline);
ghost.userData.fillMaterial = fillMaterial;
ghost.userData.outlineMaterial = outline.material;
ghost.visible = false;
scene.add(ghost);
}
function updateGhostAppearance(valid) {
if (!ghost) return;
const color = valid ? '#3ca477' : '#c74f48';
ghost.userData.fillMaterial.color.set(color);
ghost.userData.outlineMaterial.color.set(color);
ghost.traverse(child => {
if (child.isMesh && child !== ghost.userData.fillMaterial) {
if (child.material && child.material.color) child.material.color.set(color);
}
});
}
/* ---------- Camera and custom controls ---------- */
function updateCameraPosition() {
const radius = 82;
const sinPhi = Math.sin(cameraPhi);
camera.position.set(
cameraTarget.x + radius * sinPhi * Math.sin(cameraTheta),
cameraTarget.y + radius * Math.cos(cameraPhi),
cameraTarget.z + radius * sinPhi * Math.cos(cameraTheta)
);
camera.lookAt(cameraTarget);
camera.updateMatrixWorld();
}
function setCameraProjection(width, height) {
const aspect = Math.max(width / Math.max(height, 1), 0.35);
const halfHeight = Math.max(26, 41 / aspect);
camera.left = -halfHeight * aspect;
camera.right = halfHeight * aspect;
camera.top = halfHeight;
camera.bottom = -halfHeight;
camera.zoom = cameraZoom;
camera.updateProjectionMatrix();
}
updateCameraPosition();
const raycaster = new THREE.Raycaster();
const pointerNdc = new THREE.Vector2();
const groundPlane = new THREE.Plane(new THREE.Vector3(0, 1, 0), -0.14);
function getPanel(clientX) {
const rect = renderer.domElement.getBoundingClientRect();
const local = clientX - rect.left;
if (viewMode === 'compare') {
const split = Math.floor(rect.width / 2);
if (local < split) {
return { side: 'left', x0: 0, width: split, height: rect.height, allowed: false };
}
return { side: 'right', x0: split, width: rect.width - split, height: rect.height, allowed: true };
}
return {
side: viewMode === 'during' ? 'during' : 'before',
x0: 0,
width: rect.width,
height: rect.height,
allowed: viewMode === 'during'
};
}
function groundPointFromEvent(event, panel) {
const rect = renderer.domElement.getBoundingClientRect();
pointerNdc.x = ((event.clientX - rect.left - panel.x0) / panel.width) * 2 - 1;
pointerNdc.y = -((event.clientY - rect.top) / panel.height) * 2 + 1;
setCameraProjection(panel.width, panel.height);
raycaster.setFromCamera(pointerNdc, camera);
const point = new THREE.Vector3();
return raycaster.ray.intersectPlane(groundPlane, point) ? point : null;
}
function updateGhostFromEvent(event) {
if (!activeTool) {
if (ghost) ghost.visible = false;
return;
}
const panel = getPanel(event.clientX);
if (!panel.allowed) {
ghost.visible = false;
return;
}
const point = groundPointFromEvent(event, panel);
if (!point) {
ghost.visible = false;
return;
}
if (!ghost || ghostType !== activeTool) buildGhost(activeTool);
const x = Math.round(point.x * 2) / 2;
const z = Math.round(point.z * 2) / 2;
const validation = validatePlacement(activeTool, x, z, placementRotation);
ghost.position.set(x, 0, z);
ghost.rotation.y = placementRotation;
ghost.visible = true;
updateGhostAppearance(validation.ok);
}
let dragState = null;
renderer.domElement.addEventListener('pointerdown', event => {
if (event.button !== 0 && event.button !== 2) return;
event.preventDefault();
renderer.domElement.setPointerCapture(event.pointerId);
const panel = getPanel(event.clientX);
let panStart = null;
if (event.button === 2) {
panStart = groundPointFromEvent(event, panel);
}
dragState = {
button: event.button,
startX: event.clientX,
startY: event.clientY,
lastX: event.clientX,
lastY: event.clientY,
moved: false,
panel,
panStart
};
});
renderer.domElement.addEventListener('pointermove', event => {
if (dragState) {
const dx = event.clientX - dragState.lastX;
const dy = event.clientY - dragState.lastY;
const totalDistance = Math.hypot(event.clientX - dragState.startX, event.clientY - dragState.startY);
if (totalDistance > 4) dragState.moved = true;
if (dragState.button === 0 && dragState.moved) {
cameraTheta -= dx * 0.006;
cameraPhi = THREE.MathUtils.clamp(cameraPhi - dy * 0.005, 0.42, 1.28);
updateCameraPosition();
} else if (dragState.button === 2 && dragState.panStart) {
const current = groundPointFromEvent(event, dragState.panel);
if (current) {
cameraTarget.add(dragState.panStart.clone().sub(current));
updateCameraPosition();
}
}
dragState.lastX = event.clientX;
dragState.lastY = event.clientY;
}
updateGhostFromEvent(event);
});
renderer.domElement.addEventListener('pointerup', event => {
if (!dragState) return;
const wasClick = !dragState.moved && dragState.button === 0;
dragState = null;
if (wasClick) handleCanvasClick(event);
});
renderer.domElement.addEventListener('pointercancel', () => {
dragState = null;
});
renderer.domElement.addEventListener('pointerleave', () => {
if (!dragState && ghost) ghost.visible = false;
});
renderer.domElement.addEventListener('contextmenu', event => event.preventDefault());
renderer.domElement.addEventListener('wheel', event => {
event.preventDefault();
cameraZoom = THREE.MathUtils.clamp(cameraZoom * Math.exp(-event.deltaY * 0.001), 0.58, 2.35);
}, { passive: false });
renderer.domElement.addEventListener('dblclick', () => {
cameraTarget.set(0, 0, 0);
cameraTheta = 0.74;
cameraPhi = 0.83;
cameraZoom = 1.03;
updateCameraPosition();
});
/* ---------- Grid-based circulation model ---------- */
const GRID = {
minX: -22,
maxX: 22,
minZ: -14,
maxZ: 14,
step: 0.75
};
GRID.nx = Math.round((GRID.maxX - GRID.minX) / GRID.step) + 1;
GRID.nz = Math.round((GRID.maxZ - GRID.minZ) / GRID.step) + 1;
const routeSpecs = [
{ name: 'North approach', start: { x: 0, z: -14 }, goal: { x: -4, z: 0 } },
{ name: 'South approach', start: { x: 0, z: 14 }, goal: { x: 4, z: 0 } },
{ name: 'West approach', start: { x: -22, z: 0 }, goal: { x: 0, z: -4 } },
{ name: 'East approach', start: { x: 22, z: 0 }, goal: { x: 0, z: 3 } }
];
function pointInExpandedRect(x, z, rect, margin = 0) {
const c = Math.cos(rect.rot);
const s = Math.sin(rect.rot);
const dx = x - rect.x;
const dz = z - rect.z;
const localX = c * dx - s * dz;
const localZ = s * dx + c * dz;
return Math.abs(localX) <= rect.w / 2 + margin && Math.abs(localZ) <= rect.d / 2 + margin;
}
function circulationPointBlocked(x, z, temporaryObjects) {
if (x < GRID.minX || x > GRID.maxX || z < GRID.minZ || z > GRID.maxZ) return true;
for (const obstacle of permanentObstacles) {
const distance = Math.hypot(x - obstacle.x, z - obstacle.z);
if (distance < obstacle.r + 0.36) return true;
}
for (const item of temporaryObjects) {
if (pointInExpandedRect(x, z, item, 0.36)) return true;
}
return false;
}
function gridIndex(ix, iz) {
return iz * GRID.nx + ix;
}
function gridPoint(index) {
const ix = index % GRID.nx;
const iz = Math.floor(index / GRID.nx);
return {
x: GRID.minX + ix * GRID.step,
z: GRID.minZ + iz * GRID.step
};
}
function nearestOpenCell(x, z, temporaryObjects) {
const ix = Math.round((x - GRID.minX) / GRID.step);
const iz = Math.round((z - GRID.minZ) / GRID.step);
if (ix >= 0 && ix < GRID.nx && iz >= 0 && iz < GRID.nz) {
const index = gridIndex(ix, iz);
const p = gridPoint(index);
if (!circulationPointBlocked(p.x, p.z, temporaryObjects)) return index;
}
for (let radius = 1; radius <= 10; radius++) {
let best = -1;
let bestDistance = Infinity;
for (let dz = -radius; dz <= radius; dz++) {
for (let dx = -radius; dx <= radius; dx++) {
if (Math.max(Math.abs(dx), Math.abs(dz)) !== radius) continue;
const nx = ix + dx;
const nz = iz + dz;
if (nx < 0 || nx >= GRID.nx || nz < 0 || nz >= GRID.nz) continue;
const index = gridIndex(nx, nz);
const p = gridPoint(index);
if (circulationPointBlocked(p.x, p.z, temporaryObjects)) continue;
const distance = Math.hypot(p.x - x, p.z - z);
if (distance < bestDistance) {
bestDistance = distance;
best = index;
}
}
}
if (best !== -1) return best;
}
return -1;
}
function compressPath(path) {
if (path.length < 3) return path;
const result = [path[0]];
for (let i = 1; i < path.length - 1; i++) {
const a = result[result.length - 1];
const b = path[i];
const c = path[i + 1];
const d1x = Math.sign(b.x - a.x);
const d1z = Math.sign(b.z - a.z);
const d2x = Math.sign(c.x - b.x);
const d2z = Math.sign(c.z - b.z);
if (d1x !== d2x || d1z !== d2z) result.push(b);
}
result.push(path[path.length - 1]);
return result;
}
function pathLength(path) {
let length = 0;
for (let i = 1; i < path.length; i++) {
length += Math.hypot(path[i].x - path[i - 1].x, path[i].z - path[i - 1].z);
}
return length;
}
function findPath(start, goal, temporaryObjects) {
const startIndex = nearestOpenCell(start.x, start.z, temporaryObjects);
const goalIndex = nearestOpenCell(goal.x, goal.z, temporaryObjects);
if (startIndex === -1 || goalIndex === -1) return null;
const count = GRID.nx * GRID.nz;
const gScore = new Float32Array(count);
gScore.fill(Infinity);
const fScore = new Float32Array(count);
fScore.fill(Infinity);
const cameFrom = new Int32Array(count);
cameFrom.fill(-1);
const closed = new Uint8Array(count);
const open = [startIndex];
const goalPoint = gridPoint(goalIndex);
const heuristic = index => {
const p = gridPoint(index);
return Math.hypot(p.x - goalPoint.x, p.z - goalPoint.z);
};
gScore[startIndex] = 0;
fScore[startIndex] = heuristic(startIndex);
const neighbors = [
[1, 0], [-1, 0], [0, 1], [0, -1],
[1, 1], [1, -1], [-1, 1], [-1, -1]
];
while (open.length) {
let bestOpen = 0;
for (let i = 1; i < open.length; i++) {
if (fScore[open[i]] < fScore[open[bestOpen]]) bestOpen = i;
}
const current = open.splice(bestOpen, 1)[0];
if (current === goalIndex) break;
if (closed[current]) continue;
closed[current] = 1;
const ix = current % GRID.nx;
const iz = Math.floor(current / GRID.nx);
for (const [dx, dz] of neighbors) {
const nx = ix + dx;
const nz = iz + dz;
if (nx < 0 || nx >= GRID.nx || nz < 0 || nz >= GRID.nz) continue;
const next = gridIndex(nx, nz);
if (closed[next]) continue;
const p = gridPoint(next);
if (circulationPointBlocked(p.x, p.z, temporaryObjects)) continue;
if (dx !== 0 && dz !== 0) {
const sideA = gridPoint(gridIndex(ix + dx, iz));
const sideB = gridPoint(gridIndex(ix, iz + dz));
if (circulationPointBlocked(sideA.x, sideA.z, temporaryObjects) ||
circulationPointBlocked(sideB.x, sideB.z, temporaryObjects)) continue;
}
const cost = dx !== 0 && dz !== 0 ? Math.SQRT2 : 1;
const tentative = gScore[current] + cost;
if (tentative < gScore[next]) {
cameFrom[next] = current;
gScore[next] = tentative;
fScore[next] = tentative + heuristic(next);
if (!open.includes(next)) open.push(next);
}
}
}
if (cameFrom[goalIndex] === -1 && goalIndex !== startIndex) return null;
const rawPath = [];
let cursor = goalIndex;
while (cursor !== -1) {
rawPath.push(gridPoint(cursor));
if (cursor === startIndex) break;
cursor = cameFrom[cursor];
}
rawPath.reverse();
return compressPath(rawPath);
}
function computeRoutes(temporaryObjects) {
return routeSpecs.map(spec => {
const path = findPath(spec.start, spec.goal, temporaryObjects);
return {
...spec,
path,
length: path ? pathLength(path) : Infinity
};
});
}
/* ---------- Drawing circulation routes ---------- */
const routeCylinderGeometry = new THREE.CylinderGeometry(1, 1, 1, 5, 1, false);
const routeRingGeometry = new THREE.TorusGeometry(0.46, 0.075, 4, 14);
const routeMarkerGeometry = new THREE.OctahedronGeometry(0.2, 0);
const baselineRouteMaterial = new THREE.MeshBasicMaterial({
color: '#38a7bd',
transparent: true,
opacity: 0.82,
depthWrite: false
});
const eventRouteMaterial = new THREE.MeshBasicMaterial({
color: '#ee9a2f',
transparent: true,
opacity: 0.98,
depthWrite: false
});
const blockedRouteMaterial = new THREE.MeshBasicMaterial({
color: '#c74f48',
transparent: true,
opacity: 0.9,
depthWrite: false
});
const baselineRingMaterial = new THREE.MeshBasicMaterial({
color: '#38a7bd',
transparent: true,
opacity: 0.82,
depthWrite: false
});
let eventMarkers = [];
function clearRouteGroup(group) {
group.children.forEach(child => {
if (child.isSprite) {
child.material.map?.dispose();
child.material.dispose();
}
});
group.clear();
}
function addRouteSegment(group, a, b, material) {
const from = new THREE.Vector3(a.x, 0.17, a.z);
const to = new THREE.Vector3(b.x, 0.17, b.z);
const direction = to.clone().sub(from);
const length = direction.length();
if (length < 0.001) return;
const mesh = new THREE.Mesh(routeCylinderGeometry, material);
mesh.position.copy(from).add(to).multiplyScalar(0.5);
mesh.quaternion.setFromUnitVectors(new THREE.Vector3(0, 1, 0), direction.normalize());
mesh.scale.set(0.085, length, 0.085);
mesh.renderOrder = 3;
group.add(mesh);
}
function addRouteMarker(group, point, material, radius = 0.46) {
const marker = new THREE.Mesh(routeRingGeometry, material);
marker.rotation.x = Math.PI / 2;
marker.position.set(point.x, 0.19, point.z);
marker.scale.setScalar(radius / 0.46);
group.add(marker);
}
function buildRouteGroup(group, results, isEvent) {
clearRouteGroup(group);
if (isEvent) eventMarkers = [];
const material = isEvent ? eventRouteMaterial : baselineRouteMaterial;
const ringMaterial = isEvent ? eventRouteMaterial : baselineRingMaterial;
for (const result of results) {
if (result.path && result.path.length > 1) {
for (let i = 1; i < result.path.length; i++) {
addRouteSegment(group, result.path[i - 1], result.path[i], material);
}
addRouteMarker(group, result.start, ringMaterial);
addRouteMarker(group, result.path[result.path.length - 1], ringMaterial, 0.34);
if (isEvent) {
const marker = new THREE.Mesh(routeMarkerGeometry, eventRouteMaterial);
marker.position.y = 0.38;
marker.renderOrder = 5;
group.add(marker);
eventMarkers.push({
mesh: marker,
path: result.path,
lengths: [],
total: 0
});
}
} else {
addRouteMarker(group, result.start, blockedRouteMaterial);
const label = makeLabelSprite('NO CLEAR ROUTE', {
scaleX: 2.5,
scaleY: 0.52,
fontSize: 21,
background: 'rgba(167,58,53,.94)',
stroke: 'rgba(255,225,220,.8)'
});
label.position.set(result.start.x, 1.1, result.start.z);
group.add(label);
}
}
eventMarkers.forEach(marker => {
for (let i = 1; i < marker.path.length; i++) {
const length = Math.hypot(
marker.path[i].x - marker.path[i - 1].x,
marker.path[i].z - marker.path[i - 1].z
);
marker.lengths.push(length);
marker.total += length;
}
});
}
let baselineResults = [];
let currentResults = [];
function rebuildDynamicRoutes() {
currentResults = computeRoutes(objects);
buildRouteGroup(eventRoutesGroup, currentResults, true);
updateStats();
}
baselineResults = computeRoutes([]);
buildRouteGroup(baselineRoutesGroup, baselineResults, false);
/* ---------- Selection, adding and removing ---------- */
function setSelection(item) {
if (selectionHelper) {
scene.remove(selectionHelper);
selectionHelper.geometry.dispose();
selectionHelper.material.dispose();
selectionHelper = null;
}
selectedObject = item;
if (item) {
selectionHelper = new THREE.BoxHelper(item.group, '#168b70');
selectionHelper.material.depthTest = false;
selectionHelper.renderOrder = 10;
scene.add(selectionHelper);
}
}
function findObjectFromIntersection(intersection) {
let current = intersection.object;
while (current && !current.userData.objectId) current = current.parent;
if (!current) return null;
return objects.find(item => item.id === current.userData.objectId) || null;
}
function handleCanvasClick(event) {
const panel = getPanel(event.clientX);
const rect = renderer.domElement.getBoundingClientRect();
pointerNdc.x = ((event.clientX - rect.left - panel.x0) / panel.width) * 2 - 1;
pointerNdc.y = -((event.clientY - rect.top) / panel.height) * 2 + 1;
setCameraProjection(panel.width, panel.height);
raycaster.setFromCamera(pointerNdc, camera);
if (activeTool) {
if (!panel.allowed) {
showToast('Place temporary elements in the During view.', 'error');
return;
}
const point = groundPointFromEvent(event, panel);
if (!point) return;
const x = Math.round(point.x * 2) / 2;
const z = Math.round(point.z * 2) / 2;
const validation = validatePlacement(activeTool, x, z, placementRotation);
if (!validation.ok) {
showToast(validation.reason, 'error');
return;
}
const item = createTemporaryObject(activeTool);
item.x = x;
item.z = z;
item.rot = placementRotation;
item.group.position.set(x, 0, z);
item.group.rotation.y = placementRotation;
temporaryGroup.add(item.group);
objects.push(item);
rebuildDynamicRoutes();
showToast(`${dimensions[activeTool].label} placed.`, 'success');
return;
}
if (activeTool === null && panel.allowed) {
const hits = raycaster.intersectObjects(temporaryGroup.children, true);
const item = hits.length ? findObjectFromIntersection(hits[0]) : null;
setSelection(item);
if (item) showToast(`${dimensions[item.type].label} selected. Delete removes it.`);
}
}
function removeItem(item) {
if (!item) return;
const index = objects.indexOf(item);
if (index !== -1) objects.splice(index, 1);
temporaryGroup.remove(item.group);
setSelection(null);
rebuildDynamicRoutes();
}
function rotateCurrent() {
if (activeTool) {
placementRotation = (placementRotation + Math.PI / 2) % (Math.PI * 2);
showToast('Placement rotated 90°.');
return;
}
if (selectedObject) {
const oldRotation = selectedObject.rot;
const newRotation = (oldRotation + Math.PI / 2) % (Math.PI * 2);
const validation = validatePlacement(
selectedObject.type,
selectedObject.x,
selectedObject.z,
newRotation,
selectedObject.id
);
if (!validation.ok) {
showToast(validation.reason, 'error');
return;
}
selectedObject.rot = newRotation;
selectedObject.group.rotation.y = newRotation;
rebuildDynamicRoutes();
showToast('Selected module rotated 90°.');
}
}
function undoLast() {
if (!objects.length) {
showToast('There is nothing to undo.');
return;
}
removeItem(objects[objects.length - 1]);
showToast('Last temporary module removed.');
}
function clearAll() {
objects.forEach(item => temporaryGroup.remove(item.group));
objects.length = 0;
setSelection(null);
rebuildDynamicRoutes();
showToast('Temporary event layout cleared.');
}
/* ---------- UI ---------- */
function setTool(tool) {
activeTool = tool;
document.querySelectorAll('[data-tool]').forEach(button => {
button.classList.toggle('active', button.dataset.tool === tool);
});
document.getElementById('selectButton').classList.toggle('active', tool === 'select');
if (tool !== 'select' && tool !== null) {
if (viewMode === 'before') setViewMode('during');
showToast(`Place ${dimensions[tool].label.toLowerCase()} on the plaza.`);
}
if (ghost) ghost.visible = false;
}
document.querySelectorAll('[data-tool]').forEach(button => {
button.addEventListener('click', () => setTool(button.dataset.tool));
});
document.getElementById('rotateButton').addEventListener('click', rotateCurrent);
document.getElementById('undoButton').addEventListener('click', undoLast);
document.getElementById('clearButton').addEventListener('click', clearAll);
document.getElementById('selectButton').addEventListener('click', () => {
setTool('select');
activeTool = null;
showToast('Select a temporary module to inspect or remove it.');
});
document.getElementById('viewButtons').addEventListener('click', event => {
const button = event.target.closest('[data-view]');
if (button) setViewMode(button.dataset.view);
});
function setViewMode(mode) {
viewMode = mode;
document.querySelectorAll('[data-view]').forEach(button => {
button.classList.toggle('active', button.dataset.view === mode);
});
const isCompare = mode === 'compare';
divider.style.display = isCompare ? 'block' : 'none';
beforeLabel.classList.toggle('full', !isCompare);
duringLabel.classList.toggle('full', !isCompare);
if (mode === 'before') {
beforeLabel.style.display = 'block';
duringLabel.style.display = 'none';
} else if (mode === 'during') {
beforeLabel.style.display = 'none';
duringLabel.style.display = 'block';
} else {
beforeLabel.style.display = 'block';
duringLabel.style.display = 'block';
}
if (ghost) ghost.visible = false;
}
layerEntrances.addEventListener('change', () => {
entranceGroup.visible = layerEntrances.checked || !!activeTool;
});
layerRoutes.addEventListener('change', () => {
baselineRoutesGroup.visible = layerRoutes.checked;
eventRoutesGroup.visible = layerRoutes.checked;
});
layerContext.addEventListener('change', () => {
contextGroup.visible = layerContext.checked;
});
window.addEventListener('keydown', event => {
if (['INPUT', 'TEXTAREA'].includes(document.activeElement.tagName)) return;
if (event.key.toLowerCase() === 'r') {
rotateCurrent();
} else if (event.key === 'Delete' || event.key === 'Backspace') {
if (selectedObject) {
removeItem(selectedObject);
showToast('Selected module removed.');
}
} else if (event.key === 'Escape') {
setTool(null);
activeTool = null;
if (ghost) ghost.visible = false;
}
});
/* ---------- Statistics ---------- */
function updateStats() {
const buildableArea = 42 * 26;
const permanentArea = permanentObstacles.reduce((sum, obstacle) => {
return sum + Math.PI * obstacle.r * obstacle.r;
}, 0);
const beforeArea = Math.max(0, Math.round(buildableArea - permanentArea));
const temporaryArea = objects.reduce((sum, item) => sum + item.w * item.d, 0);
const duringArea = Math.max(0, Math.round(beforeArea - temporaryArea));
const beforeLength = baselineResults.reduce((sum, route) => sum + (Number.isFinite(route.length) ? route.length : 0), 0);
const duringLength = currentResults.reduce((sum, route) => sum + (Number.isFinite(route.length) ? route.length : 0), 0);
const changed = currentResults.filter((route, i) => {
const base = baselineResults[i];
return !route.path || !base.path || Math.abs(route.length - base.length) > 0.8;
}).length;
const seatCount = objects.filter(item => item.type === 'seating').length * 12;
document.getElementById('beforeArea').textContent = `${beforeArea} m²`;
document.getElementById('duringArea').textContent = `${duringArea} m²`;
document.getElementById('routeSummary').textContent = `${changed} of 4`;
document.getElementById('entranceSummary').textContent = `${entrances.length} of ${entrances.length}`;
document.getElementById('seatSummary').textContent = `${seatCount} places`;
beforeMeta.textContent = `${beforeArea} m² clear · ${beforeLength.toFixed(0)} m of routes`;
duringMeta.textContent = `${duringArea} m² clear · ${duringLength.toFixed(0)} m of routes · ${changed} changed`;
}
updateStats();
/* ---------- Rendering ---------- */
function resizeRenderer() {
const width = Math.max(1, viewport.clientWidth);
const height = Math.max(1, viewport.clientHeight);
renderer.setSize(width, height, false);
}
const resizeObserver = new ResizeObserver(resizeRenderer);
resizeObserver.observe(viewport);
resizeRenderer();
function configureSceneVisibility(showEvent) {
contextGroup.visible = layerContext.checked;
entranceGroup.visible = layerEntrances.checked || !!activeTool;
temporaryGroup.visible = showEvent;
baselineRoutesGroup.visible = layerRoutes.checked;
eventRoutesGroup.visible = layerRoutes.checked && showEvent;
}
function renderView(x, width, showEvent) {
if (width <= 0) return;
setCameraProjection(width, viewport.clientHeight);
renderer.setViewport(x, 0, width, viewport.clientHeight);
renderer.setScissor(x, 0, width, viewport.clientHeight);
configureSceneVisibility(showEvent);
baselineRouteMaterial.opacity = showEvent ? 0.18 : 0.82;
baselineRingMaterial.opacity = showEvent ? 0.24 : 0.82;
renderer.render(scene, camera);
}
function animateRouteMarkers(time) {
eventMarkers.forEach((marker, index) => {
if (!marker.total) return;
let distance = (time * 3.2 + index * 7.5) % marker.total;
let segment = 0;
while (segment < marker.lengths.length - 1 && distance > marker.lengths[segment]) {
distance -= marker.lengths[segment];
segment++;
}
const a = marker.path[segment];
const b = marker.path[Math.min(segment + 1, marker.path.length - 1)];
const length = marker.lengths[segment] || 1;
const t = distance / length;
marker.mesh.position.x = a.x + (b.x - a.x) * t;
marker.mesh.position.z = a.z + (b.z - a.z) * t;
marker.mesh.position.y = 0.38 + Math.sin(time * 4 + index) * 0.08;
marker.mesh.rotation.y = time * 1.8;
});
}
const clock = new THREE.Clock();
function render() {
requestAnimationFrame(render);
const time = clock.getElapsedTime();
renderer.setScissorTest(false);
renderer.setViewport(0, 0, viewport.clientWidth, viewport.clientHeight);
renderer.clear(true, true, true);
renderer.setScissorTest(true);
if (viewMode === 'compare') {
const split = Math.floor(viewport.clientWidth / 2);
renderView(0, split, false);
renderView(split, viewport.clientWidth - split, true);
} else if (viewMode === 'during') {
renderView(0, viewport.clientWidth, true);
} else {
renderView(0, viewport.clientWidth, false);
}
animateRouteMarkers(time);
if (selectionHelper && selectedObject) {
selectionHelper.update();
}
}
render();
</script>
</body>
</html>
```