Prompt specification
Build or customize the Three.js 3D scene "Plan delivery positions along a continuous arcade" 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: Plan delivery positions along a continuous arcade
Category: Voxel Worlds · Style: Voxel 3D
License: MIT · Reference: https://three3d.app/scene/plan-delivery-positions-along-a-continuous-arcade-x3036
Scene Description Prompt:
Create a single self-contained HTML file using Three.js from cdnjs that shows Dihua Street's commercial arcades in Taipei. Let users place temporary loading carts in a schematic block. Highlight obstructed doorways and broken pedestrian continuity while keeping the permanent column spacing unchanged. Voxel style.
Working Three.js Starter (plan-delivery-positions-along-a-continuous-arcade-x3036):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Dihua Street — Arcade Loading Study</title>
<style>
:root {
--ink: #26353a;
--muted: #687679;
--paper: #f6f1e6;
--panel: rgba(249, 246, 238, 0.94);
--line: rgba(38, 53, 58, 0.14);
--teal: #247c78;
--teal-light: #d9ece7;
--orange: #df6948;
--orange-light: #f8dfd3;
--amber: #bd8b47;
--green: #398c68;
--red: #d94c3d;
--shadow: 0 12px 36px rgba(44, 48, 43, 0.14);
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: #ded8ca;
color: var(--ink);
font-family:
Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
button,
input {
font: inherit;
}
button {
color: inherit;
}
#scene {
position: fixed;
inset: 0;
width: 100%;
height: 100%;
display: block;
outline: none;
touch-action: none;
}
.topbar {
position: fixed;
z-index: 10;
top: 16px;
left: 16px;
right: 16px;
min-height: 68px;
display: flex;
align-items: center;
justify-content: space-between;
gap: 18px;
padding: 12px 16px;
border: 1px solid rgba(255, 255, 255, 0.7);
border-radius: 12px;
background: var(--panel);
box-shadow: var(--shadow);
backdrop-filter: blur(14px);
}
.brand {
display: flex;
align-items: center;
gap: 12px;
min-width: 260px;
}
.brand-mark {
position: relative;
width: 40px;
height: 40px;
flex: 0 0 auto;
border: 2px solid var(--ink);
border-radius: 5px;
background:
linear-gradient(
90deg,
transparent 0 30%,
var(--orange) 30% 38%,
transparent 38% 100%
),
linear-gradient(
0deg,
transparent 0 58%,
var(--teal) 58% 67%,
transparent 67% 100%
),
var(--paper);
}
.brand-mark::after {
content: "";
position: absolute;
left: 8px;
right: 8px;
top: 8px;
height: 7px;
border: 2px solid var(--ink);
border-bottom: 0;
}
.eyebrow,
.tool-label,
.mini-label {
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 10px;
font-weight: 800;
line-height: 1.2;
letter-spacing: 0.12em;
text-transform: uppercase;
}
.eyebrow {
color: var(--teal);
}
.brand h1 {
margin: 3px 0 0;
font-size: 18px;
line-height: 1.1;
letter-spacing: -0.02em;
}
.brand h1 span {
color: var(--muted);
font-weight: 500;
}
.stats {
display: flex;
align-items: stretch;
justify-content: flex-end;
gap: 8px;
}
.stat {
min-width: 112px;
padding: 8px 11px;
border: 1px solid var(--line);
border-radius: 8px;
background: rgba(255, 255, 255, 0.42);
}
.stat-value {
margin-top: 3px;
font-size: 17px;
font-weight: 800;
line-height: 1;
white-space: nowrap;
}
.stat-value.bad {
color: var(--red);
}
.panel {
position: fixed;
z-index: 9;
top: 102px;
right: 16px;
width: 276px;
padding: 18px;
border: 1px solid rgba(255, 255, 255, 0.72);
border-radius: 12px;
background: var(--panel);
box-shadow: var(--shadow);
backdrop-filter: blur(14px);
}
.panel h2 {
margin: 5px 0 8px;
font-size: 20px;
letter-spacing: -0.035em;
}
.panel p {
margin: 0 0 14px;
color: var(--muted);
font-size: 12px;
line-height: 1.55;
}
.status-card {
margin: 14px 0;
padding: 11px 12px;
border-left: 4px solid var(--green);
border-radius: 5px;
background: var(--teal-light);
transition:
border-color 160ms ease,
background 160ms ease;
}
.status-card.bad {
border-color: var(--red);
background: var(--orange-light);
}
#scenarioState {
margin-top: 3px;
font-size: 13px;
font-weight: 800;
}
.legend {
display: grid;
gap: 8px;
margin: 15px 0;
}
.legend-item {
display: flex;
align-items: center;
gap: 9px;
color: var(--muted);
font-size: 11px;
}
.swatch {
width: 17px;
height: 12px;
flex: 0 0 auto;
border-radius: 3px;
border: 1px solid rgba(38, 53, 58, 0.12);
}
.swatch.clear {
background: rgba(57, 140, 104, 0.5);
}
.swatch.blocked {
background: rgba(217, 76, 61, 0.78);
}
.swatch.fixed {
background: var(--amber);
}
.swatch.cart {
background: var(--teal);
}
.fixed-note {
margin-top: 14px;
padding: 12px;
border: 1px solid rgba(189, 139, 71, 0.35);
border-radius: 7px;
background: rgba(189, 139, 71, 0.1);
}
.fixed-note strong {
display: block;
margin: 4px 0;
font-size: 13px;
}
.fixed-note p {
margin: 0;
font-size: 11px;
}
.toggle-row {
display: flex;
align-items: center;
justify-content: space-between;
gap: 10px;
padding: 8px 0;
border-top: 1px solid var(--line);
font-size: 12px;
font-weight: 650;
}
.toggle-row input {
accent-color: var(--teal);
width: 16px;
height: 16px;
}
.toolbar {
position: fixed;
z-index: 12;
left: 50%;
bottom: 18px;
display: flex;
align-items: center;
gap: 5px;
max-width: calc(100vw - 28px);
padding: 7px;
transform: translateX(-50%);
border: 1px solid rgba(255, 255, 255, 0.72);
border-radius: 11px;
background: var(--panel);
box-shadow: var(--shadow);
backdrop-filter: blur(14px);
overflow-x: auto;
}
.tool-group {
display: flex;
align-items: center;
gap: 4px;
padding: 0 6px;
border-right: 1px solid var(--line);
}
.tool-group:last-child {
padding-right: 0;
border-right: 0;
}
.tool-btn {
display: inline-flex;
align-items: center;
justify-content: center;
gap: 7px;
min-height: 36px;
padding: 8px 11px;
border: 1px solid transparent;
border-radius: 7px;
background: transparent;
cursor: pointer;
font-size: 11px;
font-weight: 750;
white-space: nowrap;
transition:
background 130ms ease,
color 130ms ease,
transform 130ms ease;
}
.tool-btn:hover {
background: rgba(36, 124, 120, 0.09);
}
.tool-btn:active {
transform: translateY(1px);
}
.tool-btn.active {
color: white;
background: var(--teal);
}
.tool-btn.danger {
color: var(--red);
}
.tool-btn:disabled {
opacity: 0.32;
cursor: not-allowed;
}
.tool-icon {
width: 17px;
height: 17px;
display: inline-grid;
place-items: center;
border: 1.5px solid currentColor;
border-radius: 3px;
font-family: ui-monospace, monospace;
font-size: 12px;
line-height: 1;
}
.size-control {
display: flex;
gap: 2px;
padding: 3px;
border-radius: 6px;
background: rgba(38, 53, 58, 0.07);
}
.size-btn {
min-width: 34px;
height: 29px;
padding: 0 7px;
border: 0;
border-radius: 4px;
background: transparent;
cursor: pointer;
font-family: ui-monospace, monospace;
font-size: 10px;
font-weight: 800;
}
.size-btn.active {
color: white;
background: var(--ink);
}
.hint {
position: fixed;
z-index: 8;
left: 50%;
bottom: 76px;
max-width: calc(100vw - 32px);
padding: 8px 12px;
transform: translateX(-50%);
border: 1px solid rgba(255, 255, 255, 0.5);
border-radius: 20px;
color: #415054;
background: rgba(249, 246, 238, 0.86);
box-shadow: 0 7px 22px rgba(44, 48, 43, 0.1);
font-size: 11px;
text-align: center;
pointer-events: none;
backdrop-filter: blur(10px);
}
.hint strong {
color: var(--teal);
}
#labelsLayer {
position: fixed;
z-index: 6;
inset: 0;
overflow: hidden;
pointer-events: none;
}
#labelsLayer.hidden {
display: none;
}
.map-label {
position: absolute;
display: none;
transform: translate(-50%, -50%);
border-radius: 4px;
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 9px;
font-weight: 800;
line-height: 1;
letter-spacing: 0.035em;
white-space: nowrap;
box-shadow: 0 3px 9px rgba(31, 42, 42, 0.15);
}
.door-label {
padding: 5px 6px;
border: 1px solid rgba(57, 140, 104, 0.35);
color: #2d7257;
background: rgba(239, 249, 241, 0.94);
}
.door-label.bad {
color: white;
border-color: var(--red);
background: rgba(217, 76, 61, 0.94);
}
.link-label {
padding: 6px 8px;
color: white;
border: 1px solid rgba(255, 255, 255, 0.4);
background: rgba(217, 76, 61, 0.94);
}
.dimension-label {
padding: 5px 7px;
color: #795421;
border: 1px solid rgba(189, 139, 71, 0.5);
background: rgba(255, 246, 225, 0.94);
}
.selection-label {
padding: 6px 9px;
color: white;
border: 1px solid rgba(255, 255, 255, 0.5);
background: rgba(36, 124, 120, 0.95);
font-size: 10px;
}
#toast {
position: fixed;
z-index: 30;
left: 50%;
top: 102px;
max-width: min(440px, calc(100vw - 30px));
padding: 10px 15px;
transform: translate(-50%, -12px);
border-radius: 8px;
color: white;
background: rgba(38, 53, 58, 0.94);
box-shadow: var(--shadow);
font-size: 12px;
font-weight: 650;
text-align: center;
opacity: 0;
pointer-events: none;
transition:
opacity 160ms ease,
transform 160ms ease;
}
#toast.show {
opacity: 1;
transform: translate(-50%, 0);
}
@media (max-width: 900px) {
.panel {
display: none;
}
.stats .stat {
min-width: 90px;
}
.brand {
min-width: 0;
}
.brand h1 {
font-size: 15px;
}
.brand h1 span {
display: none;
}
}
@media (max-width: 680px) {
.topbar {
top: 9px;
left: 9px;
right: 9px;
min-height: 57px;
padding: 9px;
}
.brand-mark {
width: 34px;
height: 34px;
}
.brand .eyebrow {
font-size: 8px;
}
.brand h1 {
font-size: 13px;
}
.stats {
gap: 4px;
}
.stat {
min-width: 63px;
padding: 7px;
}
.stat .mini-label {
font-size: 7px;
}
.stat-value {
font-size: 13px;
}
.toolbar {
bottom: 9px;
gap: 3px;
padding: 5px;
}
.tool-group {
padding: 0 4px;
}
.tool-btn {
min-height: 34px;
padding: 7px 9px;
}
.hint {
bottom: 67px;
font-size: 10px;
}
}
</style>
</head>
<body>
<canvas id="scene" aria-label="Interactive voxel model of Dihua Street arcades"></canvas>
<header class="topbar">
<div class="brand">
<div class="brand-mark" aria-hidden="true"></div>
<div>
<div class="eyebrow">Taipei / Urban Systems</div>
<h1>Dihua Street <span>— Arcade Loading Study</span></h1>
</div>
</div>
<div class="stats" aria-live="polite">
<div class="stat">
<div class="mini-label">Doors blocked</div>
<div class="stat-value" id="doorStat">0 / 12</div>
</div>
<div class="stat">
<div class="mini-label">Links broken</div>
<div class="stat-value" id="linkStat">0 / 12</div>
</div>
<div class="stat">
<div class="mini-label">Temporary carts</div>
<div class="stat-value" id="cartStat">0</div>
</div>
</div>
</header>
<aside class="panel">
<div class="eyebrow">Live clearance test</div>
<h2>Pedestrian continuity</h2>
<p>
Place temporary loading carts on the arcade sidewalk. Door thresholds
and the continuous walking links update automatically.
</p>
<div class="status-card" id="statusCard">
<div class="mini-label">Scenario status</div>
<div id="scenarioState">All routes are clear</div>
</div>
<div class="legend">
<div class="legend-item">
<span class="swatch clear"></span>
Clear doorway or walking link
</div>
<div class="legend-item">
<span class="swatch blocked"></span>
Obstructed doorway / broken continuity
</div>
<div class="legend-item">
<span class="swatch fixed"></span>
Permanent column module
</div>
<div class="legend-item">
<span class="swatch cart"></span>
Temporary loading cart
</div>
</div>
<div class="fixed-note">
<div class="mini-label">Permanent structure</div>
<strong>13 columns · 4.0 m spacing</strong>
<p>
Column positions and bay dimensions are immutable. Only temporary
carts can be added, moved, rotated, or removed.
</p>
</div>
<label class="toggle-row">
Analysis overlays
<input id="analysisToggle" type="checkbox" checked />
</label>
<label class="toggle-row">
Map labels
<input id="labelsToggle" type="checkbox" checked />
</label>
</aside>
<div class="hint" id="hint">
<strong>Place mode:</strong> click the sidewalk to add a cart · drag to orbit ·
right-drag to orbit · wheel to zoom
</div>
<nav class="toolbar" aria-label="Scenario tools">
<div class="tool-group">
<button class="tool-btn" id="selectTool" type="button" aria-pressed="false">
<span class="tool-icon">↖</span> Move
</button>
<button class="tool-btn active" id="placeTool" type="button" aria-pressed="true">
<span class="tool-icon">+</span> Place cart
</button>
</div>
<div class="tool-group">
<span class="tool-label" style="margin: 0 3px;">Size</span>
<div class="size-control" aria-label="Cart size">
<button class="size-btn" type="button" data-size="small">S</button>
<button class="size-btn active" type="button" data-size="standard">M</button>
<button class="size-btn" type="button" data-size="long">L</button>
</div>
</div>
<div class="tool-group">
<button class="tool-btn" id="rotateBtn" type="button" disabled>
<span class="tool-icon">↻</span> Rotate
</button>
<button class="tool-btn danger" id="deleteBtn" type="button" disabled>
<span class="tool-icon">×</span> Delete
</button>
</div>
<div class="tool-group">
<button class="tool-btn" id="undoBtn" type="button" disabled>
<span class="tool-icon">↶</span> Undo
</button>
<button class="tool-btn" id="exampleBtn" type="button">
Example
</button>
<button class="tool-btn danger" id="clearBtn" type="button" disabled>
Clear
</button>
</div>
<div class="tool-group">
<button class="tool-btn active" id="analysisBtn" type="button" aria-pressed="true">
Analysis
</button>
<button class="tool-btn active" id="labelsBtn" type="button" aria-pressed="true">
Labels
</button>
</div>
</nav>
<div id="labelsLayer"></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";
// ---------------------------------------------------------------------
// Core scene
// ---------------------------------------------------------------------
const canvas = document.querySelector("#scene");
const scene = new THREE.Scene();
scene.background = new THREE.Color(0xded8ca);
scene.fog = new THREE.Fog(0xded8ca, 65, 115);
const renderer = new THREE.WebGLRenderer({
canvas,
antialias: true,
powerPreference: "high-performance"
});
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;
const camera = new THREE.OrthographicCamera(-30, 30, 18, -18, 0.1, 160);
const hemisphere = new THREE.HemisphereLight(0xf8f1dd, 0x637477, 2.25);
scene.add(hemisphere);
const sun = new THREE.DirectionalLight(0xfff3d5, 3.0);
sun.position.set(-22, 38, 24);
sun.castShadow = true;
sun.shadow.mapSize.set(2048, 2048);
sun.shadow.camera.left = -42;
sun.shadow.camera.right = 42;
sun.shadow.camera.top = 35;
sun.shadow.camera.bottom = -30;
sun.shadow.camera.near = 1;
sun.shadow.camera.far = 100;
sun.shadow.normalBias = 0.035;
scene.add(sun);
const materialCache = new Map();
function solidMaterial(color) {
if (!materialCache.has(color)) {
materialCache.set(
color,
new THREE.MeshStandardMaterial({
color,
roughness: 0.92,
metalness: 0,
flatShading: true
})
);
}
return materialCache.get(color);
}
function box(
parent,
width,
height,
depth,
color,
x = 0,
y = 0,
z = 0,
options = {}
) {
const mesh = new THREE.Mesh(
new THREE.BoxGeometry(width, height, depth),
options.material || solidMaterial(color)
);
mesh.position.set(x, y, z);
mesh.castShadow = options.castShadow ?? true;
mesh.receiveShadow = options.receiveShadow ?? true;
if (options.rotationY) {
mesh.rotation.y = options.rotationY;
}
parent.add(mesh);
return mesh;
}
// ---------------------------------------------------------------------
// Fixed civic module: 13 columns on an immutable 4.0 m grid
// ---------------------------------------------------------------------
const COLUMN_SPACING = 4.0;
const COLUMN_COUNT = 13;
const COLUMN_X = Object.freeze(
Array.from(
{ length: COLUMN_COUNT },
(_, index) => (index - (COLUMN_COUNT - 1) / 2) * COLUMN_SPACING
)
);
const COLUMN_Z = -4.72;
const SHOP_COUNT = 12;
const DOOR_X = Object.freeze(
Array.from(
{ length: SHOP_COUNT },
(_, index) => (index - (SHOP_COUNT - 1) / 2) * COLUMN_SPACING
)
);
const WALK_Z_MIN = -3.95;
const WALK_Z_MAX = -2.25;
const WALK_Z = (WALK_Z_MIN + WALK_Z_MAX) / 2;
const WALK_DEPTH = WALK_Z_MAX - WALK_Z_MIN;
const ground = new THREE.Group();
scene.add(ground);
box(ground, 66, 0.8, 29, 0xcac4b4, 0, -0.55, 2.0);
// Main street and sidewalks.
box(ground, 64, 0.10, 9.6, 0x4a5659, 0, 0.02, 3.35);
box(ground, 56, 0.18, 4.8, 0xe4ddcc, 0, 0.07, -4.0);
box(ground, 64, 0.14, 2.3, 0xd8d1c0, 0, 0.05, 9.15);
// Road markings.
for (let x = -30; x <= 30; x += 4.5) {
box(
ground,
2.25,
0.025,
0.11,
0xf1dfae,
x,
0.09,
3.35,
{ castShadow: false }
);
}
// Crosswalk.
for (let i = 0; i < 8; i++) {
box(
ground,
0.36,
0.025,
7.5,
0xe9e4d8,
-12.5 + i * 0.8,
0.09,
3.35,
{ castShadow: false }
);
}
// ---------------------------------------------------------------------
// Dihua Street block: voxel shophouses and covered arcade
// ---------------------------------------------------------------------
const buildingGroup = new THREE.Group();
scene.add(buildingGroup);
const shopColors = [
0xc6ad83, 0xb7c1ae, 0xc9a78e, 0xbac7c0,
0xbfa47e, 0xc7b6a2, 0xaebbb7, 0xc8a083,
0xb9ad91, 0xb5c1bd, 0xc6aa86, 0xb8aa98
];
const awningColors = [
0x3f7772, 0xa7543f, 0xc09149, 0x506c74,
0x8b5846, 0x417d67, 0xb57d40, 0x675f68,
0x47776e, 0xa95e46, 0xb08b4f, 0x586e70
];
const shopNames = [
["茶行", "TEA"],
["布行", "TEXTILE"],
["南北貨", "GROCERIES"],
["紙行", "PAPER"],
["金屬", "METALWARE"],
["香舖", "INCENSE"],
["茶葉", "TEA LEAVES"],
["瓷器", "CERAMICS"],
["食品", "FOOD"],
["手作", "CRAFT"],
["商行", "TRADING"],
["藥行", "HERBS"]
];
function signTexture(zh, en, background, foreground = "#fff7df") {
const signCanvas = document.createElement("canvas");
signCanvas.width = 512;
signCanvas.height = 128;
const context = signCanvas.getContext("2d");
context.fillStyle = background;
context.fillRect(0, 0, 512, 128);
context.strokeStyle = "rgba(255,255,255,.32)";
context.lineWidth = 4;
context.strokeRect(8, 8, 496, 112);
context.fillStyle = foreground;
context.textAlign = "center";
context.textBaseline = "middle";
context.font = '800 48px "Microsoft JhengHei", "Noto Sans TC", sans-serif';
context.fillText(zh, 256, 43);
context.globalAlpha = 0.8;
context.font = "700 20px ui-monospace, monospace";
context.fillText(en, 256, 91);
const texture = new THREE.CanvasTexture(signCanvas);
texture.colorSpace = THREE.SRGBColorSpace;
texture.anisotropy = Math.min(renderer.capabilities.getMaxAnisotropy(), 8);
return texture;
}
for (let index = 0; index < SHOP_COUNT; index++) {
const x = DOOR_X[index];
// Individual voxel shop mass.
box(
buildingGroup,
3.96,
6.25,
4.7,
shopColors[index],
x,
3.18,
-8.65
);
// Upper facade windows.
for (let level = 0; level < 2; level++) {
const windowY = 4.35 + level * 1.12;
box(
buildingGroup,
1.22,
0.66,
0.08,
0x52676a,
x,
windowY,
-6.275,
{ castShadow: false }
);
box(
buildingGroup,
0.07,
0.7,
0.11,
0xdfd6c3,
x,
windowY,
-6.205
);
box(
buildingGroup,
1.34,
0.07,
0.11,
0xdfd6c3,
x,
windowY,
-6.205
);
}
// Recessed doorway.
box(
buildingGroup,
1.28,
2.45,
0.09,
index % 3 === 0 ? 0x374b4d : 0x455655,
x,
1.31,
-6.23
);
// Door panels.
box(
buildingGroup,
0.55,
2.25,
0.07,
0x68817c,
x - 0.31,
1.25,
-6.16
);
box(
buildingGroup,
0.55,
2.25,
0.07,
0x78908a,
x + 0.31,
1.25,
-6.16
);
// Awning.
box(
buildingGroup,
3.18,
0.18,
0.78,
awningColors[index],
x,
2.67,
-5.91
);
// Shop sign.
const signMaterial = new THREE.MeshBasicMaterial({
map: signTexture(
shopNames[index][0],
shopNames[index][1],
`#${awningColors[index].toString(16).padStart(6, "0")}`
)
});
const sign = new THREE.Mesh(
new THREE.PlaneGeometry(2.68, 0.62),
signMaterial
);
sign.position.set(x, 3.23, -6.16);
buildingGroup.add(sign);
// Small voxel awning supports.
for (const side of [-1, 1]) {
box(
buildingGroup,
0.08,
0.57,
0.08,
0x695f50,
x + side * 1.42,
2.37,
-5.68
);
}
}
// Permanent columns. These meshes are never edited by scenario tools.
const columnGroup = new THREE.Group();
scene.add(columnGroup);
for (const x of COLUMN_X) {
box(columnGroup, 0.58, 0.15, 0.58, 0xb58a4e, x, 0.24, COLUMN_Z);
box(columnGroup, 0.28, 3.18, 0.28, 0xc49b59, x, 1.85, COLUMN_Z);
box(columnGroup, 0.56, 0.18, 0.56, 0xb78b4c, x, 3.49, COLUMN_Z);
box(columnGroup, 0.34, 0.08, 0.34, 0xe1c78e, x, 3.62, COLUMN_Z);
}
// Arcade roof and cornice.
box(buildingGroup, 51.4, 0.34, 4.45, 0x6f7771, 0, 3.78, -6.62);
box(buildingGroup, 51.7, 0.16, 0.18, 0x59645f, 0, 3.55, -4.37);
box(buildingGroup, 51.7, 0.13, 0.18, 0xb4a98d, 0, 3.98, -4.37);
// Rooftop details.
for (let index = 0; index < 7; index++) {
const x = -18 + index * 6;
box(buildingGroup, 1.4, 0.75, 1.3, 0x92958a, x, 6.65, -8.8);
box(buildingGroup, 0.12, 0.5, 0.12, 0x5f6762, x, 7.22, -8.8);
box(buildingGroup, 1.9, 0.12, 1.7, 0x827f70, x, 6.37, -8.8);
}
// Arcade identity sign.
const arcadeSignMaterial = new THREE.MeshBasicMaterial({
map: signTexture("迪化街商圈", "DIHUA STREET ARCADE", "#244f4c")
});
const arcadeSign = new THREE.Mesh(
new THREE.PlaneGeometry(7.4, 0.72),
arcadeSignMaterial
);
arcadeSign.position.set(0, 4.0, -4.26);
buildingGroup.add(arcadeSign);
// ---------------------------------------------------------------------
// Opposite-side urban context
// ---------------------------------------------------------------------
const contextGroup = new THREE.Group();
scene.add(contextGroup);
const oppositeColors = [
0xaab4ad, 0xbcae94, 0xb1b8ad, 0xc2ad91,
0xa9b5b1, 0xb9aa91, 0xaab2a8, 0xc0b29b
];
for (let index = 0; index < 8; index++) {
const x = -25.5 + index * 7.3;
box(
contextGroup,
6.9,
5.5 + (index % 3) * 0.55,
4.0,
oppositeColors[index],
x,
2.8,
12.0
);
for (let column = 0; column < 3; column++) {
box(
contextGroup,
1.0,
0.85,
0.07,
0x52676a,
x - 1.9 + column * 1.9,
3.7,
9.96,
{ castShadow: false }
);
}
box(
contextGroup,
6.9,
0.18,
0.22,
0x716f65,
x,
2.3,
9.94
);
}
// Voxel planters along the curb.
for (const x of [-18, -10, 10, 18]) {
box(contextGroup, 1.05, 0.55, 0.8, 0x9e7653, x, 0.37, -1.15);
box(contextGroup, 0.18, 1.35, 0.18, 0x7d654c, x, 1.05, -1.15);
box(contextGroup, 1.05, 0.85, 0.85, 0x5f8969, x, 1.95, -1.15);
box(contextGroup, 0.8, 0.7, 0.8, 0x6f9875, x - 0.18, 2.55, -1.1);
}
// A few simple parked vehicles.
function addVoxelCar(x, z, color, reverse = false) {
const car = new THREE.Group();
car.position.set(x, 0.12, z);
car.rotation.y = reverse ? Math.PI : 0;
box(car, 3.1, 0.58, 1.38, color, 0, 0.45, 0);
box(car, 1.55, 0.62, 1.18, color, -0.15, 1.01, 0);
box(car, 1.28, 0.43, 1.20, 0x52666a, -0.15, 1.06, 0);
for (const wheelX of [-0.95, 0.95]) {
for (const wheelZ of [-0.70, 0.70]) {
box(
car,
0.42,
0.42,
0.20,
0x303a3c,
wheelX,
0.26,
wheelZ
);
}
}
contextGroup.add(car);
}
addVoxelCar(-20, 5.8, 0xb5c3bb);
addVoxelCar(14, 1.0, 0xa65f48);
// ---------------------------------------------------------------------
// Permanent-spacing dimension annotation
// ---------------------------------------------------------------------
const dimensionMaterial = new THREE.LineBasicMaterial({
color: 0xb47c36,
transparent: true,
opacity: 0.95
});
const dimensionPoints = [
new THREE.Vector3(COLUMN_X[0], 0.31, -0.73),
new THREE.Vector3(COLUMN_X[1], 0.31, -0.73),
new THREE.Vector3(COLUMN_X[0], 0.31, -0.92),
new THREE.Vector3(COLUMN_X[0], 0.31, -0.54),
new THREE.Vector3(COLUMN_X[1], 0.31, -0.92),
new THREE.Vector3(COLUMN_X[1], 0.31, -0.54)
];
const dimensionGeometry = new THREE.BufferGeometry().setFromPoints(
dimensionPoints
);
scene.add(new THREE.LineSegments(dimensionGeometry, dimensionMaterial));
// ---------------------------------------------------------------------
// Analysis layers
// ---------------------------------------------------------------------
const analysisGroup = new THREE.Group();
scene.add(analysisGroup);
const doorRecords = [];
const linkRecords = [];
const labelsLayer = document.querySelector("#labelsLayer");
function makeMapLabel(className, text) {
const element = document.createElement("div");
element.className = `map-label ${className}`;
element.textContent = text;
labelsLayer.appendChild(element);
return element;
}
function makeOverlayPlane(width, depth, color, opacity, x, z) {
const material = new THREE.MeshBasicMaterial({
color,
transparent: true,
opacity,
depthWrite: false,
side: THREE.DoubleSide
});
const plane = new THREE.Mesh(
new THREE.PlaneGeometry(width, depth),
material
);
plane.rotation.x = -Math.PI / 2;
plane.position.set(x, 0.225, z);
plane.renderOrder = 4;
analysisGroup.add(plane);
return plane;
}
for (let index = 0; index < SHOP_COUNT; index++) {
const x = DOOR_X[index];
const thresholdPlane = makeOverlayPlane(
1.58,
2.47,
0x398c68,
0.14,
x,
-5.015
);
const frameGeometry = new THREE.EdgesGeometry(
new THREE.BoxGeometry(1.52, 2.62, 0.04)
);
const frameMaterial = new THREE.LineBasicMaterial({
color: 0x398c68,
transparent: true,
opacity: 0.85
});
const frame = new THREE.LineSegments(frameGeometry, frameMaterial);
frame.position.set(x, 1.35, -6.12);
frame.renderOrder = 5;
analysisGroup.add(frame);
const label = makeMapLabel("door-label", `D${String(index + 1).padStart(2, "0")}`);
doorRecords.push({
id: index,
x,
label,
plane: thresholdPlane,
frame,
blocked: false,
rect: {
xmin: x - 0.79,
xmax: x + 0.79,
zmin: -6.25,
zmax: -3.78
}
});
}
for (let index = 0; index < SHOP_COUNT; index++) {
const xmin = COLUMN_X[index];
const xmax = COLUMN_X[index + 1];
const x = (xmin + xmax) / 2;
const plane = makeOverlayPlane(
COLUMN_SPACING - 0.08,
WALK_DEPTH,
0x398c68,
0.14,
x,
WALK_Z
);
const label = makeMapLabel("link-label", "LINK BROKEN");
linkRecords.push({
id: index,
xmin,
xmax,
x,
label,
plane,
blocked: false,
rect: {
xmin,
xmax,
zmin: WALK_Z_MIN,
zmax: WALK_Z_MAX
}
});
}
const dimensionLabel = makeMapLabel(
"dimension-label",
"4.0 m · FIXED COLUMN MODULE"
);
const selectionLabel = makeMapLabel("selection-label", "CART SELECTED");
// ---------------------------------------------------------------------
// Invisible placement plane
// ---------------------------------------------------------------------
const placementPlane = new THREE.Mesh(
new THREE.PlaneGeometry(52, 4.8),
new THREE.MeshBasicMaterial({
transparent: true,
opacity: 0,
depthWrite: false
})
);
placementPlane.rotation.x = -Math.PI / 2;
placementPlane.position.set(0, 0.225, -4.0);
scene.add(placementPlane);
// ---------------------------------------------------------------------
// Temporary loading carts
// ---------------------------------------------------------------------
const CART_SIZES = {
small: { width: 0.9, depth: 0.65, height: 1.06, label: "S" },
standard: { width: 1.28, depth: 0.82, height: 1.30, label: "M" },
long: { width: 1.86, depth: 0.82, height: 1.30, label: "L" }
};
const carts = [];
const cartGroups = [];
let nextCartId = 1;
let selectedCartId = null;
let currentSize = "standard";
let mode = "place";
const scenarioHistory = [];
const cartHitGroups = [];
function cartExtents(cart) {
const dimensions = CART_SIZES[cart.size];
const rotated = Math.abs(Math.sin(cart.rotation)) > 0.5;
return {
x: rotated ? dimensions.depth : dimensions.width,
z: rotated ? dimensions.width : dimensions.depth,
height: dimensions.height
};
}
function cartRect(cart, padding = 0) {
const extents = cartExtents(cart);
return {
xmin: cart.x - extents.x / 2 - padding,
xmax: cart.x + extents.x / 2 + padding,
zmin: cart.z - extents.z / 2 - padding,
zmax: cart.z + extents.z / 2 + padding
};
}
function rectanglesOverlap(a, b) {
return (
a.xmin < b.xmax &&
a.xmax > b.xmin &&
a.zmin < b.zmax &&
a.zmax > b.zmin
);
}
function isValidPlacement(x, z, size, rotation, ignoredId = null) {
const candidate = {
x,
z,
size,
rotation
};
const rect = cartRect(candidate, 0.025);
if (
rect.xmin < -25.4 ||
rect.xmax > 25.4 ||
rect.zmin < -6.34 ||
rect.zmax > -1.68
) {
return {
valid: false,
message: "Place the cart fully on the illustrated arcade sidewalk."
};
}
for (const cart of carts) {
if (cart.id === ignoredId) continue;
if (rectanglesOverlap(rect, cartRect(cart, 0.065))) {
return {
valid: false,
message: "That position overlaps another temporary cart."
};
}
}
for (const columnX of COLUMN_X) {
const columnRect = {
xmin: columnX - 0.34,
xmax: columnX + 0.34,
zmin: COLUMN_Z - 0.34,
zmax: COLUMN_Z + 0.34
};
if (rectanglesOverlap(rect, columnRect)) {
return {
valid: false,
message: "Permanent columns cannot be moved or occupied."
};
}
}
return { valid: true, message: "" };
}
function createCart({ id, x, z, size, rotation }) {
const dimensions = CART_SIZES[size];
const group = new THREE.Group();
group.position.set(x, 0, z);
group.rotation.y = rotation;
const frameColor = 0xd96645;
const cargoColor = 0x2f8179;
const crateColor = 0xd4ad72;
// Wheels use blocks to retain the voxel language.
for (const wheelX of [-dimensions.width * 0.37, dimensions.width * 0.37]) {
for (const wheelZ of [-dimensions.depth * 0.34, dimensions.depth * 0.34]) {
box(group, 0.22, 0.25, 0.22, 0x354144, wheelX, 0.15, wheelZ);
}
}
// Platform.
box(
group,
dimensions.width,
0.13,
dimensions.depth,
frameColor,
0,
0.34,
0
);
// Cargo blocks.
const crateWidth = dimensions.width * 0.52;
const crateDepth = dimensions.depth * 0.72;
box(
group,
crateWidth,
dimensions.height * 0.52,
crateDepth,
cargoColor,
0,
0.68 + dimensions.height * 0.26,
0
);
box(
group,
crateWidth * 0.66,
dimensions.height * 0.30,
crateDepth * 0.78,
crateColor,
-dimensions.width * 0.09,
dimensions.height * 0.77,
0
);
// Handle.
box(
group,
0.09,
dimensions.height * 0.68,
0.09,
frameColor,
-dimensions.width * 0.44,
dimensions.height * 0.56,
-dimensions.depth * 0.31
);
box(
group,
0.09,
dimensions.height * 0.68,
0.09,
frameColor,
-dimensions.width * 0.44,
dimensions.height * 0.56,
dimensions.depth * 0.31
);
box(
group,
0.09,
0.09,
dimensions.depth * 0.70,
frameColor,
-dimensions.width * 0.44,
dimensions.height * 0.88,
0
);
// Dashed temporary footprint.
const footprintGeometry = new THREE.EdgesGeometry(
new THREE.BoxGeometry(dimensions.width + 0.1, 0.035, dimensions.depth + 0.1)
);
const footprintMaterial = new THREE.LineDashedMaterial({
color: 0x247c78,
dashSize: 0.18,
gapSize: 0.11,
transparent: true,
opacity: 0.95
});
const footprint = new THREE.LineSegments(
footprintGeometry,
footprintMaterial
);
footprint.position.y = 0.25;
footprint.computeLineDistances();
group.add(footprint);
group.traverse((object) => {
object.userData.cartId = id;
});
scene.add(group);
const cart = {
id,
x,
z,
size,
rotation,
group,
footprint,
footprintMaterial,
issue: false
};
carts.push(cart);
cartGroups.push(group);
cartHitGroups.push(group);
return cart;
}
function removeAllCarts() {
for (const group of cartGroups) {
scene.remove(group);
group.traverse((object) => {
if (object.geometry) object.geometry.dispose();
if (
object.material &&
!Array.isArray(object.material) &&
!materialCache.has(object.material.color?.getHex())
) {
if (object.material.map) object.material.map.dispose();
object.material.dispose();
}
});
}
carts.length = 0;
cartGroups.length = 0;
cartHitGroups.length = 0;
selectedCartId = null;
updateSelectionBox();
}
function serializeCarts() {
return carts.map((cart) => ({
id: cart.id,
x: cart.x,
z: cart.z,
size: cart.size,
rotation: cart.rotation
}));
}
function restoreCarts(state) {
removeAllCarts();
for (const item of state) {
createCart(item);
}
nextCartId =
state.reduce((maximum, item) => Math.max(maximum, item.id), 0) + 1;
updateAnalysis();
updateHistoryButtons();
}
function pushHistory() {
scenarioHistory.push(serializeCarts());
if (scenarioHistory.length > 40) scenarioHistory.shift();
updateHistoryButtons();
}
function updateHistoryButtons() {
document.querySelector("#undoBtn").disabled = scenarioHistory.length === 0;
document.querySelector("#clearBtn").disabled = carts.length === 0;
}
function addCartAt(x, z, size = currentSize, rotation = 0, silent = false) {
const validation = isValidPlacement(x, z, size, rotation);
if (!validation.valid) {
if (!silent) showToast(validation.message);
return null;
}
const cart = createCart({
id: nextCartId++,
x,
z,
size,
rotation
});
selectCart(cart.id);
updateAnalysis();
updateHistoryButtons();
if (!silent) {
showToast(
`Cart C${String(cart.id).padStart(2, "0")} placed. Doorway and continuity checks updated.`
);
}
return cart;
}
function selectCart(id) {
selectedCartId = id;
updateSelectionBox();
updateActionButtons();
}
function selectedCart() {
return carts.find((cart) => cart.id === selectedCartId) || null;
}
function updateActionButtons() {
const hasSelection = Boolean(selectedCart());
document.querySelector("#rotateBtn").disabled = !hasSelection;
document.querySelector("#deleteBtn").disabled = !hasSelection;
}
const selectionGeometry = new THREE.EdgesGeometry(
new THREE.BoxGeometry(1, 1, 1)
);
const selectionMaterial = new THREE.LineBasicMaterial({
color: 0xf3b09b,
transparent: true,
opacity: 0.95
});
const selectionBox = new THREE.LineSegments(
selectionGeometry,
selectionMaterial
);
selectionBox.visible = false;
scene.add(selectionBox);
function updateSelectionBox() {
const cart = selectedCart();
if (!cart) {
selectionBox.visible = false;
return;
}
const dimensions = CART_SIZES[cart.size];
const extents = cartExtents(cart);
selectionBox.visible = true;
selectionBox.position.set(cart.x, dimensions.height * 0.52 + 0.1, cart.z);
selectionBox.rotation.y = cart.rotation;
selectionBox.scale.set(
extents.x + 0.18,
dimensions.height + 0.20,
extents.z + 0.18
);
}
function rotateSelected() {
const cart = selectedCart();
if (!cart) return;
const nextRotation = cart.rotation + Math.PI / 2;
const validation = isValidPlacement(
cart.x,
cart.z,
cart.size,
nextRotation,
cart.id
);
if (!validation.valid) {
showToast("The cart cannot rotate into a column or another cart.");
return;
}
pushHistory();
cart.rotation = nextRotation;
cart.group.rotation.y = nextRotation;
updateAnalysis();
}
function deleteSelected() {
const cart = selectedCart();
if (!cart) return;
pushHistory();
scene.remove(cart.group);
const cartIndex = carts.indexOf(cart);
const groupIndex = cartGroups.indexOf(cart.group);
const hitIndex = cartHitGroups.indexOf(cart.group);
if (cartIndex >= 0) carts.splice(cartIndex, 1);
if (groupIndex >= 0) cartGroups.splice(groupIndex, 1);
if (hitIndex >= 0) cartHitGroups.splice(hitIndex, 1);
selectedCartId = null;
updateSelectionBox();
updateAnalysis();
updateHistoryButtons();
showToast("Temporary cart removed.");
}
function undo() {
const state = scenarioHistory.pop();
if (!state) return;
restoreCarts(state);
showToast("Scenario change undone.");
}
// ---------------------------------------------------------------------
// Automatic analysis
// ---------------------------------------------------------------------
function updateAnalysis() {
let blockedDoors = 0;
let brokenLinks = 0;
for (const door of doorRecords) {
door.blocked = carts.some((cart) =>
rectanglesOverlap(cartRect(cart), door.rect)
);
if (door.blocked) blockedDoors++;
door.label.textContent = door.blocked
? `D${String(door.id + 1).padStart(2, "0")} · BLOCKED`
: `D${String(door.id + 1).padStart(2, "0")}`;
door.label.classList.toggle("bad", door.blocked);
door.plane.material.color.setHex(
door.blocked ? 0xd94c3d : 0x398c68
);
door.plane.material.opacity = door.blocked ? 0.48 : 0.14;
door.frame.material.color.setHex(
door.blocked ? 0xd94c3d : 0x398c68
);
}
for (const link of linkRecords) {
link.blocked = carts.some((cart) =>
rectanglesOverlap(cartRect(cart), link.rect)
);
if (link.blocked) brokenLinks++;
link.plane.material.color.setHex(
link.blocked ? 0xd94c3d : 0x398c68
);
link.plane.material.opacity = link.blocked ? 0.48 : 0.14;
}
for (const cart of carts) {
cart.issue = doorRecords.some(
(door) =>
door.blocked &&
rectanglesOverlap(cartRect(cart), door.rect)
);
cart.issue ||= linkRecords.some(
(link) =>
link.blocked &&
rectanglesOverlap(cartRect(cart), link.rect)
);
cart.footprintMaterial.color.setHex(
cart.issue ? 0xd94c3d : 0x247c78
);
}
document.querySelector("#doorStat").textContent =
`${blockedDoors} / ${SHOP_COUNT}`;
document.querySelector("#linkStat").textContent =
`${brokenLinks} / ${SHOP_COUNT}`;
document.querySelector("#cartStat").textContent = carts.length;
document.querySelector("#doorStat").classList.toggle("bad", blockedDoors > 0);
document.querySelector("#linkStat").classList.toggle("bad", brokenLinks > 0);
const statusCard = document.querySelector("#statusCard");
statusCard.classList.toggle("bad", blockedDoors > 0 || brokenLinks > 0);
const issueCount = blockedDoors + brokenLinks;
document.querySelector("#scenarioState").textContent =
issueCount === 0
? "All routes are clear"
: `${issueCount} clearance ${issueCount === 1 ? "issue" : "issues"} detected`;
updateSelectionBox();
updateActionButtons();
updateHistoryButtons();
}
// ---------------------------------------------------------------------
// UI
// ---------------------------------------------------------------------
let toastTimer;
function showToast(message) {
const toast = document.querySelector("#toast");
toast.textContent = message;
toast.classList.add("show");
clearTimeout(toastTimer);
toastTimer = setTimeout(() => {
toast.classList.remove("show");
}, 2600);
}
function setMode(nextMode) {
mode = nextMode;
const placeActive = mode === "place";
document.querySelector("#placeTool").classList.toggle("active", placeActive);
document.querySelector("#selectTool").classList.toggle("active", !placeActive);
document.querySelector("#placeTool").setAttribute(
"aria-pressed",
String(placeActive)
);
document.querySelector("#selectTool").setAttribute(
"aria-pressed",
String(!placeActive)
);
document.querySelector("#hint").innerHTML = placeActive
? "<strong>Place mode:</strong> click the sidewalk to add a cart · drag to orbit · right-drag to orbit · wheel to zoom"
: "<strong>Move mode:</strong> drag a cart to reposition it · R rotates · Delete removes · drag empty space to orbit";
canvas.style.cursor = placeActive ? "crosshair" : "grab";
}
document.querySelector("#placeTool").addEventListener("click", () => {
setMode("place");
});
document.querySelector("#selectTool").addEventListener("click", () => {
setMode("select");
});
document.querySelectorAll(".size-btn").forEach((button) => {
button.addEventListener("click", () => {
currentSize = button.dataset.size;
document.querySelectorAll(".size-btn").forEach((item) => {
item.classList.toggle("active", item === button);
});
});
});
document.querySelector("#rotateBtn").addEventListener("click", rotateSelected);
document.querySelector("#deleteBtn").addEventListener("click", deleteSelected);
document.querySelector("#undoBtn").addEventListener("click", undo);
document.querySelector("#clearBtn").addEventListener("click", () => {
if (!carts.length) return;
pushHistory();
removeAllCarts();
updateAnalysis();
showToast("Temporary carts cleared. Permanent structure is unchanged.");
});
document.querySelector("#exampleBtn").addEventListener("click", () => {
pushHistory();
removeAllCarts();
// One cart blocks a doorway approach.
addCartAt(DOOR_X[3], -5.18, "standard", 0, true);
// One cart interrupts a longitudinal pedestrian link.
addCartAt(-6, WALK_Z, "standard", 0, true);
updateAnalysis();
showToast("Example loaded: one blocked doorway and one broken walking link.");
});
function setAnalysisVisible(visible) {
analysisGroup.visible = visible;
document.querySelector("#analysisToggle").checked = visible;
document.querySelector("#analysisBtn").classList.toggle("active", visible);
document.querySelector("#analysisBtn").setAttribute(
"aria-pressed",
String(visible)
);
}
function setLabelsVisible(visible) {
labelsLayer.classList.toggle("hidden", !visible);
document.querySelector("#labelsToggle").checked = visible;
document.querySelector("#labelsBtn").classList.toggle("active", visible);
document.querySelector("#labelsBtn").setAttribute(
"aria-pressed",
String(visible)
);
}
document.querySelector("#analysisToggle").addEventListener("change", (event) => {
setAnalysisVisible(event.target.checked);
});
document.querySelector("#labelsToggle").addEventListener("change", (event) => {
setLabelsVisible(event.target.checked);
});
document.querySelector("#analysisBtn").addEventListener("click", () => {
setAnalysisVisible(!analysisGroup.visible);
});
document.querySelector("#labelsBtn").addEventListener("click", () => {
setLabelsVisible(labelsLayer.classList.contains("hidden"));
});
// ---------------------------------------------------------------------
// Direct camera controls — no external control addon
// ---------------------------------------------------------------------
const cameraState = {
target: new THREE.Vector3(0, 1.0, -2.0),
azimuth: 0.70,
elevation: 0.62,
distance: 70,
zoom: 1
};
function updateCamera() {
const horizontalDistance =
cameraState.distance * Math.cos(cameraState.elevation);
camera.position.set(
cameraState.target.x +
horizontalDistance * Math.sin(cameraState.azimuth),
cameraState.target.y +
cameraState.distance * Math.sin(cameraState.elevation),
cameraState.target.z +
horizontalDistance * Math.cos(cameraState.azimuth)
);
camera.lookAt(cameraState.target);
camera.zoom = cameraState.zoom;
camera.updateProjectionMatrix();
camera.updateMatrixWorld();
}
function panCamera(deltaX, deltaY) {
const worldPerPixel =
((camera.top - camera.bottom) / camera.zoom) /
window.innerHeight;
const right = new THREE.Vector3()
.setFromMatrixColumn(camera.matrixWorld, 0);
right.y = 0;
right.normalize();
const forward = new THREE.Vector3().subVectors(
cameraState.target,
camera.position
);
forward.y = 0;
forward.normalize();
cameraState.target.addScaledVector(right, -deltaX * worldPerPixel);
cameraState.target.addScaledVector(forward, deltaY * worldPerPixel);
updateCamera();
}
function resize() {
const width = window.innerWidth;
const height = window.innerHeight;
const aspect = width / height;
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(width, height);
const viewHeight = Math.max(29, 55 / aspect);
camera.left = (-viewHeight * aspect) / 2;
camera.right = (viewHeight * aspect) / 2;
camera.top = viewHeight / 2;
camera.bottom = -viewHeight / 2;
camera.updateProjectionMatrix();
updateCamera();
}
window.addEventListener("resize", resize);
resize();
const raycaster = new THREE.Raycaster();
const pointer = new THREE.Vector2();
const groundPlane = new THREE.Plane(new THREE.Vector3(0, 1, 0), 0);
const intersectionPoint = new THREE.Vector3();
function setPointer(event) {
const rect = canvas.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 pointOnGround() {
setPointer(arguments[0]);
return raycaster.ray.intersectPlane(groundPlane, intersectionPoint)
? intersectionPoint.clone()
: null;
}
function cartUnderPointer() {
const hits = raycaster.intersectObjects(cartHitGroups, true);
if (!hits.length) return null;
const id = hits[0].object.userData.cartId;
return carts.find((cart) => cart.id === id) || null;
}
let pointerState = null;
let dragState = null;
canvas.addEventListener("contextmenu", (event) => {
event.preventDefault();
});
canvas.addEventListener("pointerdown", (event) => {
canvas.setPointerCapture(event.pointerId);
setPointer(event);
const startX = event.clientX;
const startY = event.clientY;
const lastX = event.clientX;
const lastY = event.clientY;
if (event.button === 2) {
pointerState = {
type: event.shiftKey ? "pan" : "orbit",
startX,
startY,
lastX,
lastY,
moved: false
};
return;
}
if (event.button === 1) {
pointerState = {
type: "pan",
startX,
startY,
lastX,
lastY,
moved: false
};
event.preventDefault();
return;
}
if (event.button !== 0) return;
if (mode === "select") {
const cart = cartUnderPointer();
const point = pointOnGround(event);
if (cart && point) {
selectCart(cart.id);
dragState = {
id: cart.id,
offsetX: cart.x - point.x,
offsetZ: cart.z - point.z,
moved: false,
previousState: serializeCarts()
};
pointerState = {
type: "drag",
startX,
startY,
lastX,
lastY,
moved: false
};
canvas.style.cursor = "grabbing";
return;
}
}
pointerState = {
type: event.shiftKey ? "pan" : "orbit",
startX,
startY,
lastX,
lastY,
moved: false,
potentialPlacement: mode === "place"
};
});
canvas.addEventListener("pointermove", (event) => {
if (!pointerState) return;
const dx = event.clientX - pointerState.lastX;
const dy = event.clientY - pointerState.lastY;
const totalDistance = Math.hypot(
event.clientX - pointerState.startX,
event.clientY - pointerState.startY
);
if (totalDistance > 5) pointerState.moved = true;
if (pointerState.type === "orbit") {
cameraState.azimuth -= dx * 0.006;
cameraState.elevation = THREE.MathUtils.clamp(
cameraState.elevation + dy * 0.005,
0.28,
1.22
);
updateCamera();
} else if (pointerState.type === "pan") {
panCamera(dx, dy);
} else if (pointerState.type === "drag" && dragState) {
const point = pointOnGround(event);
if (!point) return;
const cart = carts.find((item) => item.id === dragState.id);
if (!cart) return;
const nextX = point.x + dragState.offsetX;
const nextZ = point.z + dragState.offsetZ;
const validation = isValidPlacement(
nextX,
nextZ,
cart.size,
cart.rotation,
cart.id
);
if (!validation.valid) return;
cart.x = nextX;
cart.z = nextZ;
cart.group.position.set(nextX, 0, nextZ);
dragState.moved = true;
updateAnalysis();
}
pointerState.lastX = event.clientX;
pointerState.lastY = event.clientY;
});
canvas.addEventListener("pointerup", (event) => {
if (event.button === 0 && pointerState?.potentialPlacement && !pointerState.moved) {
setPointer(event);
const hitCart = cartUnderPointer();
if (hitCart) {
selectCart(hitCart.id);
showToast("Cart selected. Use Move mode to reposition it.");
} else {
const point = pointOnGround(event);
if (point) {
addCartAt(point.x, point.z);
}
}
}
if (pointerState?.type === "drag" && dragState?.moved) {
scenarioHistory.push(dragState.previousState);
if (scenarioHistory.length > 40) scenarioHistory.shift();
updateHistoryButtons();
}
if (canvas.hasPointerCapture(event.pointerId)) {
canvas.releasePointerCapture(event.pointerId);
}
pointerState = null;
dragState = null;
canvas.style.cursor = mode === "place" ? "crosshair" : "grab";
});
canvas.addEventListener("pointercancel", () => {
pointerState = null;
dragState = null;
canvas.style.cursor = mode === "place" ? "crosshair" : "grab";
});
canvas.addEventListener(
"wheel",
(event) => {
event.preventDefault();
cameraState.zoom = THREE.MathUtils.clamp(
cameraState.zoom * Math.exp(-event.deltaY * 0.001),
0.62,
2.7
);
updateCamera();
},
{ passive: false }
);
// Keyboard shortcuts.
const pressedKeys = new Set();
window.addEventListener("keydown", (event) => {
if (event.target instanceof HTMLInputElement) return;
pressedKeys.add(event.key.toLowerCase());
if (event.key.toLowerCase() === "r") rotateSelected();
if (
event.key === "Delete" ||
event.key === "Backspace"
) {
event.preventDefault();
deleteSelected();
}
if (event.key === "Escape") {
selectCart(null);
setMode("place");
}
if (event.key.toLowerCase() === "p") {
setMode("place");
}
});
window.addEventListener("keyup", (event) => {
pressedKeys.delete(event.key.toLowerCase());
});
function updateKeyboardCamera() {
const speed = 0.035 / cameraState.zoom;
let dx = 0;
let dy = 0;
if (pressedKeys.has("arrowleft") || pressedKeys.has("a")) dx -= speed;
if (pressedKeys.has("arrowright") || pressedKeys.has("d")) dx += speed;
if (pressedKeys.has("arrowup") || pressedKeys.has("w")) dy -= speed;
if (pressedKeys.has("arrowdown") || pressedKeys.has("s")) dy += speed;
if (dx || dy) panCamera(dx * 60, dy * 60);
}
// ---------------------------------------------------------------------
// Screen-space labels
// ---------------------------------------------------------------------
const projected = new THREE.Vector3();
function placeLabel(element, worldPosition, visible = true) {
if (!visible || labelsLayer.classList.contains("hidden")) {
element.style.display = "none";
return;
}
projected.copy(worldPosition).project(camera);
const inFront = projected.z > -1 && projected.z < 1;
const x = (projected.x * 0.5 + 0.5) * window.innerWidth;
const y = (-projected.y * 0.5 + 0.5) * window.innerHeight;
const onScreen =
x > -50 &&
x < window.innerWidth + 50 &&
y > -30 &&
y < window.innerHeight + 30;
if (!inFront || !onScreen) {
element.style.display = "none";
return;
}
element.style.display = "block";
element.style.left = `${x}px`;
element.style.top = `${y}px`;
}
const labelPosition = new THREE.Vector3();
function updateLabels() {
for (const door of doorRecords) {
labelPosition.set(door.x, 1.8, -6.05);
placeLabel(door.label, labelPosition);
}
for (const link of linkRecords) {
labelPosition.set(link.x, 0.62, -2.42);
placeLabel(link.label, labelPosition, link.blocked);
}
labelPosition.set(
(COLUMN_X[0] + COLUMN_X[1]) / 2,
0.55,
-0.72
);
placeLabel(dimensionLabel, labelPosition);
const cart = selectedCart();
if (cart) {
selectionLabel.textContent =
`C${String(cart.id).padStart(2, "0")} · ${CART_SIZES[cart.size].label} CART`;
labelPosition.set(
cart.x,
CART_SIZES[cart.size].height + 0.55,
cart.z
);
placeLabel(selectionLabel, labelPosition);
} else {
selectionLabel.style.display = "none";
}
}
// ---------------------------------------------------------------------
// Animation
// ---------------------------------------------------------------------
const clock = new THREE.Clock();
function animate() {
requestAnimationFrame(animate);
const elapsed = clock.getElapsedTime();
updateKeyboardCamera();
for (const door of doorRecords) {
if (door.blocked) {
door.frame.material.opacity =
0.62 + Math.sin(elapsed * 4 + door.id * 0.7) * 0.25;
}
}
updateLabels();
renderer.render(scene, camera);
}
setMode("place");
setAnalysisVisible(true);
setLabelsVisible(true);
updateAnalysis();
updateHistoryButtons();
animate();
</script>
</body>
</html>
```