Prompt specification
Build or customize the Three.js 3D scene "Compare sidewalk layouts before and after temporary setup" 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: Compare sidewalk layouts before and after temporary setup
Category: Voxel Worlds · Style: Voxel 3D
License: MIT · Reference: https://three3d.app/scene/compare-sidewalk-layouts-before-and-after-temporary-se-x2980
Scene Description Prompt:
Create a single self-contained HTML file using Three.js from cdnjs that shows Hanoi's Old Quarter. Let users place fictional tables and parked bicycles along a street segment. Highlight route continuity and entrance access while keeping permanent building geometry fixed. Voxel style.
Working Three.js Starter (compare-sidewalk-layouts-before-and-after-temporary-se-x2980):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Hanoi Old Quarter — Street Planning Sandbox</title>
<style>
:root {
--ink: #26352f;
--muted: #6f7d73;
--paper: rgba(255, 253, 246, 0.93);
--line: rgba(49, 72, 59, 0.15);
--green: #238b68;
--green-soft: #dff3e7;
--amber: #c57c24;
--amber-soft: #fff0d7;
--red: #c94f50;
--red-soft: #ffe3df;
--shadow: 0 12px 36px rgba(50, 68, 56, 0.16);
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: #d9e2cf;
color: var(--ink);
font-family:
Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
button {
font: inherit;
}
#stage,
#stage canvas {
position: absolute;
inset: 0;
width: 100%;
height: 100%;
}
#stage canvas {
display: block;
touch-action: none;
cursor: crosshair;
outline: none;
}
.hud {
position: absolute;
inset: 0;
pointer-events: none;
z-index: 2;
}
.panel {
pointer-events: auto;
background: var(--paper);
border: 1px solid rgba(255, 255, 255, 0.8);
box-shadow: var(--shadow);
backdrop-filter: blur(12px);
-webkit-backdrop-filter: blur(12px);
}
.brand {
position: absolute;
top: 20px;
left: 20px;
width: 330px;
padding: 17px 18px 15px;
border-radius: 18px;
}
.eyebrow {
display: flex;
align-items: center;
gap: 8px;
color: var(--green);
font-size: 10px;
font-weight: 800;
letter-spacing: 0.18em;
text-transform: uppercase;
}
.eyebrow::before {
content: "";
width: 8px;
height: 8px;
border-radius: 2px;
background: var(--green);
box-shadow: 4px 4px 0 #e6aa4b;
}
h1 {
margin: 8px 0 3px;
font-size: clamp(23px, 2.2vw, 31px);
line-height: 1;
letter-spacing: -0.04em;
}
.subtitle {
margin: 0;
color: var(--muted);
font-size: 12px;
line-height: 1.5;
}
.status-panel {
position: absolute;
top: 20px;
right: 20px;
width: 286px;
overflow: hidden;
border-radius: 18px;
}
.status-card {
padding: 15px 16px;
}
.status-card + .status-card {
border-top: 1px solid var(--line);
}
.status-heading {
display: flex;
align-items: center;
justify-content: space-between;
gap: 10px;
margin-bottom: 8px;
}
.status-label {
color: var(--muted);
font-size: 10px;
font-weight: 800;
letter-spacing: 0.14em;
text-transform: uppercase;
}
.status-badge {
display: inline-flex;
align-items: center;
gap: 6px;
padding: 5px 8px;
border-radius: 999px;
background: var(--green-soft);
color: var(--green);
font-size: 10px;
font-weight: 800;
letter-spacing: 0.05em;
white-space: nowrap;
}
.status-badge::before {
content: "";
width: 6px;
height: 6px;
border-radius: 50%;
background: currentColor;
}
.status-badge[data-state="warning"] {
color: var(--amber);
background: var(--amber-soft);
}
.status-badge[data-state="bad"] {
color: var(--red);
background: var(--red-soft);
}
.status-detail {
margin: 0;
color: var(--muted);
font-size: 12px;
line-height: 1.45;
}
.route-segments {
display: flex;
gap: 4px;
margin-top: 11px;
}
.route-segments span {
flex: 1;
height: 5px;
border-radius: 3px;
background: var(--green);
transition: background 160ms ease;
}
.route-segments span.blocked {
background: var(--red);
}
.locked-note {
display: flex;
align-items: center;
gap: 8px;
margin-top: 10px;
padding-top: 10px;
border-top: 1px solid var(--line);
color: var(--muted);
font-size: 10px;
}
.locked-note strong {
color: var(--ink);
}
.lock-icon {
display: grid;
place-items: center;
width: 19px;
height: 19px;
border-radius: 6px;
background: #e9eee6;
color: var(--green);
font-size: 11px;
}
.help {
position: absolute;
left: 20px;
bottom: 20px;
width: 285px;
padding: 14px 16px;
border-radius: 16px;
}
.help-title {
margin-bottom: 8px;
font-size: 11px;
font-weight: 800;
letter-spacing: 0.1em;
text-transform: uppercase;
}
.help-row {
display: flex;
justify-content: space-between;
gap: 12px;
margin-top: 6px;
color: var(--muted);
font-size: 11px;
}
.help-row span:last-child {
color: var(--ink);
font-weight: 650;
text-align: right;
}
.toolbar {
position: absolute;
left: 50%;
bottom: 20px;
display: flex;
align-items: center;
gap: 7px;
padding: 8px;
border-radius: 17px;
transform: translateX(-50%);
white-space: nowrap;
}
.tool-group {
display: flex;
align-items: center;
gap: 5px;
}
.tool-divider {
width: 1px;
height: 27px;
margin: 0 2px;
background: var(--line);
}
.tool {
min-height: 37px;
padding: 0 11px;
border: 1px solid transparent;
border-radius: 10px;
background: transparent;
color: var(--ink);
cursor: pointer;
font-size: 11px;
font-weight: 700;
transition:
background 140ms ease,
border-color 140ms ease,
transform 140ms ease;
}
.tool:hover:not(:disabled) {
background: #eef2e9;
transform: translateY(-1px);
}
.tool.active {
border-color: rgba(35, 139, 104, 0.22);
background: var(--green-soft);
color: var(--green);
}
.tool:disabled {
opacity: 0.35;
cursor: not-allowed;
}
.tool.danger:hover:not(:disabled) {
background: var(--red-soft);
color: var(--red);
}
.tool .key {
margin-left: 4px;
opacity: 0.55;
font-size: 9px;
}
#selectionStatus {
min-width: 94px;
padding: 0 5px;
color: var(--muted);
font-size: 10px;
text-align: center;
}
#placementTip {
position: absolute;
z-index: 4;
display: none;
max-width: 230px;
padding: 8px 10px;
border-radius: 9px;
background: rgba(37, 52, 45, 0.92);
color: white;
box-shadow: 0 8px 25px rgba(30, 45, 37, 0.2);
font-size: 10px;
font-weight: 650;
line-height: 1.4;
pointer-events: none;
}
#placementTip[data-state="warning"] {
background: rgba(156, 96, 22, 0.94);
}
#placementTip[data-state="invalid"] {
background: rgba(171, 57, 57, 0.94);
}
#toast {
position: absolute;
left: 50%;
top: 22px;
max-width: min(420px, 90vw);
padding: 11px 15px;
border-radius: 12px;
background: rgba(37, 52, 45, 0.92);
color: white;
box-shadow: var(--shadow);
font-size: 12px;
opacity: 0;
transform: translate(-50%, -12px);
transition:
opacity 180ms ease,
transform 180ms ease;
pointer-events: none;
}
#toast.visible {
opacity: 1;
transform: translate(-50%, 0);
}
.legend {
position: absolute;
right: 22px;
bottom: 22px;
display: flex;
gap: 12px;
padding: 9px 12px;
border-radius: 12px;
color: var(--muted);
font-size: 10px;
}
.legend-item {
display: flex;
align-items: center;
gap: 6px;
}
.legend-dot {
width: 8px;
height: 8px;
border-radius: 2px;
background: var(--green);
}
.legend-dot.blocked {
background: var(--red);
}
.legend-dot.access {
border: 2px solid var(--amber);
background: transparent;
}
@media (max-width: 1050px) {
.help {
display: none;
}
.legend {
display: none;
}
}
@media (max-width: 720px) {
.brand {
top: 12px;
left: 12px;
width: 245px;
padding: 13px 14px;
}
.brand .subtitle {
display: none;
}
.status-panel {
top: 12px;
right: 12px;
width: 188px;
}
.status-card {
padding: 11px 12px;
}
.locked-note,
.route-segments {
display: none;
}
.toolbar {
right: 10px;
bottom: 10px;
left: 10px;
justify-content: center;
flex-wrap: wrap;
transform: none;
}
.tool {
padding: 0 9px;
}
.tool .key,
#selectionStatus {
display: none;
}
.tool-divider {
display: none;
}
}
</style>
</head>
<body>
<div id="stage" aria-label="Interactive 3D model of Hanoi's Old Quarter"></div>
<div class="hud">
<section class="panel brand">
<div class="eyebrow">Fictional streetscape</div>
<h1>Hà Nội Old Quarter</h1>
<p class="subtitle">
Place café tables and parked bicycles along a fixed shophouse street.
</p>
</section>
<aside class="panel status-panel" aria-live="polite">
<section class="status-card">
<div class="status-heading">
<span class="status-label">Route continuity</span>
<span id="routeBadge" class="status-badge">CONTINUOUS</span>
</div>
<p id="routeDetail" class="status-detail">Checking route links…</p>
<div id="routeSegments" class="route-segments"></div>
</section>
<section class="status-card">
<div class="status-heading">
<span class="status-label">Entrance access</span>
<span id="accessBadge" class="status-badge">OPEN</span>
</div>
<p id="accessDetail" class="status-detail">Checking entrances…</p>
<div class="locked-note">
<span class="lock-icon">▣</span>
<span><strong>Permanent buildings locked.</strong> Props cannot overlap them.</span>
</div>
</section>
</aside>
<section class="panel help">
<div class="help-title">Street controls</div>
<div class="help-row">
<span>Place / select</span><span>Click street or prop</span>
</div>
<div class="help-row">
<span>Orbit camera</span><span>Drag</span>
</div>
<div class="help-row">
<span>Pan camera</span><span>Right-drag / Shift-drag</span>
</div>
<div class="help-row">
<span>Zoom</span><span>Mouse wheel / pinch</span>
</div>
<div class="help-row">
<span>Rotate placement</span><span>R</span>
</div>
</section>
<nav class="panel toolbar" aria-label="Street object tools">
<div class="tool-group">
<button id="tableTool" class="tool active" aria-pressed="true">
Table <span class="key">T</span>
</button>
<button id="bikeTool" class="tool" aria-pressed="false">
Bicycle <span class="key">B</span>
</button>
</div>
<div class="tool-divider"></div>
<button id="rotateTool" class="tool" title="Rotate the next placement">
Rotate <span id="rotationLabel" class="key">0°</span>
</button>
<button id="removeTool" class="tool danger" disabled title="Delete selected object">
Remove <span class="key">Del</span>
</button>
<button id="undoTool" class="tool" disabled title="Undo last change">
Undo <span class="key">⌘Z</span>
</button>
<button id="clearTool" class="tool danger" disabled title="Remove all placed objects">
Clear
</button>
<div class="tool-divider"></div>
<button id="overlayTool" class="tool active" aria-pressed="true">
Overlays
</button>
<button id="cameraTool" class="tool" title="Reset camera">
View
</button>
<div id="selectionStatus">No object selected</div>
</nav>
<div class="panel legend">
<span class="legend-item"><i class="legend-dot"></i>Clear route</span>
<span class="legend-item"><i class="legend-dot blocked"></i>Blocked</span>
<span class="legend-item"><i class="legend-dot access"></i>Entrance</span>
</div>
</div>
<div id="placementTip"></div>
<div id="toast" role="status"></div>
<script type="module">
import * as THREE from "https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
// ------------------------------------------------------------
// Renderer, scene and camera
// ------------------------------------------------------------
const stage = document.querySelector("#stage");
const scene = new THREE.Scene();
scene.background = new THREE.Color("#d9e2cf");
scene.fog = new THREE.Fog("#d9e2cf", 67, 112);
const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.08;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
stage.appendChild(renderer.domElement);
const camera = new THREE.PerspectiveCamera(
38,
window.innerWidth / window.innerHeight,
0.1,
180
);
const cameraState = {
target: new THREE.Vector3(0, 1, 0),
yaw: 0.66,
pitch: 0.75,
radius: 49
};
function updateCamera() {
const { target, yaw, pitch, radius } = cameraState;
camera.position.set(
target.x + radius * Math.cos(pitch) * Math.sin(yaw),
target.y + radius * Math.sin(pitch),
target.z + radius * Math.cos(pitch) * Math.cos(yaw)
);
camera.lookAt(target);
}
function resetCamera() {
cameraState.target.set(0, 1, 0);
cameraState.yaw = 0.66;
cameraState.pitch = 0.75;
cameraState.radius = 49;
updateCamera();
}
updateCamera();
const hemisphere = new THREE.HemisphereLight("#fff4d8", "#6f806e", 2.15);
scene.add(hemisphere);
const sun = new THREE.DirectionalLight("#ffe2aa", 3.1);
sun.position.set(-22, 38, 24);
sun.castShadow = true;
sun.shadow.mapSize.set(2048, 2048);
sun.shadow.camera.left = -30;
sun.shadow.camera.right = 30;
sun.shadow.camera.top = 32;
sun.shadow.camera.bottom = -32;
sun.shadow.camera.near = 1;
sun.shadow.camera.far = 90;
sun.shadow.bias = -0.00025;
scene.add(sun);
const fill = new THREE.DirectionalLight("#b9d7df", 0.7);
fill.position.set(24, 15, -18);
scene.add(fill);
// ------------------------------------------------------------
// Shared helpers and voxel materials
// ------------------------------------------------------------
const materialCache = new Map();
function solidMaterial(color) {
if (!materialCache.has(color)) {
materialCache.set(
color,
new THREE.MeshStandardMaterial({
color,
roughness: 0.86,
metalness: 0.02
})
);
}
return materialCache.get(color);
}
function makeBox(parent, width, height, depth, color, x = 0, y = 0, z = 0) {
const mesh = new THREE.Mesh(
new THREE.BoxGeometry(width, height, depth),
solidMaterial(color)
);
mesh.position.set(x, y, z);
mesh.castShadow = true;
mesh.receiveShadow = true;
parent.add(mesh);
return mesh;
}
const zAxis = new THREE.Vector3(0, 0, 1);
function boxBetween(parent, a, b, thickness, color) {
const start = new THREE.Vector3(...a);
const end = new THREE.Vector3(...b);
const direction = end.clone().sub(start);
const length = direction.length();
const mesh = new THREE.Mesh(
new THREE.BoxGeometry(thickness, thickness, length),
solidMaterial(color)
);
mesh.position.copy(start).add(end).multiplyScalar(0.5);
mesh.quaternion.setFromUnitVectors(zAxis, direction.normalize());
mesh.castShadow = true;
mesh.receiveShadow = true;
parent.add(mesh);
return mesh;
}
function makeSignTexture(text, background = "#a84435", foreground = "#fff2cf") {
const canvas = document.createElement("canvas");
canvas.width = 512;
canvas.height = 128;
const context = canvas.getContext("2d");
context.fillStyle = background;
context.fillRect(0, 0, canvas.width, canvas.height);
context.strokeStyle = "rgba(255,240,204,0.55)";
context.lineWidth = 7;
context.strokeRect(9, 9, canvas.width - 18, canvas.height - 18);
context.fillStyle = foreground;
context.font = "700 58px sans-serif";
context.textAlign = "center";
context.textBaseline = "middle";
context.fillText(text, canvas.width / 2, canvas.height / 2 + 3);
const texture = new THREE.CanvasTexture(canvas);
texture.colorSpace = THREE.SRGBColorSpace;
texture.anisotropy = Math.min(4, renderer.capabilities.getMaxAnisotropy());
return texture;
}
function addFacadeSign(side, z, text, color) {
const backing = makeBox(
scene,
0.12,
0.67,
2.15,
color,
side * 5.70,
2.08,
z
);
backing.castShadow = true;
const sign = new THREE.Mesh(
new THREE.PlaneGeometry(2.0, 0.5),
new THREE.MeshBasicMaterial({
map: makeSignTexture(text, color),
transparent: true,
side: THREE.DoubleSide
})
);
sign.position.set(side * 5.625, 2.08, z);
sign.rotation.y = side > 0 ? -Math.PI / 2 : Math.PI / 2;
scene.add(sign);
}
// ------------------------------------------------------------
// Data and geometry state
// ------------------------------------------------------------
const props = [];
const fixedBoxes = [];
const entrances = [];
const routeSegments = [];
const routeGroup = new THREE.Group();
const accessGroup = new THREE.Group();
scene.add(routeGroup, accessGroup);
let groundMesh;
let nextPropId = 1;
let selectedId = null;
let selectedType = "table";
let placementRotation = 0;
let selectionBox = null;
let overlaysVisible = true;
let toastTimer = 0;
const history = [];
const routePoints = [
{ x: -0.15, z: -18.2 },
{ x: 0.12, z: -12.0 },
{ x: 0.38, z: -6.0 },
{ x: -0.34, z: 0.0 },
{ x: 0.25, z: 6.0 },
{ x: -0.15, z: 12.0 },
{ x: 0.18, z: 18.2 }
];
const routeHalfWidth = 0.78;
// ------------------------------------------------------------
// Polygon/AABB helpers used by placement and route checks
// ------------------------------------------------------------
function rectanglePolygon(minX, maxX, minZ, maxZ) {
return [
{ x: minX, z: minZ },
{ x: maxX, z: minZ },
{ x: maxX, z: maxZ },
{ x: minX, z: maxZ }
];
}
function propBounds(x, z, type, rotation = 0) {
let halfX = type === "table" ? 0.68 : 0.38;
let halfZ = type === "table" ? 0.51 : 0.91;
if (Math.abs(Math.sin(rotation)) > 0.5) {
[halfX, halfZ] = [halfZ, halfX];
}
return {
minX: x - halfX,
maxX: x + halfX,
minZ: z - halfZ,
maxZ: z + halfZ,
halfX,
halfZ
};
}
function boundsPolygon(bounds) {
return rectanglePolygon(
bounds.minX,
bounds.maxX,
bounds.minZ,
bounds.maxZ
);
}
function polygonsOverlap(polyA, polyB) {
const axes = [];
for (const polygon of [polyA, polyB]) {
for (let i = 0; i < polygon.length; i++) {
const a = polygon[i];
const b = polygon[(i + 1) % polygon.length];
const axis = {
x: -(b.z - a.z),
z: b.x - a.x
};
const length = Math.hypot(axis.x, axis.z);
if (length > 0.00001) {
axes.push({ x: axis.x / length, z: axis.z / length });
}
}
}
for (const axis of axes) {
let minA = Infinity;
let maxA = -Infinity;
let minB = Infinity;
let maxB = -Infinity;
for (const point of polyA) {
const projection = point.x * axis.x + point.z * axis.z;
minA = Math.min(minA, projection);
maxA = Math.max(maxA, projection);
}
for (const point of polyB) {
const projection = point.x * axis.x + point.z * axis.z;
minB = Math.min(minB, projection);
maxB = Math.max(maxB, projection);
}
if (maxA < minB - 0.001 || maxB < minA - 0.001) {
return false;
}
}
return true;
}
function segmentCorridorPolygon(a, b, halfWidth = routeHalfWidth) {
const dx = b.x - a.x;
const dz = b.z - a.z;
const length = Math.hypot(dx, dz) || 1;
const px = (-dz / length) * halfWidth;
const pz = (dx / length) * halfWidth;
return [
{ x: a.x + px, z: a.z + pz },
{ x: a.x - px, z: a.z - pz },
{ x: b.x - px, z: b.z - pz },
{ x: b.x + px, z: b.z + pz }
];
}
// ------------------------------------------------------------
// Old Quarter environment
// ------------------------------------------------------------
function buildEnvironment() {
const ground = new THREE.Mesh(
new THREE.PlaneGeometry(180, 180),
new THREE.MeshStandardMaterial({
color: "#cbd6bd",
roughness: 1
})
);
ground.rotation.x = -Math.PI / 2;
ground.position.y = -0.88;
ground.receiveShadow = true;
scene.add(ground);
makeBox(scene, 15.7, 0.8, 39.7, "#a98f69", 0, -0.45, 0);
groundMesh = makeBox(
scene,
11.3,
0.14,
38.2,
"#77817c",
0,
0,
0
);
groundMesh.castShadow = false;
makeBox(scene, 1.45, 0.22, 38.2, "#c8bfa8", -5.18, 0.11, 0);
makeBox(scene, 1.45, 0.22, 38.2, "#c8bfa8", 5.18, 0.11, 0);
makeBox(scene, 11.5, 0.12, 0.28, "#ddd4bb", 0, 0.12, -19.05);
makeBox(scene, 11.5, 0.12, 0.28, "#ddd4bb", 0, 0.12, 19.05);
for (let z = -16.5; z <= 16.5; z += 3.1) {
makeBox(scene, 0.08, 0.025, 1.15, "#d8d5bd", 0, 0.085, z);
}
// Drain strips and curb blocks provide additional voxel detail.
for (const side of [-1, 1]) {
for (let z = -18; z <= 18; z += 1.5) {
makeBox(
scene,
0.09,
0.04,
0.72,
"#a99f89",
side * 4.52,
0.23,
z
);
}
}
const buildingZ = [-14.3, -7.15, 0, 7.15, 14.3];
const wallColors = [
"#dba94f",
"#d3b05f",
"#c98d48",
"#dfb768",
"#c9a45d",
"#d49a55"
];
const signNames = [
"PHỞ",
"CÀ PHÊ",
"BÚN CHẢ",
"MỲ",
"TRÀ",
"HOA",
"BIA",
"NHÀ CỔ"
];
let entranceNumber = 1;
let signNumber = 0;
for (const side of [-1, 1]) {
buildingZ.forEach((z, buildingIndex) => {
const height = 4.8 + ((buildingIndex * 3 + (side > 0 ? 2 : 0)) % 4) * 0.62;
const color = wallColors[(buildingIndex + (side > 0 ? 3 : 0)) % wallColors.length];
const building = new THREE.Group();
scene.add(building);
makeBox(building, 5.4, height, 6.4, color, side * 8.55, height / 2, z);
makeBox(building, 5.72, 0.22, 6.7, "#e6c47e", side * 8.55, height + 0.08, z);
makeBox(building, 4.95, 0.32, 5.75, "#9e5d3e", side * 8.55, height + 0.32, z);
// Facade pilasters.
for (const offset of [-2.82, 2.82]) {
makeBox(
building,
0.12,
height - 0.18,
0.16,
"#e9c87f",
side * 5.81,
height / 2,
z + offset
);
}
// Ground floor door.
makeBox(building, 0.15, 1.8, 1.03, "#354d46", side * 5.77, 0.91, z);
makeBox(building, 0.16, 1.86, 0.11, "#e3c170", side * 5.70, 0.92, z - 0.52);
makeBox(building, 0.16, 1.86, 0.11, "#e3c170", side * 5.70, 0.92, z + 0.52);
// Small awning.
makeBox(building, 1.15, 0.12, 1.55, side > 0 ? "#8d493a" : "#4f7669", side * 5.22, 1.93, z);
for (const dz of [-0.65, 0.65]) {
makeBox(
building,
0.09,
0.5,
0.09,
"#5b493d",
side * 4.77,
2.18,
z + dz
);
}
const signColor = ["#a94436", "#376d62", "#b3782f"][signNumber % 3];
addFacadeSign(side, z, signNames[signNumber % signNames.length], signColor);
signNumber++;
// Upper windows with chunky shutters.
const floors = height > 5.5 ? 2 : 1;
for (let floor = 0; floor < floors; floor++) {
const windowY = 3.35 + floor * 1.78;
for (const dz of [-1.72, 1.72]) {
makeBox(
building,
0.12,
0.95,
1.18,
"#405a57",
side * 5.77,
windowY,
z + dz
);
makeBox(
building,
0.15,
0.09,
1.3,
"#ead08d",
side * 5.72,
windowY + 0.52,
z + dz
);
makeBox(
building,
0.15,
0.09,
1.3,
"#ead08d",
side * 5.72,
windowY - 0.52,
z + dz
);
makeBox(
building,
0.15,
0.9,
0.08,
"#426b62",
side * 5.71,
windowY,
z + dz + 0.64
);
}
if (floor === 0) {
// Projecting balcony.
makeBox(building, 1.05, 0.13, 2.2, "#e1bf72", side * 5.3, 2.68, z);
makeBox(building, 0.08, 0.5, 2.18, "#4f6c61", side * 4.82, 2.97, z);
for (let rail = -0.9; rail <= 0.9; rail += 0.3) {
makeBox(
building,
0.07,
0.48,
0.07,
"#e3c27a",
side * 4.82,
2.96,
z + rail
);
}
}
}
// Rooftop details.
makeBox(building, 0.48, 0.95, 0.48, "#ded0b4", side * 8.5, height + 0.86, z - 1.7);
makeBox(building, 0.58, 0.13, 0.58, "#6f786e", side * 8.5, height + 1.37, z - 1.7);
makeBox(building, 0.25, 0.7, 0.25, "#8d604a", side * 9.45, height + 0.67, z + 1.7);
// Air conditioner boxes.
makeBox(building, 0.32, 0.52, 0.72, "#c3c5b9", side * 5.63, 4.65, z + 2.55);
fixedBoxes.push({
minX: side > 0 ? 5.85 : -11.25,
maxX: side > 0 ? 11.25 : -5.85,
minZ: z - 3.2,
maxZ: z + 3.2,
kind: "building"
});
const minX = side > 0 ? 3.68 : -5.80;
const maxX = side > 0 ? 5.80 : -3.68;
entrances.push({
id: `A${entranceNumber++}`,
side,
z,
minX,
maxX,
minZ: z - 0.82,
maxZ: z + 0.82,
group: null,
markerMaterials: []
});
});
}
// Fixed planters and small voxel trees.
for (const side of [-1, 1]) {
for (const z of [-16.7, -3.2, 10.5]) {
const x = side * 4.78;
makeBox(scene, 0.72, 0.48, 0.72, "#9c7557", x, 0.42, z);
makeBox(scene, 0.16, 1.15, 0.16, "#75523e", x, 1.12, z);
makeBox(scene, 0.76, 0.72, 0.76, "#5f8255", x, 1.85, z);
makeBox(scene, 0.56, 0.56, 0.58, "#78985f", x + 0.15, 2.35, z - 0.1);
fixedBoxes.push({
minX: x - 0.4,
maxX: x + 0.4,
minZ: z - 0.4,
maxZ: z + 0.4,
kind: "planter"
});
}
}
// Street lamps.
for (const side of [-1, 1]) {
for (const z of [-11.3, 3.7, 16.2]) {
const x = side * 4.28;
makeBox(scene, 0.1, 2.65, 0.1, "#45544d", x, 1.55, z);
makeBox(scene, 0.42, 0.12, 0.42, "#3d4c46", x, 2.86, z);
makeBox(scene, 0.26, 0.34, 0.26, "#f5d48e", x, 2.65, z);
makeBox(scene, 0.5, 0.08, 0.5, "#3d4c46", x, 2.43, z);
fixedBoxes.push({
minX: x - 0.16,
maxX: x + 0.16,
minZ: z - 0.16,
maxZ: z + 0.16,
kind: "lamp"
});
}
}
// A few blocky residents.
const people = [
[-4.6, -8.3, "#b94f43"],
[4.6, 6.1, "#3e7368"],
[-4.5, 12.8, "#cf8f35"]
];
for (const [x, z, shirt] of people) {
makeBox(scene, 0.34, 0.5, 0.25, shirt, x, 1.0, z);
makeBox(scene, 0.26, 0.27, 0.25, "#d7a77c", x, 1.4, z);
makeBox(scene, 0.12, 0.5, 0.13, "#39433e", x - 0.1, 0.48, z);
makeBox(scene, 0.12, 0.5, 0.13, "#39433e", x + 0.1, 0.48, z);
}
// Overhead utility cables.
for (const z of [-12.5, -0.8, 11.2]) {
const curve = new THREE.CatmullRomCurve3([
new THREE.Vector3(-8.2, 6.4, z),
new THREE.Vector3(-3.5, 5.0, z + 0.15),
new THREE.Vector3(2.0, 4.8, z - 0.1),
new THREE.Vector3(8.0, 5.9, z)
]);
const cable = new THREE.Mesh(
new THREE.TubeGeometry(curve, 24, 0.025, 4, false),
solidMaterial("#39423e")
);
scene.add(cable);
}
// Old Quarter gate at the far end.
makeBox(scene, 0.7, 4.2, 0.7, "#a84737", -3.25, 2.05, -19.2);
makeBox(scene, 0.7, 4.2, 0.7, "#a84737", 3.25, 2.05, -19.2);
makeBox(scene, 7.6, 0.65, 0.9, "#a84737", 0, 3.93, -19.2);
makeBox(scene, 8.5, 0.25, 1.15, "#dfb56c", 0, 4.37, -19.2);
makeBox(scene, 7.2, 0.22, 0.9, "#7d3d32", 0, 4.58, -19.2);
const gateSign = new THREE.Mesh(
new THREE.PlaneGeometry(2.8, 0.65),
new THREE.MeshBasicMaterial({
map: makeSignTexture("PHỐ CỔ", "#8f3f34"),
side: THREE.DoubleSide
})
);
gateSign.position.set(0, 3.92, -18.72);
scene.add(gateSign);
}
// ------------------------------------------------------------
// Route and entrance overlays
// ------------------------------------------------------------
function buildRouteOverlay() {
for (let i = 0; i < routePoints.length - 1; i++) {
const a = routePoints[i];
const b = routePoints[i + 1];
const dx = b.x - a.x;
const dz = b.z - a.z;
const length = Math.hypot(dx, dz);
const angle = Math.atan2(dx, dz);
const corridorMaterial = new THREE.MeshBasicMaterial({
color: "#46c88f",
transparent: true,
opacity: 0.1,
depthWrite: false
});
const lineMaterial = new THREE.MeshStandardMaterial({
color: "#31bd83",
emissive: "#31bd83",
emissiveIntensity: 0.5,
roughness: 0.62,
transparent: true,
opacity: 0.95
});
const corridor = new THREE.Mesh(
new THREE.BoxGeometry(routeHalfWidth * 2, 0.018, length),
corridorMaterial
);
corridor.position.set((a.x + b.x) / 2, 0.135, (a.z + b.z) / 2);
corridor.rotation.y = angle;
routeGroup.add(corridor);
const line = new THREE.Mesh(
new THREE.BoxGeometry(0.12, 0.035, length),
lineMaterial
);
line.position.set((a.x + b.x) / 2, 0.17, (a.z + b.z) / 2);
line.rotation.y = angle;
routeGroup.add(line);
const arrowMaterial = new THREE.MeshStandardMaterial({
color: "#31bd83",
emissive: "#31bd83",
emissiveIntensity: 0.35,
transparent: true,
opacity: 0.85
});
const arrow = new THREE.Group();
arrow.position.set((a.x + b.x) / 2, 0.205, (a.z + b.z) / 2);
arrow.rotation.y = angle;
const shaft = new THREE.Mesh(
new THREE.BoxGeometry(0.07, 0.025, 0.4),
arrowMaterial
);
shaft.position.z = -0.08;
arrow.add(shaft);
const headLeft = new THREE.Mesh(
new THREE.BoxGeometry(0.06, 0.025, 0.28),
arrowMaterial
);
headLeft.position.set(-0.09, 0, 0.12);
headLeft.rotation.y = -0.72;
arrow.add(headLeft);
const headRight = headLeft.clone();
headRight.position.x = 0.09;
headRight.rotation.y = 0.72;
arrow.add(headRight);
routeGroup.add(arrow);
routeSegments.push({
a,
b,
corridor,
line,
arrow,
corridorMaterial,
lineMaterial,
arrowMaterial,
corridorPolygon: segmentCorridorPolygon(a, b),
blocked: false
});
}
const startMarker = new THREE.Mesh(
new THREE.CylinderGeometry(0.33, 0.33, 0.045, 12),
new THREE.MeshStandardMaterial({
color: "#31bd83",
emissive: "#31bd83",
emissiveIntensity: 0.4
})
);
startMarker.position.set(routePoints[0].x, 0.19, routePoints[0].z);
routeGroup.add(startMarker);
const endMarker = startMarker.clone();
endMarker.position.set(
routePoints[routePoints.length - 1].x,
0.19,
routePoints[routePoints.length - 1].z
);
routeGroup.add(endMarker);
}
function buildAccessOverlay() {
for (const entrance of entrances) {
const group = new THREE.Group();
entrance.group = group;
accessGroup.add(group);
const material = new THREE.MeshStandardMaterial({
color: "#32b77d",
emissive: "#32b77d",
emissiveIntensity: 0.38,
transparent: true,
opacity: 0.9
});
entrance.markerMaterials.push(material);
const width = entrance.maxX - entrance.minX;
const depth = entrance.maxZ - entrance.minZ;
const centerX = (entrance.minX + entrance.maxX) / 2;
const centerZ = (entrance.minZ + entrance.maxZ) / 2;
makeBox(group, width, 0.035, 0.075, material, centerX, 0.235, entrance.minZ);
makeBox(group, width, 0.035, 0.075, material, centerX, 0.235, entrance.maxZ);
makeBox(group, 0.075, 0.035, depth, material, entrance.minX, 0.235, centerZ);
makeBox(group, 0.075, 0.035, depth, material, entrance.maxX, 0.235, centerZ);
// A small doorway threshold marker.
makeBox(
group,
0.12,
0.04,
0.85,
material,
entrance.side * 5.72,
0.225,
entrance.z
);
}
}
function updateOverlays() {
let blockedSegments = 0;
for (const segment of routeSegments) {
segment.blocked = false;
for (const prop of props) {
const polygon = boundsPolygon(
propBounds(prop.x, prop.z, prop.type, prop.rotation)
);
if (polygonsOverlap(polygon, segment.corridorPolygon)) {
segment.blocked = true;
break;
}
}
const color = segment.blocked ? "#e25b58" : "#31bd83";
segment.lineMaterial.color.set(color);
segment.lineMaterial.emissive.set(color);
segment.arrowMaterial.color.set(color);
segment.arrowMaterial.emissive.set(color);
segment.corridorMaterial.color.set(color);
segment.corridorMaterial.opacity = segment.blocked ? 0.18 : 0.1;
segment.arrow.visible = !segment.blocked;
if (segment.blocked) blockedSegments++;
}
let blockedEntrances = 0;
for (const entrance of entrances) {
const zonePolygon = rectanglePolygon(
entrance.minX,
entrance.maxX,
entrance.minZ,
entrance.maxZ
);
const blocked = props.some((prop) =>
polygonsOverlap(
boundsPolygon(propBounds(prop.x, prop.z, prop.type, prop.rotation)),
zonePolygon
)
);
const color = blocked ? "#e25b58" : "#32b77d";
for (const material of entrance.markerMaterials) {
material.color.set(color);
material.emissive.set(color);
material.opacity = blocked ? 1 : 0.9;
}
if (blocked) blockedEntrances++;
}
const routeBadge = document.querySelector("#routeBadge");
const routeDetail = document.querySelector("#routeDetail");
const routeSegmentsElement = document.querySelector("#routeSegments");
if (blockedSegments > 0) {
routeBadge.textContent = "INTERRUPTED";
routeBadge.dataset.state = "bad";
routeDetail.textContent =
`${blockedSegments} of ${routeSegments.length} route links obstructed by placed objects.`;
} else {
routeBadge.textContent = "CONTINUOUS";
routeBadge.dataset.state = "";
routeDetail.textContent =
`All ${routeSegments.length} links remain open. The marked walking route stays clear.`;
}
routeSegmentsElement.innerHTML = routeSegments
.map(
(segment) =>
`<span class="${segment.blocked ? "blocked" : ""}"></span>`
)
.join("");
const accessBadge = document.querySelector("#accessBadge");
const accessDetail = document.querySelector("#accessDetail");
if (blockedEntrances > 0) {
accessBadge.textContent = "BLOCKED";
accessBadge.dataset.state = "bad";
accessDetail.textContent =
`${blockedEntrances} of ${entrances.length} shophouse entrances are obstructed.`;
} else {
accessBadge.textContent = "OPEN";
accessBadge.dataset.state = "";
accessDetail.textContent =
`All ${entrances.length} shophouse entrances have a clear approach.`;
}
}
// ------------------------------------------------------------
// Fictional prop models
// ------------------------------------------------------------
function createTableModel() {
const group = new THREE.Group();
makeBox(group, 1.25, 0.12, 0.88, "#b66a43", 0, 0.76, 0);
makeBox(group, 1.08, 0.05, 0.73, "#d18b57", 0, 0.84, 0);
for (const x of [-0.48, 0.48]) {
for (const z of [-0.31, 0.31]) {
makeBox(group, 0.11, 0.7, 0.11, "#5f4b3e", x, 0.39, z);
}
}
makeBox(group, 0.9, 0.08, 0.08, "#795742", 0, 0.31, 0);
makeBox(group, 0.25, 0.18, 0.25, "#f1e2bd", 0.18, 0.96, -0.1);
makeBox(group, 0.08, 0.08, 0.08, "#416d61", -0.26, 0.92, 0.13);
return group;
}
function createBicycleModel() {
const group = new THREE.Group();
const frameColor = "#397669";
const tireColor = "#26312e";
const metalColor = "#aeb6aa";
function squareWheel(z) {
const centerY = 0.37;
const radius = 0.34;
makeBox(group, 0.08, 0.07, radius * 2, tireColor, 0, centerY + radius, z);
makeBox(group, 0.08, 0.07, radius * 2, tireColor, 0, centerY - radius, z);
makeBox(group, 0.08, radius * 2, 0.07, tireColor, 0, centerY, z - radius);
makeBox(group, 0.08, radius * 2, 0.07, tireColor, 0, centerY, z + radius);
makeBox(group, 0.055, 0.055, 0.055, metalColor, 0, centerY, z);
}
squareWheel(-0.57);
squareWheel(0.57);
boxBetween(group, [0, 0.37, -0.57], [0, 0.79, -0.17], 0.07, frameColor);
boxBetween(group, [0, 0.79, -0.17], [0, 0.4, 0.02], 0.07, frameColor);
boxBetween(group, [0, 0.4, 0.02], [0, 0.37, -0.57], 0.07, frameColor);
boxBetween(group, [0, 0.4, 0.02], [0, 0.83, 0.43], 0.07, frameColor);
boxBetween(group, [0, 0.83, 0.43], [0, 0.37, 0.57], 0.07, frameColor);
makeBox(group, 0.25, 0.08, 0.34, "#3c3b36", 0, 0.86, -0.2);
makeBox(group, 0.07, 0.42, 0.07, metalColor, 0, 0.96, 0.43);
makeBox(group, 0.52, 0.07, 0.07, metalColor, 0, 1.13, 0.43);
makeBox(group, 0.07, 0.07, 0.22, metalColor, 0, 0.42, 0.02);
makeBox(group, 0.18, 0.11, 0.18, metalColor, 0, 0.42, 0.02);
return group;
}
function createPropModel(type) {
return type === "table" ? createTableModel() : createBicycleModel();
}
function createPropEntry(type, x, z, rotation = 0, id = nextPropId++) {
const group = createPropModel(type);
group.position.set(x, 0.2, z);
group.rotation.y = rotation;
group.userData.propId = id;
scene.add(group);
const prop = { id, type, x, z, rotation, group };
props.push(prop);
return prop;
}
function removePropEntry(prop) {
scene.remove(prop.group);
const index = props.indexOf(prop);
if (index >= 0) props.splice(index, 1);
if (selectedId === prop.id) {
selectedId = null;
updateSelectionBox();
}
}
// ------------------------------------------------------------
// Selection, history and UI state
// ------------------------------------------------------------
function updateSelectionBox() {
if (selectionBox) {
scene.remove(selectionBox);
selectionBox.geometry.dispose();
selectionBox.material.dispose();
selectionBox = null;
}
const selected = props.find((prop) => prop.id === selectedId);
if (selected) {
selectionBox = new THREE.BoxHelper(selected.group, "#f4b63e");
selectionBox.material.depthTest = false;
selectionBox.material.transparent = true;
selectionBox.material.opacity = 0.95;
selectionBox.renderOrder = 10;
scene.add(selectionBox);
}
const status = document.querySelector("#selectionStatus");
const removeButton = document.querySelector("#removeTool");
if (selected) {
status.textContent = `${selected.type === "table" ? "Table" : "Bicycle"} selected`;
removeButton.disabled = false;
} else {
status.textContent = "No object selected";
removeButton.disabled = true;
}
}
function snapshotProps() {
return props.map(({ id, type, x, z, rotation }) => ({
id,
type,
x,
z,
rotation
}));
}
function restoreProps(snapshot) {
for (const prop of props) scene.remove(prop.group);
props.length = 0;
selectedId = null;
for (const data of snapshot) {
createPropEntry(data.type, data.x, data.z, data.rotation, data.id);
}
nextPropId = Math.max(nextPropId, ...snapshot.map((item) => item.id + 1), 1);
updateSelectionBox();
updateOverlays();
updateToolbarState();
}
function commitHistory() {
history.push(snapshotProps());
if (history.length > 40) history.shift();
}
function undo() {
const snapshot = history.pop();
if (!snapshot) return;
restoreProps(snapshot);
showToast("Last change undone.");
}
function updateToolbarState() {
document.querySelector("#undoTool").disabled = history.length === 0;
document.querySelector("#clearTool").disabled = props.length === 0;
}
function selectProp(id) {
selectedId = id;
updateSelectionBox();
}
function removeSelected() {
const selected = props.find((prop) => prop.id === selectedId);
if (!selected) return;
commitHistory();
removePropEntry(selected);
updateOverlays();
updateToolbarState();
showToast("Object removed. Permanent buildings were not changed.");
}
function clearProps() {
if (props.length === 0) return;
commitHistory();
for (const prop of [...props]) removePropEntry(prop);
selectedId = null;
updateSelectionBox();
updateOverlays();
updateToolbarState();
showToast("All fictional props cleared. Buildings and street fixtures remain fixed.");
}
function setSelectedType(type) {
selectedType = type;
document.querySelector("#tableTool").classList.toggle("active", type === "table");
document.querySelector("#bikeTool").classList.toggle("active", type === "bike");
document.querySelector("#tableTool").setAttribute(
"aria-pressed",
String(type === "table")
);
document.querySelector("#bikeTool").setAttribute(
"aria-pressed",
String(type === "bike")
);
}
function rotatePlacement() {
placementRotation = (placementRotation + Math.PI / 2) % (Math.PI * 2);
const degrees = Math.round(
THREE.MathUtils.radToDeg(placementRotation) % 360
);
document.querySelector("#rotationLabel").textContent = `${degrees}°`;
updateGhost();
}
function showToast(message) {
const toast = document.querySelector("#toast");
toast.textContent = message;
toast.classList.add("visible");
clearTimeout(toastTimer);
toastTimer = setTimeout(() => toast.classList.remove("visible"), 2800);
}
// ------------------------------------------------------------
// Placement validation and ghost preview
// ------------------------------------------------------------
function candidateIssues(x, z, type, rotation) {
const bounds = propBounds(x, z, type, rotation);
const polygon = boundsPolygon(bounds);
const invalid = [];
const warnings = [];
if (Math.abs(x) > 5.15 || Math.abs(z) > 18.1) {
invalid.push("Outside the editable street segment");
}
for (const fixed of fixedBoxes) {
if (
polygonsOverlap(
polygon,
rectanglePolygon(fixed.minX, fixed.maxX, fixed.minZ, fixed.maxZ)
)
) {
invalid.push(
fixed.kind === "building"
? "Overlaps a permanent building"
: "Overlaps a fixed street fixture"
);
break;
}
}
for (const prop of props) {
if (
polygonsOverlap(
polygon,
boundsPolygon(propBounds(prop.x, prop.z, prop.type, prop.rotation))
)
) {
invalid.push("Overlaps another placed object");
break;
}
}
for (const segment of routeSegments) {
if (polygonsOverlap(polygon, segment.corridorPolygon)) {
warnings.push("Breaks route continuity");
break;
}
}
for (const entrance of entrances) {
const zone = rectanglePolygon(
entrance.minX,
entrance.maxX,
entrance.minZ,
entrance.maxZ
);
if (polygonsOverlap(polygon, zone)) {
warnings.push(`Blocks entrance ${entrance.id}`);
break;
}
}
return { invalid, warnings };
}
const ghost = createPropModel(selectedType);
ghost.visible = false;
scene.add(ghost);
function restyleGhost(color) {
ghost.traverse((child) => {
if (!child.isMesh) return;
child.material = new THREE.MeshBasicMaterial({
color,
transparent: true,
opacity: 0.48,
depthWrite: false
});
child.castShadow = false;
child.receiveShadow = false;
});
}
function replaceGhostModel() {
scene.remove(ghost);
const replacement = createPropModel(selectedType);
replacement.visible = false;
scene.add(replacement);
Object.assign(ghost, replacement);
// Keep the original group reference stable for future replacement.
ghost.children.splice(0, ghost.children.length, ...replacement.children);
replacement.children.splice(0, replacement.children.length);
replacement.parent = null;
}
function updateGhost() {
const pointer = pointerState;
const tip = document.querySelector("#placementTip");
if (!pointer.inside || !groundMesh) {
ghost.visible = false;
tip.style.display = "none";
return;
}
const point = pointer.worldPoint;
const x = Math.round(point.x * 2) / 2;
const z = Math.round(point.z * 2) / 2;
const issues = candidateIssues(
x,
z,
selectedType,
placementRotation
);
ghost.position.set(x, 0.22, z);
ghost.rotation.y = placementRotation;
ghost.visible = true;
const state = issues.invalid.length
? "invalid"
: issues.warnings.length
? "warning"
: "valid";
const color =
state === "invalid"
? "#e25b58"
: state === "warning"
? "#f1a73d"
: "#43c995";
restyleGhost(color);
const label = selectedType === "table" ? "Table" : "Bicycle";
const message =
issues.invalid.length > 0
? issues.invalid[0]
: issues.warnings.length > 0
? issues.warnings.join(" · ")
: "Clear placement";
tip.textContent = `${label} · ${message}`;
tip.dataset.state = state;
tip.style.display = "block";
tip.style.left = `${Math.min(pointer.x + 16, window.innerWidth - 245)}px`;
tip.style.top = `${Math.min(pointer.y + 18, window.innerHeight - 60)}px`;
}
function placeAt(x, z) {
const issues = candidateIssues(
x,
z,
selectedType,
placementRotation
);
if (issues.invalid.length) {
showToast(issues.invalid[0]);
return false;
}
commitHistory();
const prop = createPropEntry(
selectedType,
x,
z,
placementRotation
);
selectProp(prop.id);
updateOverlays();
updateToolbarState();
if (issues.warnings.length) {
showToast(`Object placed. ${issues.warnings.join(" · ")}.`);
} else {
showToast(`${selectedType === "table" ? "Table" : "Bicycle"} placed on the street.`);
}
return true;
}
// ------------------------------------------------------------
// Pointer interaction and direct camera controls
// ------------------------------------------------------------
const raycaster = new THREE.Raycaster();
const pointerNdc = new THREE.Vector2();
const pointerState = {
x: 0,
y: 0,
inside: false,
worldPoint: new THREE.Vector3()
};
const pointers = new Map();
let dragState = null;
let pinchDistance = 0;
let pinchRadius = 49;
function updatePointerWorld(event) {
const rect = renderer.domElement.getBoundingClientRect();
pointerState.x = event.clientX;
pointerState.y = event.clientY;
pointerState.inside = true;
pointerNdc.x = ((event.clientX - rect.left) / rect.width) * 2 - 1;
pointerNdc.y = -((event.clientY - rect.top) / rect.height) * 2 + 1;
raycaster.setFromCamera(pointerNdc, camera);
const hits = raycaster.intersectObject(groundMesh, false);
if (hits.length) {
pointerState.worldPoint.copy(hits[0].point);
updateGhost();
} else {
pointerState.inside = false;
updateGhost();
}
}
function findPropFromIntersection(intersections) {
for (const hit of intersections) {
let object = hit.object;
while (object) {
if (object.userData.propId !== undefined) {
return object.userData.propId;
}
object = object.parent;
}
}
return null;
}
function handleSceneClick(event) {
const rect = renderer.domElement.getBoundingClientRect();
pointerNdc.x = ((event.clientX - rect.left) / rect.width) * 2 - 1;
pointerNdc.y = -((event.clientY - rect.top) / rect.height) * 2 + 1;
raycaster.setFromCamera(pointerNdc, camera);
const propHits = raycaster.intersectObjects(
props.map((prop) => prop.group),
true
);
if (propHits.length) {
const id = findPropFromIntersection(propHits);
if (id !== null) {
selectProp(id);
return;
}
}
const groundHits = raycaster.intersectObject(groundMesh, false);
if (groundHits.length) {
const point = groundHits[0].point;
const x = Math.round(point.x * 2) / 2;
const z = Math.round(point.z * 2) / 2;
placeAt(x, z);
}
}
function panCamera(dx, dy) {
const scale = cameraState.radius * 0.0014;
const right = new THREE.Vector3(
Math.cos(cameraState.yaw),
0,
-Math.sin(cameraState.yaw)
);
const forward = new THREE.Vector3(
-Math.sin(cameraState.yaw),
0,
-Math.cos(cameraState.yaw)
);
cameraState.target.addScaledVector(right, -dx * scale);
cameraState.target.addScaledVector(forward, -dy * scale);
cameraState.target.x = THREE.MathUtils.clamp(
cameraState.target.x,
-8,
8
);
cameraState.target.z = THREE.MathUtils.clamp(
cameraState.target.z,
-18,
18
);
updateCamera();
}
renderer.domElement.addEventListener("contextmenu", (event) => {
event.preventDefault();
});
renderer.domElement.addEventListener("pointerdown", (event) => {
renderer.domElement.setPointerCapture(event.pointerId);
pointers.set(event.pointerId, { x: event.clientX, y: event.clientY });
if (pointers.size === 1) {
dragState = {
startX: event.clientX,
startY: event.clientY,
lastX: event.clientX,
lastY: event.clientY,
button: event.button,
dragged: false,
multiTouch: false
};
} else if (pointers.size === 2) {
dragState.multiTouch = true;
const values = [...pointers.values()];
pinchDistance = Math.hypot(
values[0].x - values[1].x,
values[0].y - values[1].y
);
pinchRadius = cameraState.radius;
}
updatePointerWorld(event);
});
renderer.domElement.addEventListener("pointermove", (event) => {
if (!pointers.has(event.pointerId)) {
updatePointerWorld(event);
return;
}
pointers.set(event.pointerId, { x: event.clientX, y: event.clientY });
updatePointerWorld(event);
if (pointers.size >= 2) {
const values = [...pointers.values()];
const distance = Math.hypot(
values[0].x - values[1].x,
values[0].y - values[1].y
);
if (pinchDistance > 0) {
cameraState.radius = THREE.MathUtils.clamp(
pinchRadius * (pinchDistance / Math.max(distance, 1)),
22,
78
);
updateCamera();
}
return;
}
if (!dragState) return;
const dx = event.clientX - dragState.startX;
const dy = event.clientY - dragState.startY;
if (Math.hypot(dx, dy) > 4) dragState.dragged = true;
if (dragState.dragged) {
if (dragState.button === 2 || event.shiftKey) {
panCamera(
event.clientX - dragState.lastX,
event.clientY - dragState.lastY
);
} else {
cameraState.yaw -= dx * 0.005;
cameraState.pitch = THREE.MathUtils.clamp(
cameraState.pitch + dy * 0.004,
0.28,
1.3
);
updateCamera();
}
}
dragState.lastX = event.clientX;
dragState.lastY = event.clientY;
});
function endPointer(event, cancelled = false) {
const wasSingle = pointers.size === 1;
pointers.delete(event.pointerId);
if (
wasSingle &&
!cancelled &&
dragState &&
!dragState.dragged &&
!dragState.multiTouch &&
event.button === 0
) {
handleSceneClick(event);
}
if (pointers.size < 2) {
pinchDistance = 0;
}
if (pointers.size === 0) {
dragState = null;
}
}
renderer.domElement.addEventListener(
"pointerup",
(event) => endPointer(event, false)
);
renderer.domElement.addEventListener(
"pointercancel",
(event) => endPointer(event, true)
);
renderer.domElement.addEventListener("pointerleave", () => {
if (pointers.size === 0) {
pointerState.inside = false;
updateGhost();
}
});
renderer.domElement.addEventListener(
"wheel",
(event) => {
event.preventDefault();
cameraState.radius = THREE.MathUtils.clamp(
cameraState.radius + event.deltaY * 0.025,
22,
78
);
updateCamera();
},
{ passive: false }
);
// ------------------------------------------------------------
// Toolbar and keyboard controls
// ------------------------------------------------------------
document.querySelector("#tableTool").addEventListener("click", () => {
setSelectedType("table");
replaceGhostModel();
updateGhost();
});
document.querySelector("#bikeTool").addEventListener("click", () => {
setSelectedType("bike");
replaceGhostModel();
updateGhost();
});
document.querySelector("#rotateTool").addEventListener("click", rotatePlacement);
document.querySelector("#removeTool").addEventListener("click", removeSelected);
document.querySelector("#undoTool").addEventListener("click", undo);
document.querySelector("#clearTool").addEventListener("click", clearProps);
document.querySelector("#cameraTool").addEventListener("click", resetCamera);
document.querySelector("#overlayTool").addEventListener("click", (event) => {
overlaysVisible = !overlaysVisible;
routeGroup.visible = overlaysVisible;
accessGroup.visible = overlaysVisible;
event.currentTarget.classList.toggle("active", overlaysVisible);
event.currentTarget.setAttribute("aria-pressed", String(overlaysVisible));
});
window.addEventListener("keydown", (event) => {
const target = event.target;
if (target instanceof HTMLInputElement || target instanceof HTMLTextAreaElement) {
return;
}
const key = event.key.toLowerCase();
if ((event.ctrlKey || event.metaKey) && key === "z") {
event.preventDefault();
undo();
} else if (key === "t") {
setSelectedType("table");
replaceGhostModel();
updateGhost();
} else if (key === "b") {
setSelectedType("bike");
replaceGhostModel();
updateGhost();
} else if (key === "r") {
rotatePlacement();
} else if (key === "delete" || key === "backspace") {
event.preventDefault();
removeSelected();
} else if (key === "escape") {
selectProp(null);
}
});
// ------------------------------------------------------------
// Initialize scene and examples
// ------------------------------------------------------------
buildEnvironment();
buildRouteOverlay();
buildAccessOverlay();
// Two harmless fictional examples show the available prop types.
createPropEntry("table", 5.0, 2.5, 0);
createPropEntry("bike", -4.8, -4.5, 0);
updateOverlays();
updateSelectionBox();
updateToolbarState();
function onResize() {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
}
window.addEventListener("resize", onResize);
function animate() {
requestAnimationFrame(animate);
if (selectionBox) {
selectionBox.update();
}
renderer.render(scene, camera);
}
animate();
</script>
</body>
</html>
```