Prompt specification
Build or customize the Three.js 3D scene "Tree Placement Counterfactual Street" 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: Tree Placement Counterfactual Street
Category: Everyday & Industrial · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/tree-placement-counterfactual-street-x3972
Scene Description Prompt:
Make a standalone HTML scene with Three.js from cdnjs that depicts shade geometry and direct solar exposure. Create matched street layouts with different tree positions and identical sun conditions. Measure the model's shaded ground area and disclose omitted effects such as airflow and evapotranspiration. Low-poly.
Working Three.js Starter (tree-placement-counterfactual-street-x3972):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Street Tree Shade — Matched Low-Poly Solar Study</title>
<style>
:root {
--ink: #14212b;
--muted: #5f6f79;
--paper: rgba(250, 252, 250, 0.92);
--line: rgba(20, 33, 43, 0.14);
--sun: #f2c14e;
--tree: #287fa5;
--built: #596574;
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: #d7e3e7;
color: var(--ink);
font-family:
Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
canvas {
position: fixed;
inset: 0;
width: 100vw;
height: 100vh;
display: block;
touch-action: none;
cursor: grab;
}
canvas.dragging {
cursor: grabbing;
}
.hero {
position: fixed;
z-index: 5;
top: 16px;
left: 18px;
max-width: 570px;
pointer-events: none;
}
.hero h1 {
margin: 0 0 5px;
font-size: clamp(19px, 2vw, 28px);
line-height: 1.08;
letter-spacing: -0.035em;
}
.hero p {
margin: 0;
color: #344751;
font-size: 12px;
line-height: 1.45;
}
.sun-badge {
display: inline-flex;
align-items: center;
gap: 7px;
margin-top: 9px;
padding: 6px 9px;
border: 1px solid rgba(119, 86, 14, 0.18);
border-radius: 999px;
background: rgba(255, 246, 205, 0.86);
color: #71560d;
font-size: 10px;
font-weight: 800;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.sun-dot {
width: 9px;
height: 9px;
border-radius: 50%;
background: var(--sun);
box-shadow: 0 0 0 4px rgba(242, 193, 78, 0.2);
}
.controls {
position: fixed;
z-index: 8;
top: 16px;
right: 18px;
display: flex;
flex-wrap: wrap;
justify-content: flex-end;
gap: 6px;
}
button {
border: 1px solid rgba(20, 33, 43, 0.16);
border-radius: 9px;
padding: 8px 10px;
background: rgba(250, 252, 250, 0.92);
color: var(--ink);
font: inherit;
font-size: 11px;
font-weight: 700;
cursor: pointer;
box-shadow: 0 3px 14px rgba(20, 33, 43, 0.08);
}
button:hover {
background: #fff;
transform: translateY(-1px);
}
.panel {
position: fixed;
z-index: 4;
width: 390px;
max-width: calc(100vw - 28px);
padding: 12px;
border: 1px solid rgba(255, 255, 255, 0.54);
border-radius: 13px;
background: rgba(249, 251, 248, 0.83);
box-shadow: 0 9px 30px rgba(20, 33, 43, 0.1);
backdrop-filter: blur(8px);
pointer-events: none;
}
.panel-kicker {
margin-bottom: 2px;
color: var(--muted);
font-size: 9px;
font-weight: 800;
letter-spacing: 0.12em;
text-transform: uppercase;
}
.panel h2 {
margin: 0;
font-size: 16px;
letter-spacing: -0.025em;
}
.panel p {
margin: 3px 0 9px;
color: var(--muted);
font-size: 10px;
line-height: 1.3;
}
.metrics {
display: grid;
grid-template-columns: repeat(4, minmax(0, 1fr));
gap: 5px;
}
.metric {
min-width: 0;
padding: 7px;
border: 1px solid var(--line);
border-radius: 8px;
background: rgba(255, 255, 255, 0.63);
}
.metric span {
display: block;
overflow: hidden;
color: var(--muted);
font-size: 8px;
font-weight: 700;
line-height: 1.1;
text-overflow: ellipsis;
white-space: nowrap;
}
.metric strong {
display: block;
margin-top: 4px;
font-size: 14px;
line-height: 1;
white-space: nowrap;
}
.metric small {
display: block;
margin-top: 3px;
color: var(--muted);
font-size: 8px;
white-space: nowrap;
}
.metric.sun strong {
color: #8b6810;
}
.metric.tree strong {
color: var(--tree);
}
.metric.built strong {
color: var(--built);
}
.legend {
position: fixed;
z-index: 5;
left: 18px;
bottom: 166px;
display: flex;
flex-wrap: wrap;
gap: 8px 13px;
max-width: 760px;
padding: 8px 10px;
border: 1px solid rgba(255, 255, 255, 0.5);
border-radius: 10px;
background: rgba(249, 251, 248, 0.86);
box-shadow: 0 4px 20px rgba(20, 33, 43, 0.08);
pointer-events: none;
font-size: 9px;
font-weight: 700;
}
.legend-item {
display: inline-flex;
align-items: center;
gap: 5px;
white-space: nowrap;
}
.swatch {
width: 12px;
height: 8px;
border-radius: 2px;
border: 1px solid rgba(0, 0, 0, 0.08);
}
.swatch.sun {
background: rgba(242, 193, 78, 0.82);
}
.swatch.tree {
background: rgba(40, 127, 165, 0.82);
}
.swatch.built {
background: rgba(89, 101, 116, 0.82);
}
.swatch.envelope {
border: 1.5px solid #216b92;
background: transparent;
}
details.scope {
position: fixed;
z-index: 7;
right: 14px;
bottom: 12px;
left: 14px;
max-height: 145px;
overflow: auto;
padding: 10px 13px;
border: 1px solid rgba(255, 255, 255, 0.55);
border-radius: 11px;
background: rgba(20, 33, 43, 0.91);
color: #eef4f3;
box-shadow: 0 8px 30px rgba(20, 33, 43, 0.2);
font-size: 10px;
line-height: 1.42;
}
details.scope summary {
cursor: pointer;
font-size: 10px;
font-weight: 800;
letter-spacing: 0.03em;
}
details.scope p {
margin: 7px 0 0;
color: #d2dcdd;
}
.loading {
position: fixed;
z-index: 10;
top: 50%;
left: 50%;
padding: 12px 16px;
transform: translate(-50%, -50%);
border-radius: 10px;
background: rgba(20, 33, 43, 0.9);
color: white;
font-size: 12px;
font-weight: 700;
box-shadow: 0 8px 30px rgba(20, 33, 43, 0.25);
}
.loading.hidden {
display: none;
}
@media (max-width: 900px) {
.hero {
max-width: calc(100vw - 36px);
}
.hero p {
max-width: 430px;
}
.controls {
top: 84px;
}
}
@media (max-width: 759px) {
.hero {
top: 12px;
left: 12px;
max-width: calc(100vw - 24px);
}
.hero h1 {
max-width: 350px;
font-size: 19px;
}
.hero p {
max-width: 320px;
font-size: 10px;
}
.sun-badge {
margin-top: 6px;
font-size: 8px;
}
.controls {
top: 103px;
right: 12px;
left: 12px;
justify-content: flex-start;
}
button {
padding: 6px 8px;
font-size: 9px;
}
.panel {
padding: 9px;
}
.panel h2 {
font-size: 14px;
}
.panel p {
display: none;
}
.metrics {
margin-top: 7px;
}
.metric {
padding: 5px;
}
.metric strong {
font-size: 12px;
}
.legend {
right: 12px;
bottom: 158px;
left: 12px;
gap: 6px 10px;
font-size: 8px;
}
details.scope {
max-height: 136px;
}
}
</style>
</head>
<body>
<canvas id="scene" aria-label="Interactive comparison of two street tree layouts"></canvas>
<header class="hero">
<h1>Street shade geometry / direct solar exposure</h1>
<p>
Matched low-poly street, buildings, and 12 tree templates. Only tree
positions change. Linked cameras ensure an identical viewpoint.
Drag to orbit, wheel to zoom, Shift-drag to pan.
</p>
<div class="sun-badge">
<span class="sun-dot"></span>
Solar azimuth 225° · elevation 42° · identical in both layouts
</div>
</header>
<div class="controls">
<button id="toggleTiles" type="button">Analysis grid: on</button>
<button id="toggleFootprints" type="button">Projected envelopes: on</button>
<button id="resetCamera" type="button">Reset view</button>
</div>
<section class="panel" id="panelA">
<div class="panel-kicker">Layout A</div>
<h2>Regular verge trees</h2>
<p>Six evenly spaced trees on each sidewalk.</p>
<div class="metrics">
<div class="metric">
<span>Shaded ground</span>
<strong id="aShade">—</strong>
<small id="aPct">—</small>
</div>
<div class="metric sun">
<span>Direct sun</span>
<strong id="aExposed">—</strong>
<small>unshaded</small>
</div>
<div class="metric tree">
<span>Tree shade</span>
<strong id="aTree">—</strong>
<small>nearest hit</small>
</div>
<div class="metric built">
<span>Built shade</span>
<strong id="aBuilding">—</strong>
<small>nearest hit</small>
</div>
</div>
</section>
<section class="panel" id="panelB">
<div class="panel-kicker">Layout B</div>
<h2>Clustered tree nodes</h2>
<p>The same crowns are grouped into three paired nodes per side.</p>
<div class="metrics">
<div class="metric">
<span>Shaded ground</span>
<strong id="bShade">—</strong>
<small id="bPct">—</small>
</div>
<div class="metric sun">
<span>Direct sun</span>
<strong id="bExposed">—</strong>
<small>unshaded</small>
</div>
<div class="metric tree">
<span>Tree shade</span>
<strong id="bTree">—</strong>
<small>nearest hit</small>
</div>
<div class="metric built">
<span>Built shade</span>
<strong id="bBuilding">—</strong>
<small>nearest hit</small>
</div>
</div>
</section>
<div class="legend" aria-label="Scene legend">
<span class="legend-item">
<span class="swatch sun"></span> Direct-sun sample
</span>
<span class="legend-item">
<span class="swatch tree"></span> Tree shadow
</span>
<span class="legend-item">
<span class="swatch built"></span> Building shadow
</span>
<span class="legend-item">
<span class="swatch envelope"></span> Projected geometry envelope
</span>
</div>
<details class="scope" open>
<summary>
Model scope and omissions — geometric shade only; excludes airflow and evapotranspiration
</summary>
<p>
The analysis domain is a 48 × 13 m street right-of-way (624 m²),
including roadway and both sidewalks. A deterministic 0.25 m ground
grid is classified by tracing each point toward the sun and testing
the fixed low-poly tree crowns, trunks, and building boxes. “Shaded” is
the nearest-hit tree or building intersection; displayed areas are
grid-resolution estimates. Outlined envelopes are projected convex
hulls and explain the geometry, but are not the area measurement.
This is one instantaneous sun position, not an annual solar study.
Omitted effects include diffuse skylight and radiative transfer,
hourly/seasonal variation, leaf-on/leaf-off variation beyond the fixed
crowns, airflow and wind-driven canopy movement, evapotranspiration,
soil moisture, heat storage, thermal comfort, albedo and glare,
vehicles/street furniture, and real-world canopy and sensor uncertainty.
The two layouts use exactly the same sun vector, street, buildings,
and tree geometry templates.
</p>
</details>
<div class="loading" id="loading">Computing geometric shade…</div>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
// -------------------------------------------------------------------------
// Constants and shared analysis settings
// -------------------------------------------------------------------------
const canvas = document.getElementById("scene");
const loading = document.getElementById("loading");
const renderer = new THREE.WebGLRenderer({
canvas,
antialias: true,
powerPreference: "high-performance"
});
renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 1.6));
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.12;
const camera = new THREE.PerspectiveCamera(42, 1, 0.1, 220);
const ANALYSIS = {
xMin: -24,
xMax: 24,
zMin: -6.5,
zMax: 6.5,
cell: 0.25
};
const analysisArea =
(ANALYSIS.xMax - ANALYSIS.xMin) *
(ANALYSIS.zMax - ANALYSIS.zMin);
const solarAzimuth = 225;
const solarElevation = 42;
const azimuth = THREE.MathUtils.degToRad(solarAzimuth);
const elevation = THREE.MathUtils.degToRad(solarElevation);
// x = east, z = south, y = up. This points from the ground toward the sun.
const sunDirection = new THREE.Vector3(
Math.sin(azimuth) * Math.cos(elevation),
Math.sin(elevation),
-Math.cos(azimuth) * Math.cos(elevation)
).normalize();
const colors = {
exposed: 0xf2c14e,
tree: 0x287fa5,
building: 0x596574,
treeEnvelope: 0x216b92,
buildingEnvelope: 0x46505c
};
const tileGroups = [];
const footprintGroups = [];
const scenes = [];
// -------------------------------------------------------------------------
// Camera controls implemented directly, without addons
// -------------------------------------------------------------------------
const view = {
theta: 0.72,
phi: 0.82,
radius: 58,
target: new THREE.Vector3(0, 0, 0)
};
let needsRender = true;
function updateCamera() {
const sinPhi = Math.sin(view.phi);
camera.position.set(
view.target.x + view.radius * sinPhi * Math.sin(view.theta),
view.target.y + view.radius * Math.cos(view.phi),
view.target.z + view.radius * sinPhi * Math.cos(view.theta)
);
camera.lookAt(view.target);
}
function resetCamera() {
view.theta = 0.72;
view.phi = 0.82;
view.radius = 58;
view.target.set(0, 0, 0);
updateCamera();
needsRender = true;
}
let dragging = false;
let dragX = 0;
let dragY = 0;
let shiftDrag = false;
canvas.addEventListener("pointerdown", (event) => {
if (event.button !== 0) return;
dragging = true;
dragX = event.clientX;
dragY = event.clientY;
shiftDrag = event.shiftKey;
canvas.setPointerCapture(event.pointerId);
canvas.classList.add("dragging");
});
canvas.addEventListener("pointermove", (event) => {
if (!dragging) return;
const dx = event.clientX - dragX;
const dy = event.clientY - dragY;
dragX = event.clientX;
dragY = event.clientY;
if (shiftDrag) {
updateCamera();
const forward = new THREE.Vector3();
camera.getWorldDirection(forward);
forward.y = 0;
forward.normalize();
const right = new THREE.Vector3()
.crossVectors(forward, new THREE.Vector3(0, 1, 0))
.normalize();
const panScale = view.radius * 0.0015;
view.target.addScaledVector(right, -dx * panScale);
view.target.addScaledVector(forward, dy * panScale);
view.target.x = THREE.MathUtils.clamp(view.target.x, -25, 25);
view.target.z = THREE.MathUtils.clamp(view.target.z, -20, 20);
} else {
view.theta -= dx * 0.006;
view.phi = THREE.MathUtils.clamp(view.phi + dy * 0.005, 0.25, 1.36);
}
updateCamera();
needsRender = true;
});
function endDrag(event) {
dragging = false;
shiftDrag = false;
canvas.classList.remove("dragging");
if (event.pointerId !== undefined && canvas.hasPointerCapture(event.pointerId)) {
canvas.releasePointerCapture(event.pointerId);
}
}
canvas.addEventListener("pointerup", endDrag);
canvas.addEventListener("pointercancel", endDrag);
canvas.addEventListener("dblclick", resetCamera);
canvas.addEventListener("contextmenu", (event) => event.preventDefault());
canvas.addEventListener(
"wheel",
(event) => {
event.preventDefault();
view.radius = THREE.MathUtils.clamp(
view.radius * Math.exp(event.deltaY * 0.001),
25,
96
);
updateCamera();
needsRender = true;
},
{ passive: false }
);
document.getElementById("resetCamera").addEventListener("click", resetCamera);
window.addEventListener("keydown", (event) => {
if (event.key.toLowerCase() === "r") resetCamera();
});
// -------------------------------------------------------------------------
// Geometry helpers
// -------------------------------------------------------------------------
function addPlane(scene, width, depth, x, z, y, color, roughness = 0.95) {
const geometry = new THREE.PlaneGeometry(width, depth);
geometry.rotateX(-Math.PI / 2);
const material = new THREE.MeshStandardMaterial({
color,
roughness,
metalness: 0
});
const mesh = new THREE.Mesh(geometry, material);
mesh.position.set(x, y, z);
mesh.receiveShadow = true;
scene.add(mesh);
return mesh;
}
function addBox(
scene,
width,
height,
depth,
x,
y,
z,
material,
castShadow = true,
receiveShadow = true
) {
const mesh = new THREE.Mesh(
new THREE.BoxGeometry(width, height, depth),
material
);
mesh.position.set(x, y, z);
mesh.castShadow = castShadow;
mesh.receiveShadow = receiveShadow;
scene.add(mesh);
return mesh;
}
function createStreet(scene) {
addPlane(scene, 54, 31, 0, 0, -0.07, 0x8fa27c);
addPlane(scene, 48, 8, 0, 0, 0.0, 0x424b52);
const sidewalkMaterial = new THREE.MeshStandardMaterial({
color: 0xc9c4b6,
roughness: 0.96
});
addPlane(scene, 48, 2.5, 0, 5.25, 0.015, 0xc9c4b6);
addPlane(scene, 48, 2.5, 0, -5.25, 0.015, 0xc9c4b6);
const curbMaterial = new THREE.MeshStandardMaterial({
color: 0xa9a69d,
roughness: 0.92
});
for (const z of [-4.08, 4.08]) {
addBox(
scene,
48,
0.13,
0.16,
0,
0.055,
z,
curbMaterial,
false,
true
);
}
const centerLineMaterial = new THREE.MeshStandardMaterial({
color: 0xe5bd48,
roughness: 0.8
});
for (let x = -21; x <= 21; x += 6) {
addBox(
scene,
3,
0.018,
0.11,
x,
0.032,
0,
centerLineMaterial,
false,
false
);
}
const crossingMaterial = new THREE.MeshStandardMaterial({
color: 0xe9ece8,
roughness: 0.85
});
for (const crossingX of [-22.3, 22.3]) {
for (let offset = -3.15; offset <= 3.15; offset += 0.9) {
addBox(
scene,
0.42,
0.018,
7.1,
crossingX,
0.034,
offset,
crossingMaterial,
false,
false
);
}
}
}
function createBuildings(scene) {
const occluders = [];
const footprintMeshes = [];
const specs = [
{ x: -16, z: 10.2, w: 7, d: 5, h: 6.0, color: 0xc88f72 },
{ x: -7, z: 10.2, w: 6, d: 5, h: 4.6, color: 0xb5a48f },
{ x: 7, z: 10.2, w: 7, d: 5, h: 7.0, color: 0xd0a16d },
{ x: 16, z: 10.2, w: 6, d: 5, h: 5.3, color: 0x9faeb0 },
{ x: -15, z: -10.2, w: 8, d: 5.2, h: 5.0, color: 0x8da8aa },
{ x: -4.5, z: -10.2, w: 7, d: 5, h: 6.5, color: 0xc17f69 },
{ x: 6, z: -10.2, w: 7, d: 5, h: 4.8, color: 0xa9a17f },
{ x: 16, z: -10.2, w: 7, d: 5, h: 5.8, color: 0x92a0b3 }
];
const windowMaterial = new THREE.MeshStandardMaterial({
color: 0x385568,
emissive: 0x102b36,
emissiveIntensity: 0.18,
roughness: 0.48,
metalness: 0.08
});
const roofMaterial = new THREE.MeshStandardMaterial({
color: 0x66717a,
roughness: 0.94
});
for (const spec of specs) {
const material = new THREE.MeshStandardMaterial({
color: spec.color,
flatShading: true,
roughness: 0.93
});
const building = addBox(
scene,
spec.w,
spec.h,
spec.d,
spec.x,
spec.h / 2,
spec.z,
material
);
building.userData.shadeType = "building";
occluders.push(building);
footprintMeshes.push(building);
const roof = addBox(
scene,
spec.w + 0.16,
0.16,
spec.d + 0.16,
spec.x,
spec.h + 0.08,
spec.z,
roofMaterial
);
roof.userData.shadeType = "building";
occluders.push(roof);
// Windows are visual detail only; the analytic occluder is the box.
const facadeZ =
spec.z + (spec.z > 0 ? -1 : 1) * (spec.d / 2 + 0.025);
const floors = Math.max(1, Math.floor(spec.h / 2.1));
const columns = Math.max(2, Math.floor(spec.w / 2));
for (let floor = 0; floor < floors; floor++) {
for (let column = 0; column < columns; column++) {
const x =
spec.x -
spec.w / 2 +
((column + 1) * spec.w) / (columns + 1);
const y = 1.15 + floor * 2.05;
if (y + 0.55 > spec.h) continue;
addBox(
scene,
0.82,
1.05,
0.045,
x,
y,
facadeZ,
windowMaterial,
false,
false
);
}
}
}
return { occluders, footprintMeshes };
}
const crownGeometry = new THREE.IcosahedronGeometry(1, 0);
const trunkGeometry = new THREE.CylinderGeometry(0.16, 0.22, 2.4, 6);
const crownBlueprints = [
{ offset: [-0.05, 3.45, 0.05], scale: [1.45, 1.35, 1.30] },
{ offset: [-0.72, 3.00, 0.10], scale: [1.05, 1.05, 1.00] },
{ offset: [0.68, 3.05, -0.15], scale: [1.05, 1.00, 1.05] },
{ offset: [0.02, 3.95, -0.38], scale: [1.05, 0.90, 0.95] }
];
const trunkMaterial = new THREE.MeshStandardMaterial({
color: 0x76513b,
roughness: 1,
flatShading: true
});
const foliagePalette = [0x477a46, 0x56854a, 0x3f7143, 0x628b50];
function createTrees(scene, rows) {
const occluders = [];
const footprintMeshes = [];
let treeId = 0;
for (const row of rows) {
for (const x of row.xs) {
const tree = new THREE.Group();
tree.position.set(x, 0, row.z);
scene.add(tree);
const trunk = new THREE.Mesh(trunkGeometry, trunkMaterial);
trunk.position.y = 1.2;
trunk.castShadow = true;
trunk.receiveShadow = true;
trunk.userData.shadeType = "tree";
tree.add(trunk);
occluders.push(trunk);
const crowns = [];
for (const blueprint of crownBlueprints) {
const foliage = new THREE.Mesh(
crownGeometry,
new THREE.MeshStandardMaterial({
color: foliagePalette[treeId % foliagePalette.length],
flatShading: true,
roughness: 1
})
);
foliage.position.set(
blueprint.offset[0],
blueprint.offset[1],
blueprint.offset[2]
);
foliage.scale.set(
blueprint.scale[0],
blueprint.scale[1],
blueprint.scale[2]
);
foliage.rotation.y = 0.23;
foliage.castShadow = true;
foliage.receiveShadow = true;
foliage.userData.shadeType = "tree";
tree.add(foliage);
crowns.push(foliage);
occluders.push(foliage);
}
footprintMeshes.push(crowns);
treeId++;
}
}
return { occluders, footprintMeshes };
}
// -------------------------------------------------------------------------
// Deterministic ground ray test and measured area
// -------------------------------------------------------------------------
function analyzeGround(scene, occluders) {
const nx = Math.round(
(ANALYSIS.xMax - ANALYSIS.xMin) / ANALYSIS.cell
);
const nz = Math.round(
(ANALYSIS.zMax - ANALYSIS.zMin) / ANALYSIS.cell
);
const count = nx * nz;
const classifications = new Uint8Array(count);
const raycaster = new THREE.Raycaster();
raycaster.near = 0.001;
raycaster.far = 120;
const origin = new THREE.Vector3();
let treeCount = 0;
let buildingCount = 0;
let exposedCount = 0;
for (let ix = 0; ix < nx; ix++) {
const x =
ANALYSIS.xMin + (ix + 0.5) * ANALYSIS.cell;
for (let iz = 0; iz < nz; iz++) {
const z =
ANALYSIS.zMin + (iz + 0.5) * ANALYSIS.cell;
origin.set(x, 0.09, z);
raycaster.set(origin, sunDirection);
const hits = raycaster.intersectObjects(occluders, false);
const index = ix * nz + iz;
if (hits.length === 0) {
classifications[index] = 0;
exposedCount++;
continue;
}
const type = hits[0].object.userData.shadeType;
if (type === "tree") {
classifications[index] = 1;
treeCount++;
} else {
classifications[index] = 2;
buildingCount++;
}
}
}
const cellArea = ANALYSIS.cell * ANALYSIS.cell;
const treeArea = treeCount * cellArea;
const buildingArea = buildingCount * cellArea;
const shadedArea = treeArea + buildingArea;
const exposedArea = exposedCount * cellArea;
const group = new THREE.Group();
group.name = "Ray-sampled analysis grid";
const tileGeometry = new THREE.PlaneGeometry(
ANALYSIS.cell * 0.92,
ANALYSIS.cell * 0.92
);
tileGeometry.rotateX(-Math.PI / 2);
const tileMaterial = new THREE.MeshBasicMaterial({
color: 0xffffff,
vertexColors: true,
transparent: true,
opacity: 0.28,
depthWrite: false,
toneMapped: false
});
const tiles = new THREE.InstancedMesh(
tileGeometry,
tileMaterial,
count
);
const dummy = new THREE.Object3D();
const exposedColor = new THREE.Color(colors.exposed);
const treeColor = new THREE.Color(colors.tree);
const buildingColor = new THREE.Color(colors.building);
let instance = 0;
for (let ix = 0; ix < nx; ix++) {
const x =
ANALYSIS.xMin + (ix + 0.5) * ANALYSIS.cell;
for (let iz = 0; iz < nz; iz++) {
const z =
ANALYSIS.zMin + (iz + 0.5) * ANALYSIS.cell;
dummy.position.set(x, 0.052, z);
dummy.updateMatrix();
tiles.setMatrixAt(instance, dummy.matrix);
const classification = classifications[instance];
if (classification === 1) {
tiles.setColorAt(instance, treeColor);
} else if (classification === 2) {
tiles.setColorAt(instance, buildingColor);
} else {
tiles.setColorAt(instance, exposedColor);
}
instance++;
}
}
tiles.instanceMatrix.needsUpdate = true;
if (tiles.instanceColor) tiles.instanceColor.needsUpdate = true;
tiles.frustumCulled = false;
tiles.renderOrder = 3;
group.add(tiles);
scene.add(group);
tileGroups.push(group);
return {
totalArea: analysisArea,
shadedArea,
exposedArea,
treeArea,
buildingArea,
shadedPercent: (shadedArea / analysisArea) * 100,
exposedPercent: (exposedArea / analysisArea) * 100,
samples: count
};
}
// -------------------------------------------------------------------------
// Projected shade envelopes: explicit low-poly geometry projections
// -------------------------------------------------------------------------
function convexHull(points) {
const sorted = points
.map((point) => ({ x: point.x, z: point.z }))
.sort((a, b) => a.x === b.x ? a.z - b.z : a.x - b.x);
const unique = sorted.filter(
(point, index) =>
index === 0 ||
point.x !== sorted[index - 1].x ||
point.z !== sorted[index - 1].z
);
if (unique.length < 3) return unique;
const cross = (o, a, b) =>
(a.x - o.x) * (b.z - o.z) -
(a.z - o.z) * (b.x - o.x);
const lower = [];
for (const point of unique) {
while (
lower.length >= 2 &&
cross(lower[lower.length - 2], lower[lower.length - 1], point) <= 0
) {
lower.pop();
}
lower.push(point);
}
const upper = [];
for (let i = unique.length - 1; i >= 0; i--) {
const point = unique[i];
while (
upper.length >= 2 &&
cross(upper[upper.length - 2], upper[upper.length - 1], point) <= 0
) {
upper.pop();
}
upper.push(point);
}
lower.pop();
upper.pop();
return lower.concat(upper);
}
function projectedPointsForMeshes(meshes) {
const points = [];
for (const mesh of meshes) {
mesh.updateWorldMatrix(true, false);
const positions = mesh.geometry.attributes.position;
const vertex = new THREE.Vector3();
for (let i = 0; i < positions.count; i++) {
vertex.fromBufferAttribute(positions, i);
vertex.applyMatrix4(mesh.matrixWorld);
// Intersect the line from the vertex toward the sun with y = 0.
const factor = vertex.y / sunDirection.y;
points.push({
x: vertex.x - sunDirection.x * factor,
z: vertex.z - sunDirection.z * factor
});
}
}
return points;
}
function addProjectedEnvelope(group, meshes, color) {
const hull = convexHull(projectedPointsForMeshes(meshes));
if (hull.length < 3) return;
const vertices = [];
const indices = [];
for (const point of hull) {
vertices.push(point.x, 0.073, point.z);
}
for (let i = 1; i < hull.length - 1; i++) {
indices.push(0, i, i + 1);
}
const geometry = new THREE.BufferGeometry();
geometry.setAttribute(
"position",
new THREE.Float32BufferAttribute(vertices, 3)
);
geometry.setIndex(indices);
geometry.computeVertexNormals();
const fill = new THREE.Mesh(
geometry,
new THREE.MeshBasicMaterial({
color,
transparent: true,
opacity: 0.12,
side: THREE.DoubleSide,
depthWrite: false,
toneMapped: false
})
);
fill.renderOrder = 2;
group.add(fill);
const outlineGeometry = new THREE.BufferGeometry().setFromPoints(
hull.map(
(point) => new THREE.Vector3(point.x, 0.079, point.z)
)
);
const outline = new THREE.LineLoop(
outlineGeometry,
new THREE.LineBasicMaterial({
color,
transparent: true,
opacity: 0.72,
toneMapped: false
})
);
outline.renderOrder = 4;
group.add(outline);
}
function createFootprintGroup(scene, treeMeshes, buildingMeshes) {
const group = new THREE.Group();
group.name = "Projected shade envelopes";
for (const crowns of treeMeshes) {
addProjectedEnvelope(group, crowns, colors.treeEnvelope);
}
for (const building of buildingMeshes) {
addProjectedEnvelope(group, [building], colors.buildingEnvelope);
}
scene.add(group);
footprintGroups.push(group);
return group;
}
// -------------------------------------------------------------------------
// Visible sun direction indicators
// -------------------------------------------------------------------------
function createSunIndicators(scene) {
const group = new THREE.Group();
group.name = "Solar direction indicators";
const lineMaterial = new THREE.LineBasicMaterial({
color: 0xffd76a,
transparent: true,
opacity: 0.34,
toneMapped: false
});
const arrowMaterial = new THREE.MeshBasicMaterial({
color: 0xffd76a,
transparent: true,
opacity: 0.7,
toneMapped: false
});
const arrowGeometry = new THREE.ConeGeometry(0.13, 0.52, 5);
const down = sunDirection.clone().negate();
for (const x of [-18, -9, 0, 9, 18]) {
for (const z of [-5, 0, 5]) {
const end = new THREE.Vector3(x, 0.22, z);
const start = end.clone().addScaledVector(sunDirection, 12);
const line = new THREE.Line(
new THREE.BufferGeometry().setFromPoints([start, end]),
lineMaterial
);
group.add(line);
const arrow = new THREE.Mesh(arrowGeometry, arrowMaterial);
arrow.position.copy(start).lerp(end, 0.53);
arrow.quaternion.setFromUnitVectors(
new THREE.Vector3(0, 1, 0),
down
);
group.add(arrow);
}
}
const sun = new THREE.Mesh(
new THREE.IcosahedronGeometry(1.15, 1),
new THREE.MeshBasicMaterial({
color: 0xffd86a,
toneMapped: false
})
);
sun.position.copy(sunDirection).multiplyScalar(34);
group.add(sun);
const halo = new THREE.Mesh(
new THREE.IcosahedronGeometry(1.8, 1),
new THREE.MeshBasicMaterial({
color: 0xffdf83,
transparent: true,
opacity: 0.13,
depthWrite: false,
toneMapped: false
})
);
halo.position.copy(sun.position);
group.add(halo);
scene.add(group);
}
// -------------------------------------------------------------------------
// Scene construction
// -------------------------------------------------------------------------
function createScene(treeRows) {
const scene = new THREE.Scene();
scene.background = new THREE.Color(0xd3e1e5);
scene.fog = new THREE.Fog(0xd3e1e5, 78, 145);
const hemisphere = new THREE.HemisphereLight(
0xe5f3ff,
0x8b765d,
1.35
);
scene.add(hemisphere);
const sunlight = new THREE.DirectionalLight(0xfff0c7, 2.8);
sunlight.position.copy(sunDirection).multiplyScalar(75);
sunlight.castShadow = true;
sunlight.shadow.mapSize.set(1024, 1024);
sunlight.shadow.camera.left = -38;
sunlight.shadow.camera.right = 38;
sunlight.shadow.camera.top = 38;
sunlight.shadow.camera.bottom = -38;
sunlight.shadow.camera.near = 1;
sunlight.shadow.camera.far = 155;
sunlight.shadow.bias = -0.00035;
sunlight.shadow.normalBias = 0.035;
sunlight.shadow.camera.updateProjectionMatrix();
const target = new THREE.Object3D();
target.position.set(0, 0, 0);
sunlight.target = target;
scene.add(target, sunlight);
createStreet(scene);
const buildings = createBuildings(scene);
const trees = createTrees(scene, treeRows);
const occluders = [
...buildings.occluders,
...trees.occluders
];
scene.updateMatrixWorld(true);
const analysis = analyzeGround(scene, occluders);
createFootprintGroup(
scene,
trees.footprintMeshes,
buildings.footprintMeshes
);
createSunIndicators(scene);
return { scene, analysis };
}
const regularRows = [
{
z: 5.25,
xs: [-17.5, -10.5, -3.5, 3.5, 10.5, 17.5]
},
{
z: -5.25,
xs: [-17.5, -10.5, -3.5, 3.5, 10.5, 17.5]
}
];
const clusteredRows = [
{
z: 5.25,
xs: [-18.8, -17.4, -7.6, -6.2, 8.1, 9.5]
},
{
z: -5.25,
xs: [-17.8, -16.4, -6.9, -5.5, 9.2, 10.6]
}
];
// -------------------------------------------------------------------------
// Metrics, layout, and rendering
// -------------------------------------------------------------------------
function updateMetrics(prefix, metrics) {
document.getElementById(`${prefix}Shade`).textContent =
`${metrics.shadedArea.toFixed(1)} m²`;
document.getElementById(`${prefix}Pct`).textContent =
`${metrics.shadedPercent.toFixed(1)}% of ${metrics.totalArea.toFixed(0)} m²`;
document.getElementById(`${prefix}Exposed`).textContent =
`${metrics.exposedArea.toFixed(1)} m²`;
document.getElementById(`${prefix}Tree`).textContent =
`${metrics.treeArea.toFixed(1)} m²`;
document.getElementById(`${prefix}Building`).textContent =
`${metrics.buildingArea.toFixed(1)} m²`;
}
function getLayoutRects() {
const width = window.innerWidth;
const height = window.innerHeight;
if (width < 760) {
const split = Math.round(height * 0.52);
return {
vertical: true,
rects: [
{ x: 0, y: 0, w: width, h: split },
{ x: 0, y: split, w: width, h: height - split }
]
};
}
const split = Math.round(width * 0.5);
return {
vertical: false,
rects: [
{ x: 0, y: 0, w: split, h: height },
{ x: split, y: 0, w: width - split, h: height }
]
};
}
function positionPanels(layout) {
const panelA = document.getElementById("panelA");
const panelB = document.getElementById("panelB");
layout.rects.forEach((rect, index) => {
const panel = index === 0 ? panelA : panelB;
panel.style.left = `${rect.x + 14}px`;
panel.style.width = `${Math.min(rect.w - 28, 430)}px`;
if (layout.vertical && index === 1) {
panel.style.top = `${rect.y + 14}px`;
} else {
panel.style.top = `${rect.y + 82}px`;
}
});
}
function resize() {
renderer.setSize(window.innerWidth, window.innerHeight, false);
const layout = getLayoutRects();
positionPanels(layout);
needsRender = true;
}
window.addEventListener("resize", resize);
function renderScenes() {
const width = window.innerWidth;
const height = window.innerHeight;
const layout = getLayoutRects();
renderer.setScissorTest(false);
renderer.setClearColor(0xd3e1e5, 1);
renderer.clear(true, true, true);
renderer.setScissorTest(true);
layout.rects.forEach((rect, index) => {
// Three.js viewport coordinates have their origin at the lower left.
const viewportY = height - rect.y - rect.h;
renderer.setViewport(rect.x, viewportY, rect.w, rect.h);
renderer.setScissor(rect.x, viewportY, rect.w, rect.h);
camera.aspect = rect.w / rect.h;
camera.updateProjectionMatrix();
renderer.render(scenes[index].scene, camera);
});
renderer.setScissorTest(false);
}
function animate() {
requestAnimationFrame(animate);
if (needsRender && scenes.length === 2) {
renderScenes();
needsRender = false;
}
}
// -------------------------------------------------------------------------
// UI toggles
// -------------------------------------------------------------------------
let tilesVisible = true;
let footprintsVisible = true;
document
.getElementById("toggleTiles")
.addEventListener("click", (event) => {
tilesVisible = !tilesVisible;
for (const group of tileGroups) {
group.visible = tilesVisible;
}
event.currentTarget.textContent =
`Analysis grid: ${tilesVisible ? "on" : "off"}`;
needsRender = true;
});
document
.getElementById("toggleFootprints")
.addEventListener("click", (event) => {
footprintsVisible = !footprintsVisible;
for (const group of footprintGroups) {
group.visible = footprintsVisible;
}
event.currentTarget.textContent =
`Projected envelopes: ${footprintsVisible ? "on" : "off"}`;
needsRender = true;
});
// -------------------------------------------------------------------------
// Start after the browser has had a chance to paint the loading state
// -------------------------------------------------------------------------
resize();
updateCamera();
animate();
requestAnimationFrame(() => {
setTimeout(() => {
const layoutA = createScene(regularRows);
const layoutB = createScene(clusteredRows);
scenes.push(layoutA, layoutB);
updateMetrics("a", layoutA.analysis);
updateMetrics("b", layoutB.analysis);
window.modelResults = {
sun: {
azimuthDegrees: solarAzimuth,
elevationDegrees: solarElevation,
vector: sunDirection.toArray()
},
analysisAreaSquareMeters: analysisArea,
sampleCellMeters: ANALYSIS.cell,
layoutA: layoutA.analysis,
layoutB: layoutB.analysis
};
loading.classList.add("hidden");
needsRender = true;
}, 40);
});
</script>
</body>
</html>
```